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