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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
19 * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 #include "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 bool occupy(DataFile f
, int32_t reg
, unsigned int size
, bool noTest
= false);
47 bool occupy(const Value
*);
48 void occupyMask(DataFile f
, int32_t reg
, uint8_t mask
);
50 inline int getMaxAssigned(DataFile f
) const { return fill
[f
]; }
52 inline unsigned int getFileSize(DataFile f
, uint8_t regSize
) const
54 if (restrictedGPR16Range
&& f
== FILE_GPR
&& regSize
== 2)
55 return (last
[f
] + 1) / 2;
59 inline unsigned int units(DataFile f
, unsigned int size
) const
61 return size
>> unit
[f
];
63 // for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)
64 inline unsigned int idToBytes(const Value
*v
) const
66 return v
->reg
.data
.id
* MIN2(v
->reg
.size
, 4);
68 inline unsigned int idToUnits(const Value
*v
) const
70 return units(v
->reg
.file
, idToBytes(v
));
72 inline int bytesToId(Value
*v
, unsigned int bytes
) const
75 return units(v
->reg
.file
, bytes
);
78 inline int unitsToId(DataFile f
, int u
, uint8_t size
) const
82 return (size
< 4) ? u
: ((u
<< unit
[f
]) / 4);
88 BitSet bits
[LAST_REGISTER_FILE
+ 1];
90 int unit
[LAST_REGISTER_FILE
+ 1]; // log2 of allocation granularity
92 int last
[LAST_REGISTER_FILE
+ 1];
93 int fill
[LAST_REGISTER_FILE
+ 1];
95 const bool restrictedGPR16Range
;
99 RegisterSet::reset(DataFile f
, bool resetMax
)
107 RegisterSet::init(const Target
*targ
)
109 for (unsigned int rf
= 0; rf
<= FILE_ADDRESS
; ++rf
) {
110 DataFile f
= static_cast<DataFile
>(rf
);
111 last
[rf
] = targ
->getFileSize(f
) - 1;
112 unit
[rf
] = targ
->getFileUnit(f
);
114 assert(last
[rf
] < MAX_REGISTER_FILE_SIZE
);
115 bits
[rf
].allocate(last
[rf
] + 1, true);
119 RegisterSet::RegisterSet(const Target
*targ
)
120 : restrictedGPR16Range(targ
->getChipset() < 0xc0)
123 for (unsigned int i
= 0; i
<= LAST_REGISTER_FILE
; ++i
)
124 reset(static_cast<DataFile
>(i
));
128 RegisterSet::periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
)
130 bits
[f
].periodicMask32(lock
, unlock
);
134 RegisterSet::intersect(DataFile f
, const RegisterSet
*set
)
136 bits
[f
] |= set
->bits
[f
];
140 RegisterSet::print() const
143 bits
[FILE_GPR
].print();
148 RegisterSet::assign(int32_t& reg
, DataFile f
, unsigned int size
)
150 reg
= bits
[f
].findFreeRange(size
);
153 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
158 RegisterSet::occupy(const Value
*v
)
160 return occupy(v
->reg
.file
, idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
164 RegisterSet::occupyMask(DataFile f
, int32_t reg
, uint8_t mask
)
166 bits
[f
].setMask(reg
& ~31, static_cast<uint32_t>(mask
) << (reg
% 32));
170 RegisterSet::occupy(DataFile f
, int32_t reg
, unsigned int size
, bool noTest
)
172 if (!noTest
&& bits
[f
].testRange(reg
, size
))
175 bits
[f
].setRange(reg
, size
);
177 INFO_DBG(0, REG_ALLOC
, "reg occupy: %u[%i] %u\n", f
, reg
, size
);
179 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
185 RegisterSet::release(DataFile f
, int32_t reg
, unsigned int size
)
187 bits
[f
].clrRange(reg
, size
);
189 INFO_DBG(0, REG_ALLOC
, "reg release: %u[%i] %u\n", f
, reg
, size
);
195 RegAlloc(Program
*program
) : prog(program
), sequence(0) { }
201 class PhiMovesPass
: public Pass
{
203 virtual bool visit(BasicBlock
*);
204 inline bool needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
);
207 class ArgumentMovesPass
: public Pass
{
209 virtual bool visit(BasicBlock
*);
212 class BuildIntervalsPass
: public Pass
{
214 virtual bool visit(BasicBlock
*);
215 void collectLiveValues(BasicBlock
*);
216 void addLiveRange(Value
*, const BasicBlock
*, int end
);
219 class InsertConstraintsPass
: public Pass
{
221 bool exec(Function
*func
);
223 virtual bool visit(BasicBlock
*);
225 bool insertConstraintMoves();
227 void condenseDefs(Instruction
*);
228 void condenseSrcs(Instruction
*, const int first
, const int last
);
230 void addHazard(Instruction
*i
, const ValueRef
*src
);
231 void textureMask(TexInstruction
*);
232 void addConstraint(Instruction
*, int s
, int n
);
233 bool detectConflict(Instruction
*, int s
);
235 // target specific functions, TODO: put in subclass or Target
236 void texConstraintNV50(TexInstruction
*);
237 void texConstraintNVC0(TexInstruction
*);
238 void texConstraintNVE0(TexInstruction
*);
240 std::list
<Instruction
*> constrList
;
245 bool buildLiveSets(BasicBlock
*);
251 // instructions in control flow / chronological order
254 int sequence
; // for manual passes through CFG
257 typedef std::pair
<Value
*, Value
*> ValuePair
;
259 class SpillCodeInserter
262 SpillCodeInserter(Function
*fn
) : func(fn
), stackSize(0), stackBase(0) { }
264 bool run(const std::list
<ValuePair
>&);
266 Symbol
*assignSlot(const Interval
&, const unsigned int size
);
267 inline int32_t getStackSize() const { return stackSize
; }
275 std::list
<Value
*> residents
; // needed to recalculate occup
278 inline uint8_t size() const { return sym
->reg
.size
; }
280 std::list
<SpillSlot
> slots
;
284 LValue
*unspill(Instruction
*usei
, LValue
*, Value
*slot
);
285 void spill(Instruction
*defi
, Value
*slot
, LValue
*);
289 RegAlloc::BuildIntervalsPass::addLiveRange(Value
*val
,
290 const BasicBlock
*bb
,
293 Instruction
*insn
= val
->getUniqueInsn();
296 insn
= bb
->getFirst();
298 assert(bb
->getFirst()->serial
<= bb
->getExit()->serial
);
299 assert(bb
->getExit()->serial
+ 1 >= end
);
301 int begin
= insn
->serial
;
302 if (begin
< bb
->getEntry()->serial
|| begin
> bb
->getExit()->serial
)
303 begin
= bb
->getEntry()->serial
;
305 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "%%%i <- live range [%i(%i), %i)\n",
306 val
->id
, begin
, insn
->serial
, end
);
308 if (begin
!= end
) // empty ranges are only added as hazards for fixed regs
309 val
->livei
.extend(begin
, end
);
313 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
)
315 if (b
->cfg
.incidentCount() <= 1)
319 for (Graph::EdgeIterator ei
= p
->cfg
.outgoing(); !ei
.end(); ei
.next())
320 if (ei
.getType() == Graph::Edge::TREE
||
321 ei
.getType() == Graph::Edge::FORWARD
)
326 // For each operand of each PHI in b, generate a new value by inserting a MOV
327 // at the end of the block it is coming from and replace the operand with its
328 // result. This eliminates liveness conflicts and enables us to let values be
329 // copied to the right register if such a conflict exists nonetheless.
331 // These MOVs are also crucial in making sure the live intervals of phi srces
332 // are extended until the end of the loop, since they are not included in the
335 RegAlloc::PhiMovesPass::visit(BasicBlock
*bb
)
337 Instruction
*phi
, *mov
;
340 std::stack
<BasicBlock
*> stack
;
342 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
343 pb
= BasicBlock::get(ei
.getNode());
345 if (needNewElseBlock(bb
, pb
))
348 while (!stack
.empty()) {
350 pn
= new BasicBlock(func
);
353 pb
->cfg
.detach(&bb
->cfg
);
354 pb
->cfg
.attach(&pn
->cfg
, Graph::Edge::TREE
);
355 pn
->cfg
.attach(&bb
->cfg
, Graph::Edge::FORWARD
);
357 assert(pb
->getExit()->op
!= OP_CALL
);
358 if (pb
->getExit()->asFlow()->target
.bb
== bb
)
359 pb
->getExit()->asFlow()->target
.bb
= pn
;
362 // insert MOVs (phi->src(j) should stem from j-th in-BB)
364 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
365 pb
= BasicBlock::get(ei
.getNode());
366 if (!pb
->isTerminated())
367 pb
->insertTail(new_FlowInstruction(func
, OP_BRA
, bb
));
369 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
) {
370 mov
= new_Instruction(func
, OP_MOV
, TYPE_U32
);
372 mov
->setSrc(0, phi
->getSrc(j
));
373 mov
->setDef(0, new_LValue(func
, phi
->getDef(0)->asLValue()));
374 phi
->setSrc(j
, mov
->getDef(0));
376 pb
->insertBefore(pb
->getExit(), mov
);
385 RegAlloc::ArgumentMovesPass::visit(BasicBlock
*bb
)
387 // Bind function call inputs/outputs to the same physical register
388 // the callee uses, inserting moves as appropriate for the case a
390 for (Instruction
*i
= bb
->getEntry(); i
; i
= i
->next
) {
391 FlowInstruction
*cal
= i
->asFlow();
392 if (!cal
|| cal
->op
!= OP_CALL
|| cal
->builtin
)
394 RegisterSet
clobberSet(prog
->getTarget());
396 // Bind input values.
397 for (int s
= 0; cal
->srcExists(s
); ++s
) {
398 LValue
*tmp
= new_LValue(func
, cal
->getSrc(s
)->asLValue());
399 tmp
->reg
.data
.id
= cal
->target
.fn
->ins
[s
].rep()->reg
.data
.id
;
402 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
404 mov
->setSrc(0, cal
->getSrc(s
));
407 bb
->insertBefore(cal
, mov
);
410 // Bind output values.
411 for (int d
= 0; cal
->defExists(d
); ++d
) {
412 LValue
*tmp
= new_LValue(func
, cal
->getDef(d
)->asLValue());
413 tmp
->reg
.data
.id
= cal
->target
.fn
->outs
[d
].rep()->reg
.data
.id
;
416 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
418 mov
->setDef(0, cal
->getDef(d
));
421 bb
->insertAfter(cal
, mov
);
422 clobberSet
.occupy(tmp
);
425 // Bind clobbered values.
426 for (std::deque
<Value
*>::iterator it
= cal
->target
.fn
->clobbers
.begin();
427 it
!= cal
->target
.fn
->clobbers
.end();
429 if (clobberSet
.occupy(*it
)) {
430 Value
*tmp
= new_LValue(func
, (*it
)->asLValue());
431 tmp
->reg
.data
.id
= (*it
)->reg
.data
.id
;
432 cal
->setDef(cal
->defCount(), tmp
);
437 // Update the clobber set of the function.
438 if (BasicBlock::get(func
->cfgExit
) == bb
) {
439 func
->buildDefSets();
440 for (unsigned int i
= 0; i
< bb
->defSet
.getSize(); ++i
)
441 if (bb
->defSet
.test(i
))
442 func
->clobbers
.push_back(func
->getLValue(i
));
448 // Build the set of live-in variables of bb.
450 RegAlloc::buildLiveSets(BasicBlock
*bb
)
452 Function
*f
= bb
->getFunction();
457 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "buildLiveSets(BB:%i)\n", bb
->getId());
459 bb
->liveSet
.allocate(func
->allLValues
.getSize(), false);
462 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
463 bn
= BasicBlock::get(ei
.getNode());
466 if (bn
->cfg
.visit(sequence
))
467 if (!buildLiveSets(bn
))
469 if (n
++ || bb
->liveSet
.marker
)
470 bb
->liveSet
|= bn
->liveSet
;
472 bb
->liveSet
= bn
->liveSet
;
474 if (!n
&& !bb
->liveSet
.marker
)
476 bb
->liveSet
.marker
= true;
478 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
479 INFO("BB:%i live set of out blocks:\n", bb
->getId());
483 // if (!bb->getEntry())
486 if (bb
== BasicBlock::get(f
->cfgExit
)) {
487 for (std::deque
<ValueRef
>::iterator it
= f
->outs
.begin();
488 it
!= f
->outs
.end(); ++it
) {
489 assert(it
->get()->asLValue());
490 bb
->liveSet
.set(it
->get()->id
);
494 for (i
= bb
->getExit(); i
&& i
!= bb
->getEntry()->prev
; i
= i
->prev
) {
495 for (d
= 0; i
->defExists(d
); ++d
)
496 bb
->liveSet
.clr(i
->getDef(d
)->id
);
497 for (s
= 0; i
->srcExists(s
); ++s
)
498 if (i
->getSrc(s
)->asLValue())
499 bb
->liveSet
.set(i
->getSrc(s
)->id
);
501 for (i
= bb
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
)
502 bb
->liveSet
.clr(i
->getDef(0)->id
);
504 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
505 INFO("BB:%i live set after propagation:\n", bb
->getId());
513 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock
*bb
)
515 BasicBlock
*bbA
= NULL
, *bbB
= NULL
;
517 if (bb
->cfg
.outgoingCount()) {
518 // trickery to save a loop of OR'ing liveSets
519 // aliasing works fine with BitSet::setOr
520 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
521 if (ei
.getType() == Graph::Edge::DUMMY
)
524 bb
->liveSet
.setOr(&bbA
->liveSet
, &bbB
->liveSet
);
529 bbB
= BasicBlock::get(ei
.getNode());
531 bb
->liveSet
.setOr(&bbB
->liveSet
, bbA
? &bbA
->liveSet
: NULL
);
533 if (bb
->cfg
.incidentCount()) {
539 RegAlloc::BuildIntervalsPass::visit(BasicBlock
*bb
)
541 collectLiveValues(bb
);
543 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "BuildIntervals(BB:%i)\n", bb
->getId());
545 // go through out blocks and delete phi sources that do not originate from
546 // the current block from the live set
547 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
548 BasicBlock
*out
= BasicBlock::get(ei
.getNode());
550 for (Instruction
*i
= out
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
) {
551 bb
->liveSet
.clr(i
->getDef(0)->id
);
553 for (int s
= 0; i
->srcExists(s
); ++s
) {
554 assert(i
->src(s
).getInsn());
555 if (i
->getSrc(s
)->getUniqueInsn()->bb
== bb
) // XXX: reachableBy ?
556 bb
->liveSet
.set(i
->getSrc(s
)->id
);
558 bb
->liveSet
.clr(i
->getSrc(s
)->id
);
563 // remaining live-outs are live until end
565 for (unsigned int j
= 0; j
< bb
->liveSet
.getSize(); ++j
)
566 if (bb
->liveSet
.test(j
))
567 addLiveRange(func
->getLValue(j
), bb
, bb
->getExit()->serial
+ 1);
570 for (Instruction
*i
= bb
->getExit(); i
&& i
->op
!= OP_PHI
; i
= i
->prev
) {
571 for (int d
= 0; i
->defExists(d
); ++d
) {
572 bb
->liveSet
.clr(i
->getDef(d
)->id
);
573 if (i
->getDef(d
)->reg
.data
.id
>= 0) // add hazard for fixed regs
574 i
->getDef(d
)->livei
.extend(i
->serial
, i
->serial
);
577 for (int s
= 0; i
->srcExists(s
); ++s
) {
578 if (!i
->getSrc(s
)->asLValue())
580 if (!bb
->liveSet
.test(i
->getSrc(s
)->id
)) {
581 bb
->liveSet
.set(i
->getSrc(s
)->id
);
582 addLiveRange(i
->getSrc(s
), bb
, i
->serial
);
587 if (bb
== BasicBlock::get(func
->cfg
.getRoot())) {
588 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
589 it
!= func
->ins
.end(); ++it
) {
590 if (it
->get()->reg
.data
.id
>= 0) // add hazard for fixed regs
591 it
->get()->livei
.extend(0, 1);
599 #define JOIN_MASK_PHI (1 << 0)
600 #define JOIN_MASK_UNION (1 << 1)
601 #define JOIN_MASK_MOV (1 << 2)
602 #define JOIN_MASK_TEX (1 << 3)
607 GCRA(Function
*, SpillCodeInserter
&);
610 bool allocateRegisters(ArrayList
& insns
);
612 void printNodeInfo() const;
615 class RIG_Node
: public Graph::Node
620 void init(const RegisterSet
&, LValue
*);
622 void addInterference(RIG_Node
*);
623 void addRegPreference(RIG_Node
*);
625 inline LValue
*getValue() const
627 return reinterpret_cast<LValue
*>(data
);
629 inline void setValue(LValue
*lval
) { data
= lval
; }
631 inline uint8_t getCompMask() const
633 return ((1 << colors
) - 1) << (reg
& 7);
636 static inline RIG_Node
*get(const Graph::EdgeIterator
& ei
)
638 return static_cast<RIG_Node
*>(ei
.getNode());
643 uint16_t degreeLimit
; // if deg < degLimit, node is trivially colourable
651 // list pointers for simplify() phase
655 // union of the live intervals of all coalesced values (we want to retain
656 // the separate intervals for testing interference of compound values)
659 std::list
<RIG_Node
*> prefRegs
;
663 inline RIG_Node
*getNode(const LValue
*v
) const { return &nodes
[v
->id
]; }
665 void buildRIG(ArrayList
&);
666 bool coalesce(ArrayList
&);
667 bool doCoalesce(ArrayList
&, unsigned int mask
);
668 void calculateSpillWeights();
670 bool selectRegisters();
671 void cleanup(const bool success
);
673 void simplifyEdge(RIG_Node
*, RIG_Node
*);
674 void simplifyNode(RIG_Node
*);
676 bool coalesceValues(Value
*, Value
*, bool force
);
677 void resolveSplitsAndMerges();
678 void makeCompound(Instruction
*, bool isSplit
);
680 inline void checkInterference(const RIG_Node
*, Graph::EdgeIterator
&);
682 inline void insertOrderedTail(std::list
<RIG_Node
*>&, RIG_Node
*);
683 void checkList(std::list
<RIG_Node
*>&);
686 std::stack
<uint32_t> stack
;
688 // list headers for simplify() phase
694 unsigned int nodeCount
;
699 static uint8_t relDegree
[17][17];
703 // need to fixup register id for participants of OP_MERGE/SPLIT
704 std::list
<Instruction
*> merges
;
705 std::list
<Instruction
*> splits
;
707 SpillCodeInserter
& spill
;
708 std::list
<ValuePair
> mustSpill
;
711 uint8_t GCRA::relDegree
[17][17];
713 GCRA::RIG_Node::RIG_Node() : Node(NULL
), next(this), prev(this)
719 GCRA::printNodeInfo() const
721 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
722 if (!nodes
[i
].colors
)
724 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
726 nodes
[i
].f
,nodes
[i
].reg
,nodes
[i
].colors
,
728 nodes
[i
].degree
, nodes
[i
].degreeLimit
);
730 for (Graph::EdgeIterator ei
= nodes
[i
].outgoing(); !ei
.end(); ei
.next())
731 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
732 for (Graph::EdgeIterator ei
= nodes
[i
].incident(); !ei
.end(); ei
.next())
733 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
739 GCRA::RIG_Node::init(const RegisterSet
& regs
, LValue
*lval
)
742 if (lval
->reg
.data
.id
>= 0)
743 lval
->noSpill
= lval
->fixedReg
= 1;
745 colors
= regs
.units(lval
->reg
.file
, lval
->reg
.size
);
748 if (lval
->reg
.data
.id
>= 0)
749 reg
= regs
.idToUnits(lval
);
751 weight
= std::numeric_limits
<float>::infinity();
753 degreeLimit
= regs
.getFileSize(f
, lval
->reg
.size
);
755 livei
.insert(lval
->livei
);
759 GCRA::coalesceValues(Value
*dst
, Value
*src
, bool force
)
761 LValue
*rep
= dst
->join
->asLValue();
762 LValue
*val
= src
->join
->asLValue();
764 if (!force
&& val
->reg
.data
.id
>= 0) {
765 rep
= src
->join
->asLValue();
766 val
= dst
->join
->asLValue();
768 RIG_Node
*nRep
= &nodes
[rep
->id
];
769 RIG_Node
*nVal
= &nodes
[val
->id
];
771 if (src
->reg
.file
!= dst
->reg
.file
) {
774 WARN("forced coalescing of values in different files !\n");
776 if (!force
&& dst
->reg
.size
!= src
->reg
.size
)
779 if ((rep
->reg
.data
.id
>= 0) && (rep
->reg
.data
.id
!= val
->reg
.data
.id
)) {
781 if (val
->reg
.data
.id
>= 0)
782 WARN("forced coalescing of values in different fixed regs !\n");
784 if (val
->reg
.data
.id
>= 0)
786 // make sure that there is no overlap with the fixed register of rep
787 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
788 !it
.end(); it
.next()) {
789 Value
*reg
= reinterpret_cast<Value
*>(it
.get())->asLValue();
791 if (reg
->interfers(rep
) && reg
->livei
.overlaps(nVal
->livei
))
797 if (!force
&& nRep
->livei
.overlaps(nVal
->livei
))
800 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "joining %%%i($%i) <- %%%i\n",
801 rep
->id
, rep
->reg
.data
.id
, val
->id
);
803 // set join pointer of all values joined with val
804 for (Value::DefIterator def
= val
->defs
.begin(); def
!= val
->defs
.end();
806 (*def
)->get()->join
= rep
;
807 assert(rep
->join
== rep
&& val
->join
== rep
);
809 // add val's definitions to rep and extend the live interval of its RIG node
810 rep
->defs
.insert(rep
->defs
.end(), val
->defs
.begin(), val
->defs
.end());
811 nRep
->livei
.unify(nVal
->livei
);
816 GCRA::coalesce(ArrayList
& insns
)
818 bool ret
= doCoalesce(insns
, JOIN_MASK_PHI
);
821 switch (func
->getProgram()->getTarget()->getChipset() & ~0xf) {
826 ret
= doCoalesce(insns
, JOIN_MASK_UNION
| JOIN_MASK_TEX
);
831 ret
= doCoalesce(insns
, JOIN_MASK_UNION
);
838 return doCoalesce(insns
, JOIN_MASK_MOV
);
841 static inline uint8_t makeCompMask(int compSize
, int base
, int size
)
843 uint8_t m
= ((1 << size
) - 1) << base
;
855 assert(compSize
<= 8);
860 // Used when coalescing moves. The non-compound value will become one, e.g.:
861 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
862 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
863 static inline void copyCompound(Value
*dst
, Value
*src
)
865 LValue
*ldst
= dst
->asLValue();
866 LValue
*lsrc
= src
->asLValue();
868 if (ldst
->compound
&& !lsrc
->compound
) {
874 ldst
->compound
= lsrc
->compound
;
875 ldst
->compMask
= lsrc
->compMask
;
879 GCRA::makeCompound(Instruction
*insn
, bool split
)
881 LValue
*rep
= (split
? insn
->getSrc(0) : insn
->getDef(0))->asLValue();
883 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
884 INFO("makeCompound(split = %i): ", split
);
888 const unsigned int size
= getNode(rep
)->colors
;
889 unsigned int base
= 0;
892 rep
->compMask
= 0xff;
895 for (int c
= 0; split
? insn
->defExists(c
) : insn
->srcExists(c
); ++c
) {
896 LValue
*val
= (split
? insn
->getDef(c
) : insn
->getSrc(c
))->asLValue();
900 val
->compMask
= 0xff;
901 val
->compMask
&= makeCompMask(size
, base
, getNode(val
)->colors
);
902 assert(val
->compMask
);
904 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "compound: %%%i:%02x <- %%%i:%02x\n",
905 rep
->id
, rep
->compMask
, val
->id
, val
->compMask
);
907 base
+= getNode(val
)->colors
;
909 assert(base
== size
);
913 GCRA::doCoalesce(ArrayList
& insns
, unsigned int mask
)
917 for (n
= 0; n
< insns
.getSize(); ++n
) {
919 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(n
));
923 if (!(mask
& JOIN_MASK_PHI
))
925 for (c
= 0; insn
->srcExists(c
); ++c
)
926 if (!coalesceValues(insn
->getDef(0), insn
->getSrc(c
), false)) {
928 ERROR("failed to coalesce phi operands\n");
934 if (!(mask
& JOIN_MASK_UNION
))
936 for (c
= 0; insn
->srcExists(c
); ++c
)
937 coalesceValues(insn
->getDef(0), insn
->getSrc(c
), true);
938 if (insn
->op
== OP_MERGE
) {
939 merges
.push_back(insn
);
940 if (insn
->srcExists(1))
941 makeCompound(insn
, false);
945 if (!(mask
& JOIN_MASK_UNION
))
947 splits
.push_back(insn
);
948 for (c
= 0; insn
->defExists(c
); ++c
)
949 coalesceValues(insn
->getSrc(0), insn
->getDef(c
), true);
950 makeCompound(insn
, true);
953 if (!(mask
& JOIN_MASK_MOV
))
956 if (!insn
->getDef(0)->uses
.empty())
957 i
= insn
->getDef(0)->uses
.front()->getInsn();
958 // if this is a contraint-move there will only be a single use
959 if (i
&& i
->op
== OP_MERGE
) // do we really still need this ?
961 i
= insn
->getSrc(0)->getUniqueInsn();
962 if (i
&& !i
->constrainedDefs()) {
963 if (coalesceValues(insn
->getDef(0), insn
->getSrc(0), false))
964 copyCompound(insn
->getSrc(0), insn
->getDef(0));
975 if (!(mask
& JOIN_MASK_TEX
))
977 for (c
= 0; insn
->srcExists(c
) && c
!= insn
->predSrc
; ++c
)
978 coalesceValues(insn
->getDef(c
), insn
->getSrc(c
), true);
988 GCRA::RIG_Node::addInterference(RIG_Node
*node
)
990 this->degree
+= relDegree
[node
->colors
][colors
];
991 node
->degree
+= relDegree
[colors
][node
->colors
];
993 this->attach(node
, Graph::Edge::CROSS
);
997 GCRA::RIG_Node::addRegPreference(RIG_Node
*node
)
999 prefRegs
.push_back(node
);
1002 GCRA::GCRA(Function
*fn
, SpillCodeInserter
& spill
) :
1004 regs(fn
->getProgram()->getTarget()),
1007 prog
= func
->getProgram();
1009 // initialize relative degrees array - i takes away from j
1010 for (int i
= 1; i
<= 16; ++i
)
1011 for (int j
= 1; j
<= 16; ++j
)
1012 relDegree
[i
][j
] = j
* ((i
+ j
- 1) / j
);
1022 GCRA::checkList(std::list
<RIG_Node
*>& lst
)
1024 GCRA::RIG_Node
*prev
= NULL
;
1026 for (std::list
<RIG_Node
*>::iterator it
= lst
.begin();
1029 assert((*it
)->getValue()->join
== (*it
)->getValue());
1031 assert(prev
->livei
.begin() <= (*it
)->livei
.begin());
1037 GCRA::insertOrderedTail(std::list
<RIG_Node
*>& list
, RIG_Node
*node
)
1039 if (node
->livei
.isEmpty())
1041 // only the intervals of joined values don't necessarily arrive in order
1042 std::list
<RIG_Node
*>::iterator prev
, it
;
1043 for (it
= list
.end(); it
!= list
.begin(); it
= prev
) {
1046 if ((*prev
)->livei
.begin() <= node
->livei
.begin())
1049 list
.insert(it
, node
);
1053 GCRA::buildRIG(ArrayList
& insns
)
1055 std::list
<RIG_Node
*> values
, active
;
1057 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
1058 it
!= func
->ins
.end(); ++it
)
1059 insertOrderedTail(values
, getNode(it
->get()->asLValue()));
1061 for (int i
= 0; i
< insns
.getSize(); ++i
) {
1062 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(i
));
1063 for (int d
= 0; insn
->defExists(d
); ++d
)
1064 if (insn
->getDef(d
)->rep() == insn
->getDef(d
))
1065 insertOrderedTail(values
, getNode(insn
->getDef(d
)->asLValue()));
1069 while (!values
.empty()) {
1070 RIG_Node
*cur
= values
.front();
1072 for (std::list
<RIG_Node
*>::iterator it
= active
.begin();
1073 it
!= active
.end();) {
1074 RIG_Node
*node
= *it
;
1076 if (node
->livei
.end() <= cur
->livei
.begin()) {
1077 it
= active
.erase(it
);
1079 if (node
->f
== cur
->f
&& node
->livei
.overlaps(cur
->livei
))
1080 cur
->addInterference(node
);
1085 active
.push_back(cur
);
1090 GCRA::calculateSpillWeights()
1092 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1093 RIG_Node
*const n
= &nodes
[i
];
1094 if (!nodes
[i
].colors
|| nodes
[i
].livei
.isEmpty())
1096 if (nodes
[i
].reg
>= 0) {
1098 regs
.occupy(n
->f
, n
->reg
, n
->colors
);
1101 LValue
*val
= nodes
[i
].getValue();
1103 if (!val
->noSpill
) {
1105 for (Value::DefIterator it
= val
->defs
.begin();
1106 it
!= val
->defs
.end();
1108 rc
+= (*it
)->get()->refCount();
1111 (float)rc
* (float)rc
/ (float)nodes
[i
].livei
.extent();
1114 if (nodes
[i
].degree
< nodes
[i
].degreeLimit
) {
1116 if (val
->reg
.size
> 4)
1118 DLLIST_ADDHEAD(&lo
[l
], &nodes
[i
]);
1120 DLLIST_ADDHEAD(&hi
, &nodes
[i
]);
1123 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1128 GCRA::simplifyEdge(RIG_Node
*a
, RIG_Node
*b
)
1130 bool move
= b
->degree
>= b
->degreeLimit
;
1132 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1133 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1134 a
->getValue()->id
, a
->degree
, a
->degreeLimit
,
1135 b
->getValue()->id
, b
->degree
, b
->degreeLimit
);
1137 b
->degree
-= relDegree
[a
->colors
][b
->colors
];
1139 move
= move
&& b
->degree
< b
->degreeLimit
;
1140 if (move
&& !DLLIST_EMPTY(b
)) {
1141 int l
= (b
->getValue()->reg
.size
> 4) ? 1 : 0;
1143 DLLIST_ADDTAIL(&lo
[l
], b
);
1148 GCRA::simplifyNode(RIG_Node
*node
)
1150 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1151 simplifyEdge(node
, RIG_Node::get(ei
));
1153 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1154 simplifyEdge(node
, RIG_Node::get(ei
));
1157 stack
.push(node
->getValue()->id
);
1159 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "SIMPLIFY: pushed %%%i%s\n",
1160 node
->getValue()->id
,
1161 (node
->degree
< node
->degreeLimit
) ? "" : "(spill)");
1168 if (!DLLIST_EMPTY(&lo
[0])) {
1170 simplifyNode(lo
[0].next
);
1171 } while (!DLLIST_EMPTY(&lo
[0]));
1173 if (!DLLIST_EMPTY(&lo
[1])) {
1174 simplifyNode(lo
[1].next
);
1176 if (!DLLIST_EMPTY(&hi
)) {
1177 RIG_Node
*best
= hi
.next
;
1178 float bestScore
= best
->weight
/ (float)best
->degree
;
1180 for (RIG_Node
*it
= best
->next
; it
!= &hi
; it
= it
->next
) {
1181 float score
= it
->weight
/ (float)it
->degree
;
1182 if (score
< bestScore
) {
1187 if (isinf(bestScore
)) {
1188 ERROR("no viable spill candidates left\n");
1199 GCRA::checkInterference(const RIG_Node
*node
, Graph::EdgeIterator
& ei
)
1201 const RIG_Node
*intf
= RIG_Node::get(ei
);
1205 const LValue
*vA
= node
->getValue();
1206 const LValue
*vB
= intf
->getValue();
1208 const uint8_t intfMask
= ((1 << intf
->colors
) - 1) << (intf
->reg
& 7);
1210 if (vA
->compound
| vB
->compound
) {
1211 // NOTE: this only works for >aligned< register tuples !
1212 for (Value::DefCIterator D
= vA
->defs
.begin(); D
!= vA
->defs
.end(); ++D
) {
1213 for (Value::DefCIterator d
= vB
->defs
.begin(); d
!= vB
->defs
.end(); ++d
) {
1214 const LValue
*vD
= (*D
)->get()->asLValue();
1215 const LValue
*vd
= (*d
)->get()->asLValue();
1217 if (!vD
->livei
.overlaps(vd
->livei
)) {
1218 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "(%%%i) X (%%%i): no overlap\n",
1223 uint8_t mask
= vD
->compound
? vD
->compMask
: ~0;
1225 assert(vB
->compound
);
1226 mask
&= vd
->compMask
& vB
->compMask
;
1231 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1232 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1234 vD
->compound
? vD
->compMask
: 0xff,
1236 vd
->compound
? vd
->compMask
: intfMask
,
1237 vB
->compMask
, intf
->reg
& ~7, mask
);
1239 regs
.occupyMask(node
->f
, intf
->reg
& ~7, mask
);
1243 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1244 "(%%%i) X (%%%i): $r%i + %u\n",
1245 vA
->id
, vB
->id
, intf
->reg
, intf
->colors
);
1246 regs
.occupy(node
->f
, intf
->reg
, intf
->colors
, true);
1251 GCRA::selectRegisters()
1253 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nSELECT phase\n");
1255 while (!stack
.empty()) {
1256 RIG_Node
*node
= &nodes
[stack
.top()];
1259 regs
.reset(node
->f
);
1261 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nNODE[%%%i, %u colors]\n",
1262 node
->getValue()->id
, node
->colors
);
1264 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1265 checkInterference(node
, ei
);
1266 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1267 checkInterference(node
, ei
);
1269 if (!node
->prefRegs
.empty()) {
1270 for (std::list
<RIG_Node
*>::const_iterator it
= node
->prefRegs
.begin();
1271 it
!= node
->prefRegs
.end();
1273 if ((*it
)->reg
>= 0 &&
1274 regs
.occupy(node
->f
, (*it
)->reg
, node
->colors
)) {
1275 node
->reg
= (*it
)->reg
;
1282 LValue
*lval
= node
->getValue();
1283 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1285 bool ret
= regs
.assign(node
->reg
, node
->f
, node
->colors
);
1287 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "assigned reg %i\n", node
->reg
);
1288 lval
->compMask
= node
->getCompMask();
1290 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "must spill: %%%i (size %u)\n",
1291 lval
->id
, lval
->reg
.size
);
1292 Symbol
*slot
= NULL
;
1293 if (lval
->reg
.file
== FILE_GPR
)
1294 slot
= spill
.assignSlot(node
->livei
, lval
->reg
.size
);
1295 mustSpill
.push_back(ValuePair(lval
, slot
));
1298 if (!mustSpill
.empty())
1300 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1301 LValue
*lval
= nodes
[i
].getValue();
1302 if (nodes
[i
].reg
>= 0 && nodes
[i
].colors
> 0)
1304 regs
.unitsToId(nodes
[i
].f
, nodes
[i
].reg
, lval
->reg
.size
);
1310 GCRA::allocateRegisters(ArrayList
& insns
)
1314 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1315 "allocateRegisters to %u instructions\n", insns
.getSize());
1317 nodeCount
= func
->allLValues
.getSize();
1318 nodes
= new RIG_Node
[nodeCount
];
1321 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1322 LValue
*lval
= reinterpret_cast<LValue
*>(func
->allLValues
.get(i
));
1324 nodes
[i
].init(regs
, lval
);
1325 RIG
.insert(&nodes
[i
]);
1329 // coalesce first, we use only 1 RIG node for a group of joined values
1330 ret
= coalesce(insns
);
1334 if (func
->getProgram()->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1335 func
->printLiveIntervals();
1338 calculateSpillWeights();
1341 ret
= selectRegisters();
1343 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1344 "selectRegisters failed, inserting spill code ...\n");
1345 regs
.reset(FILE_GPR
, true);
1346 spill
.run(mustSpill
);
1347 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1350 prog
->maxGPR
= std::max(prog
->maxGPR
, regs
.getMaxAssigned(FILE_GPR
));
1359 GCRA::cleanup(const bool success
)
1363 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
1364 !it
.end(); it
.next()) {
1365 LValue
*lval
= reinterpret_cast<LValue
*>(it
.get());
1367 lval
->livei
.clear();
1372 if (lval
->join
== lval
)
1376 lval
->reg
.data
.id
= lval
->join
->reg
.data
.id
;
1378 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1380 lval
->join
->defs
.remove(*d
);
1386 resolveSplitsAndMerges();
1387 splits
.clear(); // avoid duplicate entries on next coalesce pass
1395 SpillCodeInserter::assignSlot(const Interval
&livei
, const unsigned int size
)
1398 int32_t offsetBase
= stackSize
;
1400 std::list
<SpillSlot
>::iterator pos
= slots
.end(), it
= slots
.begin();
1402 if (offsetBase
% size
)
1403 offsetBase
+= size
- (offsetBase
% size
);
1407 for (offset
= offsetBase
; offset
< stackSize
; offset
+= size
) {
1408 const int32_t entryEnd
= offset
+ size
;
1409 while (it
!= slots
.end() && it
->offset
< offset
)
1411 if (it
== slots
.end()) // no slots left
1413 std::list
<SpillSlot
>::iterator bgn
= it
;
1415 while (it
!= slots
.end() && it
->offset
< entryEnd
) {
1417 if (it
->occup
.overlaps(livei
))
1421 if (it
== slots
.end() || it
->offset
>= entryEnd
) {
1423 for (; bgn
!= slots
.end() && bgn
->offset
< entryEnd
; ++bgn
) {
1424 bgn
->occup
.insert(livei
);
1425 if (bgn
->size() == size
)
1426 slot
.sym
= bgn
->sym
;
1432 stackSize
= offset
+ size
;
1433 slot
.offset
= offset
;
1434 slot
.sym
= new_Symbol(func
->getProgram(), FILE_MEMORY_LOCAL
);
1435 if (!func
->stackPtr
)
1436 offset
+= func
->tlsBase
;
1437 slot
.sym
->setAddress(NULL
, offset
);
1438 slot
.sym
->reg
.size
= size
;
1439 slots
.insert(pos
, slot
)->occup
.insert(livei
);
1445 SpillCodeInserter::spill(Instruction
*defi
, Value
*slot
, LValue
*lval
)
1447 const DataType ty
= typeOfSize(slot
->reg
.size
);
1450 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1451 st
= new_Instruction(func
, OP_STORE
, ty
);
1452 st
->setSrc(0, slot
);
1453 st
->setSrc(1, lval
);
1456 st
= new_Instruction(func
, OP_CVT
, ty
);
1457 st
->setDef(0, slot
);
1458 st
->setSrc(0, lval
);
1460 defi
->bb
->insertAfter(defi
, st
);
1464 SpillCodeInserter::unspill(Instruction
*usei
, LValue
*lval
, Value
*slot
)
1466 const DataType ty
= typeOfSize(slot
->reg
.size
);
1468 lval
= cloneShallow(func
, lval
);
1471 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1473 ld
= new_Instruction(func
, OP_LOAD
, ty
);
1475 ld
= new_Instruction(func
, OP_CVT
, ty
);
1477 ld
->setDef(0, lval
);
1478 ld
->setSrc(0, slot
);
1480 usei
->bb
->insertBefore(usei
, ld
);
1485 SpillCodeInserter::run(const std::list
<ValuePair
>& lst
)
1487 for (std::list
<ValuePair
>::const_iterator it
= lst
.begin(); it
!= lst
.end();
1489 LValue
*lval
= it
->first
->asLValue();
1490 Symbol
*mem
= it
->second
? it
->second
->asSym() : NULL
;
1492 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1495 static_cast<Value
*>(mem
) : new_LValue(func
, FILE_GPR
);
1497 Instruction
*last
= NULL
;
1499 LValue
*dval
= (*d
)->get()->asLValue();
1500 Instruction
*defi
= (*d
)->getInsn();
1502 // handle uses first or they'll contain the spill stores
1503 while (!dval
->uses
.empty()) {
1504 ValueRef
*u
= dval
->uses
.front();
1505 Instruction
*usei
= u
->getInsn();
1507 if (usei
->op
== OP_PHI
) {
1508 tmp
= (slot
->reg
.file
== FILE_MEMORY_LOCAL
) ? NULL
: slot
;
1511 if (!last
|| usei
!= last
->next
) { // TODO: sort uses
1512 tmp
= unspill(usei
, dval
, slot
);
1519 if (defi
->op
== OP_PHI
) {
1520 d
= lval
->defs
.erase(d
);
1522 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
)
1523 delete_Instruction(func
->getProgram(), defi
);
1525 defi
->setDef(0, slot
);
1527 spill(defi
, slot
, dval
);
1533 // TODO: We're not trying to reuse old slots in a potential next iteration.
1534 // We have to update the slots' livei intervals to be able to do that.
1535 stackBase
= stackSize
;
1543 for (IteratorRef it
= prog
->calls
.iteratorDFS(false);
1544 !it
->end(); it
->next()) {
1545 func
= Function::get(reinterpret_cast<Graph::Node
*>(it
->get()));
1547 func
->tlsBase
= prog
->tlsSize
;
1550 prog
->tlsSize
+= func
->tlsSize
;
1556 RegAlloc::execFunc()
1558 InsertConstraintsPass insertConstr
;
1559 PhiMovesPass insertPhiMoves
;
1560 ArgumentMovesPass insertArgMoves
;
1561 BuildIntervalsPass buildIntervals
;
1562 SpillCodeInserter
insertSpills(func
);
1564 GCRA
gcra(func
, insertSpills
);
1566 unsigned int i
, retries
;
1569 ret
= insertConstr
.exec(func
);
1573 ret
= insertPhiMoves
.run(func
);
1577 ret
= insertArgMoves
.run(func
);
1581 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1582 for (retries
= 0; retries
< 3; ++retries
) {
1583 if (retries
&& (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
))
1584 INFO("Retry: %i\n", retries
);
1585 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1588 // spilling to registers may add live ranges, need to rebuild everything
1590 for (sequence
= func
->cfg
.nextSequence(), i
= 0;
1591 ret
&& i
<= func
->loopNestingBound
;
1592 sequence
= func
->cfg
.nextSequence(), ++i
)
1593 ret
= buildLiveSets(BasicBlock::get(func
->cfg
.getRoot()));
1596 func
->orderInstructions(this->insns
);
1598 ret
= buildIntervals
.run(func
);
1601 ret
= gcra
.allocateRegisters(insns
);
1605 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "RegAlloc done: %i\n", ret
);
1607 func
->tlsSize
= insertSpills
.getStackSize();
1612 // TODO: check if modifying Instruction::join here breaks anything
1614 GCRA::resolveSplitsAndMerges()
1616 for (std::list
<Instruction
*>::iterator it
= splits
.begin();
1619 Instruction
*split
= *it
;
1620 unsigned int reg
= regs
.idToBytes(split
->getSrc(0));
1621 for (int d
= 0; split
->defExists(d
); ++d
) {
1622 Value
*v
= split
->getDef(d
);
1623 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1630 for (std::list
<Instruction
*>::iterator it
= merges
.begin();
1633 Instruction
*merge
= *it
;
1634 unsigned int reg
= regs
.idToBytes(merge
->getDef(0));
1635 for (int s
= 0; merge
->srcExists(s
); ++s
) {
1636 Value
*v
= merge
->getSrc(s
);
1637 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1645 bool Program::registerAllocation()
1652 RegAlloc::InsertConstraintsPass::exec(Function
*ir
)
1656 bool ret
= run(ir
, true, true);
1658 ret
= insertConstraintMoves();
1662 // TODO: make part of texture insn
1664 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction
*tex
)
1670 for (d
= 0, k
= 0, c
= 0; c
< 4; ++c
) {
1671 if (!(tex
->tex
.mask
& (1 << c
)))
1673 if (tex
->getDef(k
)->refCount()) {
1675 def
[d
++] = tex
->getDef(k
);
1679 tex
->tex
.mask
= mask
;
1681 for (c
= 0; c
< d
; ++c
)
1682 tex
->setDef(c
, def
[c
]);
1684 tex
->setDef(c
, NULL
);
1688 RegAlloc::InsertConstraintsPass::detectConflict(Instruction
*cst
, int s
)
1690 Value
*v
= cst
->getSrc(s
);
1692 // current register allocation can't handle it if a value participates in
1693 // multiple constraints
1694 for (Value::UseIterator it
= v
->uses
.begin(); it
!= v
->uses
.end(); ++it
) {
1695 if (cst
!= (*it
)->getInsn())
1699 // can start at s + 1 because detectConflict is called on all sources
1700 for (int c
= s
+ 1; cst
->srcExists(c
); ++c
)
1701 if (v
== cst
->getSrc(c
))
1704 Instruction
*defi
= v
->getInsn();
1706 return (!defi
|| defi
->constrainedDefs());
1710 RegAlloc::InsertConstraintsPass::addConstraint(Instruction
*i
, int s
, int n
)
1715 // first, look for an existing identical constraint op
1716 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
1717 it
!= constrList
.end();
1720 if (!i
->bb
->dominatedBy(cst
->bb
))
1722 for (d
= 0; d
< n
; ++d
)
1723 if (cst
->getSrc(d
) != i
->getSrc(d
+ s
))
1726 for (d
= 0; d
< n
; ++d
, ++s
)
1727 i
->setSrc(s
, cst
->getDef(d
));
1731 cst
= new_Instruction(func
, OP_CONSTRAINT
, i
->dType
);
1733 for (d
= 0; d
< n
; ++s
, ++d
) {
1734 cst
->setDef(d
, new_LValue(func
, FILE_GPR
));
1735 cst
->setSrc(d
, i
->getSrc(s
));
1736 i
->setSrc(s
, cst
->getDef(d
));
1738 i
->bb
->insertBefore(i
, cst
);
1740 constrList
.push_back(cst
);
1743 // Add a dummy use of the pointer source of >= 8 byte loads after the load
1744 // to prevent it from being assigned a register which overlapping the load's
1745 // destination, which would produce random corruptions.
1747 RegAlloc::InsertConstraintsPass::addHazard(Instruction
*i
, const ValueRef
*src
)
1749 Instruction
*hzd
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1750 hzd
->setSrc(0, src
->get());
1751 i
->bb
->insertAfter(i
, hzd
);
1755 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
1757 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction
*insn
)
1761 for (n
= 0; insn
->defExists(n
) && insn
->def(n
).getFile() == FILE_GPR
; ++n
)
1762 size
+= insn
->getDef(n
)->reg
.size
;
1765 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1766 lval
->reg
.size
= size
;
1768 Instruction
*split
= new_Instruction(func
, OP_SPLIT
, typeOfSize(size
));
1769 split
->setSrc(0, lval
);
1770 for (int d
= 0; d
< n
; ++d
) {
1771 split
->setDef(d
, insn
->getDef(d
));
1772 insn
->setDef(d
, NULL
);
1774 insn
->setDef(0, lval
);
1776 for (int k
= 1, d
= n
; insn
->defExists(d
); ++d
, ++k
) {
1777 insn
->setDef(k
, insn
->getDef(d
));
1778 insn
->setDef(d
, NULL
);
1780 // carry over predicate if any (mainly for OP_UNION uses)
1781 split
->setPredicate(insn
->cc
, insn
->getPredicate());
1783 insn
->bb
->insertAfter(insn
, split
);
1784 constrList
.push_back(split
);
1787 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction
*insn
,
1788 const int a
, const int b
)
1793 for (int s
= a
; s
<= b
; ++s
)
1794 size
+= insn
->getSrc(s
)->reg
.size
;
1797 LValue
*lval
= new_LValue(func
, FILE_GPR
);
1798 lval
->reg
.size
= size
;
1801 insn
->takeExtraSources(0, save
);
1803 Instruction
*merge
= new_Instruction(func
, OP_MERGE
, typeOfSize(size
));
1804 merge
->setDef(0, lval
);
1805 for (int s
= a
, i
= 0; s
<= b
; ++s
, ++i
) {
1806 merge
->setSrc(i
, insn
->getSrc(s
));
1807 insn
->setSrc(s
, NULL
);
1809 insn
->setSrc(a
, lval
);
1811 for (int k
= a
+ 1, s
= b
+ 1; insn
->srcExists(s
); ++s
, ++k
) {
1812 insn
->setSrc(k
, insn
->getSrc(s
));
1813 insn
->setSrc(s
, NULL
);
1815 insn
->bb
->insertBefore(insn
, merge
);
1817 insn
->putExtraSources(0, save
);
1819 constrList
.push_back(merge
);
1823 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction
*tex
)
1828 int n
= tex
->srcCount(0xff, true);
1830 condenseSrcs(tex
, 0, 3);
1831 if (n
> 5) // NOTE: first call modified positions already
1832 condenseSrcs(tex
, 4 - (4 - 1), n
- 1 - (4 - 1));
1835 condenseSrcs(tex
, 0, n
- 1);
1840 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction
*tex
)
1846 if (tex
->op
== OP_TXQ
) {
1847 s
= tex
->srcCount(0xff);
1850 s
= tex
->tex
.target
.getArgCount();
1851 if (!tex
->tex
.target
.isArray() &&
1852 (tex
->tex
.rIndirectSrc
>= 0 || tex
->tex
.sIndirectSrc
>= 0))
1854 if (tex
->op
== OP_TXD
&& tex
->tex
.useOffsets
)
1856 n
= tex
->srcCount(0xff) - s
;
1861 condenseSrcs(tex
, 0, s
- 1);
1862 if (n
> 1) // NOTE: first call modified positions already
1863 condenseSrcs(tex
, 1, n
);
1869 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction
*tex
)
1871 Value
*pred
= tex
->getPredicate();
1873 tex
->setPredicate(tex
->cc
, NULL
);
1877 assert(tex
->defExists(0) && tex
->srcExists(0));
1878 // make src and def count match
1880 for (c
= 0; tex
->srcExists(c
) || tex
->defExists(c
); ++c
) {
1881 if (!tex
->srcExists(c
))
1882 tex
->setSrc(c
, new_LValue(func
, tex
->getSrc(0)->asLValue()));
1883 if (!tex
->defExists(c
))
1884 tex
->setDef(c
, new_LValue(func
, tex
->getDef(0)->asLValue()));
1887 tex
->setPredicate(tex
->cc
, pred
);
1889 condenseSrcs(tex
, 0, c
- 1);
1892 // Insert constraint markers for instructions whose multiple sources must be
1893 // located in consecutive registers.
1895 RegAlloc::InsertConstraintsPass::visit(BasicBlock
*bb
)
1897 TexInstruction
*tex
;
1901 targ
= bb
->getProgram()->getTarget();
1903 for (Instruction
*i
= bb
->getEntry(); i
; i
= next
) {
1906 if ((tex
= i
->asTex())) {
1907 switch (targ
->getChipset() & ~0xf) {
1912 texConstraintNV50(tex
);
1916 texConstraintNVC0(tex
);
1919 case NVISA_GK110_CHIPSET
:
1920 texConstraintNVE0(tex
);
1926 if (i
->op
== OP_EXPORT
|| i
->op
== OP_STORE
) {
1927 for (size
= typeSizeof(i
->dType
), s
= 1; size
> 0; ++s
) {
1928 assert(i
->srcExists(s
));
1929 size
-= i
->getSrc(s
)->reg
.size
;
1931 condenseSrcs(i
, 1, s
- 1);
1933 if (i
->op
== OP_LOAD
|| i
->op
== OP_VFETCH
) {
1935 if (i
->src(0).isIndirect(0) && typeSizeof(i
->dType
) >= 8)
1936 addHazard(i
, i
->src(0).getIndirect(0));
1938 if (i
->op
== OP_UNION
) {
1939 constrList
.push_back(i
);
1945 // Insert extra moves so that, if multiple register constraints on a value are
1946 // in conflict, these conflicts can be resolved.
1948 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
1950 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
1951 it
!= constrList
.end();
1953 Instruction
*cst
= *it
;
1956 if (cst
->op
== OP_SPLIT
&& 0) {
1957 // spilling splits is annoying, just make sure they're separate
1958 for (int d
= 0; cst
->defExists(d
); ++d
) {
1959 if (!cst
->getDef(d
)->refCount())
1961 LValue
*lval
= new_LValue(func
, cst
->def(d
).getFile());
1962 const uint8_t size
= cst
->def(d
).getSize();
1963 lval
->reg
.size
= size
;
1965 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
1966 mov
->setSrc(0, lval
);
1967 mov
->setDef(0, cst
->getDef(d
));
1968 cst
->setDef(d
, mov
->getSrc(0));
1969 cst
->bb
->insertAfter(cst
, mov
);
1971 cst
->getSrc(0)->asLValue()->noSpill
= 1;
1972 mov
->getSrc(0)->asLValue()->noSpill
= 1;
1975 if (cst
->op
== OP_MERGE
|| cst
->op
== OP_UNION
) {
1976 for (int s
= 0; cst
->srcExists(s
); ++s
) {
1977 const uint8_t size
= cst
->src(s
).getSize();
1979 if (!cst
->getSrc(s
)->defs
.size()) {
1980 mov
= new_Instruction(func
, OP_NOP
, typeOfSize(size
));
1981 mov
->setDef(0, cst
->getSrc(s
));
1982 cst
->bb
->insertBefore(cst
, mov
);
1985 assert(cst
->getSrc(s
)->defs
.size() == 1); // still SSA
1987 Instruction
*defi
= cst
->getSrc(s
)->defs
.front()->getInsn();
1988 // catch some cases where don't really need MOVs
1989 if (cst
->getSrc(s
)->refCount() == 1 && !defi
->constrainedDefs())
1992 LValue
*lval
= new_LValue(func
, cst
->src(s
).getFile());
1993 lval
->reg
.size
= size
;
1995 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
1996 mov
->setDef(0, lval
);
1997 mov
->setSrc(0, cst
->getSrc(s
));
1998 cst
->setSrc(s
, mov
->getDef(0));
1999 cst
->bb
->insertBefore(cst
, mov
);
2001 cst
->getDef(0)->asLValue()->noSpill
= 1; // doesn't help
2003 if (cst
->op
== OP_UNION
)
2004 mov
->setPredicate(defi
->cc
, defi
->getPredicate());
2012 } // namespace nv50_ir