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