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