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"
29 #if __cplusplus >= 201103L
30 #include <unordered_map>
32 #include <tr1/unordered_map>
37 #if __cplusplus >= 201103L
39 using std::unordered_map
;
42 using std::tr1::unordered_map
;
45 #define MAX_REGISTER_FILE_SIZE 256
50 RegisterSet(const Target
*);
52 void init(const Target
*);
53 void reset(DataFile
, bool resetMax
= false);
55 void periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
);
56 void intersect(DataFile f
, const RegisterSet
*);
58 bool assign(int32_t& reg
, DataFile f
, unsigned int size
);
59 void release(DataFile f
, int32_t reg
, unsigned int size
);
60 void occupy(DataFile f
, int32_t reg
, unsigned int size
);
61 void occupy(const Value
*);
62 void occupyMask(DataFile f
, int32_t reg
, uint8_t mask
);
63 bool isOccupied(DataFile f
, int32_t reg
, unsigned int size
) const;
64 bool testOccupy(const Value
*);
65 bool testOccupy(DataFile f
, int32_t reg
, unsigned int size
);
67 inline int getMaxAssigned(DataFile f
) const { return fill
[f
]; }
69 inline unsigned int getFileSize(DataFile f
) const
74 inline unsigned int units(DataFile f
, unsigned int size
) const
76 return size
>> unit
[f
];
78 // for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)
79 inline unsigned int idToBytes(const Value
*v
) const
81 return v
->reg
.data
.id
* MIN2(v
->reg
.size
, 4);
83 inline unsigned int idToUnits(const Value
*v
) const
85 return units(v
->reg
.file
, idToBytes(v
));
87 inline int bytesToId(Value
*v
, unsigned int bytes
) const
90 return units(v
->reg
.file
, bytes
);
93 inline int unitsToId(DataFile f
, int u
, uint8_t size
) const
97 return (size
< 4) ? u
: ((u
<< unit
[f
]) / 4);
100 void print(DataFile f
) const;
102 const bool restrictedGPR16Range
;
105 BitSet bits
[LAST_REGISTER_FILE
+ 1];
107 int unit
[LAST_REGISTER_FILE
+ 1]; // log2 of allocation granularity
109 int last
[LAST_REGISTER_FILE
+ 1];
110 int fill
[LAST_REGISTER_FILE
+ 1];
114 RegisterSet::reset(DataFile f
, bool resetMax
)
122 RegisterSet::init(const Target
*targ
)
124 for (unsigned int rf
= 0; rf
<= FILE_ADDRESS
; ++rf
) {
125 DataFile f
= static_cast<DataFile
>(rf
);
126 last
[rf
] = targ
->getFileSize(f
) - 1;
127 unit
[rf
] = targ
->getFileUnit(f
);
129 assert(last
[rf
] < MAX_REGISTER_FILE_SIZE
);
130 bits
[rf
].allocate(last
[rf
] + 1, true);
134 RegisterSet::RegisterSet(const Target
*targ
)
135 : restrictedGPR16Range(targ
->getChipset() < 0xc0)
138 for (unsigned int i
= 0; i
<= LAST_REGISTER_FILE
; ++i
)
139 reset(static_cast<DataFile
>(i
));
143 RegisterSet::periodicMask(DataFile f
, uint32_t lock
, uint32_t unlock
)
145 bits
[f
].periodicMask32(lock
, unlock
);
149 RegisterSet::intersect(DataFile f
, const RegisterSet
*set
)
151 bits
[f
] |= set
->bits
[f
];
155 RegisterSet::print(DataFile f
) const
163 RegisterSet::assign(int32_t& reg
, DataFile f
, unsigned int size
)
165 reg
= bits
[f
].findFreeRange(size
);
168 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
173 RegisterSet::isOccupied(DataFile f
, int32_t reg
, unsigned int size
) const
175 return bits
[f
].testRange(reg
, size
);
179 RegisterSet::occupy(const Value
*v
)
181 occupy(v
->reg
.file
, idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
185 RegisterSet::occupyMask(DataFile f
, int32_t reg
, uint8_t mask
)
187 bits
[f
].setMask(reg
& ~31, static_cast<uint32_t>(mask
) << (reg
% 32));
191 RegisterSet::occupy(DataFile f
, int32_t reg
, unsigned int size
)
193 bits
[f
].setRange(reg
, size
);
195 INFO_DBG(0, REG_ALLOC
, "reg occupy: %u[%i] %u\n", f
, reg
, size
);
197 fill
[f
] = MAX2(fill
[f
], (int32_t)(reg
+ size
- 1));
201 RegisterSet::testOccupy(const Value
*v
)
203 return testOccupy(v
->reg
.file
,
204 idToUnits(v
), v
->reg
.size
>> unit
[v
->reg
.file
]);
208 RegisterSet::testOccupy(DataFile f
, int32_t reg
, unsigned int size
)
210 if (isOccupied(f
, reg
, size
))
212 occupy(f
, reg
, size
);
217 RegisterSet::release(DataFile f
, int32_t reg
, unsigned int size
)
219 bits
[f
].clrRange(reg
, size
);
221 INFO_DBG(0, REG_ALLOC
, "reg release: %u[%i] %u\n", f
, reg
, size
);
227 RegAlloc(Program
*program
) : prog(program
), sequence(0) { }
233 class PhiMovesPass
: public Pass
{
235 virtual bool visit(BasicBlock
*);
236 inline bool needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
);
237 inline void splitEdges(BasicBlock
*b
);
240 class ArgumentMovesPass
: public Pass
{
242 virtual bool visit(BasicBlock
*);
245 class BuildIntervalsPass
: public Pass
{
247 virtual bool visit(BasicBlock
*);
248 void collectLiveValues(BasicBlock
*);
249 void addLiveRange(Value
*, const BasicBlock
*, int end
);
252 class InsertConstraintsPass
: public Pass
{
254 bool exec(Function
*func
);
256 virtual bool visit(BasicBlock
*);
258 void insertConstraintMove(Instruction
*, int s
);
259 bool insertConstraintMoves();
261 void condenseDefs(Instruction
*);
262 void condenseDefs(Instruction
*, const int first
, const int last
);
263 void condenseSrcs(Instruction
*, const int first
, const int last
);
265 void addHazard(Instruction
*i
, const ValueRef
*src
);
266 void textureMask(TexInstruction
*);
267 void addConstraint(Instruction
*, int s
, int n
);
268 bool detectConflict(Instruction
*, int s
);
270 // target specific functions, TODO: put in subclass or Target
271 void texConstraintNV50(TexInstruction
*);
272 void texConstraintNVC0(TexInstruction
*);
273 void texConstraintNVE0(TexInstruction
*);
274 void texConstraintGM107(TexInstruction
*);
276 bool isScalarTexGM107(TexInstruction
*);
277 void handleScalarTexGM107(TexInstruction
*);
279 std::list
<Instruction
*> constrList
;
284 bool buildLiveSets(BasicBlock
*);
290 // instructions in control flow / chronological order
293 int sequence
; // for manual passes through CFG
296 typedef std::pair
<Value
*, Value
*> ValuePair
;
298 class SpillCodeInserter
301 SpillCodeInserter(Function
*fn
) : func(fn
), stackSize(0), stackBase(0) { }
303 bool run(const std::list
<ValuePair
>&);
305 Symbol
*assignSlot(const Interval
&, const unsigned int size
);
306 Value
*offsetSlot(Value
*, const LValue
*);
307 inline int32_t getStackSize() const { return stackSize
; }
315 std::list
<Value
*> residents
; // needed to recalculate occup
318 inline uint8_t size() const { return sym
->reg
.size
; }
320 std::list
<SpillSlot
> slots
;
324 LValue
*unspill(Instruction
*usei
, LValue
*, Value
*slot
);
325 void spill(Instruction
*defi
, Value
*slot
, LValue
*);
329 RegAlloc::BuildIntervalsPass::addLiveRange(Value
*val
,
330 const BasicBlock
*bb
,
333 Instruction
*insn
= val
->getUniqueInsn();
336 insn
= bb
->getFirst();
338 assert(bb
->getFirst()->serial
<= bb
->getExit()->serial
);
339 assert(bb
->getExit()->serial
+ 1 >= end
);
341 int begin
= insn
->serial
;
342 if (begin
< bb
->getEntry()->serial
|| begin
> bb
->getExit()->serial
)
343 begin
= bb
->getEntry()->serial
;
345 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "%%%i <- live range [%i(%i), %i)\n",
346 val
->id
, begin
, insn
->serial
, end
);
348 if (begin
!= end
) // empty ranges are only added as hazards for fixed regs
349 val
->livei
.extend(begin
, end
);
353 RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock
*b
, BasicBlock
*p
)
355 if (b
->cfg
.incidentCount() <= 1)
359 for (Graph::EdgeIterator ei
= p
->cfg
.outgoing(); !ei
.end(); ei
.next())
360 if (ei
.getType() == Graph::Edge::TREE
||
361 ei
.getType() == Graph::Edge::FORWARD
)
367 size_t operator()(const std::pair
<Instruction
*, BasicBlock
*>& val
) const {
368 return hash
<Instruction
*>()(val
.first
) * 31 +
369 hash
<BasicBlock
*>()(val
.second
);
373 typedef unordered_map
<
374 std::pair
<Instruction
*, BasicBlock
*>, Value
*, PhiMapHash
> PhiMap
;
376 // Critical edges need to be split up so that work can be inserted along
377 // specific edge transitions. Unfortunately manipulating incident edges into a
378 // BB invalidates all the PHI nodes since their sources are implicitly ordered
379 // by incident edge order.
381 // TODO: Make it so that that is not the case, and PHI nodes store pointers to
384 RegAlloc::PhiMovesPass::splitEdges(BasicBlock
*bb
)
388 Graph::EdgeIterator ei
;
389 std::stack
<BasicBlock
*> stack
;
392 for (ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
393 pb
= BasicBlock::get(ei
.getNode());
395 if (needNewElseBlock(bb
, pb
))
399 // No critical edges were found, no need to perform any work.
403 // We're about to, potentially, reorder the inbound edges. This means that
404 // we need to hold on to the (phi, bb) -> src mapping, and fix up the phi
405 // nodes after the graph has been modified.
409 for (ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next(), j
++) {
410 pb
= BasicBlock::get(ei
.getNode());
411 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
)
412 phis
.insert(std::make_pair(std::make_pair(phi
, pb
), phi
->getSrc(j
)));
415 while (!stack
.empty()) {
417 pn
= new BasicBlock(func
);
420 pb
->cfg
.detach(&bb
->cfg
);
421 pb
->cfg
.attach(&pn
->cfg
, Graph::Edge::TREE
);
422 pn
->cfg
.attach(&bb
->cfg
, Graph::Edge::FORWARD
);
424 assert(pb
->getExit()->op
!= OP_CALL
);
425 if (pb
->getExit()->asFlow()->target
.bb
== bb
)
426 pb
->getExit()->asFlow()->target
.bb
= pn
;
428 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
) {
429 PhiMap::iterator it
= phis
.find(std::make_pair(phi
, pb
));
430 assert(it
!= phis
.end());
431 phis
.insert(std::make_pair(std::make_pair(phi
, pn
), it
->second
));
436 // Now go through and fix up all of the phi node sources.
438 for (ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next(), j
++) {
439 pb
= BasicBlock::get(ei
.getNode());
440 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
) {
441 PhiMap::const_iterator it
= phis
.find(std::make_pair(phi
, pb
));
442 assert(it
!= phis
.end());
444 phi
->setSrc(j
, it
->second
);
449 // For each operand of each PHI in b, generate a new value by inserting a MOV
450 // at the end of the block it is coming from and replace the operand with its
451 // result. This eliminates liveness conflicts and enables us to let values be
452 // copied to the right register if such a conflict exists nonetheless.
454 // These MOVs are also crucial in making sure the live intervals of phi srces
455 // are extended until the end of the loop, since they are not included in the
458 RegAlloc::PhiMovesPass::visit(BasicBlock
*bb
)
460 Instruction
*phi
, *mov
;
464 // insert MOVs (phi->src(j) should stem from j-th in-BB)
466 for (Graph::EdgeIterator ei
= bb
->cfg
.incident(); !ei
.end(); ei
.next()) {
467 BasicBlock
*pb
= BasicBlock::get(ei
.getNode());
468 if (!pb
->isTerminated())
469 pb
->insertTail(new_FlowInstruction(func
, OP_BRA
, bb
));
471 for (phi
= bb
->getPhi(); phi
&& phi
->op
== OP_PHI
; phi
= phi
->next
) {
472 LValue
*tmp
= new_LValue(func
, phi
->getDef(0)->asLValue());
473 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
475 mov
->setSrc(0, phi
->getSrc(j
));
479 pb
->insertBefore(pb
->getExit(), mov
);
488 RegAlloc::ArgumentMovesPass::visit(BasicBlock
*bb
)
490 // Bind function call inputs/outputs to the same physical register
491 // the callee uses, inserting moves as appropriate for the case a
493 for (Instruction
*i
= bb
->getEntry(); i
; i
= i
->next
) {
494 FlowInstruction
*cal
= i
->asFlow();
495 // TODO: Handle indirect calls.
496 // Right now they should only be generated for builtins.
497 if (!cal
|| cal
->op
!= OP_CALL
|| cal
->builtin
|| cal
->indirect
)
499 RegisterSet
clobberSet(prog
->getTarget());
501 // Bind input values.
502 for (int s
= cal
->indirect
? 1 : 0; cal
->srcExists(s
); ++s
) {
503 const int t
= cal
->indirect
? (s
- 1) : s
;
504 LValue
*tmp
= new_LValue(func
, cal
->getSrc(s
)->asLValue());
505 tmp
->reg
.data
.id
= cal
->target
.fn
->ins
[t
].rep()->reg
.data
.id
;
508 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
510 mov
->setSrc(0, cal
->getSrc(s
));
513 bb
->insertBefore(cal
, mov
);
516 // Bind output values.
517 for (int d
= 0; cal
->defExists(d
); ++d
) {
518 LValue
*tmp
= new_LValue(func
, cal
->getDef(d
)->asLValue());
519 tmp
->reg
.data
.id
= cal
->target
.fn
->outs
[d
].rep()->reg
.data
.id
;
522 new_Instruction(func
, OP_MOV
, typeOfSize(tmp
->reg
.size
));
524 mov
->setDef(0, cal
->getDef(d
));
527 bb
->insertAfter(cal
, mov
);
528 clobberSet
.occupy(tmp
);
531 // Bind clobbered values.
532 for (std::deque
<Value
*>::iterator it
= cal
->target
.fn
->clobbers
.begin();
533 it
!= cal
->target
.fn
->clobbers
.end();
535 if (clobberSet
.testOccupy(*it
)) {
536 Value
*tmp
= new_LValue(func
, (*it
)->asLValue());
537 tmp
->reg
.data
.id
= (*it
)->reg
.data
.id
;
538 cal
->setDef(cal
->defCount(), tmp
);
543 // Update the clobber set of the function.
544 if (BasicBlock::get(func
->cfgExit
) == bb
) {
545 func
->buildDefSets();
546 for (unsigned int i
= 0; i
< bb
->defSet
.getSize(); ++i
)
547 if (bb
->defSet
.test(i
))
548 func
->clobbers
.push_back(func
->getLValue(i
));
554 // Build the set of live-in variables of bb.
556 RegAlloc::buildLiveSets(BasicBlock
*bb
)
558 Function
*f
= bb
->getFunction();
563 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "buildLiveSets(BB:%i)\n", bb
->getId());
565 bb
->liveSet
.allocate(func
->allLValues
.getSize(), false);
568 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
569 bn
= BasicBlock::get(ei
.getNode());
572 if (bn
->cfg
.visit(sequence
))
573 if (!buildLiveSets(bn
))
575 if (n
++ || bb
->liveSet
.marker
)
576 bb
->liveSet
|= bn
->liveSet
;
578 bb
->liveSet
= bn
->liveSet
;
580 if (!n
&& !bb
->liveSet
.marker
)
582 bb
->liveSet
.marker
= true;
584 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
585 INFO("BB:%i live set of out blocks:\n", bb
->getId());
589 // if (!bb->getEntry())
592 if (bb
== BasicBlock::get(f
->cfgExit
)) {
593 for (std::deque
<ValueRef
>::iterator it
= f
->outs
.begin();
594 it
!= f
->outs
.end(); ++it
) {
595 assert(it
->get()->asLValue());
596 bb
->liveSet
.set(it
->get()->id
);
600 for (i
= bb
->getExit(); i
&& i
!= bb
->getEntry()->prev
; i
= i
->prev
) {
601 for (d
= 0; i
->defExists(d
); ++d
)
602 bb
->liveSet
.clr(i
->getDef(d
)->id
);
603 for (s
= 0; i
->srcExists(s
); ++s
)
604 if (i
->getSrc(s
)->asLValue())
605 bb
->liveSet
.set(i
->getSrc(s
)->id
);
607 for (i
= bb
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
)
608 bb
->liveSet
.clr(i
->getDef(0)->id
);
610 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
611 INFO("BB:%i live set after propagation:\n", bb
->getId());
619 RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock
*bb
)
621 BasicBlock
*bbA
= NULL
, *bbB
= NULL
;
623 if (bb
->cfg
.outgoingCount()) {
624 // trickery to save a loop of OR'ing liveSets
625 // aliasing works fine with BitSet::setOr
626 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
627 if (ei
.getType() == Graph::Edge::DUMMY
)
630 bb
->liveSet
.setOr(&bbA
->liveSet
, &bbB
->liveSet
);
635 bbB
= BasicBlock::get(ei
.getNode());
637 bb
->liveSet
.setOr(&bbB
->liveSet
, bbA
? &bbA
->liveSet
: NULL
);
639 if (bb
->cfg
.incidentCount()) {
645 RegAlloc::BuildIntervalsPass::visit(BasicBlock
*bb
)
647 collectLiveValues(bb
);
649 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "BuildIntervals(BB:%i)\n", bb
->getId());
651 // go through out blocks and delete phi sources that do not originate from
652 // the current block from the live set
653 for (Graph::EdgeIterator ei
= bb
->cfg
.outgoing(); !ei
.end(); ei
.next()) {
654 BasicBlock
*out
= BasicBlock::get(ei
.getNode());
656 for (Instruction
*i
= out
->getPhi(); i
&& i
->op
== OP_PHI
; i
= i
->next
) {
657 bb
->liveSet
.clr(i
->getDef(0)->id
);
659 for (int s
= 0; i
->srcExists(s
); ++s
) {
660 assert(i
->src(s
).getInsn());
661 if (i
->getSrc(s
)->getUniqueInsn()->bb
== bb
) // XXX: reachableBy ?
662 bb
->liveSet
.set(i
->getSrc(s
)->id
);
664 bb
->liveSet
.clr(i
->getSrc(s
)->id
);
669 // remaining live-outs are live until end
671 for (unsigned int j
= 0; j
< bb
->liveSet
.getSize(); ++j
)
672 if (bb
->liveSet
.test(j
))
673 addLiveRange(func
->getLValue(j
), bb
, bb
->getExit()->serial
+ 1);
676 for (Instruction
*i
= bb
->getExit(); i
&& i
->op
!= OP_PHI
; i
= i
->prev
) {
677 for (int d
= 0; i
->defExists(d
); ++d
) {
678 bb
->liveSet
.clr(i
->getDef(d
)->id
);
679 if (i
->getDef(d
)->reg
.data
.id
>= 0) // add hazard for fixed regs
680 i
->getDef(d
)->livei
.extend(i
->serial
, i
->serial
);
683 for (int s
= 0; i
->srcExists(s
); ++s
) {
684 if (!i
->getSrc(s
)->asLValue())
686 if (!bb
->liveSet
.test(i
->getSrc(s
)->id
)) {
687 bb
->liveSet
.set(i
->getSrc(s
)->id
);
688 addLiveRange(i
->getSrc(s
), bb
, i
->serial
);
693 if (bb
== BasicBlock::get(func
->cfg
.getRoot())) {
694 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
695 it
!= func
->ins
.end(); ++it
) {
696 if (it
->get()->reg
.data
.id
>= 0) // add hazard for fixed regs
697 it
->get()->livei
.extend(0, 1);
705 #define JOIN_MASK_PHI (1 << 0)
706 #define JOIN_MASK_UNION (1 << 1)
707 #define JOIN_MASK_MOV (1 << 2)
708 #define JOIN_MASK_TEX (1 << 3)
713 GCRA(Function
*, SpillCodeInserter
&);
716 bool allocateRegisters(ArrayList
& insns
);
718 void printNodeInfo() const;
721 class RIG_Node
: public Graph::Node
726 void init(const RegisterSet
&, LValue
*);
728 void addInterference(RIG_Node
*);
729 void addRegPreference(RIG_Node
*);
731 inline LValue
*getValue() const
733 return reinterpret_cast<LValue
*>(data
);
735 inline void setValue(LValue
*lval
) { data
= lval
; }
737 inline uint8_t getCompMask() const
739 return ((1 << colors
) - 1) << (reg
& 7);
742 static inline RIG_Node
*get(const Graph::EdgeIterator
& ei
)
744 return static_cast<RIG_Node
*>(ei
.getNode());
749 uint16_t degreeLimit
; // if deg < degLimit, node is trivially colourable
757 // list pointers for simplify() phase
761 // union of the live intervals of all coalesced values (we want to retain
762 // the separate intervals for testing interference of compound values)
765 std::list
<RIG_Node
*> prefRegs
;
769 inline RIG_Node
*getNode(const LValue
*v
) const { return &nodes
[v
->id
]; }
771 void buildRIG(ArrayList
&);
772 bool coalesce(ArrayList
&);
773 bool doCoalesce(ArrayList
&, unsigned int mask
);
774 void calculateSpillWeights();
776 bool selectRegisters();
777 void cleanup(const bool success
);
779 void simplifyEdge(RIG_Node
*, RIG_Node
*);
780 void simplifyNode(RIG_Node
*);
782 bool coalesceValues(Value
*, Value
*, bool force
);
783 void resolveSplitsAndMerges();
784 void makeCompound(Instruction
*, bool isSplit
);
786 inline void checkInterference(const RIG_Node
*, Graph::EdgeIterator
&);
788 inline void insertOrderedTail(std::list
<RIG_Node
*>&, RIG_Node
*);
789 void checkList(std::list
<RIG_Node
*>&);
792 std::stack
<uint32_t> stack
;
794 // list headers for simplify() phase
800 unsigned int nodeCount
;
805 static uint8_t relDegree
[17][17];
809 // need to fixup register id for participants of OP_MERGE/SPLIT
810 std::list
<Instruction
*> merges
;
811 std::list
<Instruction
*> splits
;
813 SpillCodeInserter
& spill
;
814 std::list
<ValuePair
> mustSpill
;
817 uint8_t GCRA::relDegree
[17][17];
819 GCRA::RIG_Node::RIG_Node() : Node(NULL
), next(this), prev(this)
825 GCRA::printNodeInfo() const
827 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
828 if (!nodes
[i
].colors
)
830 INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",
832 nodes
[i
].f
,nodes
[i
].reg
,nodes
[i
].colors
,
834 nodes
[i
].degree
, nodes
[i
].degreeLimit
);
836 for (Graph::EdgeIterator ei
= nodes
[i
].outgoing(); !ei
.end(); ei
.next())
837 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
838 for (Graph::EdgeIterator ei
= nodes
[i
].incident(); !ei
.end(); ei
.next())
839 INFO(" %%%i", RIG_Node::get(ei
)->getValue()->id
);
845 isShortRegOp(Instruction
*insn
)
847 // Immediates are always in src1 (except zeroes, which end up getting
848 // replaced with a zero reg). Every other situation can be resolved by
849 // using a long encoding.
850 return insn
->srcExists(1) && insn
->src(1).getFile() == FILE_IMMEDIATE
&&
851 insn
->getSrc(1)->reg
.data
.u64
;
854 // Check if this LValue is ever used in an instruction that can't be encoded
855 // with long registers (i.e. > r63)
857 isShortRegVal(LValue
*lval
)
859 if (lval
->getInsn() == NULL
)
861 for (Value::DefCIterator def
= lval
->defs
.begin();
862 def
!= lval
->defs
.end(); ++def
)
863 if (isShortRegOp((*def
)->getInsn()))
865 for (Value::UseCIterator use
= lval
->uses
.begin();
866 use
!= lval
->uses
.end(); ++use
)
867 if (isShortRegOp((*use
)->getInsn()))
873 GCRA::RIG_Node::init(const RegisterSet
& regs
, LValue
*lval
)
876 if (lval
->reg
.data
.id
>= 0)
877 lval
->noSpill
= lval
->fixedReg
= 1;
879 colors
= regs
.units(lval
->reg
.file
, lval
->reg
.size
);
882 if (lval
->reg
.data
.id
>= 0)
883 reg
= regs
.idToUnits(lval
);
885 weight
= std::numeric_limits
<float>::infinity();
887 int size
= regs
.getFileSize(f
);
888 // On nv50, we lose a bit of gpr encoding when there's an embedded
890 if (regs
.restrictedGPR16Range
&& f
== FILE_GPR
&& (lval
->reg
.size
== 2 || isShortRegVal(lval
)))
893 degreeLimit
-= relDegree
[1][colors
] - 1;
895 livei
.insert(lval
->livei
);
899 GCRA::coalesceValues(Value
*dst
, Value
*src
, bool force
)
901 LValue
*rep
= dst
->join
->asLValue();
902 LValue
*val
= src
->join
->asLValue();
904 if (!force
&& val
->reg
.data
.id
>= 0) {
905 rep
= src
->join
->asLValue();
906 val
= dst
->join
->asLValue();
908 RIG_Node
*nRep
= &nodes
[rep
->id
];
909 RIG_Node
*nVal
= &nodes
[val
->id
];
911 if (src
->reg
.file
!= dst
->reg
.file
) {
914 WARN("forced coalescing of values in different files !\n");
916 if (!force
&& dst
->reg
.size
!= src
->reg
.size
)
919 if ((rep
->reg
.data
.id
>= 0) && (rep
->reg
.data
.id
!= val
->reg
.data
.id
)) {
921 if (val
->reg
.data
.id
>= 0)
922 WARN("forced coalescing of values in different fixed regs !\n");
924 if (val
->reg
.data
.id
>= 0)
926 // make sure that there is no overlap with the fixed register of rep
927 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
928 !it
.end(); it
.next()) {
929 Value
*reg
= reinterpret_cast<Value
*>(it
.get())->asLValue();
931 if (reg
->interfers(rep
) && reg
->livei
.overlaps(nVal
->livei
))
937 if (!force
&& nRep
->livei
.overlaps(nVal
->livei
))
940 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "joining %%%i($%i) <- %%%i\n",
941 rep
->id
, rep
->reg
.data
.id
, val
->id
);
943 // set join pointer of all values joined with val
944 for (Value::DefIterator def
= val
->defs
.begin(); def
!= val
->defs
.end();
946 (*def
)->get()->join
= rep
;
947 assert(rep
->join
== rep
&& val
->join
== rep
);
949 // add val's definitions to rep and extend the live interval of its RIG node
950 rep
->defs
.insert(rep
->defs
.end(), val
->defs
.begin(), val
->defs
.end());
951 nRep
->livei
.unify(nVal
->livei
);
956 GCRA::coalesce(ArrayList
& insns
)
958 bool ret
= doCoalesce(insns
, JOIN_MASK_PHI
);
961 switch (func
->getProgram()->getTarget()->getChipset() & ~0xf) {
966 ret
= doCoalesce(insns
, JOIN_MASK_UNION
| JOIN_MASK_TEX
);
976 ret
= doCoalesce(insns
, JOIN_MASK_UNION
);
983 return doCoalesce(insns
, JOIN_MASK_MOV
);
986 static inline uint8_t makeCompMask(int compSize
, int base
, int size
)
988 uint8_t m
= ((1 << size
) - 1) << base
;
1000 assert(compSize
<= 8);
1005 // Used when coalescing moves. The non-compound value will become one, e.g.:
1006 // mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }
1007 // split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d
1008 static inline void copyCompound(Value
*dst
, Value
*src
)
1010 LValue
*ldst
= dst
->asLValue();
1011 LValue
*lsrc
= src
->asLValue();
1013 if (ldst
->compound
&& !lsrc
->compound
) {
1014 LValue
*swap
= lsrc
;
1019 ldst
->compound
= lsrc
->compound
;
1020 ldst
->compMask
= lsrc
->compMask
;
1024 GCRA::makeCompound(Instruction
*insn
, bool split
)
1026 LValue
*rep
= (split
? insn
->getSrc(0) : insn
->getDef(0))->asLValue();
1028 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
) {
1029 INFO("makeCompound(split = %i): ", split
);
1033 const unsigned int size
= getNode(rep
)->colors
;
1034 unsigned int base
= 0;
1037 rep
->compMask
= 0xff;
1040 for (int c
= 0; split
? insn
->defExists(c
) : insn
->srcExists(c
); ++c
) {
1041 LValue
*val
= (split
? insn
->getDef(c
) : insn
->getSrc(c
))->asLValue();
1045 val
->compMask
= 0xff;
1046 val
->compMask
&= makeCompMask(size
, base
, getNode(val
)->colors
);
1047 assert(val
->compMask
);
1049 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "compound: %%%i:%02x <- %%%i:%02x\n",
1050 rep
->id
, rep
->compMask
, val
->id
, val
->compMask
);
1052 base
+= getNode(val
)->colors
;
1054 assert(base
== size
);
1058 GCRA::doCoalesce(ArrayList
& insns
, unsigned int mask
)
1062 for (n
= 0; n
< insns
.getSize(); ++n
) {
1064 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(n
));
1068 if (!(mask
& JOIN_MASK_PHI
))
1070 for (c
= 0; insn
->srcExists(c
); ++c
)
1071 if (!coalesceValues(insn
->getDef(0), insn
->getSrc(c
), false)) {
1073 ERROR("failed to coalesce phi operands\n");
1079 if (!(mask
& JOIN_MASK_UNION
))
1081 for (c
= 0; insn
->srcExists(c
); ++c
)
1082 coalesceValues(insn
->getDef(0), insn
->getSrc(c
), true);
1083 if (insn
->op
== OP_MERGE
) {
1084 merges
.push_back(insn
);
1085 if (insn
->srcExists(1))
1086 makeCompound(insn
, false);
1090 if (!(mask
& JOIN_MASK_UNION
))
1092 splits
.push_back(insn
);
1093 for (c
= 0; insn
->defExists(c
); ++c
)
1094 coalesceValues(insn
->getSrc(0), insn
->getDef(c
), true);
1095 makeCompound(insn
, true);
1098 if (!(mask
& JOIN_MASK_MOV
))
1101 if (!insn
->getDef(0)->uses
.empty())
1102 i
= (*insn
->getDef(0)->uses
.begin())->getInsn();
1103 // if this is a contraint-move there will only be a single use
1104 if (i
&& i
->op
== OP_MERGE
) // do we really still need this ?
1106 i
= insn
->getSrc(0)->getUniqueInsn();
1107 if (i
&& !i
->constrainedDefs()) {
1108 if (coalesceValues(insn
->getDef(0), insn
->getSrc(0), false))
1109 copyCompound(insn
->getSrc(0), insn
->getDef(0));
1122 if (!(mask
& JOIN_MASK_TEX
))
1124 for (c
= 0; insn
->srcExists(c
) && c
!= insn
->predSrc
; ++c
)
1125 coalesceValues(insn
->getDef(c
), insn
->getSrc(c
), true);
1135 GCRA::RIG_Node::addInterference(RIG_Node
*node
)
1137 this->degree
+= relDegree
[node
->colors
][colors
];
1138 node
->degree
+= relDegree
[colors
][node
->colors
];
1140 this->attach(node
, Graph::Edge::CROSS
);
1144 GCRA::RIG_Node::addRegPreference(RIG_Node
*node
)
1146 prefRegs
.push_back(node
);
1149 GCRA::GCRA(Function
*fn
, SpillCodeInserter
& spill
) :
1151 regs(fn
->getProgram()->getTarget()),
1154 prog
= func
->getProgram();
1156 // initialize relative degrees array - i takes away from j
1157 for (int i
= 1; i
<= 16; ++i
)
1158 for (int j
= 1; j
<= 16; ++j
)
1159 relDegree
[i
][j
] = j
* ((i
+ j
- 1) / j
);
1169 GCRA::checkList(std::list
<RIG_Node
*>& lst
)
1171 GCRA::RIG_Node
*prev
= NULL
;
1173 for (std::list
<RIG_Node
*>::iterator it
= lst
.begin();
1176 assert((*it
)->getValue()->join
== (*it
)->getValue());
1178 assert(prev
->livei
.begin() <= (*it
)->livei
.begin());
1184 GCRA::insertOrderedTail(std::list
<RIG_Node
*>& list
, RIG_Node
*node
)
1186 if (node
->livei
.isEmpty())
1188 // only the intervals of joined values don't necessarily arrive in order
1189 std::list
<RIG_Node
*>::iterator prev
, it
;
1190 for (it
= list
.end(); it
!= list
.begin(); it
= prev
) {
1193 if ((*prev
)->livei
.begin() <= node
->livei
.begin())
1196 list
.insert(it
, node
);
1200 GCRA::buildRIG(ArrayList
& insns
)
1202 std::list
<RIG_Node
*> values
, active
;
1204 for (std::deque
<ValueDef
>::iterator it
= func
->ins
.begin();
1205 it
!= func
->ins
.end(); ++it
)
1206 insertOrderedTail(values
, getNode(it
->get()->asLValue()));
1208 for (int i
= 0; i
< insns
.getSize(); ++i
) {
1209 Instruction
*insn
= reinterpret_cast<Instruction
*>(insns
.get(i
));
1210 for (int d
= 0; insn
->defExists(d
); ++d
)
1211 if (insn
->getDef(d
)->rep() == insn
->getDef(d
))
1212 insertOrderedTail(values
, getNode(insn
->getDef(d
)->asLValue()));
1216 while (!values
.empty()) {
1217 RIG_Node
*cur
= values
.front();
1219 for (std::list
<RIG_Node
*>::iterator it
= active
.begin();
1220 it
!= active
.end();) {
1221 RIG_Node
*node
= *it
;
1223 if (node
->livei
.end() <= cur
->livei
.begin()) {
1224 it
= active
.erase(it
);
1226 if (node
->f
== cur
->f
&& node
->livei
.overlaps(cur
->livei
))
1227 cur
->addInterference(node
);
1232 active
.push_back(cur
);
1237 GCRA::calculateSpillWeights()
1239 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1240 RIG_Node
*const n
= &nodes
[i
];
1241 if (!nodes
[i
].colors
|| nodes
[i
].livei
.isEmpty())
1243 if (nodes
[i
].reg
>= 0) {
1245 regs
.occupy(n
->f
, n
->reg
, n
->colors
);
1248 LValue
*val
= nodes
[i
].getValue();
1250 if (!val
->noSpill
) {
1252 for (Value::DefIterator it
= val
->defs
.begin();
1253 it
!= val
->defs
.end();
1255 rc
+= (*it
)->get()->refCount();
1258 (float)rc
* (float)rc
/ (float)nodes
[i
].livei
.extent();
1261 if (nodes
[i
].degree
< nodes
[i
].degreeLimit
) {
1263 if (val
->reg
.size
> 4)
1265 DLLIST_ADDHEAD(&lo
[l
], &nodes
[i
]);
1267 DLLIST_ADDHEAD(&hi
, &nodes
[i
]);
1270 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1275 GCRA::simplifyEdge(RIG_Node
*a
, RIG_Node
*b
)
1277 bool move
= b
->degree
>= b
->degreeLimit
;
1279 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1280 "edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",
1281 a
->getValue()->id
, a
->degree
, a
->degreeLimit
,
1282 b
->getValue()->id
, b
->degree
, b
->degreeLimit
);
1284 b
->degree
-= relDegree
[a
->colors
][b
->colors
];
1286 move
= move
&& b
->degree
< b
->degreeLimit
;
1287 if (move
&& !DLLIST_EMPTY(b
)) {
1288 int l
= (b
->getValue()->reg
.size
> 4) ? 1 : 0;
1290 DLLIST_ADDTAIL(&lo
[l
], b
);
1295 GCRA::simplifyNode(RIG_Node
*node
)
1297 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1298 simplifyEdge(node
, RIG_Node::get(ei
));
1300 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1301 simplifyEdge(node
, RIG_Node::get(ei
));
1304 stack
.push(node
->getValue()->id
);
1306 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "SIMPLIFY: pushed %%%i%s\n",
1307 node
->getValue()->id
,
1308 (node
->degree
< node
->degreeLimit
) ? "" : "(spill)");
1315 if (!DLLIST_EMPTY(&lo
[0])) {
1317 simplifyNode(lo
[0].next
);
1318 } while (!DLLIST_EMPTY(&lo
[0]));
1320 if (!DLLIST_EMPTY(&lo
[1])) {
1321 simplifyNode(lo
[1].next
);
1323 if (!DLLIST_EMPTY(&hi
)) {
1324 RIG_Node
*best
= hi
.next
;
1325 float bestScore
= best
->weight
/ (float)best
->degree
;
1327 for (RIG_Node
*it
= best
->next
; it
!= &hi
; it
= it
->next
) {
1328 float score
= it
->weight
/ (float)it
->degree
;
1329 if (score
< bestScore
) {
1334 if (isinf(bestScore
)) {
1335 ERROR("no viable spill candidates left\n");
1346 GCRA::checkInterference(const RIG_Node
*node
, Graph::EdgeIterator
& ei
)
1348 const RIG_Node
*intf
= RIG_Node::get(ei
);
1352 const LValue
*vA
= node
->getValue();
1353 const LValue
*vB
= intf
->getValue();
1355 const uint8_t intfMask
= ((1 << intf
->colors
) - 1) << (intf
->reg
& 7);
1357 if (vA
->compound
| vB
->compound
) {
1358 // NOTE: this only works for >aligned< register tuples !
1359 for (Value::DefCIterator D
= vA
->defs
.begin(); D
!= vA
->defs
.end(); ++D
) {
1360 for (Value::DefCIterator d
= vB
->defs
.begin(); d
!= vB
->defs
.end(); ++d
) {
1361 const LValue
*vD
= (*D
)->get()->asLValue();
1362 const LValue
*vd
= (*d
)->get()->asLValue();
1364 if (!vD
->livei
.overlaps(vd
->livei
)) {
1365 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "(%%%i) X (%%%i): no overlap\n",
1370 uint8_t mask
= vD
->compound
? vD
->compMask
: ~0;
1372 assert(vB
->compound
);
1373 mask
&= vd
->compMask
& vB
->compMask
;
1378 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1379 "(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",
1381 vD
->compound
? vD
->compMask
: 0xff,
1383 vd
->compound
? vd
->compMask
: intfMask
,
1384 vB
->compMask
, intf
->reg
& ~7, mask
);
1386 regs
.occupyMask(node
->f
, intf
->reg
& ~7, mask
);
1390 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1391 "(%%%i) X (%%%i): $r%i + %u\n",
1392 vA
->id
, vB
->id
, intf
->reg
, intf
->colors
);
1393 regs
.occupy(node
->f
, intf
->reg
, intf
->colors
);
1398 GCRA::selectRegisters()
1400 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nSELECT phase\n");
1402 while (!stack
.empty()) {
1403 RIG_Node
*node
= &nodes
[stack
.top()];
1406 regs
.reset(node
->f
);
1408 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "\nNODE[%%%i, %u colors]\n",
1409 node
->getValue()->id
, node
->colors
);
1411 for (Graph::EdgeIterator ei
= node
->outgoing(); !ei
.end(); ei
.next())
1412 checkInterference(node
, ei
);
1413 for (Graph::EdgeIterator ei
= node
->incident(); !ei
.end(); ei
.next())
1414 checkInterference(node
, ei
);
1416 if (!node
->prefRegs
.empty()) {
1417 for (std::list
<RIG_Node
*>::const_iterator it
= node
->prefRegs
.begin();
1418 it
!= node
->prefRegs
.end();
1420 if ((*it
)->reg
>= 0 &&
1421 regs
.testOccupy(node
->f
, (*it
)->reg
, node
->colors
)) {
1422 node
->reg
= (*it
)->reg
;
1429 LValue
*lval
= node
->getValue();
1430 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1431 regs
.print(node
->f
);
1432 bool ret
= regs
.assign(node
->reg
, node
->f
, node
->colors
);
1434 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "assigned reg %i\n", node
->reg
);
1435 lval
->compMask
= node
->getCompMask();
1437 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "must spill: %%%i (size %u)\n",
1438 lval
->id
, lval
->reg
.size
);
1439 Symbol
*slot
= NULL
;
1440 if (lval
->reg
.file
== FILE_GPR
)
1441 slot
= spill
.assignSlot(node
->livei
, lval
->reg
.size
);
1442 mustSpill
.push_back(ValuePair(lval
, slot
));
1445 if (!mustSpill
.empty())
1447 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1448 LValue
*lval
= nodes
[i
].getValue();
1449 if (nodes
[i
].reg
>= 0 && nodes
[i
].colors
> 0)
1451 regs
.unitsToId(nodes
[i
].f
, nodes
[i
].reg
, lval
->reg
.size
);
1457 GCRA::allocateRegisters(ArrayList
& insns
)
1461 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1462 "allocateRegisters to %u instructions\n", insns
.getSize());
1464 nodeCount
= func
->allLValues
.getSize();
1465 nodes
= new RIG_Node
[nodeCount
];
1468 for (unsigned int i
= 0; i
< nodeCount
; ++i
) {
1469 LValue
*lval
= reinterpret_cast<LValue
*>(func
->allLValues
.get(i
));
1471 nodes
[i
].init(regs
, lval
);
1472 RIG
.insert(&nodes
[i
]);
1474 if (lval
->inFile(FILE_GPR
) && lval
->getInsn() != NULL
) {
1475 Instruction
*insn
= lval
->getInsn();
1476 if (insn
->op
!= OP_MAD
&& insn
->op
!= OP_FMA
&& insn
->op
!= OP_SAD
)
1478 // For both of the cases below, we only want to add the preference
1479 // if all arguments are in registers.
1480 if (insn
->src(0).getFile() != FILE_GPR
||
1481 insn
->src(1).getFile() != FILE_GPR
||
1482 insn
->src(2).getFile() != FILE_GPR
)
1484 if (prog
->getTarget()->getChipset() < 0xc0) {
1485 // Outputting a flag is not supported with short encodings nor
1486 // with immediate arguments.
1487 // See handleMADforNV50.
1488 if (insn
->flagsDef
>= 0)
1491 // We can only fold immediate arguments if dst == src2. This
1492 // only matters if one of the first two arguments is an
1493 // immediate. This form is also only supported for floats.
1494 // See handleMADforNVC0.
1496 if (insn
->dType
!= TYPE_F32
)
1498 if (!insn
->src(0).getImmediate(imm
) &&
1499 !insn
->src(1).getImmediate(imm
))
1503 nodes
[i
].addRegPreference(getNode(insn
->getSrc(2)->asLValue()));
1508 // coalesce first, we use only 1 RIG node for a group of joined values
1509 ret
= coalesce(insns
);
1513 if (func
->getProgram()->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1514 func
->printLiveIntervals();
1517 calculateSpillWeights();
1522 ret
= selectRegisters();
1524 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
,
1525 "selectRegisters failed, inserting spill code ...\n");
1526 regs
.reset(FILE_GPR
, true);
1527 spill
.run(mustSpill
);
1528 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1531 prog
->maxGPR
= std::max(prog
->maxGPR
, regs
.getMaxAssigned(FILE_GPR
));
1540 GCRA::cleanup(const bool success
)
1544 for (ArrayList::Iterator it
= func
->allLValues
.iterator();
1545 !it
.end(); it
.next()) {
1546 LValue
*lval
= reinterpret_cast<LValue
*>(it
.get());
1548 lval
->livei
.clear();
1553 if (lval
->join
== lval
)
1557 lval
->reg
.data
.id
= lval
->join
->reg
.data
.id
;
1559 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1561 lval
->join
->defs
.remove(*d
);
1567 resolveSplitsAndMerges();
1568 splits
.clear(); // avoid duplicate entries on next coalesce pass
1573 hi
.next
= hi
.prev
= &hi
;
1574 lo
[0].next
= lo
[0].prev
= &lo
[0];
1575 lo
[1].next
= lo
[1].prev
= &lo
[1];
1579 SpillCodeInserter::assignSlot(const Interval
&livei
, const unsigned int size
)
1582 int32_t offsetBase
= stackSize
;
1584 std::list
<SpillSlot
>::iterator pos
= slots
.end(), it
= slots
.begin();
1586 if (offsetBase
% size
)
1587 offsetBase
+= size
- (offsetBase
% size
);
1591 for (offset
= offsetBase
; offset
< stackSize
; offset
+= size
) {
1592 const int32_t entryEnd
= offset
+ size
;
1593 while (it
!= slots
.end() && it
->offset
< offset
)
1595 if (it
== slots
.end()) // no slots left
1597 std::list
<SpillSlot
>::iterator bgn
= it
;
1599 while (it
!= slots
.end() && it
->offset
< entryEnd
) {
1601 if (it
->occup
.overlaps(livei
))
1605 if (it
== slots
.end() || it
->offset
>= entryEnd
) {
1607 for (; bgn
!= slots
.end() && bgn
->offset
< entryEnd
; ++bgn
) {
1608 bgn
->occup
.insert(livei
);
1609 if (bgn
->size() == size
)
1610 slot
.sym
= bgn
->sym
;
1616 stackSize
= offset
+ size
;
1617 slot
.offset
= offset
;
1618 slot
.sym
= new_Symbol(func
->getProgram(), FILE_MEMORY_LOCAL
);
1619 if (!func
->stackPtr
)
1620 offset
+= func
->tlsBase
;
1621 slot
.sym
->setAddress(NULL
, offset
);
1622 slot
.sym
->reg
.size
= size
;
1623 slots
.insert(pos
, slot
)->occup
.insert(livei
);
1629 SpillCodeInserter::offsetSlot(Value
*base
, const LValue
*lval
)
1631 if (!lval
->compound
|| (lval
->compMask
& 0x1))
1633 Value
*slot
= cloneShallow(func
, base
);
1635 slot
->reg
.data
.offset
+= (ffs(lval
->compMask
) - 1) * lval
->reg
.size
;
1636 slot
->reg
.size
= lval
->reg
.size
;
1642 SpillCodeInserter::spill(Instruction
*defi
, Value
*slot
, LValue
*lval
)
1644 const DataType ty
= typeOfSize(lval
->reg
.size
);
1646 slot
= offsetSlot(slot
, lval
);
1649 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1651 if (ty
!= TYPE_B96
) {
1652 st
= new_Instruction(func
, OP_STORE
, ty
);
1653 st
->setSrc(0, slot
);
1654 st
->setSrc(1, lval
);
1656 st
= new_Instruction(func
, OP_SPLIT
, ty
);
1657 st
->setSrc(0, lval
);
1658 for (int d
= 0; d
< lval
->reg
.size
/ 4; ++d
)
1659 st
->setDef(d
, new_LValue(func
, FILE_GPR
));
1661 for (int d
= lval
->reg
.size
/ 4 - 1; d
>= 0; --d
) {
1662 Value
*tmp
= cloneShallow(func
, slot
);
1664 tmp
->reg
.data
.offset
+= 4 * d
;
1666 Instruction
*s
= new_Instruction(func
, OP_STORE
, TYPE_U32
);
1668 s
->setSrc(1, st
->getDef(d
));
1669 defi
->bb
->insertAfter(defi
, s
);
1673 st
= new_Instruction(func
, OP_CVT
, ty
);
1674 st
->setDef(0, slot
);
1675 st
->setSrc(0, lval
);
1676 if (lval
->reg
.file
== FILE_FLAGS
)
1679 defi
->bb
->insertAfter(defi
, st
);
1683 SpillCodeInserter::unspill(Instruction
*usei
, LValue
*lval
, Value
*slot
)
1685 const DataType ty
= typeOfSize(lval
->reg
.size
);
1687 slot
= offsetSlot(slot
, lval
);
1688 lval
= cloneShallow(func
, lval
);
1691 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
) {
1693 if (ty
!= TYPE_B96
) {
1694 ld
= new_Instruction(func
, OP_LOAD
, ty
);
1696 ld
= new_Instruction(func
, OP_MERGE
, ty
);
1697 for (int d
= 0; d
< lval
->reg
.size
/ 4; ++d
) {
1698 Value
*tmp
= cloneShallow(func
, slot
);
1701 tmp
->reg
.data
.offset
+= 4 * d
;
1703 Instruction
*l
= new_Instruction(func
, OP_LOAD
, TYPE_U32
);
1704 l
->setDef(0, (val
= new_LValue(func
, FILE_GPR
)));
1706 usei
->bb
->insertBefore(usei
, l
);
1710 ld
->setDef(0, lval
);
1711 usei
->bb
->insertBefore(usei
, ld
);
1715 ld
= new_Instruction(func
, OP_CVT
, ty
);
1717 ld
->setDef(0, lval
);
1718 ld
->setSrc(0, slot
);
1719 if (lval
->reg
.file
== FILE_FLAGS
)
1722 usei
->bb
->insertBefore(usei
, ld
);
1727 value_cmp(ValueRef
*a
, ValueRef
*b
) {
1728 Instruction
*ai
= a
->getInsn(), *bi
= b
->getInsn();
1729 if (ai
->bb
!= bi
->bb
)
1730 return ai
->bb
->getId() < bi
->bb
->getId();
1731 return ai
->serial
< bi
->serial
;
1734 // For each value that is to be spilled, go through all its definitions.
1735 // A value can have multiple definitions if it has been coalesced before.
1736 // For each definition, first go through all its uses and insert an unspill
1737 // instruction before it, then replace the use with the temporary register.
1738 // Unspill can be either a load from memory or simply a move to another
1740 // For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use
1741 // if we have spilled to a memory location, or simply with the new register.
1742 // No load or conversion instruction should be needed.
1744 SpillCodeInserter::run(const std::list
<ValuePair
>& lst
)
1746 for (std::list
<ValuePair
>::const_iterator it
= lst
.begin(); it
!= lst
.end();
1748 LValue
*lval
= it
->first
->asLValue();
1749 Symbol
*mem
= it
->second
? it
->second
->asSym() : NULL
;
1751 // Keep track of which instructions to delete later. Deleting them
1752 // inside the loop is unsafe since a single instruction may have
1753 // multiple destinations that all need to be spilled (like OP_SPLIT).
1754 unordered_set
<Instruction
*> to_del
;
1756 for (Value::DefIterator d
= lval
->defs
.begin(); d
!= lval
->defs
.end();
1759 static_cast<Value
*>(mem
) : new_LValue(func
, FILE_GPR
);
1761 Instruction
*last
= NULL
;
1763 LValue
*dval
= (*d
)->get()->asLValue();
1764 Instruction
*defi
= (*d
)->getInsn();
1766 // Sort all the uses by BB/instruction so that we don't unspill
1767 // multiple times in a row, and also remove a source of
1769 std::vector
<ValueRef
*> refs(dval
->uses
.begin(), dval
->uses
.end());
1770 std::sort(refs
.begin(), refs
.end(), value_cmp
);
1772 // Unspill at each use *before* inserting spill instructions,
1773 // we don't want to have the spill instructions in the use list here.
1774 for (std::vector
<ValueRef
*>::const_iterator it
= refs
.begin();
1775 it
!= refs
.end(); ++it
) {
1777 Instruction
*usei
= u
->getInsn();
1779 if (usei
->isPseudo()) {
1780 tmp
= (slot
->reg
.file
== FILE_MEMORY_LOCAL
) ? NULL
: slot
;
1783 if (!last
|| (usei
!= last
->next
&& usei
!= last
))
1784 tmp
= unspill(usei
, dval
, slot
);
1791 if (defi
->isPseudo()) {
1792 d
= lval
->defs
.erase(d
);
1794 if (slot
->reg
.file
== FILE_MEMORY_LOCAL
)
1795 to_del
.insert(defi
);
1797 defi
->setDef(0, slot
);
1799 spill(defi
, slot
, dval
);
1803 for (unordered_set
<Instruction
*>::const_iterator it
= to_del
.begin();
1804 it
!= to_del
.end(); ++it
)
1805 delete_Instruction(func
->getProgram(), *it
);
1808 // TODO: We're not trying to reuse old slots in a potential next iteration.
1809 // We have to update the slots' livei intervals to be able to do that.
1810 stackBase
= stackSize
;
1818 for (IteratorRef it
= prog
->calls
.iteratorDFS(false);
1819 !it
->end(); it
->next()) {
1820 func
= Function::get(reinterpret_cast<Graph::Node
*>(it
->get()));
1822 func
->tlsBase
= prog
->tlsSize
;
1825 prog
->tlsSize
+= func
->tlsSize
;
1831 RegAlloc::execFunc()
1833 InsertConstraintsPass insertConstr
;
1834 PhiMovesPass insertPhiMoves
;
1835 ArgumentMovesPass insertArgMoves
;
1836 BuildIntervalsPass buildIntervals
;
1837 SpillCodeInserter
insertSpills(func
);
1839 GCRA
gcra(func
, insertSpills
);
1841 unsigned int i
, retries
;
1844 if (!func
->ins
.empty()) {
1845 // Insert a nop at the entry so inputs only used by the first instruction
1846 // don't count as having an empty live range.
1847 Instruction
*nop
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
1848 BasicBlock::get(func
->cfg
.getRoot())->insertHead(nop
);
1851 ret
= insertConstr
.exec(func
);
1855 ret
= insertPhiMoves
.run(func
);
1859 ret
= insertArgMoves
.run(func
);
1863 // TODO: need to fix up spill slot usage ranges to support > 1 retry
1864 for (retries
= 0; retries
< 3; ++retries
) {
1865 if (retries
&& (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
))
1866 INFO("Retry: %i\n", retries
);
1867 if (prog
->dbgFlags
& NV50_IR_DEBUG_REG_ALLOC
)
1870 // spilling to registers may add live ranges, need to rebuild everything
1872 for (sequence
= func
->cfg
.nextSequence(), i
= 0;
1873 ret
&& i
<= func
->loopNestingBound
;
1874 sequence
= func
->cfg
.nextSequence(), ++i
)
1875 ret
= buildLiveSets(BasicBlock::get(func
->cfg
.getRoot()));
1877 for (ArrayList::Iterator bi
= func
->allBBlocks
.iterator();
1878 !bi
.end(); bi
.next())
1879 BasicBlock::get(bi
)->liveSet
.marker
= false;
1882 func
->orderInstructions(this->insns
);
1884 ret
= buildIntervals
.run(func
);
1887 ret
= gcra
.allocateRegisters(insns
);
1891 INFO_DBG(prog
->dbgFlags
, REG_ALLOC
, "RegAlloc done: %i\n", ret
);
1893 func
->tlsSize
= insertSpills
.getStackSize();
1898 // TODO: check if modifying Instruction::join here breaks anything
1900 GCRA::resolveSplitsAndMerges()
1902 for (std::list
<Instruction
*>::iterator it
= splits
.begin();
1905 Instruction
*split
= *it
;
1906 unsigned int reg
= regs
.idToBytes(split
->getSrc(0));
1907 for (int d
= 0; split
->defExists(d
); ++d
) {
1908 Value
*v
= split
->getDef(d
);
1909 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1916 for (std::list
<Instruction
*>::iterator it
= merges
.begin();
1919 Instruction
*merge
= *it
;
1920 unsigned int reg
= regs
.idToBytes(merge
->getDef(0));
1921 for (int s
= 0; merge
->srcExists(s
); ++s
) {
1922 Value
*v
= merge
->getSrc(s
);
1923 v
->reg
.data
.id
= regs
.bytesToId(v
, reg
);
1925 // If the value is defined by a phi/union node, we also need to
1926 // perform the same fixup on that node's sources, since after RA
1927 // their registers should be identical.
1928 if (v
->getInsn()->op
== OP_PHI
|| v
->getInsn()->op
== OP_UNION
) {
1929 Instruction
*phi
= v
->getInsn();
1930 for (int phis
= 0; phi
->srcExists(phis
); ++phis
) {
1931 phi
->getSrc(phis
)->join
= v
;
1932 phi
->getSrc(phis
)->reg
.data
.id
= v
->reg
.data
.id
;
1941 bool Program::registerAllocation()
1948 RegAlloc::InsertConstraintsPass::exec(Function
*ir
)
1952 bool ret
= run(ir
, true, true);
1954 ret
= insertConstraintMoves();
1958 // TODO: make part of texture insn
1960 RegAlloc::InsertConstraintsPass::textureMask(TexInstruction
*tex
)
1966 for (d
= 0, k
= 0, c
= 0; c
< 4; ++c
) {
1967 if (!(tex
->tex
.mask
& (1 << c
)))
1969 if (tex
->getDef(k
)->refCount()) {
1971 def
[d
++] = tex
->getDef(k
);
1975 tex
->tex
.mask
= mask
;
1977 for (c
= 0; c
< d
; ++c
)
1978 tex
->setDef(c
, def
[c
]);
1980 tex
->setDef(c
, NULL
);
1984 RegAlloc::InsertConstraintsPass::detectConflict(Instruction
*cst
, int s
)
1986 Value
*v
= cst
->getSrc(s
);
1988 // current register allocation can't handle it if a value participates in
1989 // multiple constraints
1990 for (Value::UseIterator it
= v
->uses
.begin(); it
!= v
->uses
.end(); ++it
) {
1991 if (cst
!= (*it
)->getInsn())
1995 // can start at s + 1 because detectConflict is called on all sources
1996 for (int c
= s
+ 1; cst
->srcExists(c
); ++c
)
1997 if (v
== cst
->getSrc(c
))
2000 Instruction
*defi
= v
->getInsn();
2002 return (!defi
|| defi
->constrainedDefs());
2006 RegAlloc::InsertConstraintsPass::addConstraint(Instruction
*i
, int s
, int n
)
2011 // first, look for an existing identical constraint op
2012 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
2013 it
!= constrList
.end();
2016 if (!i
->bb
->dominatedBy(cst
->bb
))
2018 for (d
= 0; d
< n
; ++d
)
2019 if (cst
->getSrc(d
) != i
->getSrc(d
+ s
))
2022 for (d
= 0; d
< n
; ++d
, ++s
)
2023 i
->setSrc(s
, cst
->getDef(d
));
2027 cst
= new_Instruction(func
, OP_CONSTRAINT
, i
->dType
);
2029 for (d
= 0; d
< n
; ++s
, ++d
) {
2030 cst
->setDef(d
, new_LValue(func
, FILE_GPR
));
2031 cst
->setSrc(d
, i
->getSrc(s
));
2032 i
->setSrc(s
, cst
->getDef(d
));
2034 i
->bb
->insertBefore(i
, cst
);
2036 constrList
.push_back(cst
);
2039 // Add a dummy use of the pointer source of >= 8 byte loads after the load
2040 // to prevent it from being assigned a register which overlapping the load's
2041 // destination, which would produce random corruptions.
2043 RegAlloc::InsertConstraintsPass::addHazard(Instruction
*i
, const ValueRef
*src
)
2045 Instruction
*hzd
= new_Instruction(func
, OP_NOP
, TYPE_NONE
);
2046 hzd
->setSrc(0, src
->get());
2047 i
->bb
->insertAfter(i
, hzd
);
2051 // b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q
2053 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction
*insn
)
2056 for (n
= 0; insn
->defExists(n
) && insn
->def(n
).getFile() == FILE_GPR
; ++n
);
2057 condenseDefs(insn
, 0, n
- 1);
2061 RegAlloc::InsertConstraintsPass::condenseDefs(Instruction
*insn
,
2062 const int a
, const int b
)
2067 for (int s
= a
; s
<= b
; ++s
)
2068 size
+= insn
->getDef(s
)->reg
.size
;
2072 LValue
*lval
= new_LValue(func
, FILE_GPR
);
2073 lval
->reg
.size
= size
;
2075 Instruction
*split
= new_Instruction(func
, OP_SPLIT
, typeOfSize(size
));
2076 split
->setSrc(0, lval
);
2077 for (int d
= a
; d
<= b
; ++d
) {
2078 split
->setDef(d
- a
, insn
->getDef(d
));
2079 insn
->setDef(d
, NULL
);
2081 insn
->setDef(a
, lval
);
2083 for (int k
= a
+ 1, d
= b
+ 1; insn
->defExists(d
); ++d
, ++k
) {
2084 insn
->setDef(k
, insn
->getDef(d
));
2085 insn
->setDef(d
, NULL
);
2087 // carry over predicate if any (mainly for OP_UNION uses)
2088 split
->setPredicate(insn
->cc
, insn
->getPredicate());
2090 insn
->bb
->insertAfter(insn
, split
);
2091 constrList
.push_back(split
);
2095 RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction
*insn
,
2096 const int a
, const int b
)
2101 for (int s
= a
; s
<= b
; ++s
)
2102 size
+= insn
->getSrc(s
)->reg
.size
;
2105 LValue
*lval
= new_LValue(func
, FILE_GPR
);
2106 lval
->reg
.size
= size
;
2109 insn
->takeExtraSources(0, save
);
2111 Instruction
*merge
= new_Instruction(func
, OP_MERGE
, typeOfSize(size
));
2112 merge
->setDef(0, lval
);
2113 for (int s
= a
, i
= 0; s
<= b
; ++s
, ++i
) {
2114 merge
->setSrc(i
, insn
->getSrc(s
));
2116 insn
->moveSources(b
+ 1, a
- b
);
2117 insn
->setSrc(a
, lval
);
2118 insn
->bb
->insertBefore(insn
, merge
);
2120 insn
->putExtraSources(0, save
);
2122 constrList
.push_back(merge
);
2126 RegAlloc::InsertConstraintsPass::isScalarTexGM107(TexInstruction
*tex
)
2128 if (tex
->tex
.sIndirectSrc
>= 0 ||
2129 tex
->tex
.rIndirectSrc
>= 0)
2132 if (tex
->tex
.mask
== 5 || tex
->tex
.mask
== 6)
2171 // TLD4S: all 2D/RECT variants and only offset
2175 if (tex
->tex
.useOffsets
)
2178 switch (tex
->tex
.target
.getEnum()) {
2180 case TEX_TARGET_2D_ARRAY_SHADOW
:
2181 return tex
->tex
.levelZero
;
2182 case TEX_TARGET_CUBE
:
2183 return !tex
->tex
.levelZero
;
2185 case TEX_TARGET_2D_ARRAY
:
2186 case TEX_TARGET_2D_SHADOW
:
2188 case TEX_TARGET_RECT
:
2189 case TEX_TARGET_RECT_SHADOW
:
2196 if (tex
->tex
.useOffsets
)
2199 switch (tex
->tex
.target
.getEnum()) {
2201 case TEX_TARGET_2D_SHADOW
:
2202 case TEX_TARGET_RECT
:
2203 case TEX_TARGET_RECT_SHADOW
:
2204 case TEX_TARGET_CUBE
:
2211 switch (tex
->tex
.target
.getEnum()) {
2213 return !tex
->tex
.useOffsets
;
2215 case TEX_TARGET_RECT
:
2217 case TEX_TARGET_2D_ARRAY
:
2218 case TEX_TARGET_2D_MS
:
2220 return !tex
->tex
.useOffsets
&& tex
->tex
.levelZero
;
2226 if (tex
->tex
.useOffsets
> 1)
2228 if (tex
->tex
.mask
!= 0x3 && tex
->tex
.mask
!= 0xf)
2231 switch (tex
->tex
.target
.getEnum()) {
2233 case TEX_TARGET_2D_MS
:
2234 case TEX_TARGET_2D_SHADOW
:
2235 case TEX_TARGET_RECT
:
2236 case TEX_TARGET_RECT_SHADOW
:
2248 RegAlloc::InsertConstraintsPass::handleScalarTexGM107(TexInstruction
*tex
)
2250 int defCount
= tex
->defCount(0xff);
2251 int srcCount
= tex
->srcCount(0xff);
2253 tex
->tex
.scalar
= true;
2257 condenseDefs(tex
, 2, 3);
2259 condenseDefs(tex
, 0, 1);
2262 // special case for TXF.A2D
2263 if (tex
->op
== OP_TXF
&& tex
->tex
.target
== TEX_TARGET_2D_ARRAY
) {
2264 assert(srcCount
>= 3);
2265 condenseSrcs(tex
, 1, 2);
2268 condenseSrcs(tex
, 2, 3);
2269 // only if we have more than 2 sources
2271 condenseSrcs(tex
, 0, 1);
2274 assert(!tex
->defExists(2) && !tex
->srcExists(2));
2278 RegAlloc::InsertConstraintsPass::texConstraintGM107(TexInstruction
*tex
)
2282 if (isTextureOp(tex
->op
))
2285 if (isScalarTexGM107(tex
)) {
2286 handleScalarTexGM107(tex
);
2290 assert(!tex
->tex
.scalar
);
2293 if (isSurfaceOp(tex
->op
)) {
2294 int s
= tex
->tex
.target
.getDim() +
2295 (tex
->tex
.target
.isArray() || tex
->tex
.target
.isCube());
2305 if (tex
->subOp
== NV50_IR_SUBOP_ATOM_CAS
)
2313 condenseSrcs(tex
, 0, s
- 1);
2315 condenseSrcs(tex
, 1, n
); // do not condense the tex handle
2317 if (isTextureOp(tex
->op
)) {
2318 if (tex
->op
!= OP_TXQ
) {
2319 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
2320 if (tex
->op
== OP_TXD
) {
2321 // Indirect handle belongs in the first arg
2322 if (tex
->tex
.rIndirectSrc
>= 0)
2324 if (!tex
->tex
.target
.isArray() && tex
->tex
.useOffsets
)
2327 n
= tex
->srcCount(0xff) - s
;
2329 s
= tex
->srcCount(0xff);
2334 condenseSrcs(tex
, 0, s
- 1);
2335 if (n
> 1) // NOTE: first call modified positions already
2336 condenseSrcs(tex
, 1, n
);
2341 RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction
*tex
)
2343 if (isTextureOp(tex
->op
))
2347 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
) {
2348 condenseSrcs(tex
, 3, 6);
2350 if (isTextureOp(tex
->op
)) {
2351 int n
= tex
->srcCount(0xff, true);
2353 condenseSrcs(tex
, 0, 3);
2354 if (n
> 5) // NOTE: first call modified positions already
2355 condenseSrcs(tex
, 4 - (4 - 1), n
- 1 - (4 - 1));
2358 condenseSrcs(tex
, 0, n
- 1);
2364 RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction
*tex
)
2368 if (isTextureOp(tex
->op
))
2371 if (tex
->op
== OP_TXQ
) {
2372 s
= tex
->srcCount(0xff);
2374 } else if (isSurfaceOp(tex
->op
)) {
2375 s
= tex
->tex
.target
.getDim() + (tex
->tex
.target
.isArray() || tex
->tex
.target
.isCube());
2376 if (tex
->op
== OP_SUSTB
|| tex
->op
== OP_SUSTP
)
2381 s
= tex
->tex
.target
.getArgCount() - tex
->tex
.target
.isMS();
2382 if (!tex
->tex
.target
.isArray() &&
2383 (tex
->tex
.rIndirectSrc
>= 0 || tex
->tex
.sIndirectSrc
>= 0))
2385 if (tex
->op
== OP_TXD
&& tex
->tex
.useOffsets
)
2387 n
= tex
->srcCount(0xff) - s
;
2392 condenseSrcs(tex
, 0, s
- 1);
2393 if (n
> 1) // NOTE: first call modified positions already
2394 condenseSrcs(tex
, 1, n
);
2400 RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction
*tex
)
2402 Value
*pred
= tex
->getPredicate();
2404 tex
->setPredicate(tex
->cc
, NULL
);
2408 assert(tex
->defExists(0) && tex
->srcExists(0));
2409 // make src and def count match
2411 for (c
= 0; tex
->srcExists(c
) || tex
->defExists(c
); ++c
) {
2412 if (!tex
->srcExists(c
))
2413 tex
->setSrc(c
, new_LValue(func
, tex
->getSrc(0)->asLValue()));
2415 insertConstraintMove(tex
, c
);
2416 if (!tex
->defExists(c
))
2417 tex
->setDef(c
, new_LValue(func
, tex
->getDef(0)->asLValue()));
2420 tex
->setPredicate(tex
->cc
, pred
);
2422 condenseSrcs(tex
, 0, c
- 1);
2425 // Insert constraint markers for instructions whose multiple sources must be
2426 // located in consecutive registers.
2428 RegAlloc::InsertConstraintsPass::visit(BasicBlock
*bb
)
2430 TexInstruction
*tex
;
2434 targ
= bb
->getProgram()->getTarget();
2436 for (Instruction
*i
= bb
->getEntry(); i
; i
= next
) {
2439 if ((tex
= i
->asTex())) {
2440 switch (targ
->getChipset() & ~0xf) {
2445 texConstraintNV50(tex
);
2449 texConstraintNVC0(tex
);
2454 texConstraintNVE0(tex
);
2459 texConstraintGM107(tex
);
2465 if (i
->op
== OP_EXPORT
|| i
->op
== OP_STORE
) {
2466 for (size
= typeSizeof(i
->dType
), s
= 1; size
> 0; ++s
) {
2467 assert(i
->srcExists(s
));
2468 size
-= i
->getSrc(s
)->reg
.size
;
2470 condenseSrcs(i
, 1, s
- 1);
2472 if (i
->op
== OP_LOAD
|| i
->op
== OP_VFETCH
) {
2474 if (i
->src(0).isIndirect(0) && typeSizeof(i
->dType
) >= 8)
2475 addHazard(i
, i
->src(0).getIndirect(0));
2476 if (i
->src(0).isIndirect(1) && typeSizeof(i
->dType
) >= 8)
2477 addHazard(i
, i
->src(0).getIndirect(1));
2479 if (i
->op
== OP_UNION
||
2480 i
->op
== OP_MERGE
||
2481 i
->op
== OP_SPLIT
) {
2482 constrList
.push_back(i
);
2489 RegAlloc::InsertConstraintsPass::insertConstraintMove(Instruction
*cst
, int s
)
2491 const uint8_t size
= cst
->src(s
).getSize();
2493 assert(cst
->getSrc(s
)->defs
.size() == 1); // still SSA
2495 Instruction
*defi
= cst
->getSrc(s
)->defs
.front()->getInsn();
2496 bool imm
= defi
->op
== OP_MOV
&&
2497 defi
->src(0).getFile() == FILE_IMMEDIATE
;
2498 bool load
= defi
->op
== OP_LOAD
&&
2499 defi
->src(0).getFile() == FILE_MEMORY_CONST
&&
2500 !defi
->src(0).isIndirect(0);
2501 // catch some cases where don't really need MOVs
2502 if (cst
->getSrc(s
)->refCount() == 1 && !defi
->constrainedDefs()) {
2504 // Move the defi right before the cst. No point in expanding
2506 defi
->bb
->remove(defi
);
2507 cst
->bb
->insertBefore(cst
, defi
);
2512 LValue
*lval
= new_LValue(func
, cst
->src(s
).getFile());
2513 lval
->reg
.size
= size
;
2515 Instruction
*mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2516 mov
->setDef(0, lval
);
2517 mov
->setSrc(0, cst
->getSrc(s
));
2521 mov
->setSrc(0, defi
->getSrc(0));
2523 mov
->setSrc(0, defi
->getSrc(0));
2526 if (defi
->getPredicate())
2527 mov
->setPredicate(defi
->cc
, defi
->getPredicate());
2529 cst
->setSrc(s
, mov
->getDef(0));
2530 cst
->bb
->insertBefore(cst
, mov
);
2532 cst
->getDef(0)->asLValue()->noSpill
= 1; // doesn't help
2535 // Insert extra moves so that, if multiple register constraints on a value are
2536 // in conflict, these conflicts can be resolved.
2538 RegAlloc::InsertConstraintsPass::insertConstraintMoves()
2540 for (std::list
<Instruction
*>::iterator it
= constrList
.begin();
2541 it
!= constrList
.end();
2543 Instruction
*cst
= *it
;
2546 if (cst
->op
== OP_SPLIT
&& 0) {
2547 // spilling splits is annoying, just make sure they're separate
2548 for (int d
= 0; cst
->defExists(d
); ++d
) {
2549 if (!cst
->getDef(d
)->refCount())
2551 LValue
*lval
= new_LValue(func
, cst
->def(d
).getFile());
2552 const uint8_t size
= cst
->def(d
).getSize();
2553 lval
->reg
.size
= size
;
2555 mov
= new_Instruction(func
, OP_MOV
, typeOfSize(size
));
2556 mov
->setSrc(0, lval
);
2557 mov
->setDef(0, cst
->getDef(d
));
2558 cst
->setDef(d
, mov
->getSrc(0));
2559 cst
->bb
->insertAfter(cst
, mov
);
2561 cst
->getSrc(0)->asLValue()->noSpill
= 1;
2562 mov
->getSrc(0)->asLValue()->noSpill
= 1;
2565 if (cst
->op
== OP_MERGE
|| cst
->op
== OP_UNION
) {
2566 for (int s
= 0; cst
->srcExists(s
); ++s
) {
2567 const uint8_t size
= cst
->src(s
).getSize();
2569 if (!cst
->getSrc(s
)->defs
.size()) {
2570 mov
= new_Instruction(func
, OP_NOP
, typeOfSize(size
));
2571 mov
->setDef(0, cst
->getSrc(s
));
2572 cst
->bb
->insertBefore(cst
, mov
);
2576 insertConstraintMove(cst
, s
);
2584 } // namespace nv50_ir