gallium: remove TGSI FENCE opcodes
[mesa.git] / src / gallium / drivers / nouveau / codegen / nv50_ir_peephole.cpp
1 /*
2 * Copyright 2011 Christoph Bumiller
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20 * OTHER DEALINGS IN THE SOFTWARE.
21 */
22
23 #include "codegen/nv50_ir.h"
24 #include "codegen/nv50_ir_target.h"
25 #include "codegen/nv50_ir_build_util.h"
26
27 extern "C" {
28 #include "util/u_math.h"
29 }
30
31 namespace nv50_ir {
32
33 bool
34 Instruction::isNop() const
35 {
36 if (op == OP_PHI || op == OP_SPLIT || op == OP_MERGE || op == OP_CONSTRAINT)
37 return true;
38 if (terminator || join) // XXX: should terminator imply flow ?
39 return false;
40 if (op == OP_ATOM)
41 return false;
42 if (!fixed && op == OP_NOP)
43 return true;
44
45 if (defExists(0) && def(0).rep()->reg.data.id < 0) {
46 for (int d = 1; defExists(d); ++d)
47 if (def(d).rep()->reg.data.id >= 0)
48 WARN("part of vector result is unused !\n");
49 return true;
50 }
51
52 if (op == OP_MOV || op == OP_UNION) {
53 if (!getDef(0)->equals(getSrc(0)))
54 return false;
55 if (op == OP_UNION)
56 if (!def(0).rep()->equals(getSrc(1)))
57 return false;
58 return true;
59 }
60
61 return false;
62 }
63
64 bool Instruction::isDead() const
65 {
66 if (op == OP_STORE ||
67 op == OP_EXPORT ||
68 op == OP_ATOM ||
69 op == OP_SUSTB || op == OP_SUSTP || op == OP_SUREDP || op == OP_SUREDB ||
70 op == OP_WRSV)
71 return false;
72
73 for (int d = 0; defExists(d); ++d)
74 if (getDef(d)->refCount() || getDef(d)->reg.data.id >= 0)
75 return false;
76
77 if (terminator || asFlow())
78 return false;
79 if (fixed)
80 return false;
81
82 return true;
83 };
84
85 // =============================================================================
86
87 class CopyPropagation : public Pass
88 {
89 private:
90 virtual bool visit(BasicBlock *);
91 };
92
93 // Propagate all MOVs forward to make subsequent optimization easier, except if
94 // the sources stem from a phi, in which case we don't want to mess up potential
95 // swaps $rX <-> $rY, i.e. do not create live range overlaps of phi src and def.
96 bool
97 CopyPropagation::visit(BasicBlock *bb)
98 {
99 Instruction *mov, *si, *next;
100
101 for (mov = bb->getEntry(); mov; mov = next) {
102 next = mov->next;
103 if (mov->op != OP_MOV || mov->fixed || !mov->getSrc(0)->asLValue())
104 continue;
105 if (mov->getPredicate())
106 continue;
107 if (mov->def(0).getFile() != mov->src(0).getFile())
108 continue;
109 si = mov->getSrc(0)->getInsn();
110 if (mov->getDef(0)->reg.data.id < 0 && si && si->op != OP_PHI) {
111 // propagate
112 mov->def(0).replace(mov->getSrc(0), false);
113 delete_Instruction(prog, mov);
114 }
115 }
116 return true;
117 }
118
119 // =============================================================================
120
121 class MergeSplits : public Pass
122 {
123 private:
124 virtual bool visit(BasicBlock *);
125 };
126
127 // For SPLIT / MERGE pairs that operate on the same registers, replace the
128 // post-merge def with the SPLIT's source.
129 bool
130 MergeSplits::visit(BasicBlock *bb)
131 {
132 Instruction *i, *next, *si;
133
134 for (i = bb->getEntry(); i; i = next) {
135 next = i->next;
136 if (i->op != OP_MERGE || typeSizeof(i->dType) != 8)
137 continue;
138 si = i->getSrc(0)->getInsn();
139 if (si->op != OP_SPLIT || si != i->getSrc(1)->getInsn())
140 continue;
141 i->def(0).replace(si->getSrc(0), false);
142 delete_Instruction(prog, i);
143 }
144
145 return true;
146 }
147
148 // =============================================================================
149
150 class LoadPropagation : public Pass
151 {
152 private:
153 virtual bool visit(BasicBlock *);
154
155 void checkSwapSrc01(Instruction *);
156
157 bool isCSpaceLoad(Instruction *);
158 bool isImmdLoad(Instruction *);
159 bool isAttribOrSharedLoad(Instruction *);
160 };
161
162 bool
163 LoadPropagation::isCSpaceLoad(Instruction *ld)
164 {
165 return ld && ld->op == OP_LOAD && ld->src(0).getFile() == FILE_MEMORY_CONST;
166 }
167
168 bool
169 LoadPropagation::isImmdLoad(Instruction *ld)
170 {
171 if (!ld || (ld->op != OP_MOV) ||
172 ((typeSizeof(ld->dType) != 4) && (typeSizeof(ld->dType) != 8)))
173 return false;
174
175 // A 0 can be replaced with a register, so it doesn't count as an immediate.
176 ImmediateValue val;
177 return ld->src(0).getImmediate(val) && !val.isInteger(0);
178 }
179
180 bool
181 LoadPropagation::isAttribOrSharedLoad(Instruction *ld)
182 {
183 return ld &&
184 (ld->op == OP_VFETCH ||
185 (ld->op == OP_LOAD &&
186 (ld->src(0).getFile() == FILE_SHADER_INPUT ||
187 ld->src(0).getFile() == FILE_MEMORY_SHARED)));
188 }
189
190 void
191 LoadPropagation::checkSwapSrc01(Instruction *insn)
192 {
193 const Target *targ = prog->getTarget();
194 if (!targ->getOpInfo(insn).commutative)
195 if (insn->op != OP_SET && insn->op != OP_SLCT && insn->op != OP_SUB)
196 return;
197 if (insn->src(1).getFile() != FILE_GPR)
198 return;
199 // This is the special OP_SET used for alphatesting, we can't reverse its
200 // arguments as that will confuse the fixup code.
201 if (insn->op == OP_SET && insn->subOp)
202 return;
203
204 Instruction *i0 = insn->getSrc(0)->getInsn();
205 Instruction *i1 = insn->getSrc(1)->getInsn();
206
207 // Swap sources to inline the less frequently used source. That way,
208 // optimistically, it will eventually be able to remove the instruction.
209 int i0refs = insn->getSrc(0)->refCount();
210 int i1refs = insn->getSrc(1)->refCount();
211
212 if ((isCSpaceLoad(i0) || isImmdLoad(i0)) && targ->insnCanLoad(insn, 1, i0)) {
213 if ((!isImmdLoad(i1) && !isCSpaceLoad(i1)) ||
214 !targ->insnCanLoad(insn, 1, i1) ||
215 i0refs < i1refs)
216 insn->swapSources(0, 1);
217 else
218 return;
219 } else
220 if (isAttribOrSharedLoad(i1)) {
221 if (!isAttribOrSharedLoad(i0))
222 insn->swapSources(0, 1);
223 else
224 return;
225 } else {
226 return;
227 }
228
229 if (insn->op == OP_SET || insn->op == OP_SET_AND ||
230 insn->op == OP_SET_OR || insn->op == OP_SET_XOR)
231 insn->asCmp()->setCond = reverseCondCode(insn->asCmp()->setCond);
232 else
233 if (insn->op == OP_SLCT)
234 insn->asCmp()->setCond = inverseCondCode(insn->asCmp()->setCond);
235 else
236 if (insn->op == OP_SUB) {
237 insn->src(0).mod = insn->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);
238 insn->src(1).mod = insn->src(1).mod ^ Modifier(NV50_IR_MOD_NEG);
239 }
240 }
241
242 bool
243 LoadPropagation::visit(BasicBlock *bb)
244 {
245 const Target *targ = prog->getTarget();
246 Instruction *next;
247
248 for (Instruction *i = bb->getEntry(); i; i = next) {
249 next = i->next;
250
251 if (i->op == OP_CALL) // calls have args as sources, they must be in regs
252 continue;
253
254 if (i->op == OP_PFETCH) // pfetch expects arg1 to be a reg
255 continue;
256
257 if (i->srcExists(1))
258 checkSwapSrc01(i);
259
260 for (int s = 0; i->srcExists(s); ++s) {
261 Instruction *ld = i->getSrc(s)->getInsn();
262
263 if (!ld || ld->fixed || (ld->op != OP_LOAD && ld->op != OP_MOV))
264 continue;
265 if (!targ->insnCanLoad(i, s, ld))
266 continue;
267
268 // propagate !
269 i->setSrc(s, ld->getSrc(0));
270 if (ld->src(0).isIndirect(0))
271 i->setIndirect(s, 0, ld->getIndirect(0, 0));
272
273 if (ld->getDef(0)->refCount() == 0)
274 delete_Instruction(prog, ld);
275 }
276 }
277 return true;
278 }
279
280 // =============================================================================
281
282 class IndirectPropagation : public Pass
283 {
284 private:
285 virtual bool visit(BasicBlock *);
286 };
287
288 bool
289 IndirectPropagation::visit(BasicBlock *bb)
290 {
291 const Target *targ = prog->getTarget();
292 Instruction *next;
293
294 for (Instruction *i = bb->getEntry(); i; i = next) {
295 next = i->next;
296
297 for (int s = 0; i->srcExists(s); ++s) {
298 Instruction *insn;
299 ImmediateValue imm;
300 if (!i->src(s).isIndirect(0))
301 continue;
302 insn = i->getIndirect(s, 0)->getInsn();
303 if (!insn)
304 continue;
305 if (insn->op == OP_ADD && !isFloatType(insn->dType)) {
306 if (insn->src(0).getFile() != targ->nativeFile(FILE_ADDRESS) ||
307 !insn->src(1).getImmediate(imm) ||
308 !targ->insnCanLoadOffset(i, s, imm.reg.data.s32))
309 continue;
310 i->setIndirect(s, 0, insn->getSrc(0));
311 i->setSrc(s, cloneShallow(func, i->getSrc(s)));
312 i->src(s).get()->reg.data.offset += imm.reg.data.u32;
313 } else if (insn->op == OP_SUB && !isFloatType(insn->dType)) {
314 if (insn->src(0).getFile() != targ->nativeFile(FILE_ADDRESS) ||
315 !insn->src(1).getImmediate(imm) ||
316 !targ->insnCanLoadOffset(i, s, -imm.reg.data.s32))
317 continue;
318 i->setIndirect(s, 0, insn->getSrc(0));
319 i->setSrc(s, cloneShallow(func, i->getSrc(s)));
320 i->src(s).get()->reg.data.offset -= imm.reg.data.u32;
321 } else if (insn->op == OP_MOV) {
322 if (!insn->src(0).getImmediate(imm) ||
323 !targ->insnCanLoadOffset(i, s, imm.reg.data.s32))
324 continue;
325 i->setIndirect(s, 0, NULL);
326 i->setSrc(s, cloneShallow(func, i->getSrc(s)));
327 i->src(s).get()->reg.data.offset += imm.reg.data.u32;
328 }
329 }
330 }
331 return true;
332 }
333
334 // =============================================================================
335
336 // Evaluate constant expressions.
337 class ConstantFolding : public Pass
338 {
339 public:
340 bool foldAll(Program *);
341
342 private:
343 virtual bool visit(BasicBlock *);
344
345 void expr(Instruction *, ImmediateValue&, ImmediateValue&);
346 void expr(Instruction *, ImmediateValue&, ImmediateValue&, ImmediateValue&);
347 void opnd(Instruction *, ImmediateValue&, int s);
348 void opnd3(Instruction *, ImmediateValue&);
349
350 void unary(Instruction *, const ImmediateValue&);
351
352 void tryCollapseChainedMULs(Instruction *, const int s, ImmediateValue&);
353
354 CmpInstruction *findOriginForTestWithZero(Value *);
355
356 unsigned int foldCount;
357
358 BuildUtil bld;
359 };
360
361 // TODO: remember generated immediates and only revisit these
362 bool
363 ConstantFolding::foldAll(Program *prog)
364 {
365 unsigned int iterCount = 0;
366 do {
367 foldCount = 0;
368 if (!run(prog))
369 return false;
370 } while (foldCount && ++iterCount < 2);
371 return true;
372 }
373
374 bool
375 ConstantFolding::visit(BasicBlock *bb)
376 {
377 Instruction *i, *next;
378
379 for (i = bb->getEntry(); i; i = next) {
380 next = i->next;
381 if (i->op == OP_MOV || i->op == OP_CALL)
382 continue;
383
384 ImmediateValue src0, src1, src2;
385
386 if (i->srcExists(2) &&
387 i->src(0).getImmediate(src0) &&
388 i->src(1).getImmediate(src1) &&
389 i->src(2).getImmediate(src2))
390 expr(i, src0, src1, src2);
391 else
392 if (i->srcExists(1) &&
393 i->src(0).getImmediate(src0) && i->src(1).getImmediate(src1))
394 expr(i, src0, src1);
395 else
396 if (i->srcExists(0) && i->src(0).getImmediate(src0))
397 opnd(i, src0, 0);
398 else
399 if (i->srcExists(1) && i->src(1).getImmediate(src1))
400 opnd(i, src1, 1);
401 if (i->srcExists(2) && i->src(2).getImmediate(src2))
402 opnd3(i, src2);
403 }
404 return true;
405 }
406
407 CmpInstruction *
408 ConstantFolding::findOriginForTestWithZero(Value *value)
409 {
410 if (!value)
411 return NULL;
412 Instruction *insn = value->getInsn();
413 if (!insn)
414 return NULL;
415
416 if (insn->asCmp() && insn->op != OP_SLCT)
417 return insn->asCmp();
418
419 /* Sometimes mov's will sneak in as a result of other folding. This gets
420 * cleaned up later.
421 */
422 if (insn->op == OP_MOV)
423 return findOriginForTestWithZero(insn->getSrc(0));
424
425 /* Deal with AND 1.0 here since nv50 can't fold into boolean float */
426 if (insn->op == OP_AND) {
427 int s = 0;
428 ImmediateValue imm;
429 if (!insn->src(s).getImmediate(imm)) {
430 s = 1;
431 if (!insn->src(s).getImmediate(imm))
432 return NULL;
433 }
434 if (imm.reg.data.f32 != 1.0f)
435 return NULL;
436 /* TODO: Come up with a way to handle the condition being inverted */
437 if (insn->src(!s).mod != Modifier(0))
438 return NULL;
439 return findOriginForTestWithZero(insn->getSrc(!s));
440 }
441
442 return NULL;
443 }
444
445 void
446 Modifier::applyTo(ImmediateValue& imm) const
447 {
448 if (!bits) // avoid failure if imm.reg.type is unhandled (e.g. b128)
449 return;
450 switch (imm.reg.type) {
451 case TYPE_F32:
452 if (bits & NV50_IR_MOD_ABS)
453 imm.reg.data.f32 = fabsf(imm.reg.data.f32);
454 if (bits & NV50_IR_MOD_NEG)
455 imm.reg.data.f32 = -imm.reg.data.f32;
456 if (bits & NV50_IR_MOD_SAT) {
457 if (imm.reg.data.f32 < 0.0f)
458 imm.reg.data.f32 = 0.0f;
459 else
460 if (imm.reg.data.f32 > 1.0f)
461 imm.reg.data.f32 = 1.0f;
462 }
463 assert(!(bits & NV50_IR_MOD_NOT));
464 break;
465
466 case TYPE_S8: // NOTE: will be extended
467 case TYPE_S16:
468 case TYPE_S32:
469 case TYPE_U8: // NOTE: treated as signed
470 case TYPE_U16:
471 case TYPE_U32:
472 if (bits & NV50_IR_MOD_ABS)
473 imm.reg.data.s32 = (imm.reg.data.s32 >= 0) ?
474 imm.reg.data.s32 : -imm.reg.data.s32;
475 if (bits & NV50_IR_MOD_NEG)
476 imm.reg.data.s32 = -imm.reg.data.s32;
477 if (bits & NV50_IR_MOD_NOT)
478 imm.reg.data.s32 = ~imm.reg.data.s32;
479 break;
480
481 case TYPE_F64:
482 if (bits & NV50_IR_MOD_ABS)
483 imm.reg.data.f64 = fabs(imm.reg.data.f64);
484 if (bits & NV50_IR_MOD_NEG)
485 imm.reg.data.f64 = -imm.reg.data.f64;
486 if (bits & NV50_IR_MOD_SAT) {
487 if (imm.reg.data.f64 < 0.0)
488 imm.reg.data.f64 = 0.0;
489 else
490 if (imm.reg.data.f64 > 1.0)
491 imm.reg.data.f64 = 1.0;
492 }
493 assert(!(bits & NV50_IR_MOD_NOT));
494 break;
495
496 default:
497 assert(!"invalid/unhandled type");
498 imm.reg.data.u64 = 0;
499 break;
500 }
501 }
502
503 operation
504 Modifier::getOp() const
505 {
506 switch (bits) {
507 case NV50_IR_MOD_ABS: return OP_ABS;
508 case NV50_IR_MOD_NEG: return OP_NEG;
509 case NV50_IR_MOD_SAT: return OP_SAT;
510 case NV50_IR_MOD_NOT: return OP_NOT;
511 case 0:
512 return OP_MOV;
513 default:
514 return OP_CVT;
515 }
516 }
517
518 void
519 ConstantFolding::expr(Instruction *i,
520 ImmediateValue &imm0, ImmediateValue &imm1)
521 {
522 struct Storage *const a = &imm0.reg, *const b = &imm1.reg;
523 struct Storage res;
524 DataType type = i->dType;
525
526 memset(&res.data, 0, sizeof(res.data));
527
528 switch (i->op) {
529 case OP_MAD:
530 case OP_FMA:
531 case OP_MUL:
532 if (i->dnz && i->dType == TYPE_F32) {
533 if (!isfinite(a->data.f32))
534 a->data.f32 = 0.0f;
535 if (!isfinite(b->data.f32))
536 b->data.f32 = 0.0f;
537 }
538 switch (i->dType) {
539 case TYPE_F32:
540 res.data.f32 = a->data.f32 * b->data.f32 * exp2f(i->postFactor);
541 break;
542 case TYPE_F64: res.data.f64 = a->data.f64 * b->data.f64; break;
543 case TYPE_S32:
544 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
545 res.data.s32 = ((int64_t)a->data.s32 * b->data.s32) >> 32;
546 break;
547 }
548 /* fallthrough */
549 case TYPE_U32:
550 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
551 res.data.u32 = ((uint64_t)a->data.u32 * b->data.u32) >> 32;
552 break;
553 }
554 res.data.u32 = a->data.u32 * b->data.u32; break;
555 default:
556 return;
557 }
558 break;
559 case OP_DIV:
560 if (b->data.u32 == 0)
561 break;
562 switch (i->dType) {
563 case TYPE_F32: res.data.f32 = a->data.f32 / b->data.f32; break;
564 case TYPE_F64: res.data.f64 = a->data.f64 / b->data.f64; break;
565 case TYPE_S32: res.data.s32 = a->data.s32 / b->data.s32; break;
566 case TYPE_U32: res.data.u32 = a->data.u32 / b->data.u32; break;
567 default:
568 return;
569 }
570 break;
571 case OP_ADD:
572 switch (i->dType) {
573 case TYPE_F32: res.data.f32 = a->data.f32 + b->data.f32; break;
574 case TYPE_F64: res.data.f64 = a->data.f64 + b->data.f64; break;
575 case TYPE_S32:
576 case TYPE_U32: res.data.u32 = a->data.u32 + b->data.u32; break;
577 default:
578 return;
579 }
580 break;
581 case OP_SUB:
582 switch (i->dType) {
583 case TYPE_F32: res.data.f32 = a->data.f32 - b->data.f32; break;
584 case TYPE_F64: res.data.f64 = a->data.f64 - b->data.f64; break;
585 case TYPE_S32:
586 case TYPE_U32: res.data.u32 = a->data.u32 - b->data.u32; break;
587 default:
588 return;
589 }
590 break;
591 case OP_POW:
592 switch (i->dType) {
593 case TYPE_F32: res.data.f32 = pow(a->data.f32, b->data.f32); break;
594 case TYPE_F64: res.data.f64 = pow(a->data.f64, b->data.f64); break;
595 default:
596 return;
597 }
598 break;
599 case OP_MAX:
600 switch (i->dType) {
601 case TYPE_F32: res.data.f32 = MAX2(a->data.f32, b->data.f32); break;
602 case TYPE_F64: res.data.f64 = MAX2(a->data.f64, b->data.f64); break;
603 case TYPE_S32: res.data.s32 = MAX2(a->data.s32, b->data.s32); break;
604 case TYPE_U32: res.data.u32 = MAX2(a->data.u32, b->data.u32); break;
605 default:
606 return;
607 }
608 break;
609 case OP_MIN:
610 switch (i->dType) {
611 case TYPE_F32: res.data.f32 = MIN2(a->data.f32, b->data.f32); break;
612 case TYPE_F64: res.data.f64 = MIN2(a->data.f64, b->data.f64); break;
613 case TYPE_S32: res.data.s32 = MIN2(a->data.s32, b->data.s32); break;
614 case TYPE_U32: res.data.u32 = MIN2(a->data.u32, b->data.u32); break;
615 default:
616 return;
617 }
618 break;
619 case OP_AND:
620 res.data.u64 = a->data.u64 & b->data.u64;
621 break;
622 case OP_OR:
623 res.data.u64 = a->data.u64 | b->data.u64;
624 break;
625 case OP_XOR:
626 res.data.u64 = a->data.u64 ^ b->data.u64;
627 break;
628 case OP_SHL:
629 res.data.u32 = a->data.u32 << b->data.u32;
630 break;
631 case OP_SHR:
632 switch (i->dType) {
633 case TYPE_S32: res.data.s32 = a->data.s32 >> b->data.u32; break;
634 case TYPE_U32: res.data.u32 = a->data.u32 >> b->data.u32; break;
635 default:
636 return;
637 }
638 break;
639 case OP_SLCT:
640 if (a->data.u32 != b->data.u32)
641 return;
642 res.data.u32 = a->data.u32;
643 break;
644 case OP_EXTBF: {
645 int offset = b->data.u32 & 0xff;
646 int width = (b->data.u32 >> 8) & 0xff;
647 int rshift = offset;
648 int lshift = 0;
649 if (width == 0) {
650 res.data.u32 = 0;
651 break;
652 }
653 if (width + offset < 32) {
654 rshift = 32 - width;
655 lshift = 32 - width - offset;
656 }
657 if (i->subOp == NV50_IR_SUBOP_EXTBF_REV)
658 res.data.u32 = util_bitreverse(a->data.u32);
659 else
660 res.data.u32 = a->data.u32;
661 switch (i->dType) {
662 case TYPE_S32: res.data.s32 = (res.data.s32 << lshift) >> rshift; break;
663 case TYPE_U32: res.data.u32 = (res.data.u32 << lshift) >> rshift; break;
664 default:
665 return;
666 }
667 break;
668 }
669 case OP_POPCNT:
670 res.data.u32 = util_bitcount(a->data.u32 & b->data.u32);
671 break;
672 case OP_PFETCH:
673 // The two arguments to pfetch are logically added together. Normally
674 // the second argument will not be constant, but that can happen.
675 res.data.u32 = a->data.u32 + b->data.u32;
676 type = TYPE_U32;
677 break;
678 case OP_MERGE:
679 switch (i->dType) {
680 case TYPE_U64:
681 case TYPE_S64:
682 case TYPE_F64:
683 res.data.u64 = (((uint64_t)b->data.u32) << 32) | a->data.u32;
684 break;
685 default:
686 return;
687 }
688 break;
689 default:
690 return;
691 }
692 ++foldCount;
693
694 i->src(0).mod = Modifier(0);
695 i->src(1).mod = Modifier(0);
696 i->postFactor = 0;
697
698 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.u32));
699 i->setSrc(1, NULL);
700
701 i->getSrc(0)->reg.data = res.data;
702 i->getSrc(0)->reg.type = type;
703 i->getSrc(0)->reg.size = typeSizeof(type);
704
705 switch (i->op) {
706 case OP_MAD:
707 case OP_FMA: {
708 ImmediateValue src0, src1 = *i->getSrc(0)->asImm();
709
710 // Move the immediate into position 1, where we know it might be
711 // emittable. However it might not be anyways, as there may be other
712 // restrictions, so move it into a separate LValue.
713 bld.setPosition(i, false);
714 i->op = OP_ADD;
715 i->setSrc(1, bld.mkMov(bld.getSSA(type), i->getSrc(0), type)->getDef(0));
716 i->setSrc(0, i->getSrc(2));
717 i->src(0).mod = i->src(2).mod;
718 i->setSrc(2, NULL);
719
720 if (i->src(0).getImmediate(src0))
721 expr(i, src0, src1);
722 else
723 opnd(i, src1, 1);
724 break;
725 }
726 case OP_PFETCH:
727 // Leave PFETCH alone... we just folded its 2 args into 1.
728 break;
729 default:
730 i->op = i->saturate ? OP_SAT : OP_MOV;
731 if (i->saturate)
732 unary(i, *i->getSrc(0)->asImm());
733 break;
734 }
735 i->subOp = 0;
736 }
737
738 void
739 ConstantFolding::expr(Instruction *i,
740 ImmediateValue &imm0,
741 ImmediateValue &imm1,
742 ImmediateValue &imm2)
743 {
744 struct Storage *const a = &imm0.reg, *const b = &imm1.reg, *const c = &imm2.reg;
745 struct Storage res;
746
747 memset(&res.data, 0, sizeof(res.data));
748
749 switch (i->op) {
750 case OP_INSBF: {
751 int offset = b->data.u32 & 0xff;
752 int width = (b->data.u32 >> 8) & 0xff;
753 unsigned bitmask = ((1 << width) - 1) << offset;
754 res.data.u32 = ((a->data.u32 << offset) & bitmask) | (c->data.u32 & ~bitmask);
755 break;
756 }
757 case OP_MAD:
758 case OP_FMA: {
759 switch (i->dType) {
760 case TYPE_F32:
761 res.data.f32 = a->data.f32 * b->data.f32 * exp2f(i->postFactor) +
762 c->data.f32;
763 break;
764 case TYPE_F64:
765 res.data.f64 = a->data.f64 * b->data.f64 + c->data.f64;
766 break;
767 case TYPE_S32:
768 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
769 res.data.s32 = ((int64_t)a->data.s32 * b->data.s32 >> 32) + c->data.s32;
770 break;
771 }
772 /* fallthrough */
773 case TYPE_U32:
774 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
775 res.data.u32 = ((uint64_t)a->data.u32 * b->data.u32 >> 32) + c->data.u32;
776 break;
777 }
778 res.data.u32 = a->data.u32 * b->data.u32 + c->data.u32;
779 break;
780 default:
781 return;
782 }
783 break;
784 }
785 case OP_SHLADD:
786 res.data.u32 = (a->data.u32 << b->data.u32) + c->data.u32;
787 break;
788 default:
789 return;
790 }
791
792 ++foldCount;
793 i->src(0).mod = Modifier(0);
794 i->src(1).mod = Modifier(0);
795 i->src(2).mod = Modifier(0);
796
797 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.u32));
798 i->setSrc(1, NULL);
799 i->setSrc(2, NULL);
800
801 i->getSrc(0)->reg.data = res.data;
802 i->getSrc(0)->reg.type = i->dType;
803 i->getSrc(0)->reg.size = typeSizeof(i->dType);
804
805 i->op = OP_MOV;
806 }
807
808 void
809 ConstantFolding::unary(Instruction *i, const ImmediateValue &imm)
810 {
811 Storage res;
812
813 if (i->dType != TYPE_F32)
814 return;
815 switch (i->op) {
816 case OP_NEG: res.data.f32 = -imm.reg.data.f32; break;
817 case OP_ABS: res.data.f32 = fabsf(imm.reg.data.f32); break;
818 case OP_SAT: res.data.f32 = CLAMP(imm.reg.data.f32, 0.0f, 1.0f); break;
819 case OP_RCP: res.data.f32 = 1.0f / imm.reg.data.f32; break;
820 case OP_RSQ: res.data.f32 = 1.0f / sqrtf(imm.reg.data.f32); break;
821 case OP_LG2: res.data.f32 = log2f(imm.reg.data.f32); break;
822 case OP_EX2: res.data.f32 = exp2f(imm.reg.data.f32); break;
823 case OP_SIN: res.data.f32 = sinf(imm.reg.data.f32); break;
824 case OP_COS: res.data.f32 = cosf(imm.reg.data.f32); break;
825 case OP_SQRT: res.data.f32 = sqrtf(imm.reg.data.f32); break;
826 case OP_PRESIN:
827 case OP_PREEX2:
828 // these should be handled in subsequent OP_SIN/COS/EX2
829 res.data.f32 = imm.reg.data.f32;
830 break;
831 default:
832 return;
833 }
834 i->op = OP_MOV;
835 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res.data.f32));
836 i->src(0).mod = Modifier(0);
837 }
838
839 void
840 ConstantFolding::tryCollapseChainedMULs(Instruction *mul2,
841 const int s, ImmediateValue& imm2)
842 {
843 const int t = s ? 0 : 1;
844 Instruction *insn;
845 Instruction *mul1 = NULL; // mul1 before mul2
846 int e = 0;
847 float f = imm2.reg.data.f32 * exp2f(mul2->postFactor);
848 ImmediateValue imm1;
849
850 assert(mul2->op == OP_MUL && mul2->dType == TYPE_F32);
851
852 if (mul2->getSrc(t)->refCount() == 1) {
853 insn = mul2->getSrc(t)->getInsn();
854 if (!mul2->src(t).mod && insn->op == OP_MUL && insn->dType == TYPE_F32)
855 mul1 = insn;
856 if (mul1 && !mul1->saturate) {
857 int s1;
858
859 if (mul1->src(s1 = 0).getImmediate(imm1) ||
860 mul1->src(s1 = 1).getImmediate(imm1)) {
861 bld.setPosition(mul1, false);
862 // a = mul r, imm1
863 // d = mul a, imm2 -> d = mul r, (imm1 * imm2)
864 mul1->setSrc(s1, bld.loadImm(NULL, f * imm1.reg.data.f32));
865 mul1->src(s1).mod = Modifier(0);
866 mul2->def(0).replace(mul1->getDef(0), false);
867 mul1->saturate = mul2->saturate;
868 } else
869 if (prog->getTarget()->isPostMultiplySupported(OP_MUL, f, e)) {
870 // c = mul a, b
871 // d = mul c, imm -> d = mul_x_imm a, b
872 mul1->postFactor = e;
873 mul2->def(0).replace(mul1->getDef(0), false);
874 if (f < 0)
875 mul1->src(0).mod *= Modifier(NV50_IR_MOD_NEG);
876 mul1->saturate = mul2->saturate;
877 }
878 return;
879 }
880 }
881 if (mul2->getDef(0)->refCount() == 1 && !mul2->saturate) {
882 // b = mul a, imm
883 // d = mul b, c -> d = mul_x_imm a, c
884 int s2, t2;
885 insn = (*mul2->getDef(0)->uses.begin())->getInsn();
886 if (!insn)
887 return;
888 mul1 = mul2;
889 mul2 = NULL;
890 s2 = insn->getSrc(0) == mul1->getDef(0) ? 0 : 1;
891 t2 = s2 ? 0 : 1;
892 if (insn->op == OP_MUL && insn->dType == TYPE_F32)
893 if (!insn->src(s2).mod && !insn->src(t2).getImmediate(imm1))
894 mul2 = insn;
895 if (mul2 && prog->getTarget()->isPostMultiplySupported(OP_MUL, f, e)) {
896 mul2->postFactor = e;
897 mul2->setSrc(s2, mul1->src(t));
898 if (f < 0)
899 mul2->src(s2).mod *= Modifier(NV50_IR_MOD_NEG);
900 }
901 }
902 }
903
904 void
905 ConstantFolding::opnd3(Instruction *i, ImmediateValue &imm2)
906 {
907 switch (i->op) {
908 case OP_MAD:
909 case OP_FMA:
910 if (imm2.isInteger(0)) {
911 i->op = OP_MUL;
912 i->setSrc(2, NULL);
913 foldCount++;
914 return;
915 }
916 break;
917 case OP_SHLADD:
918 if (imm2.isInteger(0)) {
919 i->op = OP_SHL;
920 i->setSrc(2, NULL);
921 foldCount++;
922 return;
923 }
924 break;
925 default:
926 return;
927 }
928 }
929
930 void
931 ConstantFolding::opnd(Instruction *i, ImmediateValue &imm0, int s)
932 {
933 const Target *target = prog->getTarget();
934 const int t = !s;
935 const operation op = i->op;
936 Instruction *newi = i;
937
938 switch (i->op) {
939 case OP_SPLIT: {
940 bld.setPosition(i, false);
941
942 uint8_t size = i->getDef(0)->reg.size;
943 uint8_t bitsize = size * 8;
944 uint32_t mask = (1ULL << bitsize) - 1;
945 assert(bitsize <= 32);
946
947 uint64_t val = imm0.reg.data.u64;
948 for (int8_t d = 0; i->defExists(d); ++d) {
949 Value *def = i->getDef(d);
950 assert(def->reg.size == size);
951
952 newi = bld.mkMov(def, bld.mkImm((uint32_t)(val & mask)), TYPE_U32);
953 val >>= bitsize;
954 }
955 delete_Instruction(prog, i);
956 break;
957 }
958 case OP_MUL:
959 if (i->dType == TYPE_F32)
960 tryCollapseChainedMULs(i, s, imm0);
961
962 if (i->subOp == NV50_IR_SUBOP_MUL_HIGH) {
963 assert(!isFloatType(i->sType));
964 if (imm0.isInteger(1) && i->dType == TYPE_S32) {
965 bld.setPosition(i, false);
966 // Need to set to the sign value, which is a compare.
967 newi = bld.mkCmp(OP_SET, CC_LT, TYPE_S32, i->getDef(0),
968 TYPE_S32, i->getSrc(t), bld.mkImm(0));
969 delete_Instruction(prog, i);
970 } else if (imm0.isInteger(0) || imm0.isInteger(1)) {
971 // The high bits can't be set in this case (either mul by 0 or
972 // unsigned by 1)
973 i->op = OP_MOV;
974 i->subOp = 0;
975 i->setSrc(0, new_ImmediateValue(prog, 0u));
976 i->src(0).mod = Modifier(0);
977 i->setSrc(1, NULL);
978 } else if (!imm0.isNegative() && imm0.isPow2()) {
979 // Translate into a shift
980 imm0.applyLog2();
981 i->op = OP_SHR;
982 i->subOp = 0;
983 imm0.reg.data.u32 = 32 - imm0.reg.data.u32;
984 i->setSrc(0, i->getSrc(t));
985 i->src(0).mod = i->src(t).mod;
986 i->setSrc(1, new_ImmediateValue(prog, imm0.reg.data.u32));
987 i->src(1).mod = 0;
988 }
989 } else
990 if (imm0.isInteger(0)) {
991 i->op = OP_MOV;
992 i->setSrc(0, new_ImmediateValue(prog, 0u));
993 i->src(0).mod = Modifier(0);
994 i->postFactor = 0;
995 i->setSrc(1, NULL);
996 } else
997 if (!i->postFactor && (imm0.isInteger(1) || imm0.isInteger(-1))) {
998 if (imm0.isNegative())
999 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
1000 i->op = i->src(t).mod.getOp();
1001 if (s == 0) {
1002 i->setSrc(0, i->getSrc(1));
1003 i->src(0).mod = i->src(1).mod;
1004 i->src(1).mod = 0;
1005 }
1006 if (i->op != OP_CVT)
1007 i->src(0).mod = 0;
1008 i->setSrc(1, NULL);
1009 } else
1010 if (!i->postFactor && (imm0.isInteger(2) || imm0.isInteger(-2))) {
1011 if (imm0.isNegative())
1012 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
1013 i->op = OP_ADD;
1014 i->setSrc(s, i->getSrc(t));
1015 i->src(s).mod = i->src(t).mod;
1016 } else
1017 if (!isFloatType(i->sType) && !imm0.isNegative() && imm0.isPow2()) {
1018 i->op = OP_SHL;
1019 imm0.applyLog2();
1020 i->setSrc(0, i->getSrc(t));
1021 i->src(0).mod = i->src(t).mod;
1022 i->setSrc(1, new_ImmediateValue(prog, imm0.reg.data.u32));
1023 i->src(1).mod = 0;
1024 } else
1025 if (i->postFactor && i->sType == TYPE_F32) {
1026 /* Can't emit a postfactor with an immediate, have to fold it in */
1027 i->setSrc(s, new_ImmediateValue(
1028 prog, imm0.reg.data.f32 * exp2f(i->postFactor)));
1029 i->postFactor = 0;
1030 }
1031 break;
1032 case OP_FMA:
1033 case OP_MAD:
1034 if (imm0.isInteger(0)) {
1035 i->setSrc(0, i->getSrc(2));
1036 i->src(0).mod = i->src(2).mod;
1037 i->setSrc(1, NULL);
1038 i->setSrc(2, NULL);
1039 i->op = i->src(0).mod.getOp();
1040 if (i->op != OP_CVT)
1041 i->src(0).mod = 0;
1042 } else
1043 if (i->subOp != NV50_IR_SUBOP_MUL_HIGH &&
1044 (imm0.isInteger(1) || imm0.isInteger(-1))) {
1045 if (imm0.isNegative())
1046 i->src(t).mod = i->src(t).mod ^ Modifier(NV50_IR_MOD_NEG);
1047 if (s == 0) {
1048 i->setSrc(0, i->getSrc(1));
1049 i->src(0).mod = i->src(1).mod;
1050 }
1051 i->setSrc(1, i->getSrc(2));
1052 i->src(1).mod = i->src(2).mod;
1053 i->setSrc(2, NULL);
1054 i->op = OP_ADD;
1055 } else
1056 if (s == 1 && !imm0.isNegative() && imm0.isPow2() &&
1057 target->isOpSupported(OP_SHLADD, i->dType)) {
1058 i->op = OP_SHLADD;
1059 imm0.applyLog2();
1060 i->setSrc(1, new_ImmediateValue(prog, imm0.reg.data.u32));
1061 }
1062 break;
1063 case OP_SUB:
1064 if (imm0.isInteger(0) && s == 0 && typeSizeof(i->dType) == 8 &&
1065 !isFloatType(i->dType))
1066 break;
1067 /* fallthrough */
1068 case OP_ADD:
1069 if (i->usesFlags())
1070 break;
1071 if (imm0.isInteger(0)) {
1072 if (s == 0) {
1073 i->setSrc(0, i->getSrc(1));
1074 i->src(0).mod = i->src(1).mod;
1075 if (i->op == OP_SUB)
1076 i->src(0).mod = i->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);
1077 }
1078 i->setSrc(1, NULL);
1079 i->op = i->src(0).mod.getOp();
1080 if (i->op != OP_CVT)
1081 i->src(0).mod = Modifier(0);
1082 }
1083 break;
1084
1085 case OP_DIV:
1086 if (s != 1 || (i->dType != TYPE_S32 && i->dType != TYPE_U32))
1087 break;
1088 bld.setPosition(i, false);
1089 if (imm0.reg.data.u32 == 0) {
1090 break;
1091 } else
1092 if (imm0.reg.data.u32 == 1) {
1093 i->op = OP_MOV;
1094 i->setSrc(1, NULL);
1095 } else
1096 if (i->dType == TYPE_U32 && imm0.isPow2()) {
1097 i->op = OP_SHR;
1098 i->setSrc(1, bld.mkImm(util_logbase2(imm0.reg.data.u32)));
1099 } else
1100 if (i->dType == TYPE_U32) {
1101 Instruction *mul;
1102 Value *tA, *tB;
1103 const uint32_t d = imm0.reg.data.u32;
1104 uint32_t m;
1105 int r, s;
1106 uint32_t l = util_logbase2(d);
1107 if (((uint32_t)1 << l) < d)
1108 ++l;
1109 m = (((uint64_t)1 << 32) * (((uint64_t)1 << l) - d)) / d + 1;
1110 r = l ? 1 : 0;
1111 s = l ? (l - 1) : 0;
1112
1113 tA = bld.getSSA();
1114 tB = bld.getSSA();
1115 mul = bld.mkOp2(OP_MUL, TYPE_U32, tA, i->getSrc(0),
1116 bld.loadImm(NULL, m));
1117 mul->subOp = NV50_IR_SUBOP_MUL_HIGH;
1118 bld.mkOp2(OP_SUB, TYPE_U32, tB, i->getSrc(0), tA);
1119 tA = bld.getSSA();
1120 if (r)
1121 bld.mkOp2(OP_SHR, TYPE_U32, tA, tB, bld.mkImm(r));
1122 else
1123 tA = tB;
1124 tB = s ? bld.getSSA() : i->getDef(0);
1125 newi = bld.mkOp2(OP_ADD, TYPE_U32, tB, mul->getDef(0), tA);
1126 if (s)
1127 bld.mkOp2(OP_SHR, TYPE_U32, i->getDef(0), tB, bld.mkImm(s));
1128
1129 delete_Instruction(prog, i);
1130 } else
1131 if (imm0.reg.data.s32 == -1) {
1132 i->op = OP_NEG;
1133 i->setSrc(1, NULL);
1134 } else {
1135 LValue *tA, *tB;
1136 LValue *tD;
1137 const int32_t d = imm0.reg.data.s32;
1138 int32_t m;
1139 int32_t l = util_logbase2(static_cast<unsigned>(abs(d)));
1140 if ((1 << l) < abs(d))
1141 ++l;
1142 if (!l)
1143 l = 1;
1144 m = ((uint64_t)1 << (32 + l - 1)) / abs(d) + 1 - ((uint64_t)1 << 32);
1145
1146 tA = bld.getSSA();
1147 tB = bld.getSSA();
1148 bld.mkOp3(OP_MAD, TYPE_S32, tA, i->getSrc(0), bld.loadImm(NULL, m),
1149 i->getSrc(0))->subOp = NV50_IR_SUBOP_MUL_HIGH;
1150 if (l > 1)
1151 bld.mkOp2(OP_SHR, TYPE_S32, tB, tA, bld.mkImm(l - 1));
1152 else
1153 tB = tA;
1154 tA = bld.getSSA();
1155 bld.mkCmp(OP_SET, CC_LT, TYPE_S32, tA, TYPE_S32, i->getSrc(0), bld.mkImm(0));
1156 tD = (d < 0) ? bld.getSSA() : i->getDef(0)->asLValue();
1157 newi = bld.mkOp2(OP_SUB, TYPE_U32, tD, tB, tA);
1158 if (d < 0)
1159 bld.mkOp1(OP_NEG, TYPE_S32, i->getDef(0), tB);
1160
1161 delete_Instruction(prog, i);
1162 }
1163 break;
1164
1165 case OP_MOD:
1166 if (i->sType == TYPE_U32 && imm0.isPow2()) {
1167 bld.setPosition(i, false);
1168 i->op = OP_AND;
1169 i->setSrc(1, bld.loadImm(NULL, imm0.reg.data.u32 - 1));
1170 }
1171 break;
1172
1173 case OP_SET: // TODO: SET_AND,OR,XOR
1174 {
1175 /* This optimizes the case where the output of a set is being compared
1176 * to zero. Since the set can only produce 0/-1 (int) or 0/1 (float), we
1177 * can be a lot cleverer in our comparison.
1178 */
1179 CmpInstruction *si = findOriginForTestWithZero(i->getSrc(t));
1180 CondCode cc, ccZ;
1181 if (imm0.reg.data.u32 != 0 || !si)
1182 return;
1183 cc = si->setCond;
1184 ccZ = (CondCode)((unsigned int)i->asCmp()->setCond & ~CC_U);
1185 // We do everything assuming var (cmp) 0, reverse the condition if 0 is
1186 // first.
1187 if (s == 0)
1188 ccZ = reverseCondCode(ccZ);
1189 // If there is a negative modifier, we need to undo that, by flipping
1190 // the comparison to zero.
1191 if (i->src(t).mod.neg())
1192 ccZ = reverseCondCode(ccZ);
1193 // If this is a signed comparison, we expect the input to be a regular
1194 // boolean, i.e. 0/-1. However the rest of the logic assumes that true
1195 // is positive, so just flip the sign.
1196 if (i->sType == TYPE_S32) {
1197 assert(!isFloatType(si->dType));
1198 ccZ = reverseCondCode(ccZ);
1199 }
1200 switch (ccZ) {
1201 case CC_LT: cc = CC_FL; break; // bool < 0 -- this is never true
1202 case CC_GE: cc = CC_TR; break; // bool >= 0 -- this is always true
1203 case CC_EQ: cc = inverseCondCode(cc); break; // bool == 0 -- !bool
1204 case CC_LE: cc = inverseCondCode(cc); break; // bool <= 0 -- !bool
1205 case CC_GT: break; // bool > 0 -- bool
1206 case CC_NE: break; // bool != 0 -- bool
1207 default:
1208 return;
1209 }
1210
1211 // Update the condition of this SET to be identical to the origin set,
1212 // but with the updated condition code. The original SET should get
1213 // DCE'd, ideally.
1214 i->op = si->op;
1215 i->asCmp()->setCond = cc;
1216 i->setSrc(0, si->src(0));
1217 i->setSrc(1, si->src(1));
1218 if (si->srcExists(2))
1219 i->setSrc(2, si->src(2));
1220 i->sType = si->sType;
1221 }
1222 break;
1223
1224 case OP_AND:
1225 {
1226 Instruction *src = i->getSrc(t)->getInsn();
1227 ImmediateValue imm1;
1228 if (imm0.reg.data.u32 == 0) {
1229 i->op = OP_MOV;
1230 i->setSrc(0, new_ImmediateValue(prog, 0u));
1231 i->src(0).mod = Modifier(0);
1232 i->setSrc(1, NULL);
1233 } else if (imm0.reg.data.u32 == ~0U) {
1234 i->op = i->src(t).mod.getOp();
1235 if (t) {
1236 i->setSrc(0, i->getSrc(t));
1237 i->src(0).mod = i->src(t).mod;
1238 }
1239 i->setSrc(1, NULL);
1240 } else if (src->asCmp()) {
1241 CmpInstruction *cmp = src->asCmp();
1242 if (!cmp || cmp->op == OP_SLCT || cmp->getDef(0)->refCount() > 1)
1243 return;
1244 if (!prog->getTarget()->isOpSupported(cmp->op, TYPE_F32))
1245 return;
1246 if (imm0.reg.data.f32 != 1.0)
1247 return;
1248 if (cmp->dType != TYPE_U32)
1249 return;
1250
1251 cmp->dType = TYPE_F32;
1252 if (i->src(t).mod != Modifier(0)) {
1253 assert(i->src(t).mod == Modifier(NV50_IR_MOD_NOT));
1254 i->src(t).mod = Modifier(0);
1255 cmp->setCond = inverseCondCode(cmp->setCond);
1256 }
1257 i->op = OP_MOV;
1258 i->setSrc(s, NULL);
1259 if (t) {
1260 i->setSrc(0, i->getSrc(t));
1261 i->setSrc(t, NULL);
1262 }
1263 } else if (prog->getTarget()->isOpSupported(OP_EXTBF, TYPE_U32) &&
1264 src->op == OP_SHR &&
1265 src->src(1).getImmediate(imm1) &&
1266 i->src(t).mod == Modifier(0) &&
1267 util_is_power_of_two(imm0.reg.data.u32 + 1)) {
1268 // low byte = offset, high byte = width
1269 uint32_t ext = (util_last_bit(imm0.reg.data.u32) << 8) | imm1.reg.data.u32;
1270 i->op = OP_EXTBF;
1271 i->setSrc(0, src->getSrc(0));
1272 i->setSrc(1, new_ImmediateValue(prog, ext));
1273 } else if (src->op == OP_SHL &&
1274 src->src(1).getImmediate(imm1) &&
1275 i->src(t).mod == Modifier(0) &&
1276 util_is_power_of_two(~imm0.reg.data.u32 + 1) &&
1277 util_last_bit(~imm0.reg.data.u32) <= imm1.reg.data.u32) {
1278 i->op = OP_MOV;
1279 i->setSrc(s, NULL);
1280 if (t) {
1281 i->setSrc(0, i->getSrc(t));
1282 i->setSrc(t, NULL);
1283 }
1284 }
1285 }
1286 break;
1287
1288 case OP_SHL:
1289 {
1290 if (s != 1 || i->src(0).mod != Modifier(0))
1291 break;
1292 // try to concatenate shifts
1293 Instruction *si = i->getSrc(0)->getInsn();
1294 if (!si)
1295 break;
1296 ImmediateValue imm1;
1297 switch (si->op) {
1298 case OP_SHL:
1299 if (si->src(1).getImmediate(imm1)) {
1300 bld.setPosition(i, false);
1301 i->setSrc(0, si->getSrc(0));
1302 i->setSrc(1, bld.loadImm(NULL, imm0.reg.data.u32 + imm1.reg.data.u32));
1303 }
1304 break;
1305 case OP_SHR:
1306 if (si->src(1).getImmediate(imm1) && imm0.reg.data.u32 == imm1.reg.data.u32) {
1307 bld.setPosition(i, false);
1308 i->op = OP_AND;
1309 i->setSrc(0, si->getSrc(0));
1310 i->setSrc(1, bld.loadImm(NULL, ~((1 << imm0.reg.data.u32) - 1)));
1311 }
1312 break;
1313 case OP_MUL:
1314 int muls;
1315 if (isFloatType(si->dType))
1316 return;
1317 if (si->src(1).getImmediate(imm1))
1318 muls = 1;
1319 else if (si->src(0).getImmediate(imm1))
1320 muls = 0;
1321 else
1322 return;
1323
1324 bld.setPosition(i, false);
1325 i->op = OP_MUL;
1326 i->setSrc(0, si->getSrc(!muls));
1327 i->setSrc(1, bld.loadImm(NULL, imm1.reg.data.u32 << imm0.reg.data.u32));
1328 break;
1329 case OP_SUB:
1330 case OP_ADD:
1331 int adds;
1332 if (isFloatType(si->dType))
1333 return;
1334 if (si->op != OP_SUB && si->src(0).getImmediate(imm1))
1335 adds = 0;
1336 else if (si->src(1).getImmediate(imm1))
1337 adds = 1;
1338 else
1339 return;
1340 if (si->src(!adds).mod != Modifier(0))
1341 return;
1342 // SHL(ADD(x, y), z) = ADD(SHL(x, z), SHL(y, z))
1343
1344 // This is more operations, but if one of x, y is an immediate, then
1345 // we can get a situation where (a) we can use ISCADD, or (b)
1346 // propagate the add bit into an indirect load.
1347 bld.setPosition(i, false);
1348 i->op = si->op;
1349 i->setSrc(adds, bld.loadImm(NULL, imm1.reg.data.u32 << imm0.reg.data.u32));
1350 i->setSrc(!adds, bld.mkOp2v(OP_SHL, i->dType,
1351 bld.getSSA(i->def(0).getSize(), i->def(0).getFile()),
1352 si->getSrc(!adds),
1353 bld.mkImm(imm0.reg.data.u32)));
1354 break;
1355 default:
1356 return;
1357 }
1358 }
1359 break;
1360
1361 case OP_ABS:
1362 case OP_NEG:
1363 case OP_SAT:
1364 case OP_LG2:
1365 case OP_RCP:
1366 case OP_SQRT:
1367 case OP_RSQ:
1368 case OP_PRESIN:
1369 case OP_SIN:
1370 case OP_COS:
1371 case OP_PREEX2:
1372 case OP_EX2:
1373 unary(i, imm0);
1374 break;
1375 case OP_BFIND: {
1376 int32_t res;
1377 switch (i->dType) {
1378 case TYPE_S32: res = util_last_bit_signed(imm0.reg.data.s32) - 1; break;
1379 case TYPE_U32: res = util_last_bit(imm0.reg.data.u32) - 1; break;
1380 default:
1381 return;
1382 }
1383 if (i->subOp == NV50_IR_SUBOP_BFIND_SAMT && res >= 0)
1384 res = 31 - res;
1385 bld.setPosition(i, false); /* make sure bld is init'ed */
1386 i->setSrc(0, bld.mkImm(res));
1387 i->setSrc(1, NULL);
1388 i->op = OP_MOV;
1389 i->subOp = 0;
1390 break;
1391 }
1392 case OP_POPCNT: {
1393 // Only deal with 1-arg POPCNT here
1394 if (i->srcExists(1))
1395 break;
1396 uint32_t res = util_bitcount(imm0.reg.data.u32);
1397 i->setSrc(0, new_ImmediateValue(i->bb->getProgram(), res));
1398 i->setSrc(1, NULL);
1399 i->op = OP_MOV;
1400 break;
1401 }
1402 case OP_CVT: {
1403 Storage res;
1404
1405 // TODO: handle 64-bit values properly
1406 if (typeSizeof(i->dType) == 8 || typeSizeof(i->sType) == 8)
1407 return;
1408
1409 // TODO: handle single byte/word extractions
1410 if (i->subOp)
1411 return;
1412
1413 bld.setPosition(i, true); /* make sure bld is init'ed */
1414
1415 #define CASE(type, dst, fmin, fmax, imin, imax, umin, umax) \
1416 case type: \
1417 switch (i->sType) { \
1418 case TYPE_F64: \
1419 res.data.dst = util_iround(i->saturate ? \
1420 CLAMP(imm0.reg.data.f64, fmin, fmax) : \
1421 imm0.reg.data.f64); \
1422 break; \
1423 case TYPE_F32: \
1424 res.data.dst = util_iround(i->saturate ? \
1425 CLAMP(imm0.reg.data.f32, fmin, fmax) : \
1426 imm0.reg.data.f32); \
1427 break; \
1428 case TYPE_S32: \
1429 res.data.dst = i->saturate ? \
1430 CLAMP(imm0.reg.data.s32, imin, imax) : \
1431 imm0.reg.data.s32; \
1432 break; \
1433 case TYPE_U32: \
1434 res.data.dst = i->saturate ? \
1435 CLAMP(imm0.reg.data.u32, umin, umax) : \
1436 imm0.reg.data.u32; \
1437 break; \
1438 case TYPE_S16: \
1439 res.data.dst = i->saturate ? \
1440 CLAMP(imm0.reg.data.s16, imin, imax) : \
1441 imm0.reg.data.s16; \
1442 break; \
1443 case TYPE_U16: \
1444 res.data.dst = i->saturate ? \
1445 CLAMP(imm0.reg.data.u16, umin, umax) : \
1446 imm0.reg.data.u16; \
1447 break; \
1448 default: return; \
1449 } \
1450 i->setSrc(0, bld.mkImm(res.data.dst)); \
1451 break
1452
1453 switch(i->dType) {
1454 CASE(TYPE_U16, u16, 0, UINT16_MAX, 0, UINT16_MAX, 0, UINT16_MAX);
1455 CASE(TYPE_S16, s16, INT16_MIN, INT16_MAX, INT16_MIN, INT16_MAX, 0, INT16_MAX);
1456 CASE(TYPE_U32, u32, 0, UINT32_MAX, 0, INT32_MAX, 0, UINT32_MAX);
1457 CASE(TYPE_S32, s32, INT32_MIN, INT32_MAX, INT32_MIN, INT32_MAX, 0, INT32_MAX);
1458 case TYPE_F32:
1459 switch (i->sType) {
1460 case TYPE_F64:
1461 res.data.f32 = i->saturate ?
1462 CLAMP(imm0.reg.data.f64, 0.0f, 1.0f) :
1463 imm0.reg.data.f64;
1464 break;
1465 case TYPE_F32:
1466 res.data.f32 = i->saturate ?
1467 CLAMP(imm0.reg.data.f32, 0.0f, 1.0f) :
1468 imm0.reg.data.f32;
1469 break;
1470 case TYPE_U16: res.data.f32 = (float) imm0.reg.data.u16; break;
1471 case TYPE_U32: res.data.f32 = (float) imm0.reg.data.u32; break;
1472 case TYPE_S16: res.data.f32 = (float) imm0.reg.data.s16; break;
1473 case TYPE_S32: res.data.f32 = (float) imm0.reg.data.s32; break;
1474 default:
1475 return;
1476 }
1477 i->setSrc(0, bld.mkImm(res.data.f32));
1478 break;
1479 case TYPE_F64:
1480 switch (i->sType) {
1481 case TYPE_F64:
1482 res.data.f64 = i->saturate ?
1483 CLAMP(imm0.reg.data.f64, 0.0f, 1.0f) :
1484 imm0.reg.data.f64;
1485 break;
1486 case TYPE_F32:
1487 res.data.f64 = i->saturate ?
1488 CLAMP(imm0.reg.data.f32, 0.0f, 1.0f) :
1489 imm0.reg.data.f32;
1490 break;
1491 case TYPE_U16: res.data.f64 = (double) imm0.reg.data.u16; break;
1492 case TYPE_U32: res.data.f64 = (double) imm0.reg.data.u32; break;
1493 case TYPE_S16: res.data.f64 = (double) imm0.reg.data.s16; break;
1494 case TYPE_S32: res.data.f64 = (double) imm0.reg.data.s32; break;
1495 default:
1496 return;
1497 }
1498 i->setSrc(0, bld.mkImm(res.data.f64));
1499 break;
1500 default:
1501 return;
1502 }
1503 #undef CASE
1504
1505 i->setType(i->dType); /* Remove i->sType, which we don't need anymore */
1506 i->op = OP_MOV;
1507 i->saturate = 0;
1508 i->src(0).mod = Modifier(0); /* Clear the already applied modifier */
1509 break;
1510 }
1511 default:
1512 return;
1513 }
1514
1515 // This can get left behind some of the optimizations which simplify
1516 // saturatable values.
1517 if (newi->op == OP_MOV && newi->saturate) {
1518 ImmediateValue tmp;
1519 newi->saturate = 0;
1520 newi->op = OP_SAT;
1521 if (newi->src(0).getImmediate(tmp))
1522 unary(newi, tmp);
1523 }
1524
1525 if (newi->op != op)
1526 foldCount++;
1527 }
1528
1529 // =============================================================================
1530
1531 // Merge modifier operations (ABS, NEG, NOT) into ValueRefs where allowed.
1532 class ModifierFolding : public Pass
1533 {
1534 private:
1535 virtual bool visit(BasicBlock *);
1536 };
1537
1538 bool
1539 ModifierFolding::visit(BasicBlock *bb)
1540 {
1541 const Target *target = prog->getTarget();
1542
1543 Instruction *i, *next, *mi;
1544 Modifier mod;
1545
1546 for (i = bb->getEntry(); i; i = next) {
1547 next = i->next;
1548
1549 if (0 && i->op == OP_SUB) {
1550 // turn "sub" into "add neg" (do we really want this ?)
1551 i->op = OP_ADD;
1552 i->src(0).mod = i->src(0).mod ^ Modifier(NV50_IR_MOD_NEG);
1553 }
1554
1555 for (int s = 0; s < 3 && i->srcExists(s); ++s) {
1556 mi = i->getSrc(s)->getInsn();
1557 if (!mi ||
1558 mi->predSrc >= 0 || mi->getDef(0)->refCount() > 8)
1559 continue;
1560 if (i->sType == TYPE_U32 && mi->dType == TYPE_S32) {
1561 if ((i->op != OP_ADD &&
1562 i->op != OP_MUL) ||
1563 (mi->op != OP_ABS &&
1564 mi->op != OP_NEG))
1565 continue;
1566 } else
1567 if (i->sType != mi->dType) {
1568 continue;
1569 }
1570 if ((mod = Modifier(mi->op)) == Modifier(0))
1571 continue;
1572 mod *= mi->src(0).mod;
1573
1574 if ((i->op == OP_ABS) || i->src(s).mod.abs()) {
1575 // abs neg [abs] = abs
1576 mod = mod & Modifier(~(NV50_IR_MOD_NEG | NV50_IR_MOD_ABS));
1577 } else
1578 if ((i->op == OP_NEG) && mod.neg()) {
1579 assert(s == 0);
1580 // neg as both opcode and modifier on same insn is prohibited
1581 // neg neg abs = abs, neg neg = identity
1582 mod = mod & Modifier(~NV50_IR_MOD_NEG);
1583 i->op = mod.getOp();
1584 mod = mod & Modifier(~NV50_IR_MOD_ABS);
1585 if (mod == Modifier(0))
1586 i->op = OP_MOV;
1587 }
1588
1589 if (target->isModSupported(i, s, mod)) {
1590 i->setSrc(s, mi->getSrc(0));
1591 i->src(s).mod *= mod;
1592 }
1593 }
1594
1595 if (i->op == OP_SAT) {
1596 mi = i->getSrc(0)->getInsn();
1597 if (mi &&
1598 mi->getDef(0)->refCount() <= 1 && target->isSatSupported(mi)) {
1599 mi->saturate = 1;
1600 mi->setDef(0, i->getDef(0));
1601 delete_Instruction(prog, i);
1602 }
1603 }
1604 }
1605
1606 return true;
1607 }
1608
1609 // =============================================================================
1610
1611 // MUL + ADD -> MAD/FMA
1612 // MIN/MAX(a, a) -> a, etc.
1613 // SLCT(a, b, const) -> cc(const) ? a : b
1614 // RCP(RCP(a)) -> a
1615 // MUL(MUL(a, b), const) -> MUL_Xconst(a, b)
1616 class AlgebraicOpt : public Pass
1617 {
1618 private:
1619 virtual bool visit(BasicBlock *);
1620
1621 void handleABS(Instruction *);
1622 bool handleADD(Instruction *);
1623 bool tryADDToMADOrSAD(Instruction *, operation toOp);
1624 void handleMINMAX(Instruction *);
1625 void handleRCP(Instruction *);
1626 void handleSLCT(Instruction *);
1627 void handleLOGOP(Instruction *);
1628 void handleCVT_NEG(Instruction *);
1629 void handleCVT_CVT(Instruction *);
1630 void handleCVT_EXTBF(Instruction *);
1631 void handleSUCLAMP(Instruction *);
1632 void handleNEG(Instruction *);
1633
1634 BuildUtil bld;
1635 };
1636
1637 void
1638 AlgebraicOpt::handleABS(Instruction *abs)
1639 {
1640 Instruction *sub = abs->getSrc(0)->getInsn();
1641 DataType ty;
1642 if (!sub ||
1643 !prog->getTarget()->isOpSupported(OP_SAD, abs->dType))
1644 return;
1645 // expect not to have mods yet, if we do, bail
1646 if (sub->src(0).mod || sub->src(1).mod)
1647 return;
1648 // hidden conversion ?
1649 ty = intTypeToSigned(sub->dType);
1650 if (abs->dType != abs->sType || ty != abs->sType)
1651 return;
1652
1653 if ((sub->op != OP_ADD && sub->op != OP_SUB) ||
1654 sub->src(0).getFile() != FILE_GPR || sub->src(0).mod ||
1655 sub->src(1).getFile() != FILE_GPR || sub->src(1).mod)
1656 return;
1657
1658 Value *src0 = sub->getSrc(0);
1659 Value *src1 = sub->getSrc(1);
1660
1661 if (sub->op == OP_ADD) {
1662 Instruction *neg = sub->getSrc(1)->getInsn();
1663 if (neg && neg->op != OP_NEG) {
1664 neg = sub->getSrc(0)->getInsn();
1665 src0 = sub->getSrc(1);
1666 }
1667 if (!neg || neg->op != OP_NEG ||
1668 neg->dType != neg->sType || neg->sType != ty)
1669 return;
1670 src1 = neg->getSrc(0);
1671 }
1672
1673 // found ABS(SUB))
1674 abs->moveSources(1, 2); // move sources >=1 up by 2
1675 abs->op = OP_SAD;
1676 abs->setType(sub->dType);
1677 abs->setSrc(0, src0);
1678 abs->setSrc(1, src1);
1679 bld.setPosition(abs, false);
1680 abs->setSrc(2, bld.loadImm(bld.getSSA(typeSizeof(ty)), 0));
1681 }
1682
1683 bool
1684 AlgebraicOpt::handleADD(Instruction *add)
1685 {
1686 Value *src0 = add->getSrc(0);
1687 Value *src1 = add->getSrc(1);
1688
1689 if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)
1690 return false;
1691
1692 bool changed = false;
1693 // we can't optimize to MAD if the add is precise
1694 if (!add->precise && prog->getTarget()->isOpSupported(OP_MAD, add->dType))
1695 changed = tryADDToMADOrSAD(add, OP_MAD);
1696 if (!changed && prog->getTarget()->isOpSupported(OP_SAD, add->dType))
1697 changed = tryADDToMADOrSAD(add, OP_SAD);
1698 return changed;
1699 }
1700
1701 // ADD(SAD(a,b,0), c) -> SAD(a,b,c)
1702 // ADD(MUL(a,b), c) -> MAD(a,b,c)
1703 bool
1704 AlgebraicOpt::tryADDToMADOrSAD(Instruction *add, operation toOp)
1705 {
1706 Value *src0 = add->getSrc(0);
1707 Value *src1 = add->getSrc(1);
1708 Value *src;
1709 int s;
1710 const operation srcOp = toOp == OP_SAD ? OP_SAD : OP_MUL;
1711 const Modifier modBad = Modifier(~((toOp == OP_MAD) ? NV50_IR_MOD_NEG : 0));
1712 Modifier mod[4];
1713
1714 if (src0->refCount() == 1 &&
1715 src0->getUniqueInsn() && src0->getUniqueInsn()->op == srcOp)
1716 s = 0;
1717 else
1718 if (src1->refCount() == 1 &&
1719 src1->getUniqueInsn() && src1->getUniqueInsn()->op == srcOp)
1720 s = 1;
1721 else
1722 return false;
1723
1724 src = add->getSrc(s);
1725
1726 if (src->getUniqueInsn() && src->getUniqueInsn()->bb != add->bb)
1727 return false;
1728
1729 if (src->getInsn()->saturate || src->getInsn()->postFactor ||
1730 src->getInsn()->dnz || src->getInsn()->precise)
1731 return false;
1732
1733 if (toOp == OP_SAD) {
1734 ImmediateValue imm;
1735 if (!src->getInsn()->src(2).getImmediate(imm))
1736 return false;
1737 if (!imm.isInteger(0))
1738 return false;
1739 }
1740
1741 if (typeSizeof(add->dType) != typeSizeof(src->getInsn()->dType) ||
1742 isFloatType(add->dType) != isFloatType(src->getInsn()->dType))
1743 return false;
1744
1745 mod[0] = add->src(0).mod;
1746 mod[1] = add->src(1).mod;
1747 mod[2] = src->getUniqueInsn()->src(0).mod;
1748 mod[3] = src->getUniqueInsn()->src(1).mod;
1749
1750 if (((mod[0] | mod[1]) | (mod[2] | mod[3])) & modBad)
1751 return false;
1752
1753 add->op = toOp;
1754 add->subOp = src->getInsn()->subOp; // potentially mul-high
1755 add->dnz = src->getInsn()->dnz;
1756 add->dType = src->getInsn()->dType; // sign matters for imad hi
1757 add->sType = src->getInsn()->sType;
1758
1759 add->setSrc(2, add->src(s ? 0 : 1));
1760
1761 add->setSrc(0, src->getInsn()->getSrc(0));
1762 add->src(0).mod = mod[2] ^ mod[s];
1763 add->setSrc(1, src->getInsn()->getSrc(1));
1764 add->src(1).mod = mod[3];
1765
1766 return true;
1767 }
1768
1769 void
1770 AlgebraicOpt::handleMINMAX(Instruction *minmax)
1771 {
1772 Value *src0 = minmax->getSrc(0);
1773 Value *src1 = minmax->getSrc(1);
1774
1775 if (src0 != src1 || src0->reg.file != FILE_GPR)
1776 return;
1777 if (minmax->src(0).mod == minmax->src(1).mod) {
1778 if (minmax->def(0).mayReplace(minmax->src(0))) {
1779 minmax->def(0).replace(minmax->src(0), false);
1780 minmax->bb->remove(minmax);
1781 } else {
1782 minmax->op = OP_CVT;
1783 minmax->setSrc(1, NULL);
1784 }
1785 } else {
1786 // TODO:
1787 // min(x, -x) = -abs(x)
1788 // min(x, -abs(x)) = -abs(x)
1789 // min(x, abs(x)) = x
1790 // max(x, -abs(x)) = x
1791 // max(x, abs(x)) = abs(x)
1792 // max(x, -x) = abs(x)
1793 }
1794 }
1795
1796 void
1797 AlgebraicOpt::handleRCP(Instruction *rcp)
1798 {
1799 Instruction *si = rcp->getSrc(0)->getUniqueInsn();
1800
1801 if (si && si->op == OP_RCP) {
1802 Modifier mod = rcp->src(0).mod * si->src(0).mod;
1803 rcp->op = mod.getOp();
1804 rcp->setSrc(0, si->getSrc(0));
1805 }
1806 }
1807
1808 void
1809 AlgebraicOpt::handleSLCT(Instruction *slct)
1810 {
1811 if (slct->getSrc(2)->reg.file == FILE_IMMEDIATE) {
1812 if (slct->getSrc(2)->asImm()->compare(slct->asCmp()->setCond, 0.0f))
1813 slct->setSrc(0, slct->getSrc(1));
1814 } else
1815 if (slct->getSrc(0) != slct->getSrc(1)) {
1816 return;
1817 }
1818 slct->op = OP_MOV;
1819 slct->setSrc(1, NULL);
1820 slct->setSrc(2, NULL);
1821 }
1822
1823 void
1824 AlgebraicOpt::handleLOGOP(Instruction *logop)
1825 {
1826 Value *src0 = logop->getSrc(0);
1827 Value *src1 = logop->getSrc(1);
1828
1829 if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)
1830 return;
1831
1832 if (src0 == src1) {
1833 if ((logop->op == OP_AND || logop->op == OP_OR) &&
1834 logop->def(0).mayReplace(logop->src(0))) {
1835 logop->def(0).replace(logop->src(0), false);
1836 delete_Instruction(prog, logop);
1837 }
1838 } else {
1839 // try AND(SET, SET) -> SET_AND(SET)
1840 Instruction *set0 = src0->getInsn();
1841 Instruction *set1 = src1->getInsn();
1842
1843 if (!set0 || set0->fixed || !set1 || set1->fixed)
1844 return;
1845 if (set1->op != OP_SET) {
1846 Instruction *xchg = set0;
1847 set0 = set1;
1848 set1 = xchg;
1849 if (set1->op != OP_SET)
1850 return;
1851 }
1852 operation redOp = (logop->op == OP_AND ? OP_SET_AND :
1853 logop->op == OP_XOR ? OP_SET_XOR : OP_SET_OR);
1854 if (!prog->getTarget()->isOpSupported(redOp, set1->sType))
1855 return;
1856 if (set0->op != OP_SET &&
1857 set0->op != OP_SET_AND &&
1858 set0->op != OP_SET_OR &&
1859 set0->op != OP_SET_XOR)
1860 return;
1861 if (set0->getDef(0)->refCount() > 1 &&
1862 set1->getDef(0)->refCount() > 1)
1863 return;
1864 if (set0->getPredicate() || set1->getPredicate())
1865 return;
1866 // check that they don't source each other
1867 for (int s = 0; s < 2; ++s)
1868 if (set0->getSrc(s) == set1->getDef(0) ||
1869 set1->getSrc(s) == set0->getDef(0))
1870 return;
1871
1872 set0 = cloneForward(func, set0);
1873 set1 = cloneShallow(func, set1);
1874 logop->bb->insertAfter(logop, set1);
1875 logop->bb->insertAfter(logop, set0);
1876
1877 set0->dType = TYPE_U8;
1878 set0->getDef(0)->reg.file = FILE_PREDICATE;
1879 set0->getDef(0)->reg.size = 1;
1880 set1->setSrc(2, set0->getDef(0));
1881 set1->op = redOp;
1882 set1->setDef(0, logop->getDef(0));
1883 delete_Instruction(prog, logop);
1884 }
1885 }
1886
1887 // F2I(NEG(SET with result 1.0f/0.0f)) -> SET with result -1/0
1888 // nv50:
1889 // F2I(NEG(I2F(ABS(SET))))
1890 void
1891 AlgebraicOpt::handleCVT_NEG(Instruction *cvt)
1892 {
1893 Instruction *insn = cvt->getSrc(0)->getInsn();
1894 if (cvt->sType != TYPE_F32 ||
1895 cvt->dType != TYPE_S32 || cvt->src(0).mod != Modifier(0))
1896 return;
1897 if (!insn || insn->op != OP_NEG || insn->dType != TYPE_F32)
1898 return;
1899 if (insn->src(0).mod != Modifier(0))
1900 return;
1901 insn = insn->getSrc(0)->getInsn();
1902
1903 // check for nv50 SET(-1,0) -> SET(1.0f/0.0f) chain and nvc0's f32 SET
1904 if (insn && insn->op == OP_CVT &&
1905 insn->dType == TYPE_F32 &&
1906 insn->sType == TYPE_S32) {
1907 insn = insn->getSrc(0)->getInsn();
1908 if (!insn || insn->op != OP_ABS || insn->sType != TYPE_S32 ||
1909 insn->src(0).mod)
1910 return;
1911 insn = insn->getSrc(0)->getInsn();
1912 if (!insn || insn->op != OP_SET || insn->dType != TYPE_U32)
1913 return;
1914 } else
1915 if (!insn || insn->op != OP_SET || insn->dType != TYPE_F32) {
1916 return;
1917 }
1918
1919 Instruction *bset = cloneShallow(func, insn);
1920 bset->dType = TYPE_U32;
1921 bset->setDef(0, cvt->getDef(0));
1922 cvt->bb->insertAfter(cvt, bset);
1923 delete_Instruction(prog, cvt);
1924 }
1925
1926 // F2I(TRUNC()) and so on can be expressed as a single CVT. If the earlier CVT
1927 // does a type conversion, this becomes trickier as there might be range
1928 // changes/etc. We could handle those in theory as long as the range was being
1929 // reduced or kept the same.
1930 void
1931 AlgebraicOpt::handleCVT_CVT(Instruction *cvt)
1932 {
1933 Instruction *insn = cvt->getSrc(0)->getInsn();
1934 RoundMode rnd = insn->rnd;
1935
1936 if (insn->saturate ||
1937 insn->subOp ||
1938 insn->dType != insn->sType ||
1939 insn->dType != cvt->sType)
1940 return;
1941
1942 switch (insn->op) {
1943 case OP_CEIL:
1944 rnd = ROUND_PI;
1945 break;
1946 case OP_FLOOR:
1947 rnd = ROUND_MI;
1948 break;
1949 case OP_TRUNC:
1950 rnd = ROUND_ZI;
1951 break;
1952 case OP_CVT:
1953 break;
1954 default:
1955 return;
1956 }
1957
1958 if (!isFloatType(cvt->dType) || !isFloatType(insn->sType))
1959 rnd = (RoundMode)(rnd & 3);
1960
1961 cvt->rnd = rnd;
1962 cvt->setSrc(0, insn->getSrc(0));
1963 cvt->src(0).mod *= insn->src(0).mod;
1964 cvt->sType = insn->sType;
1965 }
1966
1967 // Some shaders extract packed bytes out of words and convert them to
1968 // e.g. float. The Fermi+ CVT instruction can extract those directly, as can
1969 // nv50 for word sizes.
1970 //
1971 // CVT(EXTBF(x, byte/word))
1972 // CVT(AND(bytemask, x))
1973 // CVT(AND(bytemask, SHR(x, 8/16/24)))
1974 // CVT(SHR(x, 16/24))
1975 void
1976 AlgebraicOpt::handleCVT_EXTBF(Instruction *cvt)
1977 {
1978 Instruction *insn = cvt->getSrc(0)->getInsn();
1979 ImmediateValue imm;
1980 Value *arg = NULL;
1981 unsigned width, offset;
1982 if ((cvt->sType != TYPE_U32 && cvt->sType != TYPE_S32) || !insn)
1983 return;
1984 if (insn->op == OP_EXTBF && insn->src(1).getImmediate(imm)) {
1985 width = (imm.reg.data.u32 >> 8) & 0xff;
1986 offset = imm.reg.data.u32 & 0xff;
1987 arg = insn->getSrc(0);
1988
1989 if (width != 8 && width != 16)
1990 return;
1991 if (width == 8 && offset & 0x7)
1992 return;
1993 if (width == 16 && offset & 0xf)
1994 return;
1995 } else if (insn->op == OP_AND) {
1996 int s;
1997 if (insn->src(0).getImmediate(imm))
1998 s = 0;
1999 else if (insn->src(1).getImmediate(imm))
2000 s = 1;
2001 else
2002 return;
2003
2004 if (imm.reg.data.u32 == 0xff)
2005 width = 8;
2006 else if (imm.reg.data.u32 == 0xffff)
2007 width = 16;
2008 else
2009 return;
2010
2011 arg = insn->getSrc(!s);
2012 Instruction *shift = arg->getInsn();
2013 offset = 0;
2014 if (shift && shift->op == OP_SHR &&
2015 shift->sType == cvt->sType &&
2016 shift->src(1).getImmediate(imm) &&
2017 ((width == 8 && (imm.reg.data.u32 & 0x7) == 0) ||
2018 (width == 16 && (imm.reg.data.u32 & 0xf) == 0))) {
2019 arg = shift->getSrc(0);
2020 offset = imm.reg.data.u32;
2021 }
2022 // We just AND'd the high bits away, which means this is effectively an
2023 // unsigned value.
2024 cvt->sType = TYPE_U32;
2025 } else if (insn->op == OP_SHR &&
2026 insn->sType == cvt->sType &&
2027 insn->src(1).getImmediate(imm)) {
2028 arg = insn->getSrc(0);
2029 if (imm.reg.data.u32 == 24) {
2030 width = 8;
2031 offset = 24;
2032 } else if (imm.reg.data.u32 == 16) {
2033 width = 16;
2034 offset = 16;
2035 } else {
2036 return;
2037 }
2038 }
2039
2040 if (!arg)
2041 return;
2042
2043 // Irrespective of what came earlier, we can undo a shift on the argument
2044 // by adjusting the offset.
2045 Instruction *shift = arg->getInsn();
2046 if (shift && shift->op == OP_SHL &&
2047 shift->src(1).getImmediate(imm) &&
2048 ((width == 8 && (imm.reg.data.u32 & 0x7) == 0) ||
2049 (width == 16 && (imm.reg.data.u32 & 0xf) == 0)) &&
2050 imm.reg.data.u32 <= offset) {
2051 arg = shift->getSrc(0);
2052 offset -= imm.reg.data.u32;
2053 }
2054
2055 // The unpackSnorm lowering still leaves a few shifts behind, but it's too
2056 // annoying to detect them.
2057
2058 if (width == 8) {
2059 cvt->sType = cvt->sType == TYPE_U32 ? TYPE_U8 : TYPE_S8;
2060 } else {
2061 assert(width == 16);
2062 cvt->sType = cvt->sType == TYPE_U32 ? TYPE_U16 : TYPE_S16;
2063 }
2064 cvt->setSrc(0, arg);
2065 cvt->subOp = offset >> 3;
2066 }
2067
2068 // SUCLAMP dst, (ADD b imm), k, 0 -> SUCLAMP dst, b, k, imm (if imm fits s6)
2069 void
2070 AlgebraicOpt::handleSUCLAMP(Instruction *insn)
2071 {
2072 ImmediateValue imm;
2073 int32_t val = insn->getSrc(2)->asImm()->reg.data.s32;
2074 int s;
2075 Instruction *add;
2076
2077 assert(insn->srcExists(0) && insn->src(0).getFile() == FILE_GPR);
2078
2079 // look for ADD (TODO: only count references by non-SUCLAMP)
2080 if (insn->getSrc(0)->refCount() > 1)
2081 return;
2082 add = insn->getSrc(0)->getInsn();
2083 if (!add || add->op != OP_ADD ||
2084 (add->dType != TYPE_U32 &&
2085 add->dType != TYPE_S32))
2086 return;
2087
2088 // look for immediate
2089 for (s = 0; s < 2; ++s)
2090 if (add->src(s).getImmediate(imm))
2091 break;
2092 if (s >= 2)
2093 return;
2094 s = s ? 0 : 1;
2095 // determine if immediate fits
2096 val += imm.reg.data.s32;
2097 if (val > 31 || val < -32)
2098 return;
2099 // determine if other addend fits
2100 if (add->src(s).getFile() != FILE_GPR || add->src(s).mod != Modifier(0))
2101 return;
2102
2103 bld.setPosition(insn, false); // make sure bld is init'ed
2104 // replace sources
2105 insn->setSrc(2, bld.mkImm(val));
2106 insn->setSrc(0, add->getSrc(s));
2107 }
2108
2109 // NEG(AND(SET, 1)) -> SET
2110 void
2111 AlgebraicOpt::handleNEG(Instruction *i) {
2112 Instruction *src = i->getSrc(0)->getInsn();
2113 ImmediateValue imm;
2114 int b;
2115
2116 if (isFloatType(i->sType) || !src || src->op != OP_AND)
2117 return;
2118
2119 if (src->src(0).getImmediate(imm))
2120 b = 1;
2121 else if (src->src(1).getImmediate(imm))
2122 b = 0;
2123 else
2124 return;
2125
2126 if (!imm.isInteger(1))
2127 return;
2128
2129 Instruction *set = src->getSrc(b)->getInsn();
2130 if ((set->op == OP_SET || set->op == OP_SET_AND ||
2131 set->op == OP_SET_OR || set->op == OP_SET_XOR) &&
2132 !isFloatType(set->dType)) {
2133 i->def(0).replace(set->getDef(0), false);
2134 }
2135 }
2136
2137 bool
2138 AlgebraicOpt::visit(BasicBlock *bb)
2139 {
2140 Instruction *next;
2141 for (Instruction *i = bb->getEntry(); i; i = next) {
2142 next = i->next;
2143 switch (i->op) {
2144 case OP_ABS:
2145 handleABS(i);
2146 break;
2147 case OP_ADD:
2148 handleADD(i);
2149 break;
2150 case OP_RCP:
2151 handleRCP(i);
2152 break;
2153 case OP_MIN:
2154 case OP_MAX:
2155 handleMINMAX(i);
2156 break;
2157 case OP_SLCT:
2158 handleSLCT(i);
2159 break;
2160 case OP_AND:
2161 case OP_OR:
2162 case OP_XOR:
2163 handleLOGOP(i);
2164 break;
2165 case OP_CVT:
2166 handleCVT_NEG(i);
2167 handleCVT_CVT(i);
2168 if (prog->getTarget()->isOpSupported(OP_EXTBF, TYPE_U32))
2169 handleCVT_EXTBF(i);
2170 break;
2171 case OP_SUCLAMP:
2172 handleSUCLAMP(i);
2173 break;
2174 case OP_NEG:
2175 handleNEG(i);
2176 break;
2177 default:
2178 break;
2179 }
2180 }
2181
2182 return true;
2183 }
2184
2185 // =============================================================================
2186
2187 // ADD(SHL(a, b), c) -> SHLADD(a, b, c)
2188 class LateAlgebraicOpt : public Pass
2189 {
2190 private:
2191 virtual bool visit(Instruction *);
2192
2193 void handleADD(Instruction *);
2194 bool tryADDToSHLADD(Instruction *);
2195 };
2196
2197 void
2198 LateAlgebraicOpt::handleADD(Instruction *add)
2199 {
2200 Value *src0 = add->getSrc(0);
2201 Value *src1 = add->getSrc(1);
2202
2203 if (src0->reg.file != FILE_GPR || src1->reg.file != FILE_GPR)
2204 return;
2205
2206 if (prog->getTarget()->isOpSupported(OP_SHLADD, add->dType))
2207 tryADDToSHLADD(add);
2208 }
2209
2210 // ADD(SHL(a, b), c) -> SHLADD(a, b, c)
2211 bool
2212 LateAlgebraicOpt::tryADDToSHLADD(Instruction *add)
2213 {
2214 Value *src0 = add->getSrc(0);
2215 Value *src1 = add->getSrc(1);
2216 ImmediateValue imm;
2217 Instruction *shl;
2218 Value *src;
2219 int s;
2220
2221 if (add->saturate || add->usesFlags() || typeSizeof(add->dType) == 8
2222 || isFloatType(add->dType))
2223 return false;
2224
2225 if (src0->getUniqueInsn() && src0->getUniqueInsn()->op == OP_SHL)
2226 s = 0;
2227 else
2228 if (src1->getUniqueInsn() && src1->getUniqueInsn()->op == OP_SHL)
2229 s = 1;
2230 else
2231 return false;
2232
2233 src = add->getSrc(s);
2234 shl = src->getUniqueInsn();
2235
2236 if (shl->bb != add->bb || shl->usesFlags() || shl->subOp || shl->src(0).mod)
2237 return false;
2238
2239 if (!shl->src(1).getImmediate(imm))
2240 return false;
2241
2242 add->op = OP_SHLADD;
2243 add->setSrc(2, add->src(!s));
2244 // SHL can't have any modifiers, but the ADD source may have had
2245 // one. Preserve it.
2246 add->setSrc(0, shl->getSrc(0));
2247 if (s == 1)
2248 add->src(0).mod = add->src(1).mod;
2249 add->setSrc(1, new_ImmediateValue(shl->bb->getProgram(), imm.reg.data.u32));
2250 add->src(1).mod = Modifier(0);
2251
2252 return true;
2253 }
2254
2255 bool
2256 LateAlgebraicOpt::visit(Instruction *i)
2257 {
2258 switch (i->op) {
2259 case OP_ADD:
2260 handleADD(i);
2261 break;
2262 default:
2263 break;
2264 }
2265
2266 return true;
2267 }
2268
2269 // =============================================================================
2270
2271 // Split 64-bit MUL and MAD
2272 class Split64BitOpPreRA : public Pass
2273 {
2274 private:
2275 virtual bool visit(BasicBlock *);
2276 void split64MulMad(Function *, Instruction *, DataType);
2277
2278 BuildUtil bld;
2279 };
2280
2281 bool
2282 Split64BitOpPreRA::visit(BasicBlock *bb)
2283 {
2284 Instruction *i, *next;
2285 Modifier mod;
2286
2287 for (i = bb->getEntry(); i; i = next) {
2288 next = i->next;
2289
2290 DataType hTy;
2291 switch (i->dType) {
2292 case TYPE_U64: hTy = TYPE_U32; break;
2293 case TYPE_S64: hTy = TYPE_S32; break;
2294 default:
2295 continue;
2296 }
2297
2298 if (i->op == OP_MAD || i->op == OP_MUL)
2299 split64MulMad(func, i, hTy);
2300 }
2301
2302 return true;
2303 }
2304
2305 void
2306 Split64BitOpPreRA::split64MulMad(Function *fn, Instruction *i, DataType hTy)
2307 {
2308 assert(i->op == OP_MAD || i->op == OP_MUL);
2309 assert(!isFloatType(i->dType) && !isFloatType(i->sType));
2310 assert(typeSizeof(hTy) == 4);
2311
2312 bld.setPosition(i, true);
2313
2314 Value *zero = bld.mkImm(0u);
2315 Value *carry = bld.getSSA(1, FILE_FLAGS);
2316
2317 // We want to compute `d = a * b (+ c)?`, where a, b, c and d are 64-bit
2318 // values (a, b and c might be 32-bit values), using 32-bit operations. This
2319 // gives the following operations:
2320 // * `d.low = low(a.low * b.low) (+ c.low)?`
2321 // * `d.high = low(a.high * b.low) + low(a.low * b.high)
2322 // + high(a.low * b.low) (+ c.high)?`
2323 //
2324 // To compute the high bits, we can split in the following operations:
2325 // * `tmp1 = low(a.high * b.low) (+ c.high)?`
2326 // * `tmp2 = low(a.low * b.high) + tmp1`
2327 // * `d.high = high(a.low * b.low) + tmp2`
2328 //
2329 // mkSplit put lower bits at index 0 and higher bits at index 1
2330
2331 Value *op1[2];
2332 if (i->getSrc(0)->reg.size == 8)
2333 bld.mkSplit(op1, 4, i->getSrc(0));
2334 else {
2335 op1[0] = i->getSrc(0);
2336 op1[1] = zero;
2337 }
2338 Value *op2[2];
2339 if (i->getSrc(1)->reg.size == 8)
2340 bld.mkSplit(op2, 4, i->getSrc(1));
2341 else {
2342 op2[0] = i->getSrc(1);
2343 op2[1] = zero;
2344 }
2345
2346 Value *op3[2] = { NULL, NULL };
2347 if (i->op == OP_MAD) {
2348 if (i->getSrc(2)->reg.size == 8)
2349 bld.mkSplit(op3, 4, i->getSrc(2));
2350 else {
2351 op3[0] = i->getSrc(2);
2352 op3[1] = zero;
2353 }
2354 }
2355
2356 Value *tmpRes1Hi = bld.getSSA();
2357 if (i->op == OP_MAD)
2358 bld.mkOp3(OP_MAD, hTy, tmpRes1Hi, op1[1], op2[0], op3[1]);
2359 else
2360 bld.mkOp2(OP_MUL, hTy, tmpRes1Hi, op1[1], op2[0]);
2361
2362 Value *tmpRes2Hi = bld.mkOp3v(OP_MAD, hTy, bld.getSSA(), op1[0], op2[1], tmpRes1Hi);
2363
2364 Value *def[2] = { bld.getSSA(), bld.getSSA() };
2365
2366 // If it was a MAD, add the carry from the low bits
2367 // It is not needed if it was a MUL, since we added high(a.low * b.low) to
2368 // d.high
2369 if (i->op == OP_MAD)
2370 bld.mkOp3(OP_MAD, hTy, def[0], op1[0], op2[0], op3[0])->setFlagsDef(1, carry);
2371 else
2372 bld.mkOp2(OP_MUL, hTy, def[0], op1[0], op2[0]);
2373
2374 Instruction *hiPart3 = bld.mkOp3(OP_MAD, hTy, def[1], op1[0], op2[0], tmpRes2Hi);
2375 hiPart3->subOp = NV50_IR_SUBOP_MUL_HIGH;
2376 if (i->op == OP_MAD)
2377 hiPart3->setFlagsSrc(3, carry);
2378
2379 bld.mkOp2(OP_MERGE, i->dType, i->getDef(0), def[0], def[1]);
2380
2381 delete_Instruction(fn->getProgram(), i);
2382 }
2383
2384 // =============================================================================
2385
2386 static inline void
2387 updateLdStOffset(Instruction *ldst, int32_t offset, Function *fn)
2388 {
2389 if (offset != ldst->getSrc(0)->reg.data.offset) {
2390 if (ldst->getSrc(0)->refCount() > 1)
2391 ldst->setSrc(0, cloneShallow(fn, ldst->getSrc(0)));
2392 ldst->getSrc(0)->reg.data.offset = offset;
2393 }
2394 }
2395
2396 // Combine loads and stores, forward stores to loads where possible.
2397 class MemoryOpt : public Pass
2398 {
2399 private:
2400 class Record
2401 {
2402 public:
2403 Record *next;
2404 Instruction *insn;
2405 const Value *rel[2];
2406 const Value *base;
2407 int32_t offset;
2408 int8_t fileIndex;
2409 uint8_t size;
2410 bool locked;
2411 Record *prev;
2412
2413 bool overlaps(const Instruction *ldst) const;
2414
2415 inline void link(Record **);
2416 inline void unlink(Record **);
2417 inline void set(const Instruction *ldst);
2418 };
2419
2420 public:
2421 MemoryOpt();
2422
2423 Record *loads[DATA_FILE_COUNT];
2424 Record *stores[DATA_FILE_COUNT];
2425
2426 MemoryPool recordPool;
2427
2428 private:
2429 virtual bool visit(BasicBlock *);
2430 bool runOpt(BasicBlock *);
2431
2432 Record **getList(const Instruction *);
2433
2434 Record *findRecord(const Instruction *, bool load, bool& isAdjacent) const;
2435
2436 // merge @insn into load/store instruction from @rec
2437 bool combineLd(Record *rec, Instruction *ld);
2438 bool combineSt(Record *rec, Instruction *st);
2439
2440 bool replaceLdFromLd(Instruction *ld, Record *ldRec);
2441 bool replaceLdFromSt(Instruction *ld, Record *stRec);
2442 bool replaceStFromSt(Instruction *restrict st, Record *stRec);
2443
2444 void addRecord(Instruction *ldst);
2445 void purgeRecords(Instruction *const st, DataFile);
2446 void lockStores(Instruction *const ld);
2447 void reset();
2448
2449 private:
2450 Record *prevRecord;
2451 };
2452
2453 MemoryOpt::MemoryOpt() : recordPool(sizeof(MemoryOpt::Record), 6)
2454 {
2455 for (int i = 0; i < DATA_FILE_COUNT; ++i) {
2456 loads[i] = NULL;
2457 stores[i] = NULL;
2458 }
2459 prevRecord = NULL;
2460 }
2461
2462 void
2463 MemoryOpt::reset()
2464 {
2465 for (unsigned int i = 0; i < DATA_FILE_COUNT; ++i) {
2466 Record *it, *next;
2467 for (it = loads[i]; it; it = next) {
2468 next = it->next;
2469 recordPool.release(it);
2470 }
2471 loads[i] = NULL;
2472 for (it = stores[i]; it; it = next) {
2473 next = it->next;
2474 recordPool.release(it);
2475 }
2476 stores[i] = NULL;
2477 }
2478 }
2479
2480 bool
2481 MemoryOpt::combineLd(Record *rec, Instruction *ld)
2482 {
2483 int32_t offRc = rec->offset;
2484 int32_t offLd = ld->getSrc(0)->reg.data.offset;
2485 int sizeRc = rec->size;
2486 int sizeLd = typeSizeof(ld->dType);
2487 int size = sizeRc + sizeLd;
2488 int d, j;
2489
2490 if (!prog->getTarget()->
2491 isAccessSupported(ld->getSrc(0)->reg.file, typeOfSize(size)))
2492 return false;
2493 // no unaligned loads
2494 if (((size == 0x8) && (MIN2(offLd, offRc) & 0x7)) ||
2495 ((size == 0xc) && (MIN2(offLd, offRc) & 0xf)))
2496 return false;
2497 // for compute indirect loads are not guaranteed to be aligned
2498 if (prog->getType() == Program::TYPE_COMPUTE && rec->rel[0])
2499 return false;
2500
2501 assert(sizeRc + sizeLd <= 16 && offRc != offLd);
2502
2503 // lock any stores that overlap with the load being merged into the
2504 // existing record.
2505 lockStores(ld);
2506
2507 for (j = 0; sizeRc; sizeRc -= rec->insn->getDef(j)->reg.size, ++j);
2508
2509 if (offLd < offRc) {
2510 int sz;
2511 for (sz = 0, d = 0; sz < sizeLd; sz += ld->getDef(d)->reg.size, ++d);
2512 // d: nr of definitions in ld
2513 // j: nr of definitions in rec->insn, move:
2514 for (d = d + j - 1; j > 0; --j, --d)
2515 rec->insn->setDef(d, rec->insn->getDef(j - 1));
2516
2517 if (rec->insn->getSrc(0)->refCount() > 1)
2518 rec->insn->setSrc(0, cloneShallow(func, rec->insn->getSrc(0)));
2519 rec->offset = rec->insn->getSrc(0)->reg.data.offset = offLd;
2520
2521 d = 0;
2522 } else {
2523 d = j;
2524 }
2525 // move definitions of @ld to @rec->insn
2526 for (j = 0; sizeLd; ++j, ++d) {
2527 sizeLd -= ld->getDef(j)->reg.size;
2528 rec->insn->setDef(d, ld->getDef(j));
2529 }
2530
2531 rec->size = size;
2532 rec->insn->getSrc(0)->reg.size = size;
2533 rec->insn->setType(typeOfSize(size));
2534
2535 delete_Instruction(prog, ld);
2536
2537 return true;
2538 }
2539
2540 bool
2541 MemoryOpt::combineSt(Record *rec, Instruction *st)
2542 {
2543 int32_t offRc = rec->offset;
2544 int32_t offSt = st->getSrc(0)->reg.data.offset;
2545 int sizeRc = rec->size;
2546 int sizeSt = typeSizeof(st->dType);
2547 int s = sizeSt / 4;
2548 int size = sizeRc + sizeSt;
2549 int j, k;
2550 Value *src[4]; // no modifiers in ValueRef allowed for st
2551 Value *extra[3];
2552
2553 if (!prog->getTarget()->
2554 isAccessSupported(st->getSrc(0)->reg.file, typeOfSize(size)))
2555 return false;
2556 // no unaligned stores
2557 if (size == 8 && MIN2(offRc, offSt) & 0x7)
2558 return false;
2559 // for compute indirect stores are not guaranteed to be aligned
2560 if (prog->getType() == Program::TYPE_COMPUTE && rec->rel[0])
2561 return false;
2562
2563 // remove any existing load/store records for the store being merged into
2564 // the existing record.
2565 purgeRecords(st, DATA_FILE_COUNT);
2566
2567 st->takeExtraSources(0, extra); // save predicate and indirect address
2568
2569 if (offRc < offSt) {
2570 // save values from @st
2571 for (s = 0; sizeSt; ++s) {
2572 sizeSt -= st->getSrc(s + 1)->reg.size;
2573 src[s] = st->getSrc(s + 1);
2574 }
2575 // set record's values as low sources of @st
2576 for (j = 1; sizeRc; ++j) {
2577 sizeRc -= rec->insn->getSrc(j)->reg.size;
2578 st->setSrc(j, rec->insn->getSrc(j));
2579 }
2580 // set saved values as high sources of @st
2581 for (k = j, j = 0; j < s; ++j)
2582 st->setSrc(k++, src[j]);
2583
2584 updateLdStOffset(st, offRc, func);
2585 } else {
2586 for (j = 1; sizeSt; ++j)
2587 sizeSt -= st->getSrc(j)->reg.size;
2588 for (s = 1; sizeRc; ++j, ++s) {
2589 sizeRc -= rec->insn->getSrc(s)->reg.size;
2590 st->setSrc(j, rec->insn->getSrc(s));
2591 }
2592 rec->offset = offSt;
2593 }
2594 st->putExtraSources(0, extra); // restore pointer and predicate
2595
2596 delete_Instruction(prog, rec->insn);
2597 rec->insn = st;
2598 rec->size = size;
2599 rec->insn->getSrc(0)->reg.size = size;
2600 rec->insn->setType(typeOfSize(size));
2601 return true;
2602 }
2603
2604 void
2605 MemoryOpt::Record::set(const Instruction *ldst)
2606 {
2607 const Symbol *mem = ldst->getSrc(0)->asSym();
2608 fileIndex = mem->reg.fileIndex;
2609 rel[0] = ldst->getIndirect(0, 0);
2610 rel[1] = ldst->getIndirect(0, 1);
2611 offset = mem->reg.data.offset;
2612 base = mem->getBase();
2613 size = typeSizeof(ldst->sType);
2614 }
2615
2616 void
2617 MemoryOpt::Record::link(Record **list)
2618 {
2619 next = *list;
2620 if (next)
2621 next->prev = this;
2622 prev = NULL;
2623 *list = this;
2624 }
2625
2626 void
2627 MemoryOpt::Record::unlink(Record **list)
2628 {
2629 if (next)
2630 next->prev = prev;
2631 if (prev)
2632 prev->next = next;
2633 else
2634 *list = next;
2635 }
2636
2637 MemoryOpt::Record **
2638 MemoryOpt::getList(const Instruction *insn)
2639 {
2640 if (insn->op == OP_LOAD || insn->op == OP_VFETCH)
2641 return &loads[insn->src(0).getFile()];
2642 return &stores[insn->src(0).getFile()];
2643 }
2644
2645 void
2646 MemoryOpt::addRecord(Instruction *i)
2647 {
2648 Record **list = getList(i);
2649 Record *it = reinterpret_cast<Record *>(recordPool.allocate());
2650
2651 it->link(list);
2652 it->set(i);
2653 it->insn = i;
2654 it->locked = false;
2655 }
2656
2657 MemoryOpt::Record *
2658 MemoryOpt::findRecord(const Instruction *insn, bool load, bool& isAdj) const
2659 {
2660 const Symbol *sym = insn->getSrc(0)->asSym();
2661 const int size = typeSizeof(insn->sType);
2662 Record *rec = NULL;
2663 Record *it = load ? loads[sym->reg.file] : stores[sym->reg.file];
2664
2665 for (; it; it = it->next) {
2666 if (it->locked && insn->op != OP_LOAD && insn->op != OP_VFETCH)
2667 continue;
2668 if ((it->offset >> 4) != (sym->reg.data.offset >> 4) ||
2669 it->rel[0] != insn->getIndirect(0, 0) ||
2670 it->fileIndex != sym->reg.fileIndex ||
2671 it->rel[1] != insn->getIndirect(0, 1))
2672 continue;
2673
2674 if (it->offset < sym->reg.data.offset) {
2675 if (it->offset + it->size >= sym->reg.data.offset) {
2676 isAdj = (it->offset + it->size == sym->reg.data.offset);
2677 if (!isAdj)
2678 return it;
2679 if (!(it->offset & 0x7))
2680 rec = it;
2681 }
2682 } else {
2683 isAdj = it->offset != sym->reg.data.offset;
2684 if (size <= it->size && !isAdj)
2685 return it;
2686 else
2687 if (!(sym->reg.data.offset & 0x7))
2688 if (it->offset - size <= sym->reg.data.offset)
2689 rec = it;
2690 }
2691 }
2692 return rec;
2693 }
2694
2695 bool
2696 MemoryOpt::replaceLdFromSt(Instruction *ld, Record *rec)
2697 {
2698 Instruction *st = rec->insn;
2699 int32_t offSt = rec->offset;
2700 int32_t offLd = ld->getSrc(0)->reg.data.offset;
2701 int d, s;
2702
2703 for (s = 1; offSt != offLd && st->srcExists(s); ++s)
2704 offSt += st->getSrc(s)->reg.size;
2705 if (offSt != offLd)
2706 return false;
2707
2708 for (d = 0; ld->defExists(d) && st->srcExists(s); ++d, ++s) {
2709 if (ld->getDef(d)->reg.size != st->getSrc(s)->reg.size)
2710 return false;
2711 if (st->getSrc(s)->reg.file != FILE_GPR)
2712 return false;
2713 ld->def(d).replace(st->src(s), false);
2714 }
2715 ld->bb->remove(ld);
2716 return true;
2717 }
2718
2719 bool
2720 MemoryOpt::replaceLdFromLd(Instruction *ldE, Record *rec)
2721 {
2722 Instruction *ldR = rec->insn;
2723 int32_t offR = rec->offset;
2724 int32_t offE = ldE->getSrc(0)->reg.data.offset;
2725 int dR, dE;
2726
2727 assert(offR <= offE);
2728 for (dR = 0; offR < offE && ldR->defExists(dR); ++dR)
2729 offR += ldR->getDef(dR)->reg.size;
2730 if (offR != offE)
2731 return false;
2732
2733 for (dE = 0; ldE->defExists(dE) && ldR->defExists(dR); ++dE, ++dR) {
2734 if (ldE->getDef(dE)->reg.size != ldR->getDef(dR)->reg.size)
2735 return false;
2736 ldE->def(dE).replace(ldR->getDef(dR), false);
2737 }
2738
2739 delete_Instruction(prog, ldE);
2740 return true;
2741 }
2742
2743 bool
2744 MemoryOpt::replaceStFromSt(Instruction *restrict st, Record *rec)
2745 {
2746 const Instruction *const ri = rec->insn;
2747 Value *extra[3];
2748
2749 int32_t offS = st->getSrc(0)->reg.data.offset;
2750 int32_t offR = rec->offset;
2751 int32_t endS = offS + typeSizeof(st->dType);
2752 int32_t endR = offR + typeSizeof(ri->dType);
2753
2754 rec->size = MAX2(endS, endR) - MIN2(offS, offR);
2755
2756 st->takeExtraSources(0, extra);
2757
2758 if (offR < offS) {
2759 Value *vals[10];
2760 int s, n;
2761 int k = 0;
2762 // get non-replaced sources of ri
2763 for (s = 1; offR < offS; offR += ri->getSrc(s)->reg.size, ++s)
2764 vals[k++] = ri->getSrc(s);
2765 n = s;
2766 // get replaced sources of st
2767 for (s = 1; st->srcExists(s); offS += st->getSrc(s)->reg.size, ++s)
2768 vals[k++] = st->getSrc(s);
2769 // skip replaced sources of ri
2770 for (s = n; offR < endS; offR += ri->getSrc(s)->reg.size, ++s);
2771 // get non-replaced sources after values covered by st
2772 for (; offR < endR; offR += ri->getSrc(s)->reg.size, ++s)
2773 vals[k++] = ri->getSrc(s);
2774 assert((unsigned int)k <= ARRAY_SIZE(vals));
2775 for (s = 0; s < k; ++s)
2776 st->setSrc(s + 1, vals[s]);
2777 st->setSrc(0, ri->getSrc(0));
2778 } else
2779 if (endR > endS) {
2780 int j, s;
2781 for (j = 1; offR < endS; offR += ri->getSrc(j++)->reg.size);
2782 for (s = 1; offS < endS; offS += st->getSrc(s++)->reg.size);
2783 for (; offR < endR; offR += ri->getSrc(j++)->reg.size)
2784 st->setSrc(s++, ri->getSrc(j));
2785 }
2786 st->putExtraSources(0, extra);
2787
2788 delete_Instruction(prog, rec->insn);
2789
2790 rec->insn = st;
2791 rec->offset = st->getSrc(0)->reg.data.offset;
2792
2793 st->setType(typeOfSize(rec->size));
2794
2795 return true;
2796 }
2797
2798 bool
2799 MemoryOpt::Record::overlaps(const Instruction *ldst) const
2800 {
2801 Record that;
2802 that.set(ldst);
2803
2804 // This assumes that images/buffers can't overlap. They can.
2805 // TODO: Plumb the restrict logic through, and only skip when it's a
2806 // restrict situation, or there can implicitly be no writes.
2807 if (this->fileIndex != that.fileIndex && this->rel[1] == that.rel[1])
2808 return false;
2809
2810 if (this->rel[0] || that.rel[0])
2811 return this->base == that.base;
2812
2813 return
2814 (this->offset < that.offset + that.size) &&
2815 (this->offset + this->size > that.offset);
2816 }
2817
2818 // We must not eliminate stores that affect the result of @ld if
2819 // we find later stores to the same location, and we may no longer
2820 // merge them with later stores.
2821 // The stored value can, however, still be used to determine the value
2822 // returned by future loads.
2823 void
2824 MemoryOpt::lockStores(Instruction *const ld)
2825 {
2826 for (Record *r = stores[ld->src(0).getFile()]; r; r = r->next)
2827 if (!r->locked && r->overlaps(ld))
2828 r->locked = true;
2829 }
2830
2831 // Prior loads from the location of @st are no longer valid.
2832 // Stores to the location of @st may no longer be used to derive
2833 // the value at it nor be coalesced into later stores.
2834 void
2835 MemoryOpt::purgeRecords(Instruction *const st, DataFile f)
2836 {
2837 if (st)
2838 f = st->src(0).getFile();
2839
2840 for (Record *r = loads[f]; r; r = r->next)
2841 if (!st || r->overlaps(st))
2842 r->unlink(&loads[f]);
2843
2844 for (Record *r = stores[f]; r; r = r->next)
2845 if (!st || r->overlaps(st))
2846 r->unlink(&stores[f]);
2847 }
2848
2849 bool
2850 MemoryOpt::visit(BasicBlock *bb)
2851 {
2852 bool ret = runOpt(bb);
2853 // Run again, one pass won't combine 4 32 bit ld/st to a single 128 bit ld/st
2854 // where 96 bit memory operations are forbidden.
2855 if (ret)
2856 ret = runOpt(bb);
2857 return ret;
2858 }
2859
2860 bool
2861 MemoryOpt::runOpt(BasicBlock *bb)
2862 {
2863 Instruction *ldst, *next;
2864 Record *rec;
2865 bool isAdjacent = true;
2866
2867 for (ldst = bb->getEntry(); ldst; ldst = next) {
2868 bool keep = true;
2869 bool isLoad = true;
2870 next = ldst->next;
2871
2872 if (ldst->op == OP_LOAD || ldst->op == OP_VFETCH) {
2873 if (ldst->isDead()) {
2874 // might have been produced by earlier optimization
2875 delete_Instruction(prog, ldst);
2876 continue;
2877 }
2878 } else
2879 if (ldst->op == OP_STORE || ldst->op == OP_EXPORT) {
2880 if (typeSizeof(ldst->dType) == 4 &&
2881 ldst->src(1).getFile() == FILE_GPR &&
2882 ldst->getSrc(1)->getInsn()->op == OP_NOP) {
2883 delete_Instruction(prog, ldst);
2884 continue;
2885 }
2886 isLoad = false;
2887 } else {
2888 // TODO: maybe have all fixed ops act as barrier ?
2889 if (ldst->op == OP_CALL ||
2890 ldst->op == OP_BAR ||
2891 ldst->op == OP_MEMBAR) {
2892 purgeRecords(NULL, FILE_MEMORY_LOCAL);
2893 purgeRecords(NULL, FILE_MEMORY_GLOBAL);
2894 purgeRecords(NULL, FILE_MEMORY_SHARED);
2895 purgeRecords(NULL, FILE_SHADER_OUTPUT);
2896 } else
2897 if (ldst->op == OP_ATOM || ldst->op == OP_CCTL) {
2898 if (ldst->src(0).getFile() == FILE_MEMORY_GLOBAL) {
2899 purgeRecords(NULL, FILE_MEMORY_LOCAL);
2900 purgeRecords(NULL, FILE_MEMORY_GLOBAL);
2901 purgeRecords(NULL, FILE_MEMORY_SHARED);
2902 } else {
2903 purgeRecords(NULL, ldst->src(0).getFile());
2904 }
2905 } else
2906 if (ldst->op == OP_EMIT || ldst->op == OP_RESTART) {
2907 purgeRecords(NULL, FILE_SHADER_OUTPUT);
2908 }
2909 continue;
2910 }
2911 if (ldst->getPredicate()) // TODO: handle predicated ld/st
2912 continue;
2913 if (ldst->perPatch) // TODO: create separate per-patch lists
2914 continue;
2915
2916 if (isLoad) {
2917 DataFile file = ldst->src(0).getFile();
2918
2919 // if ld l[]/g[] look for previous store to eliminate the reload
2920 if (file == FILE_MEMORY_GLOBAL || file == FILE_MEMORY_LOCAL) {
2921 // TODO: shared memory ?
2922 rec = findRecord(ldst, false, isAdjacent);
2923 if (rec && !isAdjacent)
2924 keep = !replaceLdFromSt(ldst, rec);
2925 }
2926
2927 // or look for ld from the same location and replace this one
2928 rec = keep ? findRecord(ldst, true, isAdjacent) : NULL;
2929 if (rec) {
2930 if (!isAdjacent)
2931 keep = !replaceLdFromLd(ldst, rec);
2932 else
2933 // or combine a previous load with this one
2934 keep = !combineLd(rec, ldst);
2935 }
2936 if (keep)
2937 lockStores(ldst);
2938 } else {
2939 rec = findRecord(ldst, false, isAdjacent);
2940 if (rec) {
2941 if (!isAdjacent)
2942 keep = !replaceStFromSt(ldst, rec);
2943 else
2944 keep = !combineSt(rec, ldst);
2945 }
2946 if (keep)
2947 purgeRecords(ldst, DATA_FILE_COUNT);
2948 }
2949 if (keep)
2950 addRecord(ldst);
2951 }
2952 reset();
2953
2954 return true;
2955 }
2956
2957 // =============================================================================
2958
2959 // Turn control flow into predicated instructions (after register allocation !).
2960 // TODO:
2961 // Could move this to before register allocation on NVC0 and also handle nested
2962 // constructs.
2963 class FlatteningPass : public Pass
2964 {
2965 private:
2966 virtual bool visit(Function *);
2967 virtual bool visit(BasicBlock *);
2968
2969 bool tryPredicateConditional(BasicBlock *);
2970 void predicateInstructions(BasicBlock *, Value *pred, CondCode cc);
2971 void tryPropagateBranch(BasicBlock *);
2972 inline bool isConstantCondition(Value *pred);
2973 inline bool mayPredicate(const Instruction *, const Value *pred) const;
2974 inline void removeFlow(Instruction *);
2975
2976 uint8_t gpr_unit;
2977 };
2978
2979 bool
2980 FlatteningPass::isConstantCondition(Value *pred)
2981 {
2982 Instruction *insn = pred->getUniqueInsn();
2983 assert(insn);
2984 if (insn->op != OP_SET || insn->srcExists(2))
2985 return false;
2986
2987 for (int s = 0; s < 2 && insn->srcExists(s); ++s) {
2988 Instruction *ld = insn->getSrc(s)->getUniqueInsn();
2989 DataFile file;
2990 if (ld) {
2991 if (ld->op != OP_MOV && ld->op != OP_LOAD)
2992 return false;
2993 if (ld->src(0).isIndirect(0))
2994 return false;
2995 file = ld->src(0).getFile();
2996 } else {
2997 file = insn->src(s).getFile();
2998 // catch $r63 on NVC0 and $r63/$r127 on NV50. Unfortunately maxGPR is
2999 // in register "units", which can vary between targets.
3000 if (file == FILE_GPR) {
3001 Value *v = insn->getSrc(s);
3002 int bytes = v->reg.data.id * MIN2(v->reg.size, 4);
3003 int units = bytes >> gpr_unit;
3004 if (units > prog->maxGPR)
3005 file = FILE_IMMEDIATE;
3006 }
3007 }
3008 if (file != FILE_IMMEDIATE && file != FILE_MEMORY_CONST)
3009 return false;
3010 }
3011 return true;
3012 }
3013
3014 void
3015 FlatteningPass::removeFlow(Instruction *insn)
3016 {
3017 FlowInstruction *term = insn ? insn->asFlow() : NULL;
3018 if (!term)
3019 return;
3020 Graph::Edge::Type ty = term->bb->cfg.outgoing().getType();
3021
3022 if (term->op == OP_BRA) {
3023 // TODO: this might get more difficult when we get arbitrary BRAs
3024 if (ty == Graph::Edge::CROSS || ty == Graph::Edge::BACK)
3025 return;
3026 } else
3027 if (term->op != OP_JOIN)
3028 return;
3029
3030 Value *pred = term->getPredicate();
3031
3032 delete_Instruction(prog, term);
3033
3034 if (pred && pred->refCount() == 0) {
3035 Instruction *pSet = pred->getUniqueInsn();
3036 pred->join->reg.data.id = -1; // deallocate
3037 if (pSet->isDead())
3038 delete_Instruction(prog, pSet);
3039 }
3040 }
3041
3042 void
3043 FlatteningPass::predicateInstructions(BasicBlock *bb, Value *pred, CondCode cc)
3044 {
3045 for (Instruction *i = bb->getEntry(); i; i = i->next) {
3046 if (i->isNop())
3047 continue;
3048 assert(!i->getPredicate());
3049 i->setPredicate(cc, pred);
3050 }
3051 removeFlow(bb->getExit());
3052 }
3053
3054 bool
3055 FlatteningPass::mayPredicate(const Instruction *insn, const Value *pred) const
3056 {
3057 if (insn->isPseudo())
3058 return true;
3059 // TODO: calls where we don't know which registers are modified
3060
3061 if (!prog->getTarget()->mayPredicate(insn, pred))
3062 return false;
3063 for (int d = 0; insn->defExists(d); ++d)
3064 if (insn->getDef(d)->equals(pred))
3065 return false;
3066 return true;
3067 }
3068
3069 // If we jump to BRA/RET/EXIT, replace the jump with it.
3070 // NOTE: We do not update the CFG anymore here !
3071 //
3072 // TODO: Handle cases where we skip over a branch (maybe do that elsewhere ?):
3073 // BB:0
3074 // @p0 bra BB:2 -> @!p0 bra BB:3 iff (!) BB:2 immediately adjoins BB:1
3075 // BB1:
3076 // bra BB:3
3077 // BB2:
3078 // ...
3079 // BB3:
3080 // ...
3081 void
3082 FlatteningPass::tryPropagateBranch(BasicBlock *bb)
3083 {
3084 for (Instruction *i = bb->getExit(); i && i->op == OP_BRA; i = i->prev) {
3085 BasicBlock *bf = i->asFlow()->target.bb;
3086
3087 if (bf->getInsnCount() != 1)
3088 continue;
3089
3090 FlowInstruction *bra = i->asFlow();
3091 FlowInstruction *rep = bf->getExit()->asFlow();
3092
3093 if (!rep || rep->getPredicate())
3094 continue;
3095 if (rep->op != OP_BRA &&
3096 rep->op != OP_JOIN &&
3097 rep->op != OP_EXIT)
3098 continue;
3099
3100 // TODO: If there are multiple branches to @rep, only the first would
3101 // be replaced, so only remove them after this pass is done ?
3102 // Also, need to check all incident blocks for fall-through exits and
3103 // add the branch there.
3104 bra->op = rep->op;
3105 bra->target.bb = rep->target.bb;
3106 if (bf->cfg.incidentCount() == 1)
3107 bf->remove(rep);
3108 }
3109 }
3110
3111 bool
3112 FlatteningPass::visit(Function *fn)
3113 {
3114 gpr_unit = prog->getTarget()->getFileUnit(FILE_GPR);
3115
3116 return true;
3117 }
3118
3119 bool
3120 FlatteningPass::visit(BasicBlock *bb)
3121 {
3122 if (tryPredicateConditional(bb))
3123 return true;
3124
3125 // try to attach join to previous instruction
3126 if (prog->getTarget()->hasJoin) {
3127 Instruction *insn = bb->getExit();
3128 if (insn && insn->op == OP_JOIN && !insn->getPredicate()) {
3129 insn = insn->prev;
3130 if (insn && !insn->getPredicate() &&
3131 !insn->asFlow() &&
3132 insn->op != OP_DISCARD &&
3133 insn->op != OP_TEXBAR &&
3134 !isTextureOp(insn->op) && // probably just nve4
3135 !isSurfaceOp(insn->op) && // not confirmed
3136 insn->op != OP_LINTERP && // probably just nve4
3137 insn->op != OP_PINTERP && // probably just nve4
3138 ((insn->op != OP_LOAD && insn->op != OP_STORE && insn->op != OP_ATOM) ||
3139 (typeSizeof(insn->dType) <= 4 && !insn->src(0).isIndirect(0))) &&
3140 !insn->isNop()) {
3141 insn->join = 1;
3142 bb->remove(bb->getExit());
3143 return true;
3144 }
3145 }
3146 }
3147
3148 tryPropagateBranch(bb);
3149
3150 return true;
3151 }
3152
3153 bool
3154 FlatteningPass::tryPredicateConditional(BasicBlock *bb)
3155 {
3156 BasicBlock *bL = NULL, *bR = NULL;
3157 unsigned int nL = 0, nR = 0, limit = 12;
3158 Instruction *insn;
3159 unsigned int mask;
3160
3161 mask = bb->initiatesSimpleConditional();
3162 if (!mask)
3163 return false;
3164
3165 assert(bb->getExit());
3166 Value *pred = bb->getExit()->getPredicate();
3167 assert(pred);
3168
3169 if (isConstantCondition(pred))
3170 limit = 4;
3171
3172 Graph::EdgeIterator ei = bb->cfg.outgoing();
3173
3174 if (mask & 1) {
3175 bL = BasicBlock::get(ei.getNode());
3176 for (insn = bL->getEntry(); insn; insn = insn->next, ++nL)
3177 if (!mayPredicate(insn, pred))
3178 return false;
3179 if (nL > limit)
3180 return false; // too long, do a real branch
3181 }
3182 ei.next();
3183
3184 if (mask & 2) {
3185 bR = BasicBlock::get(ei.getNode());
3186 for (insn = bR->getEntry(); insn; insn = insn->next, ++nR)
3187 if (!mayPredicate(insn, pred))
3188 return false;
3189 if (nR > limit)
3190 return false; // too long, do a real branch
3191 }
3192
3193 if (bL)
3194 predicateInstructions(bL, pred, bb->getExit()->cc);
3195 if (bR)
3196 predicateInstructions(bR, pred, inverseCondCode(bb->getExit()->cc));
3197
3198 if (bb->joinAt) {
3199 bb->remove(bb->joinAt);
3200 bb->joinAt = NULL;
3201 }
3202 removeFlow(bb->getExit()); // delete the branch/join at the fork point
3203
3204 // remove potential join operations at the end of the conditional
3205 if (prog->getTarget()->joinAnterior) {
3206 bb = BasicBlock::get((bL ? bL : bR)->cfg.outgoing().getNode());
3207 if (bb->getEntry() && bb->getEntry()->op == OP_JOIN)
3208 removeFlow(bb->getEntry());
3209 }
3210
3211 return true;
3212 }
3213
3214 // =============================================================================
3215
3216 // Fold Immediate into MAD; must be done after register allocation due to
3217 // constraint SDST == SSRC2
3218 // TODO:
3219 // Does NVC0+ have other situations where this pass makes sense?
3220 class PostRaLoadPropagation : public Pass
3221 {
3222 private:
3223 virtual bool visit(Instruction *);
3224
3225 void handleMADforNV50(Instruction *);
3226 void handleMADforNVC0(Instruction *);
3227 };
3228
3229 static bool
3230 post_ra_dead(Instruction *i)
3231 {
3232 for (int d = 0; i->defExists(d); ++d)
3233 if (i->getDef(d)->refCount())
3234 return false;
3235 return true;
3236 }
3237
3238 // Fold Immediate into MAD; must be done after register allocation due to
3239 // constraint SDST == SSRC2
3240 void
3241 PostRaLoadPropagation::handleMADforNV50(Instruction *i)
3242 {
3243 if (i->def(0).getFile() != FILE_GPR ||
3244 i->src(0).getFile() != FILE_GPR ||
3245 i->src(1).getFile() != FILE_GPR ||
3246 i->src(2).getFile() != FILE_GPR ||
3247 i->getDef(0)->reg.data.id != i->getSrc(2)->reg.data.id)
3248 return;
3249
3250 if (i->getDef(0)->reg.data.id >= 64 ||
3251 i->getSrc(0)->reg.data.id >= 64)
3252 return;
3253
3254 if (i->flagsSrc >= 0 && i->getSrc(i->flagsSrc)->reg.data.id != 0)
3255 return;
3256
3257 if (i->getPredicate())
3258 return;
3259
3260 Value *vtmp;
3261 Instruction *def = i->getSrc(1)->getInsn();
3262
3263 if (def && def->op == OP_SPLIT && typeSizeof(def->sType) == 4)
3264 def = def->getSrc(0)->getInsn();
3265 if (def && def->op == OP_MOV && def->src(0).getFile() == FILE_IMMEDIATE) {
3266 vtmp = i->getSrc(1);
3267 if (isFloatType(i->sType)) {
3268 i->setSrc(1, def->getSrc(0));
3269 } else {
3270 ImmediateValue val;
3271 bool ret = def->src(0).getImmediate(val);
3272 assert(ret);
3273 if (i->getSrc(1)->reg.data.id & 1)
3274 val.reg.data.u32 >>= 16;
3275 val.reg.data.u32 &= 0xffff;
3276 i->setSrc(1, new_ImmediateValue(prog, val.reg.data.u32));
3277 }
3278
3279 /* There's no post-RA dead code elimination, so do it here
3280 * XXX: if we add more code-removing post-RA passes, we might
3281 * want to create a post-RA dead-code elim pass */
3282 if (post_ra_dead(vtmp->getInsn())) {
3283 Value *src = vtmp->getInsn()->getSrc(0);
3284 // Careful -- splits will have already been removed from the
3285 // functions. Don't double-delete.
3286 if (vtmp->getInsn()->bb)
3287 delete_Instruction(prog, vtmp->getInsn());
3288 if (src->getInsn() && post_ra_dead(src->getInsn()))
3289 delete_Instruction(prog, src->getInsn());
3290 }
3291 }
3292 }
3293
3294 void
3295 PostRaLoadPropagation::handleMADforNVC0(Instruction *i)
3296 {
3297 if (i->def(0).getFile() != FILE_GPR ||
3298 i->src(0).getFile() != FILE_GPR ||
3299 i->src(1).getFile() != FILE_GPR ||
3300 i->src(2).getFile() != FILE_GPR ||
3301 i->getDef(0)->reg.data.id != i->getSrc(2)->reg.data.id)
3302 return;
3303
3304 // TODO: gm107 can also do this for S32, maybe other chipsets as well
3305 if (i->dType != TYPE_F32)
3306 return;
3307
3308 if ((i->src(2).mod | Modifier(NV50_IR_MOD_NEG)) != Modifier(NV50_IR_MOD_NEG))
3309 return;
3310
3311 ImmediateValue val;
3312 int s;
3313
3314 if (i->src(0).getImmediate(val))
3315 s = 1;
3316 else if (i->src(1).getImmediate(val))
3317 s = 0;
3318 else
3319 return;
3320
3321 if ((i->src(s).mod | Modifier(NV50_IR_MOD_NEG)) != Modifier(NV50_IR_MOD_NEG))
3322 return;
3323
3324 if (s == 1)
3325 i->swapSources(0, 1);
3326
3327 Instruction *imm = i->getSrc(1)->getInsn();
3328 i->setSrc(1, imm->getSrc(0));
3329 if (post_ra_dead(imm))
3330 delete_Instruction(prog, imm);
3331 }
3332
3333 bool
3334 PostRaLoadPropagation::visit(Instruction *i)
3335 {
3336 switch (i->op) {
3337 case OP_FMA:
3338 case OP_MAD:
3339 if (prog->getTarget()->getChipset() < 0xc0)
3340 handleMADforNV50(i);
3341 else
3342 handleMADforNVC0(i);
3343 break;
3344 default:
3345 break;
3346 }
3347
3348 return true;
3349 }
3350
3351 // =============================================================================
3352
3353 // Common subexpression elimination. Stupid O^2 implementation.
3354 class LocalCSE : public Pass
3355 {
3356 private:
3357 virtual bool visit(BasicBlock *);
3358
3359 inline bool tryReplace(Instruction **, Instruction *);
3360
3361 DLList ops[OP_LAST + 1];
3362 };
3363
3364 class GlobalCSE : public Pass
3365 {
3366 private:
3367 virtual bool visit(BasicBlock *);
3368 };
3369
3370 bool
3371 Instruction::isActionEqual(const Instruction *that) const
3372 {
3373 if (this->op != that->op ||
3374 this->dType != that->dType ||
3375 this->sType != that->sType)
3376 return false;
3377 if (this->cc != that->cc)
3378 return false;
3379
3380 if (this->asTex()) {
3381 if (memcmp(&this->asTex()->tex,
3382 &that->asTex()->tex,
3383 sizeof(this->asTex()->tex)))
3384 return false;
3385 } else
3386 if (this->asCmp()) {
3387 if (this->asCmp()->setCond != that->asCmp()->setCond)
3388 return false;
3389 } else
3390 if (this->asFlow()) {
3391 return false;
3392 } else {
3393 if (this->ipa != that->ipa ||
3394 this->lanes != that->lanes ||
3395 this->perPatch != that->perPatch)
3396 return false;
3397 if (this->postFactor != that->postFactor)
3398 return false;
3399 }
3400
3401 if (this->subOp != that->subOp ||
3402 this->saturate != that->saturate ||
3403 this->rnd != that->rnd ||
3404 this->ftz != that->ftz ||
3405 this->dnz != that->dnz ||
3406 this->cache != that->cache ||
3407 this->mask != that->mask)
3408 return false;
3409
3410 return true;
3411 }
3412
3413 bool
3414 Instruction::isResultEqual(const Instruction *that) const
3415 {
3416 unsigned int d, s;
3417
3418 // NOTE: location of discard only affects tex with liveOnly and quadops
3419 if (!this->defExists(0) && this->op != OP_DISCARD)
3420 return false;
3421
3422 if (!isActionEqual(that))
3423 return false;
3424
3425 if (this->predSrc != that->predSrc)
3426 return false;
3427
3428 for (d = 0; this->defExists(d); ++d) {
3429 if (!that->defExists(d) ||
3430 !this->getDef(d)->equals(that->getDef(d), false))
3431 return false;
3432 }
3433 if (that->defExists(d))
3434 return false;
3435
3436 for (s = 0; this->srcExists(s); ++s) {
3437 if (!that->srcExists(s))
3438 return false;
3439 if (this->src(s).mod != that->src(s).mod)
3440 return false;
3441 if (!this->getSrc(s)->equals(that->getSrc(s), true))
3442 return false;
3443 }
3444 if (that->srcExists(s))
3445 return false;
3446
3447 if (op == OP_LOAD || op == OP_VFETCH || op == OP_ATOM) {
3448 switch (src(0).getFile()) {
3449 case FILE_MEMORY_CONST:
3450 case FILE_SHADER_INPUT:
3451 return true;
3452 case FILE_SHADER_OUTPUT:
3453 return bb->getProgram()->getType() == Program::TYPE_TESSELLATION_EVAL;
3454 default:
3455 return false;
3456 }
3457 }
3458
3459 return true;
3460 }
3461
3462 // pull through common expressions from different in-blocks
3463 bool
3464 GlobalCSE::visit(BasicBlock *bb)
3465 {
3466 Instruction *phi, *next, *ik;
3467 int s;
3468
3469 // TODO: maybe do this with OP_UNION, too
3470
3471 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = next) {
3472 next = phi->next;
3473 if (phi->getSrc(0)->refCount() > 1)
3474 continue;
3475 ik = phi->getSrc(0)->getInsn();
3476 if (!ik)
3477 continue; // probably a function input
3478 if (ik->defCount(0xff) > 1)
3479 continue; // too painful to check if we can really push this forward
3480 for (s = 1; phi->srcExists(s); ++s) {
3481 if (phi->getSrc(s)->refCount() > 1)
3482 break;
3483 if (!phi->getSrc(s)->getInsn() ||
3484 !phi->getSrc(s)->getInsn()->isResultEqual(ik))
3485 break;
3486 }
3487 if (!phi->srcExists(s)) {
3488 Instruction *entry = bb->getEntry();
3489 ik->bb->remove(ik);
3490 if (!entry || entry->op != OP_JOIN)
3491 bb->insertHead(ik);
3492 else
3493 bb->insertAfter(entry, ik);
3494 ik->setDef(0, phi->getDef(0));
3495 delete_Instruction(prog, phi);
3496 }
3497 }
3498
3499 return true;
3500 }
3501
3502 bool
3503 LocalCSE::tryReplace(Instruction **ptr, Instruction *i)
3504 {
3505 Instruction *old = *ptr;
3506
3507 // TODO: maybe relax this later (causes trouble with OP_UNION)
3508 if (i->isPredicated())
3509 return false;
3510
3511 if (!old->isResultEqual(i))
3512 return false;
3513
3514 for (int d = 0; old->defExists(d); ++d)
3515 old->def(d).replace(i->getDef(d), false);
3516 delete_Instruction(prog, old);
3517 *ptr = NULL;
3518 return true;
3519 }
3520
3521 bool
3522 LocalCSE::visit(BasicBlock *bb)
3523 {
3524 unsigned int replaced;
3525
3526 do {
3527 Instruction *ir, *next;
3528
3529 replaced = 0;
3530
3531 // will need to know the order of instructions
3532 int serial = 0;
3533 for (ir = bb->getFirst(); ir; ir = ir->next)
3534 ir->serial = serial++;
3535
3536 for (ir = bb->getFirst(); ir; ir = next) {
3537 int s;
3538 Value *src = NULL;
3539
3540 next = ir->next;
3541
3542 if (ir->fixed) {
3543 ops[ir->op].insert(ir);
3544 continue;
3545 }
3546
3547 for (s = 0; ir->srcExists(s); ++s)
3548 if (ir->getSrc(s)->asLValue())
3549 if (!src || ir->getSrc(s)->refCount() < src->refCount())
3550 src = ir->getSrc(s);
3551
3552 if (src) {
3553 for (Value::UseIterator it = src->uses.begin();
3554 it != src->uses.end(); ++it) {
3555 Instruction *ik = (*it)->getInsn();
3556 if (ik && ik->bb == ir->bb && ik->serial < ir->serial)
3557 if (tryReplace(&ir, ik))
3558 break;
3559 }
3560 } else {
3561 DLLIST_FOR_EACH(&ops[ir->op], iter)
3562 {
3563 Instruction *ik = reinterpret_cast<Instruction *>(iter.get());
3564 if (tryReplace(&ir, ik))
3565 break;
3566 }
3567 }
3568
3569 if (ir)
3570 ops[ir->op].insert(ir);
3571 else
3572 ++replaced;
3573 }
3574 for (unsigned int i = 0; i <= OP_LAST; ++i)
3575 ops[i].clear();
3576
3577 } while (replaced);
3578
3579 return true;
3580 }
3581
3582 // =============================================================================
3583
3584 // Remove computations of unused values.
3585 class DeadCodeElim : public Pass
3586 {
3587 public:
3588 bool buryAll(Program *);
3589
3590 private:
3591 virtual bool visit(BasicBlock *);
3592
3593 void checkSplitLoad(Instruction *ld); // for partially dead loads
3594
3595 unsigned int deadCount;
3596 };
3597
3598 bool
3599 DeadCodeElim::buryAll(Program *prog)
3600 {
3601 do {
3602 deadCount = 0;
3603 if (!this->run(prog, false, false))
3604 return false;
3605 } while (deadCount);
3606
3607 return true;
3608 }
3609
3610 bool
3611 DeadCodeElim::visit(BasicBlock *bb)
3612 {
3613 Instruction *prev;
3614
3615 for (Instruction *i = bb->getExit(); i; i = prev) {
3616 prev = i->prev;
3617 if (i->isDead()) {
3618 ++deadCount;
3619 delete_Instruction(prog, i);
3620 } else
3621 if (i->defExists(1) &&
3622 i->subOp == 0 &&
3623 (i->op == OP_VFETCH || i->op == OP_LOAD)) {
3624 checkSplitLoad(i);
3625 } else
3626 if (i->defExists(0) && !i->getDef(0)->refCount()) {
3627 if (i->op == OP_ATOM ||
3628 i->op == OP_SUREDP ||
3629 i->op == OP_SUREDB) {
3630 i->setDef(0, NULL);
3631 if (i->op == OP_ATOM && i->subOp == NV50_IR_SUBOP_ATOM_EXCH) {
3632 i->cache = CACHE_CV;
3633 i->op = OP_STORE;
3634 i->subOp = 0;
3635 }
3636 } else if (i->op == OP_LOAD && i->subOp == NV50_IR_SUBOP_LOAD_LOCKED) {
3637 i->setDef(0, i->getDef(1));
3638 i->setDef(1, NULL);
3639 }
3640 }
3641 }
3642 return true;
3643 }
3644
3645 // Each load can go into up to 4 destinations, any of which might potentially
3646 // be dead (i.e. a hole). These can always be split into 2 loads, independent
3647 // of where the holes are. We find the first contiguous region, put it into
3648 // the first load, and then put the second contiguous region into the second
3649 // load. There can be at most 2 contiguous regions.
3650 //
3651 // Note that there are some restrictions, for example it's not possible to do
3652 // a 64-bit load that's not 64-bit aligned, so such a load has to be split
3653 // up. Also hardware doesn't support 96-bit loads, so those also have to be
3654 // split into a 64-bit and 32-bit load.
3655 void
3656 DeadCodeElim::checkSplitLoad(Instruction *ld1)
3657 {
3658 Instruction *ld2 = NULL; // can get at most 2 loads
3659 Value *def1[4];
3660 Value *def2[4];
3661 int32_t addr1, addr2;
3662 int32_t size1, size2;
3663 int d, n1, n2;
3664 uint32_t mask = 0xffffffff;
3665
3666 for (d = 0; ld1->defExists(d); ++d)
3667 if (!ld1->getDef(d)->refCount() && ld1->getDef(d)->reg.data.id < 0)
3668 mask &= ~(1 << d);
3669 if (mask == 0xffffffff)
3670 return;
3671
3672 addr1 = ld1->getSrc(0)->reg.data.offset;
3673 n1 = n2 = 0;
3674 size1 = size2 = 0;
3675
3676 // Compute address/width for first load
3677 for (d = 0; ld1->defExists(d); ++d) {
3678 if (mask & (1 << d)) {
3679 if (size1 && (addr1 & 0x7))
3680 break;
3681 def1[n1] = ld1->getDef(d);
3682 size1 += def1[n1++]->reg.size;
3683 } else
3684 if (!n1) {
3685 addr1 += ld1->getDef(d)->reg.size;
3686 } else {
3687 break;
3688 }
3689 }
3690
3691 // Scale back the size of the first load until it can be loaded. This
3692 // typically happens for TYPE_B96 loads.
3693 while (n1 &&
3694 !prog->getTarget()->isAccessSupported(ld1->getSrc(0)->reg.file,
3695 typeOfSize(size1))) {
3696 size1 -= def1[--n1]->reg.size;
3697 d--;
3698 }
3699
3700 // Compute address/width for second load
3701 for (addr2 = addr1 + size1; ld1->defExists(d); ++d) {
3702 if (mask & (1 << d)) {
3703 assert(!size2 || !(addr2 & 0x7));
3704 def2[n2] = ld1->getDef(d);
3705 size2 += def2[n2++]->reg.size;
3706 } else if (!n2) {
3707 assert(!n2);
3708 addr2 += ld1->getDef(d)->reg.size;
3709 } else {
3710 break;
3711 }
3712 }
3713
3714 // Make sure that we've processed all the values
3715 for (; ld1->defExists(d); ++d)
3716 assert(!(mask & (1 << d)));
3717
3718 updateLdStOffset(ld1, addr1, func);
3719 ld1->setType(typeOfSize(size1));
3720 for (d = 0; d < 4; ++d)
3721 ld1->setDef(d, (d < n1) ? def1[d] : NULL);
3722
3723 if (!n2)
3724 return;
3725
3726 ld2 = cloneShallow(func, ld1);
3727 updateLdStOffset(ld2, addr2, func);
3728 ld2->setType(typeOfSize(size2));
3729 for (d = 0; d < 4; ++d)
3730 ld2->setDef(d, (d < n2) ? def2[d] : NULL);
3731
3732 ld1->bb->insertAfter(ld1, ld2);
3733 }
3734
3735 // =============================================================================
3736
3737 #define RUN_PASS(l, n, f) \
3738 if (level >= (l)) { \
3739 if (dbgFlags & NV50_IR_DEBUG_VERBOSE) \
3740 INFO("PEEPHOLE: %s\n", #n); \
3741 n pass; \
3742 if (!pass.f(this)) \
3743 return false; \
3744 }
3745
3746 bool
3747 Program::optimizeSSA(int level)
3748 {
3749 RUN_PASS(1, DeadCodeElim, buryAll);
3750 RUN_PASS(1, CopyPropagation, run);
3751 RUN_PASS(1, MergeSplits, run);
3752 RUN_PASS(2, GlobalCSE, run);
3753 RUN_PASS(1, LocalCSE, run);
3754 RUN_PASS(2, AlgebraicOpt, run);
3755 RUN_PASS(2, ModifierFolding, run); // before load propagation -> less checks
3756 RUN_PASS(1, ConstantFolding, foldAll);
3757 RUN_PASS(2, LateAlgebraicOpt, run);
3758 RUN_PASS(1, Split64BitOpPreRA, run);
3759 RUN_PASS(1, LoadPropagation, run);
3760 RUN_PASS(1, IndirectPropagation, run);
3761 RUN_PASS(2, MemoryOpt, run);
3762 RUN_PASS(2, LocalCSE, run);
3763 RUN_PASS(0, DeadCodeElim, buryAll);
3764
3765 return true;
3766 }
3767
3768 bool
3769 Program::optimizePostRA(int level)
3770 {
3771 RUN_PASS(2, FlatteningPass, run);
3772 RUN_PASS(2, PostRaLoadPropagation, run);
3773
3774 return true;
3775 }
3776
3777 }