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