nv50/ir: use unordered_set instead of list to keep track of var uses
[mesa.git] / src / gallium / drivers / nouveau / codegen / nv50_ir_ra.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
26 #include <stack>
27 #include <limits>
28
29 namespace nv50_ir {
30
31 #define MAX_REGISTER_FILE_SIZE 256
32
33 class RegisterSet
34 {
35 public:
36 RegisterSet(const Target *);
37
38 void init(const Target *);
39 void reset(DataFile, bool resetMax = false);
40
41 void periodicMask(DataFile f, uint32_t lock, uint32_t unlock);
42 void intersect(DataFile f, const RegisterSet *);
43
44 bool assign(int32_t& reg, DataFile f, unsigned int size);
45 void release(DataFile f, int32_t reg, unsigned int size);
46 void occupy(DataFile f, int32_t reg, unsigned int size);
47 void occupy(const Value *);
48 void occupyMask(DataFile f, int32_t reg, uint8_t mask);
49 bool isOccupied(DataFile f, int32_t reg, unsigned int size) const;
50 bool testOccupy(const Value *);
51 bool testOccupy(DataFile f, int32_t reg, unsigned int size);
52
53 inline int getMaxAssigned(DataFile f) const { return fill[f]; }
54
55 inline unsigned int getFileSize(DataFile f, uint8_t regSize) const
56 {
57 if (restrictedGPR16Range && f == FILE_GPR && regSize == 2)
58 return (last[f] + 1) / 2;
59 return last[f] + 1;
60 }
61
62 inline unsigned int units(DataFile f, unsigned int size) const
63 {
64 return size >> unit[f];
65 }
66 // for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)
67 inline unsigned int idToBytes(const Value *v) const
68 {
69 return v->reg.data.id * MIN2(v->reg.size, 4);
70 }
71 inline unsigned int idToUnits(const Value *v) const
72 {
73 return units(v->reg.file, idToBytes(v));
74 }
75 inline int bytesToId(Value *v, unsigned int bytes) const
76 {
77 if (v->reg.size < 4)
78 return units(v->reg.file, bytes);
79 return bytes / 4;
80 }
81 inline int unitsToId(DataFile f, int u, uint8_t size) const
82 {
83 if (u < 0)
84 return -1;
85 return (size < 4) ? u : ((u << unit[f]) / 4);
86 }
87
88 void print() const;
89
90 private:
91 BitSet bits[LAST_REGISTER_FILE + 1];
92
93 int unit[LAST_REGISTER_FILE + 1]; // log2 of allocation granularity
94
95 int last[LAST_REGISTER_FILE + 1];
96 int fill[LAST_REGISTER_FILE + 1];
97
98 const bool restrictedGPR16Range;
99 };
100
101 void
102 RegisterSet::reset(DataFile f, bool resetMax)
103 {
104 bits[f].fill(0);
105 if (resetMax)
106 fill[f] = -1;
107 }
108
109 void
110 RegisterSet::init(const Target *targ)
111 {
112 for (unsigned int rf = 0; rf <= FILE_ADDRESS; ++rf) {
113 DataFile f = static_cast<DataFile>(rf);
114 last[rf] = targ->getFileSize(f) - 1;
115 unit[rf] = targ->getFileUnit(f);
116 fill[rf] = -1;
117 assert(last[rf] < MAX_REGISTER_FILE_SIZE);
118 bits[rf].allocate(last[rf] + 1, true);
119 }
120 }
121
122 RegisterSet::RegisterSet(const Target *targ)
123 : restrictedGPR16Range(targ->getChipset() < 0xc0)
124 {
125 init(targ);
126 for (unsigned int i = 0; i <= LAST_REGISTER_FILE; ++i)
127 reset(static_cast<DataFile>(i));
128 }
129
130 void
131 RegisterSet::periodicMask(DataFile f, uint32_t lock, uint32_t unlock)
132 {
133 bits[f].periodicMask32(lock, unlock);
134 }
135
136 void
137 RegisterSet::intersect(DataFile f, const RegisterSet *set)
138 {
139 bits[f] |= set->bits[f];
140 }
141
142 void
143 RegisterSet::print() const
144 {
145 INFO("GPR:");
146 bits[FILE_GPR].print();
147 INFO("\n");
148 }
149
150 bool
151 RegisterSet::assign(int32_t& reg, DataFile f, unsigned int size)
152 {
153 reg = bits[f].findFreeRange(size);
154 if (reg < 0)
155 return false;
156 fill[f] = MAX2(fill[f], (int32_t)(reg + size - 1));
157 return true;
158 }
159
160 bool
161 RegisterSet::isOccupied(DataFile f, int32_t reg, unsigned int size) const
162 {
163 return bits[f].testRange(reg, size);
164 }
165
166 void
167 RegisterSet::occupy(const Value *v)
168 {
169 occupy(v->reg.file, idToUnits(v), v->reg.size >> unit[v->reg.file]);
170 }
171
172 void
173 RegisterSet::occupyMask(DataFile f, int32_t reg, uint8_t mask)
174 {
175 bits[f].setMask(reg & ~31, static_cast<uint32_t>(mask) << (reg % 32));
176 }
177
178 void
179 RegisterSet::occupy(DataFile f, int32_t reg, unsigned int size)
180 {
181 bits[f].setRange(reg, size);
182
183 INFO_DBG(0, REG_ALLOC, "reg occupy: %u[%i] %u\n", f, reg, size);
184
185 fill[f] = MAX2(fill[f], (int32_t)(reg + size - 1));
186 }
187
188 bool
189 RegisterSet::testOccupy(const Value *v)
190 {
191 return testOccupy(v->reg.file,
192 idToUnits(v), v->reg.size >> unit[v->reg.file]);
193 }
194
195 bool
196 RegisterSet::testOccupy(DataFile f, int32_t reg, unsigned int size)
197 {
198 if (isOccupied(f, reg, size))
199 return false;
200 occupy(f, reg, size);
201 return true;
202 }
203
204 void
205 RegisterSet::release(DataFile f, int32_t reg, unsigned int size)
206 {
207 bits[f].clrRange(reg, size);
208
209 INFO_DBG(0, REG_ALLOC, "reg release: %u[%i] %u\n", f, reg, size);
210 }
211
212 class RegAlloc
213 {
214 public:
215 RegAlloc(Program *program) : prog(program), sequence(0) { }
216
217 bool exec();
218 bool execFunc();
219
220 private:
221 class PhiMovesPass : public Pass {
222 private:
223 virtual bool visit(BasicBlock *);
224 inline bool needNewElseBlock(BasicBlock *b, BasicBlock *p);
225 };
226
227 class ArgumentMovesPass : public Pass {
228 private:
229 virtual bool visit(BasicBlock *);
230 };
231
232 class BuildIntervalsPass : public Pass {
233 private:
234 virtual bool visit(BasicBlock *);
235 void collectLiveValues(BasicBlock *);
236 void addLiveRange(Value *, const BasicBlock *, int end);
237 };
238
239 class InsertConstraintsPass : public Pass {
240 public:
241 bool exec(Function *func);
242 private:
243 virtual bool visit(BasicBlock *);
244
245 bool insertConstraintMoves();
246
247 void condenseDefs(Instruction *);
248 void condenseSrcs(Instruction *, const int first, const int last);
249
250 void addHazard(Instruction *i, const ValueRef *src);
251 void textureMask(TexInstruction *);
252 void addConstraint(Instruction *, int s, int n);
253 bool detectConflict(Instruction *, int s);
254
255 // target specific functions, TODO: put in subclass or Target
256 void texConstraintNV50(TexInstruction *);
257 void texConstraintNVC0(TexInstruction *);
258 void texConstraintNVE0(TexInstruction *);
259 void texConstraintGM107(TexInstruction *);
260
261 std::list<Instruction *> constrList;
262
263 const Target *targ;
264 };
265
266 bool buildLiveSets(BasicBlock *);
267
268 private:
269 Program *prog;
270 Function *func;
271
272 // instructions in control flow / chronological order
273 ArrayList insns;
274
275 int sequence; // for manual passes through CFG
276 };
277
278 typedef std::pair<Value *, Value *> ValuePair;
279
280 class SpillCodeInserter
281 {
282 public:
283 SpillCodeInserter(Function *fn) : func(fn), stackSize(0), stackBase(0) { }
284
285 bool run(const std::list<ValuePair>&);
286
287 Symbol *assignSlot(const Interval&, const unsigned int size);
288 Value *offsetSlot(Value *, const LValue *);
289 inline int32_t getStackSize() const { return stackSize; }
290
291 private:
292 Function *func;
293
294 struct SpillSlot
295 {
296 Interval occup;
297 std::list<Value *> residents; // needed to recalculate occup
298 Symbol *sym;
299 int32_t offset;
300 inline uint8_t size() const { return sym->reg.size; }
301 };
302 std::list<SpillSlot> slots;
303 int32_t stackSize;
304 int32_t stackBase;
305
306 LValue *unspill(Instruction *usei, LValue *, Value *slot);
307 void spill(Instruction *defi, Value *slot, LValue *);
308 };
309
310 void
311 RegAlloc::BuildIntervalsPass::addLiveRange(Value *val,
312 const BasicBlock *bb,
313 int end)
314 {
315 Instruction *insn = val->getUniqueInsn();
316
317 if (!insn)
318 insn = bb->getFirst();
319
320 assert(bb->getFirst()->serial <= bb->getExit()->serial);
321 assert(bb->getExit()->serial + 1 >= end);
322
323 int begin = insn->serial;
324 if (begin < bb->getEntry()->serial || begin > bb->getExit()->serial)
325 begin = bb->getEntry()->serial;
326
327 INFO_DBG(prog->dbgFlags, REG_ALLOC, "%%%i <- live range [%i(%i), %i)\n",
328 val->id, begin, insn->serial, end);
329
330 if (begin != end) // empty ranges are only added as hazards for fixed regs
331 val->livei.extend(begin, end);
332 }
333
334 bool
335 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock *b, BasicBlock *p)
336 {
337 if (b->cfg.incidentCount() <= 1)
338 return false;
339
340 int n = 0;
341 for (Graph::EdgeIterator ei = p->cfg.outgoing(); !ei.end(); ei.next())
342 if (ei.getType() == Graph::Edge::TREE ||
343 ei.getType() == Graph::Edge::FORWARD)
344 ++n;
345 return (n == 2);
346 }
347
348 // For each operand of each PHI in b, generate a new value by inserting a MOV
349 // at the end of the block it is coming from and replace the operand with its
350 // result. This eliminates liveness conflicts and enables us to let values be
351 // copied to the right register if such a conflict exists nonetheless.
352 //
353 // These MOVs are also crucial in making sure the live intervals of phi srces
354 // are extended until the end of the loop, since they are not included in the
355 // live-in sets.
356 bool
357 RegAlloc::PhiMovesPass::visit(BasicBlock *bb)
358 {
359 Instruction *phi, *mov;
360 BasicBlock *pb, *pn;
361
362 std::stack<BasicBlock *> stack;
363
364 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
365 pb = BasicBlock::get(ei.getNode());
366 assert(pb);
367 if (needNewElseBlock(bb, pb))
368 stack.push(pb);
369 }
370 while (!stack.empty()) {
371 pb = stack.top();
372 pn = new BasicBlock(func);
373 stack.pop();
374
375 pb->cfg.detach(&bb->cfg);
376 pb->cfg.attach(&pn->cfg, Graph::Edge::TREE);
377 pn->cfg.attach(&bb->cfg, Graph::Edge::FORWARD);
378
379 assert(pb->getExit()->op != OP_CALL);
380 if (pb->getExit()->asFlow()->target.bb == bb)
381 pb->getExit()->asFlow()->target.bb = pn;
382 }
383
384 // insert MOVs (phi->src(j) should stem from j-th in-BB)
385 int j = 0;
386 for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {
387 pb = BasicBlock::get(ei.getNode());
388 if (!pb->isTerminated())
389 pb->insertTail(new_FlowInstruction(func, OP_BRA, bb));
390
391 for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next) {
392 mov = new_Instruction(func, OP_MOV, TYPE_U32);
393
394 mov->setSrc(0, phi->getSrc(j));
395 mov->setDef(0, new_LValue(func, phi->getDef(0)->asLValue()));
396 phi->setSrc(j, mov->getDef(0));
397
398 pb->insertBefore(pb->getExit(), mov);
399 }
400 ++j;
401 }
402
403 return true;
404 }
405
406 bool
407 RegAlloc::ArgumentMovesPass::visit(BasicBlock *bb)
408 {
409 // Bind function call inputs/outputs to the same physical register
410 // the callee uses, inserting moves as appropriate for the case a
411 // conflict arises.
412 for (Instruction *i = bb->getEntry(); i; i = i->next) {
413 FlowInstruction *cal = i->asFlow();
414 // TODO: Handle indirect calls.
415 // Right now they should only be generated for builtins.
416 if (!cal || cal->op != OP_CALL || cal->builtin || cal->indirect)
417 continue;
418 RegisterSet clobberSet(prog->getTarget());
419
420 // Bind input values.
421 for (int s = cal->indirect ? 1 : 0; cal->srcExists(s); ++s) {
422 const int t = cal->indirect ? (s - 1) : s;
423 LValue *tmp = new_LValue(func, cal->getSrc(s)->asLValue());
424 tmp->reg.data.id = cal->target.fn->ins[t].rep()->reg.data.id;
425
426 Instruction *mov =
427 new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));
428 mov->setDef(0, tmp);
429 mov->setSrc(0, cal->getSrc(s));
430 cal->setSrc(s, tmp);
431
432 bb->insertBefore(cal, mov);
433 }
434
435 // Bind output values.
436 for (int d = 0; cal->defExists(d); ++d) {
437 LValue *tmp = new_LValue(func, cal->getDef(d)->asLValue());
438 tmp->reg.data.id = cal->target.fn->outs[d].rep()->reg.data.id;
439
440 Instruction *mov =
441 new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));
442 mov->setSrc(0, tmp);
443 mov->setDef(0, cal->getDef(d));
444 cal->setDef(d, tmp);
445
446 bb->insertAfter(cal, mov);
447 clobberSet.occupy(tmp);
448 }
449
450 // Bind clobbered values.
451 for (std::deque<Value *>::iterator it = cal->target.fn->clobbers.begin();
452 it != cal->target.fn->clobbers.end();
453 ++it) {
454 if (clobberSet.testOccupy(*it)) {
455 Value *tmp = new_LValue(func, (*it)->asLValue());
456 tmp->reg.data.id = (*it)->reg.data.id;
457 cal->setDef(cal->defCount(), tmp);
458 }
459 }
460 }
461
462 // Update the clobber set of the function.
463 if (BasicBlock::get(func->cfgExit) == bb) {
464 func->buildDefSets();
465 for (unsigned int i = 0; i < bb->defSet.getSize(); ++i)
466 if (bb->defSet.test(i))
467 func->clobbers.push_back(func->getLValue(i));
468 }
469
470 return true;
471 }
472
473 // Build the set of live-in variables of bb.
474 bool
475 RegAlloc::buildLiveSets(BasicBlock *bb)
476 {
477 Function *f = bb->getFunction();
478 BasicBlock *bn;
479 Instruction *i;
480 unsigned int s, d;
481
482 INFO_DBG(prog->dbgFlags, REG_ALLOC, "buildLiveSets(BB:%i)\n", bb->getId());
483
484 bb->liveSet.allocate(func->allLValues.getSize(), false);
485
486 int n = 0;
487 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
488 bn = BasicBlock::get(ei.getNode());
489 if (bn == bb)
490 continue;
491 if (bn->cfg.visit(sequence))
492 if (!buildLiveSets(bn))
493 return false;
494 if (n++ || bb->liveSet.marker)
495 bb->liveSet |= bn->liveSet;
496 else
497 bb->liveSet = bn->liveSet;
498 }
499 if (!n && !bb->liveSet.marker)
500 bb->liveSet.fill(0);
501 bb->liveSet.marker = true;
502
503 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
504 INFO("BB:%i live set of out blocks:\n", bb->getId());
505 bb->liveSet.print();
506 }
507
508 // if (!bb->getEntry())
509 // return true;
510
511 if (bb == BasicBlock::get(f->cfgExit)) {
512 for (std::deque<ValueRef>::iterator it = f->outs.begin();
513 it != f->outs.end(); ++it) {
514 assert(it->get()->asLValue());
515 bb->liveSet.set(it->get()->id);
516 }
517 }
518
519 for (i = bb->getExit(); i && i != bb->getEntry()->prev; i = i->prev) {
520 for (d = 0; i->defExists(d); ++d)
521 bb->liveSet.clr(i->getDef(d)->id);
522 for (s = 0; i->srcExists(s); ++s)
523 if (i->getSrc(s)->asLValue())
524 bb->liveSet.set(i->getSrc(s)->id);
525 }
526 for (i = bb->getPhi(); i && i->op == OP_PHI; i = i->next)
527 bb->liveSet.clr(i->getDef(0)->id);
528
529 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
530 INFO("BB:%i live set after propagation:\n", bb->getId());
531 bb->liveSet.print();
532 }
533
534 return true;
535 }
536
537 void
538 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock *bb)
539 {
540 BasicBlock *bbA = NULL, *bbB = NULL;
541
542 if (bb->cfg.outgoingCount()) {
543 // trickery to save a loop of OR'ing liveSets
544 // aliasing works fine with BitSet::setOr
545 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
546 if (ei.getType() == Graph::Edge::DUMMY)
547 continue;
548 if (bbA) {
549 bb->liveSet.setOr(&bbA->liveSet, &bbB->liveSet);
550 bbA = bb;
551 } else {
552 bbA = bbB;
553 }
554 bbB = BasicBlock::get(ei.getNode());
555 }
556 bb->liveSet.setOr(&bbB->liveSet, bbA ? &bbA->liveSet : NULL);
557 } else
558 if (bb->cfg.incidentCount()) {
559 bb->liveSet.fill(0);
560 }
561 }
562
563 bool
564 RegAlloc::BuildIntervalsPass::visit(BasicBlock *bb)
565 {
566 collectLiveValues(bb);
567
568 INFO_DBG(prog->dbgFlags, REG_ALLOC, "BuildIntervals(BB:%i)\n", bb->getId());
569
570 // go through out blocks and delete phi sources that do not originate from
571 // the current block from the live set
572 for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {
573 BasicBlock *out = BasicBlock::get(ei.getNode());
574
575 for (Instruction *i = out->getPhi(); i && i->op == OP_PHI; i = i->next) {
576 bb->liveSet.clr(i->getDef(0)->id);
577
578 for (int s = 0; i->srcExists(s); ++s) {
579 assert(i->src(s).getInsn());
580 if (i->getSrc(s)->getUniqueInsn()->bb == bb) // XXX: reachableBy ?
581 bb->liveSet.set(i->getSrc(s)->id);
582 else
583 bb->liveSet.clr(i->getSrc(s)->id);
584 }
585 }
586 }
587
588 // remaining live-outs are live until end
589 if (bb->getExit()) {
590 for (unsigned int j = 0; j < bb->liveSet.getSize(); ++j)
591 if (bb->liveSet.test(j))
592 addLiveRange(func->getLValue(j), bb, bb->getExit()->serial + 1);
593 }
594
595 for (Instruction *i = bb->getExit(); i && i->op != OP_PHI; i = i->prev) {
596 for (int d = 0; i->defExists(d); ++d) {
597 bb->liveSet.clr(i->getDef(d)->id);
598 if (i->getDef(d)->reg.data.id >= 0) // add hazard for fixed regs
599 i->getDef(d)->livei.extend(i->serial, i->serial);
600 }
601
602 for (int s = 0; i->srcExists(s); ++s) {
603 if (!i->getSrc(s)->asLValue())
604 continue;
605 if (!bb->liveSet.test(i->getSrc(s)->id)) {
606 bb->liveSet.set(i->getSrc(s)->id);
607 addLiveRange(i->getSrc(s), bb, i->serial);
608 }
609 }
610 }
611
612 if (bb == BasicBlock::get(func->cfg.getRoot())) {
613 for (std::deque<ValueDef>::iterator it = func->ins.begin();
614 it != func->ins.end(); ++it) {
615 if (it->get()->reg.data.id >= 0) // add hazard for fixed regs
616 it->get()->livei.extend(0, 1);
617 }
618 }
619
620 return true;
621 }
622
623
624 #define JOIN_MASK_PHI (1 << 0)
625 #define JOIN_MASK_UNION (1 << 1)
626 #define JOIN_MASK_MOV (1 << 2)
627 #define JOIN_MASK_TEX (1 << 3)
628
629 class GCRA
630 {
631 public:
632 GCRA(Function *, SpillCodeInserter&);
633 ~GCRA();
634
635 bool allocateRegisters(ArrayList& insns);
636
637 void printNodeInfo() const;
638
639 private:
640 class RIG_Node : public Graph::Node
641 {
642 public:
643 RIG_Node();
644
645 void init(const RegisterSet&, LValue *);
646
647 void addInterference(RIG_Node *);
648 void addRegPreference(RIG_Node *);
649
650 inline LValue *getValue() const
651 {
652 return reinterpret_cast<LValue *>(data);
653 }
654 inline void setValue(LValue *lval) { data = lval; }
655
656 inline uint8_t getCompMask() const
657 {
658 return ((1 << colors) - 1) << (reg & 7);
659 }
660
661 static inline RIG_Node *get(const Graph::EdgeIterator& ei)
662 {
663 return static_cast<RIG_Node *>(ei.getNode());
664 }
665
666 public:
667 uint32_t degree;
668 uint16_t degreeLimit; // if deg < degLimit, node is trivially colourable
669 uint16_t colors;
670
671 DataFile f;
672 int32_t reg;
673
674 float weight;
675
676 // list pointers for simplify() phase
677 RIG_Node *next;
678 RIG_Node *prev;
679
680 // union of the live intervals of all coalesced values (we want to retain
681 // the separate intervals for testing interference of compound values)
682 Interval livei;
683
684 std::list<RIG_Node *> prefRegs;
685 };
686
687 private:
688 inline RIG_Node *getNode(const LValue *v) const { return &nodes[v->id]; }
689
690 void buildRIG(ArrayList&);
691 bool coalesce(ArrayList&);
692 bool doCoalesce(ArrayList&, unsigned int mask);
693 void calculateSpillWeights();
694 void simplify();
695 bool selectRegisters();
696 void cleanup(const bool success);
697
698 void simplifyEdge(RIG_Node *, RIG_Node *);
699 void simplifyNode(RIG_Node *);
700
701 bool coalesceValues(Value *, Value *, bool force);
702 void resolveSplitsAndMerges();
703 void makeCompound(Instruction *, bool isSplit);
704
705 inline void checkInterference(const RIG_Node *, Graph::EdgeIterator&);
706
707 inline void insertOrderedTail(std::list<RIG_Node *>&, RIG_Node *);
708 void checkList(std::list<RIG_Node *>&);
709
710 private:
711 std::stack<uint32_t> stack;
712
713 // list headers for simplify() phase
714 RIG_Node lo[2];
715 RIG_Node hi;
716
717 Graph RIG;
718 RIG_Node *nodes;
719 unsigned int nodeCount;
720
721 Function *func;
722 Program *prog;
723
724 static uint8_t relDegree[17][17];
725
726 RegisterSet regs;
727
728 // need to fixup register id for participants of OP_MERGE/SPLIT
729 std::list<Instruction *> merges;
730 std::list<Instruction *> splits;
731
732 SpillCodeInserter& spill;
733 std::list<ValuePair> mustSpill;
734 };
735
736 uint8_t GCRA::relDegree[17][17];
737
738 GCRA::RIG_Node::RIG_Node() : Node(NULL), next(this), prev(this)
739 {
740 colors = 0;
741 }
742
743 void
744 GCRA::printNodeInfo() const
745 {
746 for (unsigned int i = 0; i < nodeCount; ++i) {
747 if (!nodes[i].colors)
748 continue;
749 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
750 i,
751 nodes[i].f,nodes[i].reg,nodes[i].colors,
752 nodes[i].weight,
753 nodes[i].degree, nodes[i].degreeLimit);
754
755 for (Graph::EdgeIterator ei = nodes[i].outgoing(); !ei.end(); ei.next())
756 INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);
757 for (Graph::EdgeIterator ei = nodes[i].incident(); !ei.end(); ei.next())
758 INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);
759 INFO("\n");
760 }
761 }
762
763 void
764 GCRA::RIG_Node::init(const RegisterSet& regs, LValue *lval)
765 {
766 setValue(lval);
767 if (lval->reg.data.id >= 0)
768 lval->noSpill = lval->fixedReg = 1;
769
770 colors = regs.units(lval->reg.file, lval->reg.size);
771 f = lval->reg.file;
772 reg = -1;
773 if (lval->reg.data.id >= 0)
774 reg = regs.idToUnits(lval);
775
776 weight = std::numeric_limits<float>::infinity();
777 degree = 0;
778 degreeLimit = regs.getFileSize(f, lval->reg.size);
779 degreeLimit -= relDegree[1][colors] - 1;
780
781 livei.insert(lval->livei);
782 }
783
784 bool
785 GCRA::coalesceValues(Value *dst, Value *src, bool force)
786 {
787 LValue *rep = dst->join->asLValue();
788 LValue *val = src->join->asLValue();
789
790 if (!force && val->reg.data.id >= 0) {
791 rep = src->join->asLValue();
792 val = dst->join->asLValue();
793 }
794 RIG_Node *nRep = &nodes[rep->id];
795 RIG_Node *nVal = &nodes[val->id];
796
797 if (src->reg.file != dst->reg.file) {
798 if (!force)
799 return false;
800 WARN("forced coalescing of values in different files !\n");
801 }
802 if (!force && dst->reg.size != src->reg.size)
803 return false;
804
805 if ((rep->reg.data.id >= 0) && (rep->reg.data.id != val->reg.data.id)) {
806 if (force) {
807 if (val->reg.data.id >= 0)
808 WARN("forced coalescing of values in different fixed regs !\n");
809 } else {
810 if (val->reg.data.id >= 0)
811 return false;
812 // make sure that there is no overlap with the fixed register of rep
813 for (ArrayList::Iterator it = func->allLValues.iterator();
814 !it.end(); it.next()) {
815 Value *reg = reinterpret_cast<Value *>(it.get())->asLValue();
816 assert(reg);
817 if (reg->interfers(rep) && reg->livei.overlaps(nVal->livei))
818 return false;
819 }
820 }
821 }
822
823 if (!force && nRep->livei.overlaps(nVal->livei))
824 return false;
825
826 INFO_DBG(prog->dbgFlags, REG_ALLOC, "joining %%%i($%i) <- %%%i\n",
827 rep->id, rep->reg.data.id, val->id);
828
829 // set join pointer of all values joined with val
830 for (Value::DefIterator def = val->defs.begin(); def != val->defs.end();
831 ++def)
832 (*def)->get()->join = rep;
833 assert(rep->join == rep && val->join == rep);
834
835 // add val's definitions to rep and extend the live interval of its RIG node
836 rep->defs.insert(rep->defs.end(), val->defs.begin(), val->defs.end());
837 nRep->livei.unify(nVal->livei);
838 return true;
839 }
840
841 bool
842 GCRA::coalesce(ArrayList& insns)
843 {
844 bool ret = doCoalesce(insns, JOIN_MASK_PHI);
845 if (!ret)
846 return false;
847 switch (func->getProgram()->getTarget()->getChipset() & ~0xf) {
848 case 0x50:
849 case 0x80:
850 case 0x90:
851 case 0xa0:
852 ret = doCoalesce(insns, JOIN_MASK_UNION | JOIN_MASK_TEX);
853 break;
854 case 0xc0:
855 case 0xd0:
856 case 0xe0:
857 case 0xf0:
858 case 0x100:
859 case 0x110:
860 ret = doCoalesce(insns, JOIN_MASK_UNION);
861 break;
862 default:
863 break;
864 }
865 if (!ret)
866 return false;
867 return doCoalesce(insns, JOIN_MASK_MOV);
868 }
869
870 static inline uint8_t makeCompMask(int compSize, int base, int size)
871 {
872 uint8_t m = ((1 << size) - 1) << base;
873
874 switch (compSize) {
875 case 1:
876 return 0xff;
877 case 2:
878 m |= (m << 2);
879 return (m << 4) | m;
880 case 3:
881 case 4:
882 return (m << 4) | m;
883 default:
884 assert(compSize <= 8);
885 return m;
886 }
887 }
888
889 // Used when coalescing moves. The non-compound value will become one, e.g.:
890 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
891 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
892 static inline void copyCompound(Value *dst, Value *src)
893 {
894 LValue *ldst = dst->asLValue();
895 LValue *lsrc = src->asLValue();
896
897 if (ldst->compound && !lsrc->compound) {
898 LValue *swap = lsrc;
899 lsrc = ldst;
900 ldst = swap;
901 }
902
903 ldst->compound = lsrc->compound;
904 ldst->compMask = lsrc->compMask;
905 }
906
907 void
908 GCRA::makeCompound(Instruction *insn, bool split)
909 {
910 LValue *rep = (split ? insn->getSrc(0) : insn->getDef(0))->asLValue();
911
912 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {
913 INFO("makeCompound(split = %i): ", split);
914 insn->print();
915 }
916
917 const unsigned int size = getNode(rep)->colors;
918 unsigned int base = 0;
919
920 if (!rep->compound)
921 rep->compMask = 0xff;
922 rep->compound = 1;
923
924 for (int c = 0; split ? insn->defExists(c) : insn->srcExists(c); ++c) {
925 LValue *val = (split ? insn->getDef(c) : insn->getSrc(c))->asLValue();
926
927 val->compound = 1;
928 if (!val->compMask)
929 val->compMask = 0xff;
930 val->compMask &= makeCompMask(size, base, getNode(val)->colors);
931 assert(val->compMask);
932
933 INFO_DBG(prog->dbgFlags, REG_ALLOC, "compound: %%%i:%02x <- %%%i:%02x\n",
934 rep->id, rep->compMask, val->id, val->compMask);
935
936 base += getNode(val)->colors;
937 }
938 assert(base == size);
939 }
940
941 bool
942 GCRA::doCoalesce(ArrayList& insns, unsigned int mask)
943 {
944 int c, n;
945
946 for (n = 0; n < insns.getSize(); ++n) {
947 Instruction *i;
948 Instruction *insn = reinterpret_cast<Instruction *>(insns.get(n));
949
950 switch (insn->op) {
951 case OP_PHI:
952 if (!(mask & JOIN_MASK_PHI))
953 break;
954 for (c = 0; insn->srcExists(c); ++c)
955 if (!coalesceValues(insn->getDef(0), insn->getSrc(c), false)) {
956 // this is bad
957 ERROR("failed to coalesce phi operands\n");
958 return false;
959 }
960 break;
961 case OP_UNION:
962 case OP_MERGE:
963 if (!(mask & JOIN_MASK_UNION))
964 break;
965 for (c = 0; insn->srcExists(c); ++c)
966 coalesceValues(insn->getDef(0), insn->getSrc(c), true);
967 if (insn->op == OP_MERGE) {
968 merges.push_back(insn);
969 if (insn->srcExists(1))
970 makeCompound(insn, false);
971 }
972 break;
973 case OP_SPLIT:
974 if (!(mask & JOIN_MASK_UNION))
975 break;
976 splits.push_back(insn);
977 for (c = 0; insn->defExists(c); ++c)
978 coalesceValues(insn->getSrc(0), insn->getDef(c), true);
979 makeCompound(insn, true);
980 break;
981 case OP_MOV:
982 if (!(mask & JOIN_MASK_MOV))
983 break;
984 i = NULL;
985 if (!insn->getDef(0)->uses.empty())
986 i = (*insn->getDef(0)->uses.begin())->getInsn();
987 // if this is a contraint-move there will only be a single use
988 if (i && i->op == OP_MERGE) // do we really still need this ?
989 break;
990 i = insn->getSrc(0)->getUniqueInsn();
991 if (i && !i->constrainedDefs()) {
992 if (coalesceValues(insn->getDef(0), insn->getSrc(0), false))
993 copyCompound(insn->getSrc(0), insn->getDef(0));
994 }
995 break;
996 case OP_TEX:
997 case OP_TXB:
998 case OP_TXL:
999 case OP_TXF:
1000 case OP_TXQ:
1001 case OP_TXD:
1002 case OP_TXG:
1003 case OP_TXLQ:
1004 case OP_TEXCSAA:
1005 case OP_TEXPREP:
1006 if (!(mask & JOIN_MASK_TEX))
1007 break;
1008 for (c = 0; insn->srcExists(c) && c != insn->predSrc; ++c)
1009 coalesceValues(insn->getDef(c), insn->getSrc(c), true);
1010 break;
1011 default:
1012 break;
1013 }
1014 }
1015 return true;
1016 }
1017
1018 void
1019 GCRA::RIG_Node::addInterference(RIG_Node *node)
1020 {
1021 this->degree += relDegree[node->colors][colors];
1022 node->degree += relDegree[colors][node->colors];
1023
1024 this->attach(node, Graph::Edge::CROSS);
1025 }
1026
1027 void
1028 GCRA::RIG_Node::addRegPreference(RIG_Node *node)
1029 {
1030 prefRegs.push_back(node);
1031 }
1032
1033 GCRA::GCRA(Function *fn, SpillCodeInserter& spill) :
1034 func(fn),
1035 regs(fn->getProgram()->getTarget()),
1036 spill(spill)
1037 {
1038 prog = func->getProgram();
1039
1040 // initialize relative degrees array - i takes away from j
1041 for (int i = 1; i <= 16; ++i)
1042 for (int j = 1; j <= 16; ++j)
1043 relDegree[i][j] = j * ((i + j - 1) / j);
1044 }
1045
1046 GCRA::~GCRA()
1047 {
1048 if (nodes)
1049 delete[] nodes;
1050 }
1051
1052 void
1053 GCRA::checkList(std::list<RIG_Node *>& lst)
1054 {
1055 GCRA::RIG_Node *prev = NULL;
1056
1057 for (std::list<RIG_Node *>::iterator it = lst.begin();
1058 it != lst.end();
1059 ++it) {
1060 assert((*it)->getValue()->join == (*it)->getValue());
1061 if (prev)
1062 assert(prev->livei.begin() <= (*it)->livei.begin());
1063 prev = *it;
1064 }
1065 }
1066
1067 void
1068 GCRA::insertOrderedTail(std::list<RIG_Node *>& list, RIG_Node *node)
1069 {
1070 if (node->livei.isEmpty())
1071 return;
1072 // only the intervals of joined values don't necessarily arrive in order
1073 std::list<RIG_Node *>::iterator prev, it;
1074 for (it = list.end(); it != list.begin(); it = prev) {
1075 prev = it;
1076 --prev;
1077 if ((*prev)->livei.begin() <= node->livei.begin())
1078 break;
1079 }
1080 list.insert(it, node);
1081 }
1082
1083 void
1084 GCRA::buildRIG(ArrayList& insns)
1085 {
1086 std::list<RIG_Node *> values, active;
1087
1088 for (std::deque<ValueDef>::iterator it = func->ins.begin();
1089 it != func->ins.end(); ++it)
1090 insertOrderedTail(values, getNode(it->get()->asLValue()));
1091
1092 for (int i = 0; i < insns.getSize(); ++i) {
1093 Instruction *insn = reinterpret_cast<Instruction *>(insns.get(i));
1094 for (int d = 0; insn->defExists(d); ++d)
1095 if (insn->getDef(d)->rep() == insn->getDef(d))
1096 insertOrderedTail(values, getNode(insn->getDef(d)->asLValue()));
1097 }
1098 checkList(values);
1099
1100 while (!values.empty()) {
1101 RIG_Node *cur = values.front();
1102
1103 for (std::list<RIG_Node *>::iterator it = active.begin();
1104 it != active.end();) {
1105 RIG_Node *node = *it;
1106
1107 if (node->livei.end() <= cur->livei.begin()) {
1108 it = active.erase(it);
1109 } else {
1110 if (node->f == cur->f && node->livei.overlaps(cur->livei))
1111 cur->addInterference(node);
1112 ++it;
1113 }
1114 }
1115 values.pop_front();
1116 active.push_back(cur);
1117 }
1118 }
1119
1120 void
1121 GCRA::calculateSpillWeights()
1122 {
1123 for (unsigned int i = 0; i < nodeCount; ++i) {
1124 RIG_Node *const n = &nodes[i];
1125 if (!nodes[i].colors || nodes[i].livei.isEmpty())
1126 continue;
1127 if (nodes[i].reg >= 0) {
1128 // update max reg
1129 regs.occupy(n->f, n->reg, n->colors);
1130 continue;
1131 }
1132 LValue *val = nodes[i].getValue();
1133
1134 if (!val->noSpill) {
1135 int rc = 0;
1136 for (Value::DefIterator it = val->defs.begin();
1137 it != val->defs.end();
1138 ++it)
1139 rc += (*it)->get()->refCount();
1140
1141 nodes[i].weight =
1142 (float)rc * (float)rc / (float)nodes[i].livei.extent();
1143 }
1144
1145 if (nodes[i].degree < nodes[i].degreeLimit) {
1146 int l = 0;
1147 if (val->reg.size > 4)
1148 l = 1;
1149 DLLIST_ADDHEAD(&lo[l], &nodes[i]);
1150 } else {
1151 DLLIST_ADDHEAD(&hi, &nodes[i]);
1152 }
1153 }
1154 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1155 printNodeInfo();
1156 }
1157
1158 void
1159 GCRA::simplifyEdge(RIG_Node *a, RIG_Node *b)
1160 {
1161 bool move = b->degree >= b->degreeLimit;
1162
1163 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1164 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1165 a->getValue()->id, a->degree, a->degreeLimit,
1166 b->getValue()->id, b->degree, b->degreeLimit);
1167
1168 b->degree -= relDegree[a->colors][b->colors];
1169
1170 move = move && b->degree < b->degreeLimit;
1171 if (move && !DLLIST_EMPTY(b)) {
1172 int l = (b->getValue()->reg.size > 4) ? 1 : 0;
1173 DLLIST_DEL(b);
1174 DLLIST_ADDTAIL(&lo[l], b);
1175 }
1176 }
1177
1178 void
1179 GCRA::simplifyNode(RIG_Node *node)
1180 {
1181 for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())
1182 simplifyEdge(node, RIG_Node::get(ei));
1183
1184 for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())
1185 simplifyEdge(node, RIG_Node::get(ei));
1186
1187 DLLIST_DEL(node);
1188 stack.push(node->getValue()->id);
1189
1190 INFO_DBG(prog->dbgFlags, REG_ALLOC, "SIMPLIFY: pushed %%%i%s\n",
1191 node->getValue()->id,
1192 (node->degree < node->degreeLimit) ? "" : "(spill)");
1193 }
1194
1195 void
1196 GCRA::simplify()
1197 {
1198 for (;;) {
1199 if (!DLLIST_EMPTY(&lo[0])) {
1200 do {
1201 simplifyNode(lo[0].next);
1202 } while (!DLLIST_EMPTY(&lo[0]));
1203 } else
1204 if (!DLLIST_EMPTY(&lo[1])) {
1205 simplifyNode(lo[1].next);
1206 } else
1207 if (!DLLIST_EMPTY(&hi)) {
1208 RIG_Node *best = hi.next;
1209 float bestScore = best->weight / (float)best->degree;
1210 // spill candidate
1211 for (RIG_Node *it = best->next; it != &hi; it = it->next) {
1212 float score = it->weight / (float)it->degree;
1213 if (score < bestScore) {
1214 best = it;
1215 bestScore = score;
1216 }
1217 }
1218 if (isinf(bestScore)) {
1219 ERROR("no viable spill candidates left\n");
1220 break;
1221 }
1222 simplifyNode(best);
1223 } else {
1224 break;
1225 }
1226 }
1227 }
1228
1229 void
1230 GCRA::checkInterference(const RIG_Node *node, Graph::EdgeIterator& ei)
1231 {
1232 const RIG_Node *intf = RIG_Node::get(ei);
1233
1234 if (intf->reg < 0)
1235 return;
1236 const LValue *vA = node->getValue();
1237 const LValue *vB = intf->getValue();
1238
1239 const uint8_t intfMask = ((1 << intf->colors) - 1) << (intf->reg & 7);
1240
1241 if (vA->compound | vB->compound) {
1242 // NOTE: this only works for >aligned< register tuples !
1243 for (Value::DefCIterator D = vA->defs.begin(); D != vA->defs.end(); ++D) {
1244 for (Value::DefCIterator d = vB->defs.begin(); d != vB->defs.end(); ++d) {
1245 const LValue *vD = (*D)->get()->asLValue();
1246 const LValue *vd = (*d)->get()->asLValue();
1247
1248 if (!vD->livei.overlaps(vd->livei)) {
1249 INFO_DBG(prog->dbgFlags, REG_ALLOC, "(%%%i) X (%%%i): no overlap\n",
1250 vD->id, vd->id);
1251 continue;
1252 }
1253
1254 uint8_t mask = vD->compound ? vD->compMask : ~0;
1255 if (vd->compound) {
1256 assert(vB->compound);
1257 mask &= vd->compMask & vB->compMask;
1258 } else {
1259 mask &= intfMask;
1260 }
1261
1262 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1263 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1264 vD->id,
1265 vD->compound ? vD->compMask : 0xff,
1266 vd->id,
1267 vd->compound ? vd->compMask : intfMask,
1268 vB->compMask, intf->reg & ~7, mask);
1269 if (mask)
1270 regs.occupyMask(node->f, intf->reg & ~7, mask);
1271 }
1272 }
1273 } else {
1274 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1275 "(%%%i) X (%%%i): $r%i + %u\n",
1276 vA->id, vB->id, intf->reg, intf->colors);
1277 regs.occupy(node->f, intf->reg, intf->colors);
1278 }
1279 }
1280
1281 bool
1282 GCRA::selectRegisters()
1283 {
1284 INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nSELECT phase\n");
1285
1286 while (!stack.empty()) {
1287 RIG_Node *node = &nodes[stack.top()];
1288 stack.pop();
1289
1290 regs.reset(node->f);
1291
1292 INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nNODE[%%%i, %u colors]\n",
1293 node->getValue()->id, node->colors);
1294
1295 for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())
1296 checkInterference(node, ei);
1297 for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())
1298 checkInterference(node, ei);
1299
1300 if (!node->prefRegs.empty()) {
1301 for (std::list<RIG_Node *>::const_iterator it = node->prefRegs.begin();
1302 it != node->prefRegs.end();
1303 ++it) {
1304 if ((*it)->reg >= 0 &&
1305 regs.testOccupy(node->f, (*it)->reg, node->colors)) {
1306 node->reg = (*it)->reg;
1307 break;
1308 }
1309 }
1310 }
1311 if (node->reg >= 0)
1312 continue;
1313 LValue *lval = node->getValue();
1314 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1315 regs.print();
1316 bool ret = regs.assign(node->reg, node->f, node->colors);
1317 if (ret) {
1318 INFO_DBG(prog->dbgFlags, REG_ALLOC, "assigned reg %i\n", node->reg);
1319 lval->compMask = node->getCompMask();
1320 } else {
1321 INFO_DBG(prog->dbgFlags, REG_ALLOC, "must spill: %%%i (size %u)\n",
1322 lval->id, lval->reg.size);
1323 Symbol *slot = NULL;
1324 if (lval->reg.file == FILE_GPR)
1325 slot = spill.assignSlot(node->livei, lval->reg.size);
1326 mustSpill.push_back(ValuePair(lval, slot));
1327 }
1328 }
1329 if (!mustSpill.empty())
1330 return false;
1331 for (unsigned int i = 0; i < nodeCount; ++i) {
1332 LValue *lval = nodes[i].getValue();
1333 if (nodes[i].reg >= 0 && nodes[i].colors > 0)
1334 lval->reg.data.id =
1335 regs.unitsToId(nodes[i].f, nodes[i].reg, lval->reg.size);
1336 }
1337 return true;
1338 }
1339
1340 bool
1341 GCRA::allocateRegisters(ArrayList& insns)
1342 {
1343 bool ret;
1344
1345 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1346 "allocateRegisters to %u instructions\n", insns.getSize());
1347
1348 nodeCount = func->allLValues.getSize();
1349 nodes = new RIG_Node[nodeCount];
1350 if (!nodes)
1351 return false;
1352 for (unsigned int i = 0; i < nodeCount; ++i) {
1353 LValue *lval = reinterpret_cast<LValue *>(func->allLValues.get(i));
1354 if (lval) {
1355 nodes[i].init(regs, lval);
1356 RIG.insert(&nodes[i]);
1357 }
1358 }
1359
1360 // coalesce first, we use only 1 RIG node for a group of joined values
1361 ret = coalesce(insns);
1362 if (!ret)
1363 goto out;
1364
1365 if (func->getProgram()->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1366 func->printLiveIntervals();
1367
1368 buildRIG(insns);
1369 calculateSpillWeights();
1370 simplify();
1371
1372 ret = selectRegisters();
1373 if (!ret) {
1374 INFO_DBG(prog->dbgFlags, REG_ALLOC,
1375 "selectRegisters failed, inserting spill code ...\n");
1376 regs.reset(FILE_GPR, true);
1377 spill.run(mustSpill);
1378 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1379 func->print();
1380 } else {
1381 prog->maxGPR = std::max(prog->maxGPR, regs.getMaxAssigned(FILE_GPR));
1382 }
1383
1384 out:
1385 cleanup(ret);
1386 return ret;
1387 }
1388
1389 void
1390 GCRA::cleanup(const bool success)
1391 {
1392 mustSpill.clear();
1393
1394 for (ArrayList::Iterator it = func->allLValues.iterator();
1395 !it.end(); it.next()) {
1396 LValue *lval = reinterpret_cast<LValue *>(it.get());
1397
1398 lval->livei.clear();
1399
1400 lval->compound = 0;
1401 lval->compMask = 0;
1402
1403 if (lval->join == lval)
1404 continue;
1405
1406 if (success) {
1407 lval->reg.data.id = lval->join->reg.data.id;
1408 } else {
1409 for (Value::DefIterator d = lval->defs.begin(); d != lval->defs.end();
1410 ++d)
1411 lval->join->defs.remove(*d);
1412 lval->join = lval;
1413 }
1414 }
1415
1416 if (success)
1417 resolveSplitsAndMerges();
1418 splits.clear(); // avoid duplicate entries on next coalesce pass
1419 merges.clear();
1420
1421 delete[] nodes;
1422 nodes = NULL;
1423 }
1424
1425 Symbol *
1426 SpillCodeInserter::assignSlot(const Interval &livei, const unsigned int size)
1427 {
1428 SpillSlot slot;
1429 int32_t offsetBase = stackSize;
1430 int32_t offset;
1431 std::list<SpillSlot>::iterator pos = slots.end(), it = slots.begin();
1432
1433 if (offsetBase % size)
1434 offsetBase += size - (offsetBase % size);
1435
1436 slot.sym = NULL;
1437
1438 for (offset = offsetBase; offset < stackSize; offset += size) {
1439 const int32_t entryEnd = offset + size;
1440 while (it != slots.end() && it->offset < offset)
1441 ++it;
1442 if (it == slots.end()) // no slots left
1443 break;
1444 std::list<SpillSlot>::iterator bgn = it;
1445
1446 while (it != slots.end() && it->offset < entryEnd) {
1447 it->occup.print();
1448 if (it->occup.overlaps(livei))
1449 break;
1450 ++it;
1451 }
1452 if (it == slots.end() || it->offset >= entryEnd) {
1453 // fits
1454 for (; bgn != slots.end() && bgn->offset < entryEnd; ++bgn) {
1455 bgn->occup.insert(livei);
1456 if (bgn->size() == size)
1457 slot.sym = bgn->sym;
1458 }
1459 break;
1460 }
1461 }
1462 if (!slot.sym) {
1463 stackSize = offset + size;
1464 slot.offset = offset;
1465 slot.sym = new_Symbol(func->getProgram(), FILE_MEMORY_LOCAL);
1466 if (!func->stackPtr)
1467 offset += func->tlsBase;
1468 slot.sym->setAddress(NULL, offset);
1469 slot.sym->reg.size = size;
1470 slots.insert(pos, slot)->occup.insert(livei);
1471 }
1472 return slot.sym;
1473 }
1474
1475 Value *
1476 SpillCodeInserter::offsetSlot(Value *base, const LValue *lval)
1477 {
1478 if (!lval->compound || (lval->compMask & 0x1))
1479 return base;
1480 Value *slot = cloneShallow(func, base);
1481
1482 slot->reg.data.offset += (ffs(lval->compMask) - 1) * lval->reg.size;
1483 slot->reg.size = lval->reg.size;
1484
1485 return slot;
1486 }
1487
1488 void
1489 SpillCodeInserter::spill(Instruction *defi, Value *slot, LValue *lval)
1490 {
1491 const DataType ty = typeOfSize(lval->reg.size);
1492
1493 slot = offsetSlot(slot, lval);
1494
1495 Instruction *st;
1496 if (slot->reg.file == FILE_MEMORY_LOCAL) {
1497 st = new_Instruction(func, OP_STORE, ty);
1498 st->setSrc(0, slot);
1499 st->setSrc(1, lval);
1500 lval->noSpill = 1;
1501 } else {
1502 st = new_Instruction(func, OP_CVT, ty);
1503 st->setDef(0, slot);
1504 st->setSrc(0, lval);
1505 }
1506 defi->bb->insertAfter(defi, st);
1507 }
1508
1509 LValue *
1510 SpillCodeInserter::unspill(Instruction *usei, LValue *lval, Value *slot)
1511 {
1512 const DataType ty = typeOfSize(lval->reg.size);
1513
1514 slot = offsetSlot(slot, lval);
1515 lval = cloneShallow(func, lval);
1516
1517 Instruction *ld;
1518 if (slot->reg.file == FILE_MEMORY_LOCAL) {
1519 lval->noSpill = 1;
1520 ld = new_Instruction(func, OP_LOAD, ty);
1521 } else {
1522 ld = new_Instruction(func, OP_CVT, ty);
1523 }
1524 ld->setDef(0, lval);
1525 ld->setSrc(0, slot);
1526
1527 usei->bb->insertBefore(usei, ld);
1528 return lval;
1529 }
1530
1531
1532 // For each value that is to be spilled, go through all its definitions.
1533 // A value can have multiple definitions if it has been coalesced before.
1534 // For each definition, first go through all its uses and insert an unspill
1535 // instruction before it, then replace the use with the temporary register.
1536 // Unspill can be either a load from memory or simply a move to another
1537 // register file.
1538 // For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use
1539 // if we have spilled to a memory location, or simply with the new register.
1540 // No load or conversion instruction should be needed.
1541 bool
1542 SpillCodeInserter::run(const std::list<ValuePair>& lst)
1543 {
1544 for (std::list<ValuePair>::const_iterator it = lst.begin(); it != lst.end();
1545 ++it) {
1546 LValue *lval = it->first->asLValue();
1547 Symbol *mem = it->second ? it->second->asSym() : NULL;
1548
1549 for (Value::DefIterator d = lval->defs.begin(); d != lval->defs.end();
1550 ++d) {
1551 Value *slot = mem ?
1552 static_cast<Value *>(mem) : new_LValue(func, FILE_GPR);
1553 Value *tmp = NULL;
1554 Instruction *last = NULL;
1555
1556 LValue *dval = (*d)->get()->asLValue();
1557 Instruction *defi = (*d)->getInsn();
1558
1559 // Unspill at each use *before* inserting spill instructions,
1560 // we don't want to have the spill instructions in the use list here.
1561 while (!dval->uses.empty()) {
1562 ValueRef *u = *dval->uses.begin();
1563 Instruction *usei = u->getInsn();
1564 assert(usei);
1565 if (usei->isPseudo()) {
1566 tmp = (slot->reg.file == FILE_MEMORY_LOCAL) ? NULL : slot;
1567 last = NULL;
1568 } else
1569 if (!last || usei != last->next) { // TODO: sort uses
1570 tmp = unspill(usei, dval, slot);
1571 last = usei;
1572 }
1573 u->set(tmp);
1574 }
1575
1576 assert(defi);
1577 if (defi->isPseudo()) {
1578 d = lval->defs.erase(d);
1579 --d;
1580 if (slot->reg.file == FILE_MEMORY_LOCAL)
1581 delete_Instruction(func->getProgram(), defi);
1582 else
1583 defi->setDef(0, slot);
1584 } else {
1585 spill(defi, slot, dval);
1586 }
1587 }
1588
1589 }
1590
1591 // TODO: We're not trying to reuse old slots in a potential next iteration.
1592 // We have to update the slots' livei intervals to be able to do that.
1593 stackBase = stackSize;
1594 slots.clear();
1595 return true;
1596 }
1597
1598 bool
1599 RegAlloc::exec()
1600 {
1601 for (IteratorRef it = prog->calls.iteratorDFS(false);
1602 !it->end(); it->next()) {
1603 func = Function::get(reinterpret_cast<Graph::Node *>(it->get()));
1604
1605 func->tlsBase = prog->tlsSize;
1606 if (!execFunc())
1607 return false;
1608 prog->tlsSize += func->tlsSize;
1609 }
1610 return true;
1611 }
1612
1613 bool
1614 RegAlloc::execFunc()
1615 {
1616 InsertConstraintsPass insertConstr;
1617 PhiMovesPass insertPhiMoves;
1618 ArgumentMovesPass insertArgMoves;
1619 BuildIntervalsPass buildIntervals;
1620 SpillCodeInserter insertSpills(func);
1621
1622 GCRA gcra(func, insertSpills);
1623
1624 unsigned int i, retries;
1625 bool ret;
1626
1627 if (!func->ins.empty()) {
1628 // Insert a nop at the entry so inputs only used by the first instruction
1629 // don't count as having an empty live range.
1630 Instruction *nop = new_Instruction(func, OP_NOP, TYPE_NONE);
1631 BasicBlock::get(func->cfg.getRoot())->insertHead(nop);
1632 }
1633
1634 ret = insertConstr.exec(func);
1635 if (!ret)
1636 goto out;
1637
1638 ret = insertPhiMoves.run(func);
1639 if (!ret)
1640 goto out;
1641
1642 ret = insertArgMoves.run(func);
1643 if (!ret)
1644 goto out;
1645
1646 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1647 for (retries = 0; retries < 3; ++retries) {
1648 if (retries && (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC))
1649 INFO("Retry: %i\n", retries);
1650 if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)
1651 func->print();
1652
1653 // spilling to registers may add live ranges, need to rebuild everything
1654 ret = true;
1655 for (sequence = func->cfg.nextSequence(), i = 0;
1656 ret && i <= func->loopNestingBound;
1657 sequence = func->cfg.nextSequence(), ++i)
1658 ret = buildLiveSets(BasicBlock::get(func->cfg.getRoot()));
1659 if (!ret)
1660 break;
1661 func->orderInstructions(this->insns);
1662
1663 ret = buildIntervals.run(func);
1664 if (!ret)
1665 break;
1666 ret = gcra.allocateRegisters(insns);
1667 if (ret)
1668 break; // success
1669 }
1670 INFO_DBG(prog->dbgFlags, REG_ALLOC, "RegAlloc done: %i\n", ret);
1671
1672 func->tlsSize = insertSpills.getStackSize();
1673 out:
1674 return ret;
1675 }
1676
1677 // TODO: check if modifying Instruction::join here breaks anything
1678 void
1679 GCRA::resolveSplitsAndMerges()
1680 {
1681 for (std::list<Instruction *>::iterator it = splits.begin();
1682 it != splits.end();
1683 ++it) {
1684 Instruction *split = *it;
1685 unsigned int reg = regs.idToBytes(split->getSrc(0));
1686 for (int d = 0; split->defExists(d); ++d) {
1687 Value *v = split->getDef(d);
1688 v->reg.data.id = regs.bytesToId(v, reg);
1689 v->join = v;
1690 reg += v->reg.size;
1691 }
1692 }
1693 splits.clear();
1694
1695 for (std::list<Instruction *>::iterator it = merges.begin();
1696 it != merges.end();
1697 ++it) {
1698 Instruction *merge = *it;
1699 unsigned int reg = regs.idToBytes(merge->getDef(0));
1700 for (int s = 0; merge->srcExists(s); ++s) {
1701 Value *v = merge->getSrc(s);
1702 v->reg.data.id = regs.bytesToId(v, reg);
1703 v->join = v;
1704 reg += v->reg.size;
1705 }
1706 }
1707 merges.clear();
1708 }
1709
1710 bool Program::registerAllocation()
1711 {
1712 RegAlloc ra(this);
1713 return ra.exec();
1714 }
1715
1716 bool
1717 RegAlloc::InsertConstraintsPass::exec(Function *ir)
1718 {
1719 constrList.clear();
1720
1721 bool ret = run(ir, true, true);
1722 if (ret)
1723 ret = insertConstraintMoves();
1724 return ret;
1725 }
1726
1727 // TODO: make part of texture insn
1728 void
1729 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction *tex)
1730 {
1731 Value *def[4];
1732 int c, k, d;
1733 uint8_t mask = 0;
1734
1735 for (d = 0, k = 0, c = 0; c < 4; ++c) {
1736 if (!(tex->tex.mask & (1 << c)))
1737 continue;
1738 if (tex->getDef(k)->refCount()) {
1739 mask |= 1 << c;
1740 def[d++] = tex->getDef(k);
1741 }
1742 ++k;
1743 }
1744 tex->tex.mask = mask;
1745
1746 for (c = 0; c < d; ++c)
1747 tex->setDef(c, def[c]);
1748 for (; c < 4; ++c)
1749 tex->setDef(c, NULL);
1750 }
1751
1752 bool
1753 RegAlloc::InsertConstraintsPass::detectConflict(Instruction *cst, int s)
1754 {
1755 Value *v = cst->getSrc(s);
1756
1757 // current register allocation can't handle it if a value participates in
1758 // multiple constraints
1759 for (Value::UseIterator it = v->uses.begin(); it != v->uses.end(); ++it) {
1760 if (cst != (*it)->getInsn())
1761 return true;
1762 }
1763
1764 // can start at s + 1 because detectConflict is called on all sources
1765 for (int c = s + 1; cst->srcExists(c); ++c)
1766 if (v == cst->getSrc(c))
1767 return true;
1768
1769 Instruction *defi = v->getInsn();
1770
1771 return (!defi || defi->constrainedDefs());
1772 }
1773
1774 void
1775 RegAlloc::InsertConstraintsPass::addConstraint(Instruction *i, int s, int n)
1776 {
1777 Instruction *cst;
1778 int d;
1779
1780 // first, look for an existing identical constraint op
1781 for (std::list<Instruction *>::iterator it = constrList.begin();
1782 it != constrList.end();
1783 ++it) {
1784 cst = (*it);
1785 if (!i->bb->dominatedBy(cst->bb))
1786 break;
1787 for (d = 0; d < n; ++d)
1788 if (cst->getSrc(d) != i->getSrc(d + s))
1789 break;
1790 if (d >= n) {
1791 for (d = 0; d < n; ++d, ++s)
1792 i->setSrc(s, cst->getDef(d));
1793 return;
1794 }
1795 }
1796 cst = new_Instruction(func, OP_CONSTRAINT, i->dType);
1797
1798 for (d = 0; d < n; ++s, ++d) {
1799 cst->setDef(d, new_LValue(func, FILE_GPR));
1800 cst->setSrc(d, i->getSrc(s));
1801 i->setSrc(s, cst->getDef(d));
1802 }
1803 i->bb->insertBefore(i, cst);
1804
1805 constrList.push_back(cst);
1806 }
1807
1808 // Add a dummy use of the pointer source of >= 8 byte loads after the load
1809 // to prevent it from being assigned a register which overlapping the load's
1810 // destination, which would produce random corruptions.
1811 void
1812 RegAlloc::InsertConstraintsPass::addHazard(Instruction *i, const ValueRef *src)
1813 {
1814 Instruction *hzd = new_Instruction(func, OP_NOP, TYPE_NONE);
1815 hzd->setSrc(0, src->get());
1816 i->bb->insertAfter(i, hzd);
1817
1818 }
1819
1820 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
1821 void
1822 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction *insn)
1823 {
1824 uint8_t size = 0;
1825 int n;
1826 for (n = 0; insn->defExists(n) && insn->def(n).getFile() == FILE_GPR; ++n)
1827 size += insn->getDef(n)->reg.size;
1828 if (n < 2)
1829 return;
1830 LValue *lval = new_LValue(func, FILE_GPR);
1831 lval->reg.size = size;
1832
1833 Instruction *split = new_Instruction(func, OP_SPLIT, typeOfSize(size));
1834 split->setSrc(0, lval);
1835 for (int d = 0; d < n; ++d) {
1836 split->setDef(d, insn->getDef(d));
1837 insn->setDef(d, NULL);
1838 }
1839 insn->setDef(0, lval);
1840
1841 for (int k = 1, d = n; insn->defExists(d); ++d, ++k) {
1842 insn->setDef(k, insn->getDef(d));
1843 insn->setDef(d, NULL);
1844 }
1845 // carry over predicate if any (mainly for OP_UNION uses)
1846 split->setPredicate(insn->cc, insn->getPredicate());
1847
1848 insn->bb->insertAfter(insn, split);
1849 constrList.push_back(split);
1850 }
1851 void
1852 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction *insn,
1853 const int a, const int b)
1854 {
1855 uint8_t size = 0;
1856 if (a >= b)
1857 return;
1858 for (int s = a; s <= b; ++s)
1859 size += insn->getSrc(s)->reg.size;
1860 if (!size)
1861 return;
1862 LValue *lval = new_LValue(func, FILE_GPR);
1863 lval->reg.size = size;
1864
1865 Value *save[3];
1866 insn->takeExtraSources(0, save);
1867
1868 Instruction *merge = new_Instruction(func, OP_MERGE, typeOfSize(size));
1869 merge->setDef(0, lval);
1870 for (int s = a, i = 0; s <= b; ++s, ++i) {
1871 merge->setSrc(i, insn->getSrc(s));
1872 insn->setSrc(s, NULL);
1873 }
1874 insn->setSrc(a, lval);
1875
1876 for (int k = a + 1, s = b + 1; insn->srcExists(s); ++s, ++k) {
1877 insn->setSrc(k, insn->getSrc(s));
1878 insn->setSrc(s, NULL);
1879 }
1880 insn->bb->insertBefore(insn, merge);
1881
1882 insn->putExtraSources(0, save);
1883
1884 constrList.push_back(merge);
1885 }
1886
1887 void
1888 RegAlloc::InsertConstraintsPass::texConstraintGM107(TexInstruction *tex)
1889 {
1890 int n, s;
1891
1892 if (isTextureOp(tex->op))
1893 textureMask(tex);
1894 condenseDefs(tex);
1895
1896 if (tex->op == OP_SUSTB || tex->op == OP_SUSTP) {
1897 condenseSrcs(tex, 3, (3 + typeSizeof(tex->dType) / 4) - 1);
1898 } else
1899 if (isTextureOp(tex->op)) {
1900 if (tex->op != OP_TXQ) {
1901 s = tex->tex.target.getArgCount() - tex->tex.target.isMS();
1902 n = tex->srcCount(0xff) - s;
1903 } else {
1904 s = tex->srcCount(0xff);
1905 n = 0;
1906 }
1907
1908 if (s > 1)
1909 condenseSrcs(tex, 0, s - 1);
1910 if (n > 1) // NOTE: first call modified positions already
1911 condenseSrcs(tex, 1, n);
1912 }
1913 }
1914
1915 void
1916 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction *tex)
1917 {
1918 if (isTextureOp(tex->op))
1919 textureMask(tex);
1920 condenseDefs(tex);
1921
1922 if (tex->op == OP_SUSTB || tex->op == OP_SUSTP) {
1923 condenseSrcs(tex, 3, (3 + typeSizeof(tex->dType) / 4) - 1);
1924 } else
1925 if (isTextureOp(tex->op)) {
1926 int n = tex->srcCount(0xff, true);
1927 if (n > 4) {
1928 condenseSrcs(tex, 0, 3);
1929 if (n > 5) // NOTE: first call modified positions already
1930 condenseSrcs(tex, 4 - (4 - 1), n - 1 - (4 - 1));
1931 } else
1932 if (n > 1) {
1933 condenseSrcs(tex, 0, n - 1);
1934 }
1935 }
1936 }
1937
1938 void
1939 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction *tex)
1940 {
1941 int n, s;
1942
1943 textureMask(tex);
1944
1945 if (tex->op == OP_TXQ) {
1946 s = tex->srcCount(0xff);
1947 n = 0;
1948 } else {
1949 s = tex->tex.target.getArgCount() - tex->tex.target.isMS();
1950 if (!tex->tex.target.isArray() &&
1951 (tex->tex.rIndirectSrc >= 0 || tex->tex.sIndirectSrc >= 0))
1952 ++s;
1953 if (tex->op == OP_TXD && tex->tex.useOffsets)
1954 ++s;
1955 n = tex->srcCount(0xff) - s;
1956 assert(n <= 4);
1957 }
1958
1959 if (s > 1)
1960 condenseSrcs(tex, 0, s - 1);
1961 if (n > 1) // NOTE: first call modified positions already
1962 condenseSrcs(tex, 1, n);
1963
1964 condenseDefs(tex);
1965 }
1966
1967 void
1968 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction *tex)
1969 {
1970 Value *pred = tex->getPredicate();
1971 if (pred)
1972 tex->setPredicate(tex->cc, NULL);
1973
1974 textureMask(tex);
1975
1976 assert(tex->defExists(0) && tex->srcExists(0));
1977 // make src and def count match
1978 int c;
1979 for (c = 0; tex->srcExists(c) || tex->defExists(c); ++c) {
1980 if (!tex->srcExists(c))
1981 tex->setSrc(c, new_LValue(func, tex->getSrc(0)->asLValue()));
1982 if (!tex->defExists(c))
1983 tex->setDef(c, new_LValue(func, tex->getDef(0)->asLValue()));
1984 }
1985 if (pred)
1986 tex->setPredicate(tex->cc, pred);
1987 condenseDefs(tex);
1988 condenseSrcs(tex, 0, c - 1);
1989 }
1990
1991 // Insert constraint markers for instructions whose multiple sources must be
1992 // located in consecutive registers.
1993 bool
1994 RegAlloc::InsertConstraintsPass::visit(BasicBlock *bb)
1995 {
1996 TexInstruction *tex;
1997 Instruction *next;
1998 int s, size;
1999
2000 targ = bb->getProgram()->getTarget();
2001
2002 for (Instruction *i = bb->getEntry(); i; i = next) {
2003 next = i->next;
2004
2005 if ((tex = i->asTex())) {
2006 switch (targ->getChipset() & ~0xf) {
2007 case 0x50:
2008 case 0x80:
2009 case 0x90:
2010 case 0xa0:
2011 texConstraintNV50(tex);
2012 break;
2013 case 0xc0:
2014 case 0xd0:
2015 texConstraintNVC0(tex);
2016 break;
2017 case 0xe0:
2018 case 0xf0:
2019 case 0x100:
2020 texConstraintNVE0(tex);
2021 break;
2022 case 0x110:
2023 texConstraintGM107(tex);
2024 break;
2025 default:
2026 break;
2027 }
2028 } else
2029 if (i->op == OP_EXPORT || i->op == OP_STORE) {
2030 for (size = typeSizeof(i->dType), s = 1; size > 0; ++s) {
2031 assert(i->srcExists(s));
2032 size -= i->getSrc(s)->reg.size;
2033 }
2034 condenseSrcs(i, 1, s - 1);
2035 } else
2036 if (i->op == OP_LOAD || i->op == OP_VFETCH) {
2037 condenseDefs(i);
2038 if (i->src(0).isIndirect(0) && typeSizeof(i->dType) >= 8)
2039 addHazard(i, i->src(0).getIndirect(0));
2040 } else
2041 if (i->op == OP_UNION ||
2042 i->op == OP_MERGE ||
2043 i->op == OP_SPLIT) {
2044 constrList.push_back(i);
2045 }
2046 }
2047 return true;
2048 }
2049
2050 // Insert extra moves so that, if multiple register constraints on a value are
2051 // in conflict, these conflicts can be resolved.
2052 bool
2053 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
2054 {
2055 for (std::list<Instruction *>::iterator it = constrList.begin();
2056 it != constrList.end();
2057 ++it) {
2058 Instruction *cst = *it;
2059 Instruction *mov;
2060
2061 if (cst->op == OP_SPLIT && 0) {
2062 // spilling splits is annoying, just make sure they're separate
2063 for (int d = 0; cst->defExists(d); ++d) {
2064 if (!cst->getDef(d)->refCount())
2065 continue;
2066 LValue *lval = new_LValue(func, cst->def(d).getFile());
2067 const uint8_t size = cst->def(d).getSize();
2068 lval->reg.size = size;
2069
2070 mov = new_Instruction(func, OP_MOV, typeOfSize(size));
2071 mov->setSrc(0, lval);
2072 mov->setDef(0, cst->getDef(d));
2073 cst->setDef(d, mov->getSrc(0));
2074 cst->bb->insertAfter(cst, mov);
2075
2076 cst->getSrc(0)->asLValue()->noSpill = 1;
2077 mov->getSrc(0)->asLValue()->noSpill = 1;
2078 }
2079 } else
2080 if (cst->op == OP_MERGE || cst->op == OP_UNION) {
2081 for (int s = 0; cst->srcExists(s); ++s) {
2082 const uint8_t size = cst->src(s).getSize();
2083
2084 if (!cst->getSrc(s)->defs.size()) {
2085 mov = new_Instruction(func, OP_NOP, typeOfSize(size));
2086 mov->setDef(0, cst->getSrc(s));
2087 cst->bb->insertBefore(cst, mov);
2088 continue;
2089 }
2090 assert(cst->getSrc(s)->defs.size() == 1); // still SSA
2091
2092 Instruction *defi = cst->getSrc(s)->defs.front()->getInsn();
2093 // catch some cases where don't really need MOVs
2094 if (cst->getSrc(s)->refCount() == 1 && !defi->constrainedDefs())
2095 continue;
2096
2097 LValue *lval = new_LValue(func, cst->src(s).getFile());
2098 lval->reg.size = size;
2099
2100 mov = new_Instruction(func, OP_MOV, typeOfSize(size));
2101 mov->setDef(0, lval);
2102 mov->setSrc(0, cst->getSrc(s));
2103 cst->setSrc(s, mov->getDef(0));
2104 cst->bb->insertBefore(cst, mov);
2105
2106 cst->getDef(0)->asLValue()->noSpill = 1; // doesn't help
2107
2108 if (cst->op == OP_UNION)
2109 mov->setPredicate(defi->cc, defi->getPredicate());
2110 }
2111 }
2112 }
2113
2114 return true;
2115 }
2116
2117 } // namespace nv50_ir