2 * Copyright 2011 Christoph Bumiller
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:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
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.
23 #include "codegen/nv50_ir.h"
24 #include "codegen/nv50_ir_target.h"
31 #define MAX_REGISTER_FILE_SIZE 256
36 RegisterSet(const Target
*);
38 void init(const Target
*);
39 void reset(DataFile
, bool resetMax
= false);
41 void periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
);
42 void intersect(DataFile f
, const RegisterSet
*);
44 bool assign(int32_t& reg
, DataFile f
, unsigned int size
);
45 void release(DataFile f
, int32_t reg
, unsigned int size
);
46 void occupy(DataFile f
, int32_t reg
, unsigned int size
);
47 void occupy(const Value
*);
48 void occupyMask(DataFile f
, int32_t reg
, uint8_t mask
);
49 bool isOccupied(DataFile f
, int32_t reg
, unsigned int size
) const;
50 bool testOccupy(const Value
*);
51 bool testOccupy(DataFile f
, int32_t reg
, unsigned int size
);
53 inline int getMaxAssigned(DataFile f
) const { return fill
[f
]; }
55 inline unsigned int getFileSize(DataFile f
, uint8_t regSize
) const
57 if (restrictedGPR16Range
&& f
== FILE_GPR
&& regSize
== 2)
58 return (last
[f
] + 1) / 2;
62 inline unsigned int units(DataFile f
, unsigned int size
) const
64 return size
>> unit
[f
];
66 // for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)
67 inline unsigned int idToBytes(const Value
*v
) const
69 return v
->reg
.data
.id
* MIN2(v
->reg
.size
, 4);
71 inline unsigned int idToUnits(const Value
*v
) const
73 return units(v
->reg
.file
, idToBytes(v
));
75 inline int bytesToId(Value
*v
, unsigned int bytes
) const
78 return units(v
->reg
.file
, bytes
);
81 inline int unitsToId(DataFile f
, int u
, uint8_t size
) const
85 return (size
< 4) ? u
: ((u
<< unit
[f
]) / 4);
91 BitSet bits
[LAST_REGISTER_FILE
+ 1];
93 int unit
[LAST_REGISTER_FILE
+ 1]; // log2 of allocation granularity
95 int last
[LAST_REGISTER_FILE
+ 1];
96 int fill
[LAST_REGISTER_FILE
+ 1];
98 const bool restrictedGPR16Range
;
102 RegisterSet::reset(DataFile f
, bool resetMax
)
110 RegisterSet::init(const Target
*targ
)
112 for (unsigned int rf
= 0; rf
<= FILE_ADDRESS
; ++rf
) {
113 DataFile f
= static_cast<DataFile
>(rf
);
114 last
[rf
] = targ
->getFileSize(f
) - 1;
115 unit
[rf
] = targ
->getFileUnit(f
);
117 assert(last
[rf
] < MAX_REGISTER_FILE_SIZE
);
118 bits
[rf
].allocate(last
[rf
] + 1, true);
122 RegisterSet::RegisterSet(const Target
*targ
)
123 : restrictedGPR16Range(targ
->getChipset() < 0xc0)
126 for (unsigned int i
= 0; i
<= LAST_REGISTER_FILE
; ++i
)
127 reset(static_cast<DataFile
>(i
));
131 RegisterSet::periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
)
133 bits
[f
].periodicMask32(lock
, unlock
);
137 RegisterSet::intersect(DataFile f
, const RegisterSet
*set
)
139 bits
[f
] |= set
->bits
[f
];
143 RegisterSet::print() const
146 bits
[FILE_GPR
].print();
151 RegisterSet::assign(int32_t& reg
, DataFile f
, unsigned int size
)
153 reg
= bits
[f
].findFreeRange(size
);
156 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
161 RegisterSet::isOccupied(DataFile f
, int32_t reg
, unsigned int size
) const
163 return bits
[f
].testRange(reg
, size
);
167 RegisterSet::occupy(const Value
*v
)
169 occupy(v
->reg
.file
, idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
173 RegisterSet::occupyMask(DataFile f
, int32_t reg
, uint8_t mask
)
175 bits
[f
].setMask(reg
& ~31, static_cast<uint32_t>(mask
) << (reg
% 32));
179 RegisterSet::occupy(DataFile f
, int32_t reg
, unsigned int size
)
181 bits
[f
].setRange(reg
, size
);
183 INFO_DBG(0, REG_ALLOC
, "reg occupy: %u[%i] %u\n", f
, reg
, size
);
185 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
189 RegisterSet::testOccupy(const Value
*v
)
191 return testOccupy(v
->reg
.file
,
192 idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
196 RegisterSet::testOccupy(DataFile f
, int32_t reg
, unsigned int size
)
198 if (isOccupied(f
, reg
, size
))
200 occupy(f
, reg
, size
);
205 RegisterSet::release(DataFile f
, int32_t reg
, unsigned int size
)
207 bits
[f
].clrRange(reg
, size
);
209 INFO_DBG(0, REG_ALLOC
, "reg release: %u[%i] %u\n", f
, reg
, size
);
215 RegAlloc(Program
*program
) : prog(program
), sequence(0) { }
221 class PhiMovesPass
: public Pass
{
223 virtual bool visit(BasicBlock
*);
224 inline bool needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
);
227 class ArgumentMovesPass
: public Pass
{
229 virtual bool visit(BasicBlock
*);
232 class BuildIntervalsPass
: public Pass
{
234 virtual bool visit(BasicBlock
*);
235 void collectLiveValues(BasicBlock
*);
236 void addLiveRange(Value
*, const BasicBlock
*, int end
);
239 class InsertConstraintsPass
: public Pass
{
241 bool exec(Function
*func
);
243 virtual bool visit(BasicBlock
*);
245 bool insertConstraintMoves();
247 void condenseDefs(Instruction
*);
248 void condenseSrcs(Instruction
*, const int first
, const int last
);
250 void addHazard(Instruction
*i
, const ValueRef
*src
);
251 void textureMask(TexInstruction
*);
252 void addConstraint(Instruction
*, int s
, int n
);
253 bool detectConflict(Instruction
*, int s
);
255 // target specific functions, TODO: put in subclass or Target
256 void texConstraintNV50(TexInstruction
*);
257 void texConstraintNVC0(TexInstruction
*);
258 void texConstraintNVE0(TexInstruction
*);
259 void texConstraintGM107(TexInstruction
*);
261 std::list
<Instruction
*> constrList
;
266 bool buildLiveSets(BasicBlock
*);
272 // instructions in control flow / chronological order
275 int sequence
; // for manual passes through CFG
278 typedef std::pair
<Value
*, Value
*> ValuePair
;
280 class SpillCodeInserter
283 SpillCodeInserter(Function
*fn
) : func(fn
), stackSize(0), stackBase(0) { }
285 bool run(const std::list
<ValuePair
>&);
287 Symbol
*assignSlot(const Interval
&, const unsigned int size
);
288 Value
*offsetSlot(Value
*, const LValue
*);
289 inline int32_t getStackSize() const { return stackSize
; }
297 std::list
<Value
*> residents
; // needed to recalculate occup
300 inline uint8_t size() const { return sym
->reg
.size
; }
302 std::list
<SpillSlot
> slots
;
306 LValue
*unspill(Instruction
*usei
, LValue
*, Value
*slot
);
307 void spill(Instruction
*defi
, Value
*slot
, LValue
*);
311 RegAlloc::BuildIntervalsPass::addLiveRange(Value
*val
,
312 const BasicBlock
*bb
,
315 Instruction
*insn
= val
->getUniqueInsn();
318 insn
= bb
->getFirst();
320 assert(bb
->getFirst()->serial
<= bb
->getExit()->serial
);
321 assert(bb
->getExit()->serial
+ 1 >= end
);
323 int begin
= insn
->serial
;
324 if (begin
< bb
->getEntry()->serial
|| begin
> bb
->getExit()->serial
)
325 begin
= bb
->getEntry()->serial
;
327 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "%%%i <- live range [%i(%i), %i)\n",
328 val
->id
, begin
, insn
->serial
, end
);
330 if (begin
!= end
) // empty ranges are only added as hazards for fixed regs
331 val
->livei
.extend(begin
, end
);
335 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
)
337 if (b
->cfg
.incidentCount() <= 1)
341 for (Graph::EdgeIterator ei
= p
->cfg
.outgoing(); !ei
.end(); ei
.next())
342 if (ei
.getType() == Graph::Edge::TREE
||
343 ei
.getType() == Graph::Edge::FORWARD
)
348 // For each operand of each PHI in b, generate a new value by inserting a MOV
349 // at the end of the block it is coming from and replace the operand with its
350 // result. This eliminates liveness conflicts and enables us to let values be
351 // copied to the right register if such a conflict exists nonetheless.
353 // These MOVs are also crucial in making sure the live intervals of phi srces
354 // are extended until the end of the loop, since they are not included in the
357 RegAlloc::PhiMovesPass::visit(BasicBlock
*bb
)
359 Instruction
*phi
, *mov
;
362 std::stack
<BasicBlock
*> stack
;
364 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
365 pb
= BasicBlock::get(ei
.getNode());
367 if (needNewElseBlock(bb
, pb
))
370 while (!stack
.empty()) {
372 pn
= new BasicBlock(func
);
375 pb
->cfg
.detach(&bb
->cfg
);
376 pb
->cfg
.attach(&pn
->cfg
, Graph::Edge::TREE
);
377 pn
->cfg
.attach(&bb
->cfg
, Graph::Edge::FORWARD
);
379 assert(pb
->getExit()->op
!= OP_CALL
);
380 if (pb
->getExit()->asFlow()->target
.bb
== bb
)
381 pb
->getExit()->asFlow()->target
.bb
= pn
;
384 // insert MOVs (phi->src(j) should stem from j-th in-BB)
386 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
387 pb
= BasicBlock::get(ei
.getNode());
388 if (!pb
->isTerminated())
389 pb
->insertTail(new_FlowInstruction(func
, OP_BRA
, bb
));
391 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
) {
392 LValue
*tmp
= new_LValue(func
, phi
->getDef(0)->asLValue());
393 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
395 mov
->setSrc(0, phi
->getSrc(j
));
399 pb
->insertBefore(pb
->getExit(), mov
);
408 RegAlloc::ArgumentMovesPass::visit(BasicBlock
*bb
)
410 // Bind function call inputs/outputs to the same physical register
411 // the callee uses, inserting moves as appropriate for the case a
413 for (Instruction
*i
= bb
->getEntry(); i
; i
= i
->next
) {
414 FlowInstruction
*cal
= i
->asFlow();
415 // TODO: Handle indirect calls.
416 // Right now they should only be generated for builtins.
417 if (!cal
|| cal
->op
!= OP_CALL
|| cal
->builtin
|| cal
->indirect
)
419 RegisterSet
clobberSet(prog
->getTarget());
421 // Bind input values.
422 for (int s
= cal
->indirect
? 1 : 0; cal
->srcExists(s
); ++s
) {
423 const int t
= cal
->indirect
? (s
- 1) : s
;
424 LValue
*tmp
= new_LValue(func
, cal
->getSrc(s
)->asLValue());
425 tmp
->reg
.data
.id
= cal
->target
.fn
->ins
[t
].rep()->reg
.data
.id
;
428 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
430 mov
->setSrc(0, cal
->getSrc(s
));
433 bb
->insertBefore(cal
, mov
);
436 // Bind output values.
437 for (int d
= 0; cal
->defExists(d
); ++d
) {
438 LValue
*tmp
= new_LValue(func
, cal
->getDef(d
)->asLValue());
439 tmp
->reg
.data
.id
= cal
->target
.fn
->outs
[d
].rep()->reg
.data
.id
;
442 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
444 mov
->setDef(0, cal
->getDef(d
));
447 bb
->insertAfter(cal
, mov
);
448 clobberSet
.occupy(tmp
);
451 // Bind clobbered values.
452 for (std::deque
<Value
*>::iterator it
= cal
->target
.fn
->clobbers
.begin();
453 it
!= cal
->target
.fn
->clobbers
.end();
455 if (clobberSet
.testOccupy(*it
)) {
456 Value
*tmp
= new_LValue(func
, (*it
)->asLValue());
457 tmp
->reg
.data
.id
= (*it
)->reg
.data
.id
;
458 cal
->setDef(cal
->defCount(), tmp
);
463 // Update the clobber set of the function.
464 if (BasicBlock::get(func
->cfgExit
) == bb
) {
465 func
->buildDefSets();
466 for (unsigned int i
= 0; i
< bb
->defSet
.getSize(); ++i
)
467 if (bb
->defSet
.test(i
))
468 func
->clobbers
.push_back(func
->getLValue(i
));
474 // Build the set of live-in variables of bb.
476 RegAlloc::buildLiveSets(BasicBlock
*bb
)
478 Function
*f
= bb
->getFunction();
483 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "buildLiveSets(BB:%i)\n", bb
->getId());
485 bb
->liveSet
.allocate(func
->allLValues
.getSize(), false);
488 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
489 bn
= BasicBlock::get(ei
.getNode());
492 if (bn
->cfg
.visit(sequence
))
493 if (!buildLiveSets(bn
))
495 if (n
++ || bb
->liveSet
.marker
)
496 bb
->liveSet
|= bn
->liveSet
;
498 bb
->liveSet
= bn
->liveSet
;
500 if (!n
&& !bb
->liveSet
.marker
)
502 bb
->liveSet
.marker
= true;
504 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
505 INFO("BB:%i live set of out blocks:\n", bb
->getId());
509 // if (!bb->getEntry())
512 if (bb
== BasicBlock::get(f
->cfgExit
)) {
513 for (std::deque
<ValueRef
>::iterator it
= f
->outs
.begin();
514 it
!= f
->outs
.end(); ++it
) {
515 assert(it
->get()->asLValue());
516 bb
->liveSet
.set(it
->get()->id
);
520 for (i
= bb
->getExit(); i
&& i
!= bb
->getEntry()->prev
; i
= i
->prev
) {
521 for (d
= 0; i
->defExists(d
); ++d
)
522 bb
->liveSet
.clr(i
->getDef(d
)->id
);
523 for (s
= 0; i
->srcExists(s
); ++s
)
524 if (i
->getSrc(s
)->asLValue())
525 bb
->liveSet
.set(i
->getSrc(s
)->id
);
527 for (i
= bb
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
)
528 bb
->liveSet
.clr(i
->getDef(0)->id
);
530 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
531 INFO("BB:%i live set after propagation:\n", bb
->getId());
539 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock
*bb
)
541 BasicBlock
*bbA
= NULL
, *bbB
= NULL
;
543 if (bb
->cfg
.outgoingCount()) {
544 // trickery to save a loop of OR'ing liveSets
545 // aliasing works fine with BitSet::setOr
546 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
547 if (ei
.getType() == Graph::Edge::DUMMY
)
550 bb
->liveSet
.setOr(&bbA
->liveSet
, &bbB
->liveSet
);
555 bbB
= BasicBlock::get(ei
.getNode());
557 bb
->liveSet
.setOr(&bbB
->liveSet
, bbA
? &bbA
->liveSet
: NULL
);
559 if (bb
->cfg
.incidentCount()) {
565 RegAlloc::BuildIntervalsPass::visit(BasicBlock
*bb
)
567 collectLiveValues(bb
);
569 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "BuildIntervals(BB:%i)\n", bb
->getId());
571 // go through out blocks and delete phi sources that do not originate from
572 // the current block from the live set
573 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
574 BasicBlock
*out
= BasicBlock::get(ei
.getNode());
576 for (Instruction
*i
= out
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
) {
577 bb
->liveSet
.clr(i
->getDef(0)->id
);
579 for (int s
= 0; i
->srcExists(s
); ++s
) {
580 assert(i
->src(s
).getInsn());
581 if (i
->getSrc(s
)->getUniqueInsn()->bb
== bb
) // XXX: reachableBy ?
582 bb
->liveSet
.set(i
->getSrc(s
)->id
);
584 bb
->liveSet
.clr(i
->getSrc(s
)->id
);
589 // remaining live-outs are live until end
591 for (unsigned int j
= 0; j
< bb
->liveSet
.getSize(); ++j
)
592 if (bb
->liveSet
.test(j
))
593 addLiveRange(func
->getLValue(j
), bb
, bb
->getExit()->serial
+ 1);
596 for (Instruction
*i
= bb
->getExit(); i
&& i
->op
!= OP_PHI
; i
= i
->prev
) {
597 for (int d
= 0; i
->defExists(d
); ++d
) {
598 bb
->liveSet
.clr(i
->getDef(d
)->id
);
599 if (i
->getDef(d
)->reg
.data
.id
>= 0) // add hazard for fixed regs
600 i
->getDef(d
)->livei
.extend(i
->serial
, i
->serial
);
603 for (int s
= 0; i
->srcExists(s
); ++s
) {
604 if (!i
->getSrc(s
)->asLValue())
606 if (!bb
->liveSet
.test(i
->getSrc(s
)->id
)) {
607 bb
->liveSet
.set(i
->getSrc(s
)->id
);
608 addLiveRange(i
->getSrc(s
), bb
, i
->serial
);
613 if (bb
== BasicBlock::get(func
->cfg
.getRoot())) {
614 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
615 it
!= func
->ins
.end(); ++it
) {
616 if (it
->get()->reg
.data
.id
>= 0) // add hazard for fixed regs
617 it
->get()->livei
.extend(0, 1);
625 #define JOIN_MASK_PHI (1 << 0)
626 #define JOIN_MASK_UNION (1 << 1)
627 #define JOIN_MASK_MOV (1 << 2)
628 #define JOIN_MASK_TEX (1 << 3)
633 GCRA(Function
*, SpillCodeInserter
&);
636 bool allocateRegisters(ArrayList
& insns
);
638 void printNodeInfo() const;
641 class RIG_Node
: public Graph::Node
646 void init(const RegisterSet
&, LValue
*);
648 void addInterference(RIG_Node
*);
649 void addRegPreference(RIG_Node
*);
651 inline LValue
*getValue() const
653 return reinterpret_cast<LValue
*>(data
);
655 inline void setValue(LValue
*lval
) { data
= lval
; }
657 inline uint8_t getCompMask() const
659 return ((1 << colors
) - 1) << (reg
& 7);
662 static inline RIG_Node
*get(const Graph::EdgeIterator
& ei
)
664 return static_cast<RIG_Node
*>(ei
.getNode());
669 uint16_t degreeLimit
; // if deg < degLimit, node is trivially colourable
677 // list pointers for simplify() phase
681 // union of the live intervals of all coalesced values (we want to retain
682 // the separate intervals for testing interference of compound values)
685 std::list
<RIG_Node
*> prefRegs
;
689 inline RIG_Node
*getNode(const LValue
*v
) const { return &nodes
[v
->id
]; }
691 void buildRIG(ArrayList
&);
692 bool coalesce(ArrayList
&);
693 bool doCoalesce(ArrayList
&, unsigned int mask
);
694 void calculateSpillWeights();
696 bool selectRegisters();
697 void cleanup(const bool success
);
699 void simplifyEdge(RIG_Node
*, RIG_Node
*);
700 void simplifyNode(RIG_Node
*);
702 bool coalesceValues(Value
*, Value
*, bool force
);
703 void resolveSplitsAndMerges();
704 void makeCompound(Instruction
*, bool isSplit
);
706 inline void checkInterference(const RIG_Node
*, Graph::EdgeIterator
&);
708 inline void insertOrderedTail(std::list
<RIG_Node
*>&, RIG_Node
*);
709 void checkList(std::list
<RIG_Node
*>&);
712 std::stack
<uint32_t> stack
;
714 // list headers for simplify() phase
720 unsigned int nodeCount
;
725 static uint8_t relDegree
[17][17];
729 // need to fixup register id for participants of OP_MERGE/SPLIT
730 std::list
<Instruction
*> merges
;
731 std::list
<Instruction
*> splits
;
733 SpillCodeInserter
& spill
;
734 std::list
<ValuePair
> mustSpill
;
737 uint8_t GCRA::relDegree
[17][17];
739 GCRA::RIG_Node::RIG_Node() : Node(NULL
), next(this), prev(this)
745 GCRA::printNodeInfo() const
747 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
748 if (!nodes
[i
].colors
)
750 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
752 nodes
[i
].f
,nodes
[i
].reg
,nodes
[i
].colors
,
754 nodes
[i
].degree
, nodes
[i
].degreeLimit
);
756 for (Graph::EdgeIterator ei
= nodes
[i
].outgoing(); !ei
.end(); ei
.next())
757 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
758 for (Graph::EdgeIterator ei
= nodes
[i
].incident(); !ei
.end(); ei
.next())
759 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
765 GCRA::RIG_Node::init(const RegisterSet
& regs
, LValue
*lval
)
768 if (lval
->reg
.data
.id
>= 0)
769 lval
->noSpill
= lval
->fixedReg
= 1;
771 colors
= regs
.units(lval
->reg
.file
, lval
->reg
.size
);
774 if (lval
->reg
.data
.id
>= 0)
775 reg
= regs
.idToUnits(lval
);
777 weight
= std::numeric_limits
<float>::infinity();
779 degreeLimit
= regs
.getFileSize(f
, lval
->reg
.size
);
780 degreeLimit
-= relDegree
[1][colors
] - 1;
782 livei
.insert(lval
->livei
);
786 GCRA::coalesceValues(Value
*dst
, Value
*src
, bool force
)
788 LValue
*rep
= dst
->join
->asLValue();
789 LValue
*val
= src
->join
->asLValue();
791 if (!force
&& val
->reg
.data
.id
>= 0) {
792 rep
= src
->join
->asLValue();
793 val
= dst
->join
->asLValue();
795 RIG_Node
*nRep
= &nodes
[rep
->id
];
796 RIG_Node
*nVal
= &nodes
[val
->id
];
798 if (src
->reg
.file
!= dst
->reg
.file
) {
801 WARN("forced coalescing of values in different files !\n");
803 if (!force
&& dst
->reg
.size
!= src
->reg
.size
)
806 if ((rep
->reg
.data
.id
>= 0) && (rep
->reg
.data
.id
!= val
->reg
.data
.id
)) {
808 if (val
->reg
.data
.id
>= 0)
809 WARN("forced coalescing of values in different fixed regs !\n");
811 if (val
->reg
.data
.id
>= 0)
813 // make sure that there is no overlap with the fixed register of rep
814 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
815 !it
.end(); it
.next()) {
816 Value
*reg
= reinterpret_cast<Value
*>(it
.get())->asLValue();
818 if (reg
->interfers(rep
) && reg
->livei
.overlaps(nVal
->livei
))
824 if (!force
&& nRep
->livei
.overlaps(nVal
->livei
))
827 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "joining %%%i($%i) <- %%%i\n",
828 rep
->id
, rep
->reg
.data
.id
, val
->id
);
830 // set join pointer of all values joined with val
831 for (Value::DefIterator def
= val
->defs
.begin(); def
!= val
->defs
.end();
833 (*def
)->get()->join
= rep
;
834 assert(rep
->join
== rep
&& val
->join
== rep
);
836 // add val's definitions to rep and extend the live interval of its RIG node
837 rep
->defs
.insert(rep
->defs
.end(), val
->defs
.begin(), val
->defs
.end());
838 nRep
->livei
.unify(nVal
->livei
);
843 GCRA::coalesce(ArrayList
& insns
)
845 bool ret
= doCoalesce(insns
, JOIN_MASK_PHI
);
848 switch (func
->getProgram()->getTarget()->getChipset() & ~0xf) {
853 ret
= doCoalesce(insns
, JOIN_MASK_UNION
| JOIN_MASK_TEX
);
861 ret
= doCoalesce(insns
, JOIN_MASK_UNION
);
868 return doCoalesce(insns
, JOIN_MASK_MOV
);
871 static inline uint8_t makeCompMask(int compSize
, int base
, int size
)
873 uint8_t m
= ((1 << size
) - 1) << base
;
885 assert(compSize
<= 8);
890 // Used when coalescing moves. The non-compound value will become one, e.g.:
891 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
892 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
893 static inline void copyCompound(Value
*dst
, Value
*src
)
895 LValue
*ldst
= dst
->asLValue();
896 LValue
*lsrc
= src
->asLValue();
898 if (ldst
->compound
&& !lsrc
->compound
) {
904 ldst
->compound
= lsrc
->compound
;
905 ldst
->compMask
= lsrc
->compMask
;
909 GCRA::makeCompound(Instruction
*insn
, bool split
)
911 LValue
*rep
= (split
? insn
->getSrc(0) : insn
->getDef(0))->asLValue();
913 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
914 INFO("makeCompound(split = %i): ", split
);
918 const unsigned int size
= getNode(rep
)->colors
;
919 unsigned int base
= 0;
922 rep
->compMask
= 0xff;
925 for (int c
= 0; split
? insn
->defExists(c
) : insn
->srcExists(c
); ++c
) {
926 LValue
*val
= (split
? insn
->getDef(c
) : insn
->getSrc(c
))->asLValue();
930 val
->compMask
= 0xff;
931 val
->compMask
&= makeCompMask(size
, base
, getNode(val
)->colors
);
932 assert(val
->compMask
);
934 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "compound: %%%i:%02x <- %%%i:%02x\n",
935 rep
->id
, rep
->compMask
, val
->id
, val
->compMask
);
937 base
+= getNode(val
)->colors
;
939 assert(base
== size
);
943 GCRA::doCoalesce(ArrayList
& insns
, unsigned int mask
)
947 for (n
= 0; n
< insns
.getSize(); ++n
) {
949 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(n
));
953 if (!(mask
& JOIN_MASK_PHI
))
955 for (c
= 0; insn
->srcExists(c
); ++c
)
956 if (!coalesceValues(insn
->getDef(0), insn
->getSrc(c
), false)) {
958 ERROR("failed to coalesce phi operands\n");
964 if (!(mask
& JOIN_MASK_UNION
))
966 for (c
= 0; insn
->srcExists(c
); ++c
)
967 coalesceValues(insn
->getDef(0), insn
->getSrc(c
), true);
968 if (insn
->op
== OP_MERGE
) {
969 merges
.push_back(insn
);
970 if (insn
->srcExists(1))
971 makeCompound(insn
, false);
975 if (!(mask
& JOIN_MASK_UNION
))
977 splits
.push_back(insn
);
978 for (c
= 0; insn
->defExists(c
); ++c
)
979 coalesceValues(insn
->getSrc(0), insn
->getDef(c
), true);
980 makeCompound(insn
, true);
983 if (!(mask
& JOIN_MASK_MOV
))
986 if (!insn
->getDef(0)->uses
.empty())
987 i
= (*insn
->getDef(0)->uses
.begin())->getInsn();
988 // if this is a contraint-move there will only be a single use
989 if (i
&& i
->op
== OP_MERGE
) // do we really still need this ?
991 i
= insn
->getSrc(0)->getUniqueInsn();
992 if (i
&& !i
->constrainedDefs()) {
993 if (coalesceValues(insn
->getDef(0), insn
->getSrc(0), false))
994 copyCompound(insn
->getSrc(0), insn
->getDef(0));
1007 if (!(mask
& JOIN_MASK_TEX
))
1009 for (c
= 0; insn
->srcExists(c
) && c
!= insn
->predSrc
; ++c
)
1010 coalesceValues(insn
->getDef(c
), insn
->getSrc(c
), true);
1020 GCRA::RIG_Node::addInterference(RIG_Node
*node
)
1022 this->degree
+= relDegree
[node
->colors
][colors
];
1023 node
->degree
+= relDegree
[colors
][node
->colors
];
1025 this->attach(node
, Graph::Edge::CROSS
);
1029 GCRA::RIG_Node::addRegPreference(RIG_Node
*node
)
1031 prefRegs
.push_back(node
);
1034 GCRA::GCRA(Function
*fn
, SpillCodeInserter
& spill
) :
1036 regs(fn
->getProgram()->getTarget()),
1039 prog
= func
->getProgram();
1041 // initialize relative degrees array - i takes away from j
1042 for (int i
= 1; i
<= 16; ++i
)
1043 for (int j
= 1; j
<= 16; ++j
)
1044 relDegree
[i
][j
] = j
* ((i
+ j
- 1) / j
);
1054 GCRA::checkList(std::list
<RIG_Node
*>& lst
)
1056 GCRA::RIG_Node
*prev
= NULL
;
1058 for (std::list
<RIG_Node
*>::iterator it
= lst
.begin();
1061 assert((*it
)->getValue()->join
== (*it
)->getValue());
1063 assert(prev
->livei
.begin() <= (*it
)->livei
.begin());
1069 GCRA::insertOrderedTail(std::list
<RIG_Node
*>& list
, RIG_Node
*node
)
1071 if (node
->livei
.isEmpty())
1073 // only the intervals of joined values don't necessarily arrive in order
1074 std::list
<RIG_Node
*>::iterator prev
, it
;
1075 for (it
= list
.end(); it
!= list
.begin(); it
= prev
) {
1078 if ((*prev
)->livei
.begin() <= node
->livei
.begin())
1081 list
.insert(it
, node
);
1085 GCRA::buildRIG(ArrayList
& insns
)
1087 std::list
<RIG_Node
*> values
, active
;
1089 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
1090 it
!= func
->ins
.end(); ++it
)
1091 insertOrderedTail(values
, getNode(it
->get()->asLValue()));
1093 for (int i
= 0; i
< insns
.getSize(); ++i
) {
1094 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(i
));
1095 for (int d
= 0; insn
->defExists(d
); ++d
)
1096 if (insn
->getDef(d
)->rep() == insn
->getDef(d
))
1097 insertOrderedTail(values
, getNode(insn
->getDef(d
)->asLValue()));
1101 while (!values
.empty()) {
1102 RIG_Node
*cur
= values
.front();
1104 for (std::list
<RIG_Node
*>::iterator it
= active
.begin();
1105 it
!= active
.end();) {
1106 RIG_Node
*node
= *it
;
1108 if (node
->livei
.end() <= cur
->livei
.begin()) {
1109 it
= active
.erase(it
);
1111 if (node
->f
== cur
->f
&& node
->livei
.overlaps(cur
->livei
))
1112 cur
->addInterference(node
);
1117 active
.push_back(cur
);
1122 GCRA::calculateSpillWeights()
1124 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1125 RIG_Node
*const n
= &nodes
[i
];
1126 if (!nodes
[i
].colors
|| nodes
[i
].livei
.isEmpty())
1128 if (nodes
[i
].reg
>= 0) {
1130 regs
.occupy(n
->f
, n
->reg
, n
->colors
);
1133 LValue
*val
= nodes
[i
].getValue();
1135 if (!val
->noSpill
) {
1137 for (Value::DefIterator it
= val
->defs
.begin();
1138 it
!= val
->defs
.end();
1140 rc
+= (*it
)->get()->refCount();
1143 (float)rc
* (float)rc
/ (float)nodes
[i
].livei
.extent();
1146 if (nodes
[i
].degree
< nodes
[i
].degreeLimit
) {
1148 if (val
->reg
.size
> 4)
1150 DLLIST_ADDHEAD(&lo
[l
], &nodes
[i
]);
1152 DLLIST_ADDHEAD(&hi
, &nodes
[i
]);
1155 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1160 GCRA::simplifyEdge(RIG_Node
*a
, RIG_Node
*b
)
1162 bool move
= b
->degree
>= b
->degreeLimit
;
1164 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1165 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1166 a
->getValue()->id
, a
->degree
, a
->degreeLimit
,
1167 b
->getValue()->id
, b
->degree
, b
->degreeLimit
);
1169 b
->degree
-= relDegree
[a
->colors
][b
->colors
];
1171 move
= move
&& b
->degree
< b
->degreeLimit
;
1172 if (move
&& !DLLIST_EMPTY(b
)) {
1173 int l
= (b
->getValue()->reg
.size
> 4) ? 1 : 0;
1175 DLLIST_ADDTAIL(&lo
[l
], b
);
1180 GCRA::simplifyNode(RIG_Node
*node
)
1182 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1183 simplifyEdge(node
, RIG_Node::get(ei
));
1185 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1186 simplifyEdge(node
, RIG_Node::get(ei
));
1189 stack
.push(node
->getValue()->id
);
1191 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "SIMPLIFY: pushed %%%i%s\n",
1192 node
->getValue()->id
,
1193 (node
->degree
< node
->degreeLimit
) ? "" : "(spill)");
1200 if (!DLLIST_EMPTY(&lo
[0])) {
1202 simplifyNode(lo
[0].next
);
1203 } while (!DLLIST_EMPTY(&lo
[0]));
1205 if (!DLLIST_EMPTY(&lo
[1])) {
1206 simplifyNode(lo
[1].next
);
1208 if (!DLLIST_EMPTY(&hi
)) {
1209 RIG_Node
*best
= hi
.next
;
1210 float bestScore
= best
->weight
/ (float)best
->degree
;
1212 for (RIG_Node
*it
= best
->next
; it
!= &hi
; it
= it
->next
) {
1213 float score
= it
->weight
/ (float)it
->degree
;
1214 if (score
< bestScore
) {
1219 if (isinf(bestScore
)) {
1220 ERROR("no viable spill candidates left\n");
1231 GCRA::checkInterference(const RIG_Node
*node
, Graph::EdgeIterator
& ei
)
1233 const RIG_Node
*intf
= RIG_Node::get(ei
);
1237 const LValue
*vA
= node
->getValue();
1238 const LValue
*vB
= intf
->getValue();
1240 const uint8_t intfMask
= ((1 << intf
->colors
) - 1) << (intf
->reg
& 7);
1242 if (vA
->compound
| vB
->compound
) {
1243 // NOTE: this only works for >aligned< register tuples !
1244 for (Value::DefCIterator D
= vA
->defs
.begin(); D
!= vA
->defs
.end(); ++D
) {
1245 for (Value::DefCIterator d
= vB
->defs
.begin(); d
!= vB
->defs
.end(); ++d
) {
1246 const LValue
*vD
= (*D
)->get()->asLValue();
1247 const LValue
*vd
= (*d
)->get()->asLValue();
1249 if (!vD
->livei
.overlaps(vd
->livei
)) {
1250 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "(%%%i) X (%%%i): no overlap\n",
1255 uint8_t mask
= vD
->compound
? vD
->compMask
: ~0;
1257 assert(vB
->compound
);
1258 mask
&= vd
->compMask
& vB
->compMask
;
1263 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1264 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1266 vD
->compound
? vD
->compMask
: 0xff,
1268 vd
->compound
? vd
->compMask
: intfMask
,
1269 vB
->compMask
, intf
->reg
& ~7, mask
);
1271 regs
.occupyMask(node
->f
, intf
->reg
& ~7, mask
);
1275 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1276 "(%%%i) X (%%%i): $r%i + %u\n",
1277 vA
->id
, vB
->id
, intf
->reg
, intf
->colors
);
1278 regs
.occupy(node
->f
, intf
->reg
, intf
->colors
);
1283 GCRA::selectRegisters()
1285 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nSELECT phase\n");
1287 while (!stack
.empty()) {
1288 RIG_Node
*node
= &nodes
[stack
.top()];
1291 regs
.reset(node
->f
);
1293 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nNODE[%%%i, %u colors]\n",
1294 node
->getValue()->id
, node
->colors
);
1296 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1297 checkInterference(node
, ei
);
1298 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1299 checkInterference(node
, ei
);
1301 if (!node
->prefRegs
.empty()) {
1302 for (std::list
<RIG_Node
*>::const_iterator it
= node
->prefRegs
.begin();
1303 it
!= node
->prefRegs
.end();
1305 if ((*it
)->reg
>= 0 &&
1306 regs
.testOccupy(node
->f
, (*it
)->reg
, node
->colors
)) {
1307 node
->reg
= (*it
)->reg
;
1314 LValue
*lval
= node
->getValue();
1315 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1317 bool ret
= regs
.assign(node
->reg
, node
->f
, node
->colors
);
1319 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "assigned reg %i\n", node
->reg
);
1320 lval
->compMask
= node
->getCompMask();
1322 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "must spill: %%%i (size %u)\n",
1323 lval
->id
, lval
->reg
.size
);
1324 Symbol
*slot
= NULL
;
1325 if (lval
->reg
.file
== FILE_GPR
)
1326 slot
= spill
.assignSlot(node
->livei
, lval
->reg
.size
);
1327 mustSpill
.push_back(ValuePair(lval
, slot
));
1330 if (!mustSpill
.empty())
1332 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1333 LValue
*lval
= nodes
[i
].getValue();
1334 if (nodes
[i
].reg
>= 0 && nodes
[i
].colors
> 0)
1336 regs
.unitsToId(nodes
[i
].f
, nodes
[i
].reg
, lval
->reg
.size
);
1342 GCRA::allocateRegisters(ArrayList
& insns
)
1346 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1347 "allocateRegisters to %u instructions\n", insns
.getSize());
1349 nodeCount
= func
->allLValues
.getSize();
1350 nodes
= new RIG_Node
[nodeCount
];
1353 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1354 LValue
*lval
= reinterpret_cast<LValue
*>(func
->allLValues
.get(i
));
1356 nodes
[i
].init(regs
, lval
);
1357 RIG
.insert(&nodes
[i
]);
1361 // coalesce first, we use only 1 RIG node for a group of joined values
1362 ret
= coalesce(insns
);
1366 if (func
->getProgram()->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1367 func
->printLiveIntervals();
1370 calculateSpillWeights();
1373 ret
= selectRegisters();
1375 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1376 "selectRegisters failed, inserting spill code ...\n");
1377 regs
.reset(FILE_GPR
, true);
1378 spill
.run(mustSpill
);
1379 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1382 prog
->maxGPR
= std::max(prog
->maxGPR
, regs
.getMaxAssigned(FILE_GPR
));
1391 GCRA::cleanup(const bool success
)
1395 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
1396 !it
.end(); it
.next()) {
1397 LValue
*lval
= reinterpret_cast<LValue
*>(it
.get());
1399 lval
->livei
.clear();
1404 if (lval
->join
== lval
)
1408 lval
->reg
.data
.id
= lval
->join
->reg
.data
.id
;
1410 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1412 lval
->join
->defs
.remove(*d
);
1418 resolveSplitsAndMerges();
1419 splits
.clear(); // avoid duplicate entries on next coalesce pass
1427 SpillCodeInserter::assignSlot(const Interval
&livei
, const unsigned int size
)
1430 int32_t offsetBase
= stackSize
;
1432 std::list
<SpillSlot
>::iterator pos
= slots
.end(), it
= slots
.begin();
1434 if (offsetBase
% size
)
1435 offsetBase
+= size
- (offsetBase
% size
);
1439 for (offset
= offsetBase
; offset
< stackSize
; offset
+= size
) {
1440 const int32_t entryEnd
= offset
+ size
;
1441 while (it
!= slots
.end() && it
->offset
< offset
)
1443 if (it
== slots
.end()) // no slots left
1445 std::list
<SpillSlot
>::iterator bgn
= it
;
1447 while (it
!= slots
.end() && it
->offset
< entryEnd
) {
1449 if (it
->occup
.overlaps(livei
))
1453 if (it
== slots
.end() || it
->offset
>= entryEnd
) {
1455 for (; bgn
!= slots
.end() && bgn
->offset
< entryEnd
; ++bgn
) {
1456 bgn
->occup
.insert(livei
);
1457 if (bgn
->size() == size
)
1458 slot
.sym
= bgn
->sym
;
1464 stackSize
= offset
+ size
;
1465 slot
.offset
= offset
;
1466 slot
.sym
= new_Symbol(func
->getProgram(), FILE_MEMORY_LOCAL
);
1467 if (!func
->stackPtr
)
1468 offset
+= func
->tlsBase
;
1469 slot
.sym
->setAddress(NULL
, offset
);
1470 slot
.sym
->reg
.size
= size
;
1471 slots
.insert(pos
, slot
)->occup
.insert(livei
);
1477 SpillCodeInserter::offsetSlot(Value
*base
, const LValue
*lval
)
1479 if (!lval
->compound
|| (lval
->compMask
& 0x1))
1481 Value
*slot
= cloneShallow(func
, base
);
1483 slot
->reg
.data
.offset
+= (ffs(lval
->compMask
) - 1) * lval
->reg
.size
;
1484 slot
->reg
.size
= lval
->reg
.size
;
1490 SpillCodeInserter::spill(Instruction
*defi
, Value
*slot
, LValue
*lval
)
1492 const DataType ty
= typeOfSize(lval
->reg
.size
);
1494 slot
= offsetSlot(slot
, lval
);
1497 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1498 st
= new_Instruction(func
, OP_STORE
, ty
);
1499 st
->setSrc(0, slot
);
1500 st
->setSrc(1, lval
);
1503 st
= new_Instruction(func
, OP_CVT
, ty
);
1504 st
->setDef(0, slot
);
1505 st
->setSrc(0, lval
);
1507 defi
->bb
->insertAfter(defi
, st
);
1511 SpillCodeInserter::unspill(Instruction
*usei
, LValue
*lval
, Value
*slot
)
1513 const DataType ty
= typeOfSize(lval
->reg
.size
);
1515 slot
= offsetSlot(slot
, lval
);
1516 lval
= cloneShallow(func
, lval
);
1519 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1521 ld
= new_Instruction(func
, OP_LOAD
, ty
);
1523 ld
= new_Instruction(func
, OP_CVT
, ty
);
1525 ld
->setDef(0, lval
);
1526 ld
->setSrc(0, slot
);
1528 usei
->bb
->insertBefore(usei
, ld
);
1533 // For each value that is to be spilled, go through all its definitions.
1534 // A value can have multiple definitions if it has been coalesced before.
1535 // For each definition, first go through all its uses and insert an unspill
1536 // instruction before it, then replace the use with the temporary register.
1537 // Unspill can be either a load from memory or simply a move to another
1539 // For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use
1540 // if we have spilled to a memory location, or simply with the new register.
1541 // No load or conversion instruction should be needed.
1543 SpillCodeInserter::run(const std::list
<ValuePair
>& lst
)
1545 for (std::list
<ValuePair
>::const_iterator it
= lst
.begin(); it
!= lst
.end();
1547 LValue
*lval
= it
->first
->asLValue();
1548 Symbol
*mem
= it
->second
? it
->second
->asSym() : NULL
;
1550 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1553 static_cast<Value
*>(mem
) : new_LValue(func
, FILE_GPR
);
1555 Instruction
*last
= NULL
;
1557 LValue
*dval
= (*d
)->get()->asLValue();
1558 Instruction
*defi
= (*d
)->getInsn();
1560 // Unspill at each use *before* inserting spill instructions,
1561 // we don't want to have the spill instructions in the use list here.
1562 while (!dval
->uses
.empty()) {
1563 ValueRef
*u
= *dval
->uses
.begin();
1564 Instruction
*usei
= u
->getInsn();
1566 if (usei
->isPseudo()) {
1567 tmp
= (slot
->reg
.file
== FILE_MEMORY_LOCAL
) ? NULL
: slot
;
1570 if (!last
|| usei
!= last
->next
) { // TODO: sort uses
1571 tmp
= unspill(usei
, dval
, slot
);
1578 if (defi
->isPseudo()) {
1579 d
= lval
->defs
.erase(d
);
1581 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
)
1582 delete_Instruction(func
->getProgram(), defi
);
1584 defi
->setDef(0, slot
);
1586 spill(defi
, slot
, dval
);
1592 // TODO: We're not trying to reuse old slots in a potential next iteration.
1593 // We have to update the slots' livei intervals to be able to do that.
1594 stackBase
= stackSize
;
1602 for (IteratorRef it
= prog
->calls
.iteratorDFS(false);
1603 !it
->end(); it
->next()) {
1604 func
= Function::get(reinterpret_cast<Graph::Node
*>(it
->get()));
1606 func
->tlsBase
= prog
->tlsSize
;
1609 prog
->tlsSize
+= func
->tlsSize
;
1615 RegAlloc::execFunc()
1617 InsertConstraintsPass insertConstr
;
1618 PhiMovesPass insertPhiMoves
;
1619 ArgumentMovesPass insertArgMoves
;
1620 BuildIntervalsPass buildIntervals
;
1621 SpillCodeInserter
insertSpills(func
);
1623 GCRA
gcra(func
, insertSpills
);
1625 unsigned int i
, retries
;
1628 if (!func
->ins
.empty()) {
1629 // Insert a nop at the entry so inputs only used by the first instruction
1630 // don't count as having an empty live range.
1631 Instruction
*nop
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1632 BasicBlock::get(func
->cfg
.getRoot())->insertHead(nop
);
1635 ret
= insertConstr
.exec(func
);
1639 ret
= insertPhiMoves
.run(func
);
1643 ret
= insertArgMoves
.run(func
);
1647 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1648 for (retries
= 0; retries
< 3; ++retries
) {
1649 if (retries
&& (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
))
1650 INFO("Retry: %i\n", retries
);
1651 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1654 // spilling to registers may add live ranges, need to rebuild everything
1656 for (sequence
= func
->cfg
.nextSequence(), i
= 0;
1657 ret
&& i
<= func
->loopNestingBound
;
1658 sequence
= func
->cfg
.nextSequence(), ++i
)
1659 ret
= buildLiveSets(BasicBlock::get(func
->cfg
.getRoot()));
1662 func
->orderInstructions(this->insns
);
1664 ret
= buildIntervals
.run(func
);
1667 ret
= gcra
.allocateRegisters(insns
);
1671 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "RegAlloc done: %i\n", ret
);
1673 func
->tlsSize
= insertSpills
.getStackSize();
1678 // TODO: check if modifying Instruction::join here breaks anything
1680 GCRA::resolveSplitsAndMerges()
1682 for (std::list
<Instruction
*>::iterator it
= splits
.begin();
1685 Instruction
*split
= *it
;
1686 unsigned int reg
= regs
.idToBytes(split
->getSrc(0));
1687 for (int d
= 0; split
->defExists(d
); ++d
) {
1688 Value
*v
= split
->getDef(d
);
1689 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1696 for (std::list
<Instruction
*>::iterator it
= merges
.begin();
1699 Instruction
*merge
= *it
;
1700 unsigned int reg
= regs
.idToBytes(merge
->getDef(0));
1701 for (int s
= 0; merge
->srcExists(s
); ++s
) {
1702 Value
*v
= merge
->getSrc(s
);
1703 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1711 bool Program::registerAllocation()
1718 RegAlloc::InsertConstraintsPass::exec(Function
*ir
)
1722 bool ret
= run(ir
, true, true);
1724 ret
= insertConstraintMoves();
1728 // TODO: make part of texture insn
1730 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction
*tex
)
1736 for (d
= 0, k
= 0, c
= 0; c
< 4; ++c
) {
1737 if (!(tex
->tex
.mask
& (1 << c
)))
1739 if (tex
->getDef(k
)->refCount()) {
1741 def
[d
++] = tex
->getDef(k
);
1745 tex
->tex
.mask
= mask
;
1747 for (c
= 0; c
< d
; ++c
)
1748 tex
->setDef(c
, def
[c
]);
1750 tex
->setDef(c
, NULL
);
1754 RegAlloc::InsertConstraintsPass::detectConflict(Instruction
*cst
, int s
)
1756 Value
*v
= cst
->getSrc(s
);
1758 // current register allocation can't handle it if a value participates in
1759 // multiple constraints
1760 for (Value::UseIterator it
= v
->uses
.begin(); it
!= v
->uses
.end(); ++it
) {
1761 if (cst
!= (*it
)->getInsn())
1765 // can start at s + 1 because detectConflict is called on all sources
1766 for (int c
= s
+ 1; cst
->srcExists(c
); ++c
)
1767 if (v
== cst
->getSrc(c
))
1770 Instruction
*defi
= v
->getInsn();
1772 return (!defi
|| defi
->constrainedDefs());
1776 RegAlloc::InsertConstraintsPass::addConstraint(Instruction
*i
, int s
, int n
)
1781 // first, look for an existing identical constraint op
1782 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
1783 it
!= constrList
.end();
1786 if (!i
->bb
->dominatedBy(cst
->bb
))
1788 for (d
= 0; d
< n
; ++d
)
1789 if (cst
->getSrc(d
) != i
->getSrc(d
+ s
))
1792 for (d
= 0; d
< n
; ++d
, ++s
)
1793 i
->setSrc(s
, cst
->getDef(d
));
1797 cst
= new_Instruction(func
, OP_CONSTRAINT
, i
->dType
);
1799 for (d
= 0; d
< n
; ++s
, ++d
) {
1800 cst
->setDef(d
, new_LValue(func
, FILE_GPR
));
1801 cst
->setSrc(d
, i
->getSrc(s
));
1802 i
->setSrc(s
, cst
->getDef(d
));
1804 i
->bb
->insertBefore(i
, cst
);
1806 constrList
.push_back(cst
);
1809 // Add a dummy use of the pointer source of >= 8 byte loads after the load
1810 // to prevent it from being assigned a register which overlapping the load's
1811 // destination, which would produce random corruptions.
1813 RegAlloc::InsertConstraintsPass::addHazard(Instruction
*i
, const ValueRef
*src
)
1815 Instruction
*hzd
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1816 hzd
->setSrc(0, src
->get());
1817 i
->bb
->insertAfter(i
, hzd
);
1821 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
1823 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction
*insn
)
1827 for (n
= 0; insn
->defExists(n
) && insn
->def(n
).getFile() == FILE_GPR
; ++n
)
1828 size
+= insn
->getDef(n
)->reg
.size
;
1831 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1832 lval
->reg
.size
= size
;
1834 Instruction
*split
= new_Instruction(func
, OP_SPLIT
, typeOfSize(size
));
1835 split
->setSrc(0, lval
);
1836 for (int d
= 0; d
< n
; ++d
) {
1837 split
->setDef(d
, insn
->getDef(d
));
1838 insn
->setDef(d
, NULL
);
1840 insn
->setDef(0, lval
);
1842 for (int k
= 1, d
= n
; insn
->defExists(d
); ++d
, ++k
) {
1843 insn
->setDef(k
, insn
->getDef(d
));
1844 insn
->setDef(d
, NULL
);
1846 // carry over predicate if any (mainly for OP_UNION uses)
1847 split
->setPredicate(insn
->cc
, insn
->getPredicate());
1849 insn
->bb
->insertAfter(insn
, split
);
1850 constrList
.push_back(split
);
1853 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction
*insn
,
1854 const int a
, const int b
)
1859 for (int s
= a
; s
<= b
; ++s
)
1860 size
+= insn
->getSrc(s
)->reg
.size
;
1863 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1864 lval
->reg
.size
= size
;
1867 insn
->takeExtraSources(0, save
);
1869 Instruction
*merge
= new_Instruction(func
, OP_MERGE
, typeOfSize(size
));
1870 merge
->setDef(0, lval
);
1871 for (int s
= a
, i
= 0; s
<= b
; ++s
, ++i
) {
1872 merge
->setSrc(i
, insn
->getSrc(s
));
1873 insn
->setSrc(s
, NULL
);
1875 insn
->setSrc(a
, lval
);
1877 for (int k
= a
+ 1, s
= b
+ 1; insn
->srcExists(s
); ++s
, ++k
) {
1878 insn
->setSrc(k
, insn
->getSrc(s
));
1879 insn
->setSrc(s
, NULL
);
1881 insn
->bb
->insertBefore(insn
, merge
);
1883 insn
->putExtraSources(0, save
);
1885 constrList
.push_back(merge
);
1889 RegAlloc::InsertConstraintsPass::texConstraintGM107(TexInstruction
*tex
)
1893 if (isTextureOp(tex
->op
))
1897 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
1898 condenseSrcs(tex
, 3, (3 + typeSizeof(tex
->dType
) / 4) - 1);
1900 if (isTextureOp(tex
->op
)) {
1901 if (tex
->op
!= OP_TXQ
) {
1902 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
1903 n
= tex
->srcCount(0xff) - s
;
1905 s
= tex
->srcCount(0xff);
1910 condenseSrcs(tex
, 0, s
- 1);
1911 if (n
> 1) // NOTE: first call modified positions already
1912 condenseSrcs(tex
, 1, n
);
1917 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction
*tex
)
1919 if (isTextureOp(tex
->op
))
1923 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
1924 condenseSrcs(tex
, 3, (3 + typeSizeof(tex
->dType
) / 4) - 1);
1926 if (isTextureOp(tex
->op
)) {
1927 int n
= tex
->srcCount(0xff, true);
1929 condenseSrcs(tex
, 0, 3);
1930 if (n
> 5) // NOTE: first call modified positions already
1931 condenseSrcs(tex
, 4 - (4 - 1), n
- 1 - (4 - 1));
1934 condenseSrcs(tex
, 0, n
- 1);
1940 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction
*tex
)
1946 if (tex
->op
== OP_TXQ
) {
1947 s
= tex
->srcCount(0xff);
1950 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
1951 if (!tex
->tex
.target
.isArray() &&
1952 (tex
->tex
.rIndirectSrc
>= 0 || tex
->tex
.sIndirectSrc
>= 0))
1954 if (tex
->op
== OP_TXD
&& tex
->tex
.useOffsets
)
1956 n
= tex
->srcCount(0xff) - s
;
1961 condenseSrcs(tex
, 0, s
- 1);
1962 if (n
> 1) // NOTE: first call modified positions already
1963 condenseSrcs(tex
, 1, n
);
1969 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction
*tex
)
1971 Value
*pred
= tex
->getPredicate();
1973 tex
->setPredicate(tex
->cc
, NULL
);
1977 assert(tex
->defExists(0) && tex
->srcExists(0));
1978 // make src and def count match
1980 for (c
= 0; tex
->srcExists(c
) || tex
->defExists(c
); ++c
) {
1981 if (!tex
->srcExists(c
))
1982 tex
->setSrc(c
, new_LValue(func
, tex
->getSrc(0)->asLValue()));
1983 if (!tex
->defExists(c
))
1984 tex
->setDef(c
, new_LValue(func
, tex
->getDef(0)->asLValue()));
1987 tex
->setPredicate(tex
->cc
, pred
);
1989 condenseSrcs(tex
, 0, c
- 1);
1992 // Insert constraint markers for instructions whose multiple sources must be
1993 // located in consecutive registers.
1995 RegAlloc::InsertConstraintsPass::visit(BasicBlock
*bb
)
1997 TexInstruction
*tex
;
2001 targ
= bb
->getProgram()->getTarget();
2003 for (Instruction
*i
= bb
->getEntry(); i
; i
= next
) {
2006 if ((tex
= i
->asTex())) {
2007 switch (targ
->getChipset() & ~0xf) {
2012 texConstraintNV50(tex
);
2016 texConstraintNVC0(tex
);
2021 texConstraintNVE0(tex
);
2024 texConstraintGM107(tex
);
2030 if (i
->op
== OP_EXPORT
|| i
->op
== OP_STORE
) {
2031 for (size
= typeSizeof(i
->dType
), s
= 1; size
> 0; ++s
) {
2032 assert(i
->srcExists(s
));
2033 size
-= i
->getSrc(s
)->reg
.size
;
2035 condenseSrcs(i
, 1, s
- 1);
2037 if (i
->op
== OP_LOAD
|| i
->op
== OP_VFETCH
) {
2039 if (i
->src(0).isIndirect(0) && typeSizeof(i
->dType
) >= 8)
2040 addHazard(i
, i
->src(0).getIndirect(0));
2042 if (i
->op
== OP_UNION
||
2043 i
->op
== OP_MERGE
||
2044 i
->op
== OP_SPLIT
) {
2045 constrList
.push_back(i
);
2051 // Insert extra moves so that, if multiple register constraints on a value are
2052 // in conflict, these conflicts can be resolved.
2054 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
2056 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
2057 it
!= constrList
.end();
2059 Instruction
*cst
= *it
;
2062 if (cst
->op
== OP_SPLIT
&& 0) {
2063 // spilling splits is annoying, just make sure they're separate
2064 for (int d
= 0; cst
->defExists(d
); ++d
) {
2065 if (!cst
->getDef(d
)->refCount())
2067 LValue
*lval
= new_LValue(func
, cst
->def(d
).getFile());
2068 const uint8_t size
= cst
->def(d
).getSize();
2069 lval
->reg
.size
= size
;
2071 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2072 mov
->setSrc(0, lval
);
2073 mov
->setDef(0, cst
->getDef(d
));
2074 cst
->setDef(d
, mov
->getSrc(0));
2075 cst
->bb
->insertAfter(cst
, mov
);
2077 cst
->getSrc(0)->asLValue()->noSpill
= 1;
2078 mov
->getSrc(0)->asLValue()->noSpill
= 1;
2081 if (cst
->op
== OP_MERGE
|| cst
->op
== OP_UNION
) {
2082 for (int s
= 0; cst
->srcExists(s
); ++s
) {
2083 const uint8_t size
= cst
->src(s
).getSize();
2085 if (!cst
->getSrc(s
)->defs
.size()) {
2086 mov
= new_Instruction(func
, OP_NOP
, typeOfSize(size
));
2087 mov
->setDef(0, cst
->getSrc(s
));
2088 cst
->bb
->insertBefore(cst
, mov
);
2091 assert(cst
->getSrc(s
)->defs
.size() == 1); // still SSA
2093 Instruction
*defi
= cst
->getSrc(s
)->defs
.front()->getInsn();
2094 // catch some cases where don't really need MOVs
2095 if (cst
->getSrc(s
)->refCount() == 1 && !defi
->constrainedDefs())
2098 LValue
*lval
= new_LValue(func
, cst
->src(s
).getFile());
2099 lval
->reg
.size
= size
;
2101 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2102 mov
->setDef(0, lval
);
2103 mov
->setSrc(0, cst
->getSrc(s
));
2104 cst
->setSrc(s
, mov
->getDef(0));
2105 cst
->bb
->insertBefore(cst
, mov
);
2107 cst
->getDef(0)->asLValue()->noSpill
= 1; // doesn't help
2109 if (cst
->op
== OP_UNION
)
2110 mov
->setPredicate(defi
->cc
, defi
->getPredicate());
2118 } // namespace nv50_ir