Path: blob/21.2-virgl/src/gallium/drivers/nouveau/codegen/nv50_ir_ra.cpp
4574 views
/*1* Copyright 2011 Christoph Bumiller2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice shall be included in11* all copies or substantial portions of the Software.12*13* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL16* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR17* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,18* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR19* OTHER DEALINGS IN THE SOFTWARE.20*/2122#include "codegen/nv50_ir.h"23#include "codegen/nv50_ir_target.h"2425#include <algorithm>26#include <stack>27#include <limits>28#if __cplusplus >= 201103L29#include <unordered_map>30#else31#include <tr1/unordered_map>32#endif3334namespace nv50_ir {3536#if __cplusplus >= 201103L37using std::hash;38using std::unordered_map;39#else40using std::tr1::hash;41using std::tr1::unordered_map;42#endif4344#define MAX_REGISTER_FILE_SIZE 2564546class RegisterSet47{48public:49RegisterSet(const Target *);5051void init(const Target *);52void reset(DataFile, bool resetMax = false);5354void periodicMask(DataFile f, uint32_t lock, uint32_t unlock);55void intersect(DataFile f, const RegisterSet *);5657bool assign(int32_t& reg, DataFile f, unsigned int size, unsigned int maxReg);58void release(DataFile f, int32_t reg, unsigned int size);59void occupy(DataFile f, int32_t reg, unsigned int size);60void occupy(const Value *);61void occupyMask(DataFile f, int32_t reg, uint8_t mask);62bool isOccupied(DataFile f, int32_t reg, unsigned int size) const;63bool testOccupy(const Value *);64bool testOccupy(DataFile f, int32_t reg, unsigned int size);6566inline int getMaxAssigned(DataFile f) const { return fill[f]; }6768inline unsigned int getFileSize(DataFile f) const69{70return last[f] + 1;71}7273inline unsigned int units(DataFile f, unsigned int size) const74{75return size >> unit[f];76}77// for regs of size >= 4, id is counted in 4-byte words (like nv50/c0 binary)78inline unsigned int idToBytes(const Value *v) const79{80return v->reg.data.id * MIN2(v->reg.size, 4);81}82inline unsigned int idToUnits(const Value *v) const83{84return units(v->reg.file, idToBytes(v));85}86inline int bytesToId(Value *v, unsigned int bytes) const87{88if (v->reg.size < 4)89return units(v->reg.file, bytes);90return bytes / 4;91}92inline int unitsToId(DataFile f, int u, uint8_t size) const93{94if (u < 0)95return -1;96return (size < 4) ? u : ((u << unit[f]) / 4);97}9899void print(DataFile f) const;100101const bool restrictedGPR16Range;102103private:104BitSet bits[LAST_REGISTER_FILE + 1];105106int unit[LAST_REGISTER_FILE + 1]; // log2 of allocation granularity107108int last[LAST_REGISTER_FILE + 1];109int fill[LAST_REGISTER_FILE + 1];110};111112void113RegisterSet::reset(DataFile f, bool resetMax)114{115bits[f].fill(0);116if (resetMax)117fill[f] = -1;118}119120void121RegisterSet::init(const Target *targ)122{123for (unsigned int rf = 0; rf <= LAST_REGISTER_FILE; ++rf) {124DataFile f = static_cast<DataFile>(rf);125last[rf] = targ->getFileSize(f) - 1;126unit[rf] = targ->getFileUnit(f);127fill[rf] = -1;128assert(last[rf] < MAX_REGISTER_FILE_SIZE);129bits[rf].allocate(last[rf] + 1, true);130}131}132133RegisterSet::RegisterSet(const Target *targ)134: restrictedGPR16Range(targ->getChipset() < 0xc0)135{136init(targ);137for (unsigned int i = 0; i <= LAST_REGISTER_FILE; ++i)138reset(static_cast<DataFile>(i));139}140141void142RegisterSet::periodicMask(DataFile f, uint32_t lock, uint32_t unlock)143{144bits[f].periodicMask32(lock, unlock);145}146147void148RegisterSet::intersect(DataFile f, const RegisterSet *set)149{150bits[f] |= set->bits[f];151}152153void154RegisterSet::print(DataFile f) const155{156INFO("GPR:");157bits[f].print();158INFO("\n");159}160161bool162RegisterSet::assign(int32_t& reg, DataFile f, unsigned int size, unsigned int maxReg)163{164reg = bits[f].findFreeRange(size, maxReg);165if (reg < 0)166return false;167fill[f] = MAX2(fill[f], (int32_t)(reg + size - 1));168return true;169}170171bool172RegisterSet::isOccupied(DataFile f, int32_t reg, unsigned int size) const173{174return bits[f].testRange(reg, size);175}176177void178RegisterSet::occupy(const Value *v)179{180occupy(v->reg.file, idToUnits(v), v->reg.size >> unit[v->reg.file]);181}182183void184RegisterSet::occupyMask(DataFile f, int32_t reg, uint8_t mask)185{186bits[f].setMask(reg & ~31, static_cast<uint32_t>(mask) << (reg % 32));187}188189void190RegisterSet::occupy(DataFile f, int32_t reg, unsigned int size)191{192bits[f].setRange(reg, size);193194INFO_DBG(0, REG_ALLOC, "reg occupy: %u[%i] %u\n", f, reg, size);195196fill[f] = MAX2(fill[f], (int32_t)(reg + size - 1));197}198199bool200RegisterSet::testOccupy(const Value *v)201{202return testOccupy(v->reg.file,203idToUnits(v), v->reg.size >> unit[v->reg.file]);204}205206bool207RegisterSet::testOccupy(DataFile f, int32_t reg, unsigned int size)208{209if (isOccupied(f, reg, size))210return false;211occupy(f, reg, size);212return true;213}214215void216RegisterSet::release(DataFile f, int32_t reg, unsigned int size)217{218bits[f].clrRange(reg, size);219220INFO_DBG(0, REG_ALLOC, "reg release: %u[%i] %u\n", f, reg, size);221}222223class RegAlloc224{225public:226RegAlloc(Program *program) : prog(program), func(NULL), sequence(0) { }227228bool exec();229bool execFunc();230231private:232class PhiMovesPass : public Pass {233private:234virtual bool visit(BasicBlock *);235inline bool needNewElseBlock(BasicBlock *b, BasicBlock *p);236inline void splitEdges(BasicBlock *b);237};238239class ArgumentMovesPass : public Pass {240private:241virtual bool visit(BasicBlock *);242};243244class BuildIntervalsPass : public Pass {245private:246virtual bool visit(BasicBlock *);247void collectLiveValues(BasicBlock *);248void addLiveRange(Value *, const BasicBlock *, int end);249};250251class InsertConstraintsPass : public Pass {252public:253InsertConstraintsPass() : targ(NULL) { }254bool exec(Function *func);255private:256virtual bool visit(BasicBlock *);257258void insertConstraintMove(Instruction *, int s);259bool insertConstraintMoves();260261void condenseDefs(Instruction *);262void condenseDefs(Instruction *, const int first, const int last);263void condenseSrcs(Instruction *, const int first, const int last);264265void addHazard(Instruction *i, const ValueRef *src);266void textureMask(TexInstruction *);267void addConstraint(Instruction *, int s, int n);268bool detectConflict(Instruction *, int s);269270// target specific functions, TODO: put in subclass or Target271void texConstraintNV50(TexInstruction *);272void texConstraintNVC0(TexInstruction *);273void texConstraintNVE0(TexInstruction *);274void texConstraintGM107(TexInstruction *);275276bool isScalarTexGM107(TexInstruction *);277void handleScalarTexGM107(TexInstruction *);278279std::list<Instruction *> constrList;280281const Target *targ;282};283284bool buildLiveSets(BasicBlock *);285286private:287Program *prog;288Function *func;289290// instructions in control flow / chronological order291ArrayList insns;292293int sequence; // for manual passes through CFG294};295296typedef std::pair<Value *, Value *> ValuePair;297298class MergedDefs299{300private:301std::list<ValueDef *>& entry(Value *val) {302auto it = defs.find(val);303304if (it == defs.end()) {305std::list<ValueDef *> &res = defs[val];306res = val->defs;307return res;308} else {309return (*it).second;310}311}312313std::unordered_map<Value *, std::list<ValueDef *> > defs;314315public:316std::list<ValueDef *>& operator()(Value *val) {317return entry(val);318}319320void add(Value *val, const std::list<ValueDef *> &vals) {321assert(val);322std::list<ValueDef *> &valdefs = entry(val);323valdefs.insert(valdefs.end(), vals.begin(), vals.end());324}325326void removeDefsOfInstruction(Instruction *insn) {327for (int d = 0; insn->defExists(d); ++d) {328ValueDef *def = &insn->def(d);329defs.erase(def->get());330for (auto &p : defs)331p.second.remove(def);332}333}334335void merge() {336for (auto &p : defs)337p.first->defs = p.second;338}339};340341class SpillCodeInserter342{343public:344SpillCodeInserter(Function *fn, MergedDefs &mergedDefs) : func(fn), mergedDefs(mergedDefs), stackSize(0), stackBase(0) { }345346bool run(const std::list<ValuePair>&);347348Symbol *assignSlot(const Interval&, const unsigned int size);349Value *offsetSlot(Value *, const LValue *);350inline int32_t getStackSize() const { return stackSize; }351352private:353Function *func;354MergedDefs &mergedDefs;355356struct SpillSlot357{358Interval occup;359std::list<Value *> residents; // needed to recalculate occup360Symbol *sym;361int32_t offset;362inline uint8_t size() const { return sym->reg.size; }363};364std::list<SpillSlot> slots;365int32_t stackSize;366int32_t stackBase;367368LValue *unspill(Instruction *usei, LValue *, Value *slot);369void spill(Instruction *defi, Value *slot, LValue *);370};371372void373RegAlloc::BuildIntervalsPass::addLiveRange(Value *val,374const BasicBlock *bb,375int end)376{377Instruction *insn = val->getUniqueInsn();378379if (!insn)380insn = bb->getFirst();381382assert(bb->getFirst()->serial <= bb->getExit()->serial);383assert(bb->getExit()->serial + 1 >= end);384385int begin = insn->serial;386if (begin < bb->getEntry()->serial || begin > bb->getExit()->serial)387begin = bb->getEntry()->serial;388389INFO_DBG(prog->dbgFlags, REG_ALLOC, "%%%i <- live range [%i(%i), %i)\n",390val->id, begin, insn->serial, end);391392if (begin != end) // empty ranges are only added as hazards for fixed regs393val->livei.extend(begin, end);394}395396bool397RegAlloc::PhiMovesPass::needNewElseBlock(BasicBlock *b, BasicBlock *p)398{399if (b->cfg.incidentCount() <= 1)400return false;401402int n = 0;403for (Graph::EdgeIterator ei = p->cfg.outgoing(); !ei.end(); ei.next())404if (ei.getType() == Graph::Edge::TREE ||405ei.getType() == Graph::Edge::FORWARD)406++n;407return (n == 2);408}409410struct PhiMapHash {411size_t operator()(const std::pair<Instruction *, BasicBlock *>& val) const {412return hash<Instruction*>()(val.first) * 31 +413hash<BasicBlock*>()(val.second);414}415};416417typedef unordered_map<418std::pair<Instruction *, BasicBlock *>, Value *, PhiMapHash> PhiMap;419420// Critical edges need to be split up so that work can be inserted along421// specific edge transitions. Unfortunately manipulating incident edges into a422// BB invalidates all the PHI nodes since their sources are implicitly ordered423// by incident edge order.424//425// TODO: Make it so that that is not the case, and PHI nodes store pointers to426// the original BBs.427void428RegAlloc::PhiMovesPass::splitEdges(BasicBlock *bb)429{430BasicBlock *pb, *pn;431Instruction *phi;432Graph::EdgeIterator ei;433std::stack<BasicBlock *> stack;434int j = 0;435436for (ei = bb->cfg.incident(); !ei.end(); ei.next()) {437pb = BasicBlock::get(ei.getNode());438assert(pb);439if (needNewElseBlock(bb, pb))440stack.push(pb);441}442443// No critical edges were found, no need to perform any work.444if (stack.empty())445return;446447// We're about to, potentially, reorder the inbound edges. This means that448// we need to hold on to the (phi, bb) -> src mapping, and fix up the phi449// nodes after the graph has been modified.450PhiMap phis;451452j = 0;453for (ei = bb->cfg.incident(); !ei.end(); ei.next(), j++) {454pb = BasicBlock::get(ei.getNode());455for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next)456phis.insert(std::make_pair(std::make_pair(phi, pb), phi->getSrc(j)));457}458459while (!stack.empty()) {460pb = stack.top();461pn = new BasicBlock(func);462stack.pop();463464pb->cfg.detach(&bb->cfg);465pb->cfg.attach(&pn->cfg, Graph::Edge::TREE);466pn->cfg.attach(&bb->cfg, Graph::Edge::FORWARD);467468assert(pb->getExit()->op != OP_CALL);469if (pb->getExit()->asFlow()->target.bb == bb)470pb->getExit()->asFlow()->target.bb = pn;471472for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next) {473PhiMap::iterator it = phis.find(std::make_pair(phi, pb));474assert(it != phis.end());475phis.insert(std::make_pair(std::make_pair(phi, pn), it->second));476phis.erase(it);477}478}479480// Now go through and fix up all of the phi node sources.481j = 0;482for (ei = bb->cfg.incident(); !ei.end(); ei.next(), j++) {483pb = BasicBlock::get(ei.getNode());484for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next) {485PhiMap::const_iterator it = phis.find(std::make_pair(phi, pb));486assert(it != phis.end());487488phi->setSrc(j, it->second);489}490}491}492493// For each operand of each PHI in b, generate a new value by inserting a MOV494// at the end of the block it is coming from and replace the operand with its495// result. This eliminates liveness conflicts and enables us to let values be496// copied to the right register if such a conflict exists nonetheless.497//498// These MOVs are also crucial in making sure the live intervals of phi srces499// are extended until the end of the loop, since they are not included in the500// live-in sets.501bool502RegAlloc::PhiMovesPass::visit(BasicBlock *bb)503{504Instruction *phi, *mov;505506splitEdges(bb);507508// insert MOVs (phi->src(j) should stem from j-th in-BB)509int j = 0;510for (Graph::EdgeIterator ei = bb->cfg.incident(); !ei.end(); ei.next()) {511BasicBlock *pb = BasicBlock::get(ei.getNode());512if (!pb->isTerminated())513pb->insertTail(new_FlowInstruction(func, OP_BRA, bb));514515for (phi = bb->getPhi(); phi && phi->op == OP_PHI; phi = phi->next) {516LValue *tmp = new_LValue(func, phi->getDef(0)->asLValue());517mov = new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));518519mov->setSrc(0, phi->getSrc(j));520mov->setDef(0, tmp);521phi->setSrc(j, tmp);522523pb->insertBefore(pb->getExit(), mov);524}525++j;526}527528return true;529}530531bool532RegAlloc::ArgumentMovesPass::visit(BasicBlock *bb)533{534// Bind function call inputs/outputs to the same physical register535// the callee uses, inserting moves as appropriate for the case a536// conflict arises.537for (Instruction *i = bb->getEntry(); i; i = i->next) {538FlowInstruction *cal = i->asFlow();539// TODO: Handle indirect calls.540// Right now they should only be generated for builtins.541if (!cal || cal->op != OP_CALL || cal->builtin || cal->indirect)542continue;543RegisterSet clobberSet(prog->getTarget());544545// Bind input values.546for (int s = cal->indirect ? 1 : 0; cal->srcExists(s); ++s) {547const int t = cal->indirect ? (s - 1) : s;548LValue *tmp = new_LValue(func, cal->getSrc(s)->asLValue());549tmp->reg.data.id = cal->target.fn->ins[t].rep()->reg.data.id;550551Instruction *mov =552new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));553mov->setDef(0, tmp);554mov->setSrc(0, cal->getSrc(s));555cal->setSrc(s, tmp);556557bb->insertBefore(cal, mov);558}559560// Bind output values.561for (int d = 0; cal->defExists(d); ++d) {562LValue *tmp = new_LValue(func, cal->getDef(d)->asLValue());563tmp->reg.data.id = cal->target.fn->outs[d].rep()->reg.data.id;564565Instruction *mov =566new_Instruction(func, OP_MOV, typeOfSize(tmp->reg.size));567mov->setSrc(0, tmp);568mov->setDef(0, cal->getDef(d));569cal->setDef(d, tmp);570571bb->insertAfter(cal, mov);572clobberSet.occupy(tmp);573}574575// Bind clobbered values.576for (std::deque<Value *>::iterator it = cal->target.fn->clobbers.begin();577it != cal->target.fn->clobbers.end();578++it) {579if (clobberSet.testOccupy(*it)) {580Value *tmp = new_LValue(func, (*it)->asLValue());581tmp->reg.data.id = (*it)->reg.data.id;582cal->setDef(cal->defCount(), tmp);583}584}585}586587// Update the clobber set of the function.588if (BasicBlock::get(func->cfgExit) == bb) {589func->buildDefSets();590for (unsigned int i = 0; i < bb->defSet.getSize(); ++i)591if (bb->defSet.test(i))592func->clobbers.push_back(func->getLValue(i));593}594595return true;596}597598// Build the set of live-in variables of bb.599bool600RegAlloc::buildLiveSets(BasicBlock *bb)601{602Function *f = bb->getFunction();603BasicBlock *bn;604Instruction *i;605unsigned int s, d;606607INFO_DBG(prog->dbgFlags, REG_ALLOC, "buildLiveSets(BB:%i)\n", bb->getId());608609bb->liveSet.allocate(func->allLValues.getSize(), false);610611int n = 0;612for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {613bn = BasicBlock::get(ei.getNode());614if (bn == bb)615continue;616if (bn->cfg.visit(sequence))617if (!buildLiveSets(bn))618return false;619if (n++ || bb->liveSet.marker)620bb->liveSet |= bn->liveSet;621else622bb->liveSet = bn->liveSet;623}624if (!n && !bb->liveSet.marker)625bb->liveSet.fill(0);626bb->liveSet.marker = true;627628if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {629INFO("BB:%i live set of out blocks:\n", bb->getId());630bb->liveSet.print();631}632633// if (!bb->getEntry())634// return true;635636if (bb == BasicBlock::get(f->cfgExit)) {637for (std::deque<ValueRef>::iterator it = f->outs.begin();638it != f->outs.end(); ++it) {639assert(it->get()->asLValue());640bb->liveSet.set(it->get()->id);641}642}643644for (i = bb->getExit(); i && i != bb->getEntry()->prev; i = i->prev) {645for (d = 0; i->defExists(d); ++d)646bb->liveSet.clr(i->getDef(d)->id);647for (s = 0; i->srcExists(s); ++s)648if (i->getSrc(s)->asLValue())649bb->liveSet.set(i->getSrc(s)->id);650}651for (i = bb->getPhi(); i && i->op == OP_PHI; i = i->next)652bb->liveSet.clr(i->getDef(0)->id);653654if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {655INFO("BB:%i live set after propagation:\n", bb->getId());656bb->liveSet.print();657}658659return true;660}661662void663RegAlloc::BuildIntervalsPass::collectLiveValues(BasicBlock *bb)664{665BasicBlock *bbA = NULL, *bbB = NULL;666667if (bb->cfg.outgoingCount()) {668// trickery to save a loop of OR'ing liveSets669// aliasing works fine with BitSet::setOr670for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {671if (bbA) {672bb->liveSet.setOr(&bbA->liveSet, &bbB->liveSet);673bbA = bb;674} else {675bbA = bbB;676}677bbB = BasicBlock::get(ei.getNode());678}679bb->liveSet.setOr(&bbB->liveSet, bbA ? &bbA->liveSet : NULL);680} else681if (bb->cfg.incidentCount()) {682bb->liveSet.fill(0);683}684}685686bool687RegAlloc::BuildIntervalsPass::visit(BasicBlock *bb)688{689collectLiveValues(bb);690691INFO_DBG(prog->dbgFlags, REG_ALLOC, "BuildIntervals(BB:%i)\n", bb->getId());692693// go through out blocks and delete phi sources that do not originate from694// the current block from the live set695for (Graph::EdgeIterator ei = bb->cfg.outgoing(); !ei.end(); ei.next()) {696BasicBlock *out = BasicBlock::get(ei.getNode());697698for (Instruction *i = out->getPhi(); i && i->op == OP_PHI; i = i->next) {699bb->liveSet.clr(i->getDef(0)->id);700701for (int s = 0; i->srcExists(s); ++s) {702assert(i->src(s).getInsn());703if (i->getSrc(s)->getUniqueInsn()->bb == bb) // XXX: reachableBy ?704bb->liveSet.set(i->getSrc(s)->id);705else706bb->liveSet.clr(i->getSrc(s)->id);707}708}709}710711// remaining live-outs are live until end712if (bb->getExit()) {713for (unsigned int j = 0; j < bb->liveSet.getSize(); ++j)714if (bb->liveSet.test(j))715addLiveRange(func->getLValue(j), bb, bb->getExit()->serial + 1);716}717718for (Instruction *i = bb->getExit(); i && i->op != OP_PHI; i = i->prev) {719for (int d = 0; i->defExists(d); ++d) {720bb->liveSet.clr(i->getDef(d)->id);721if (i->getDef(d)->reg.data.id >= 0) // add hazard for fixed regs722i->getDef(d)->livei.extend(i->serial, i->serial);723}724725for (int s = 0; i->srcExists(s); ++s) {726if (!i->getSrc(s)->asLValue())727continue;728if (!bb->liveSet.test(i->getSrc(s)->id)) {729bb->liveSet.set(i->getSrc(s)->id);730addLiveRange(i->getSrc(s), bb, i->serial);731}732}733}734735if (bb == BasicBlock::get(func->cfg.getRoot())) {736for (std::deque<ValueDef>::iterator it = func->ins.begin();737it != func->ins.end(); ++it) {738if (it->get()->reg.data.id >= 0) // add hazard for fixed regs739it->get()->livei.extend(0, 1);740}741}742743return true;744}745746747#define JOIN_MASK_PHI (1 << 0)748#define JOIN_MASK_UNION (1 << 1)749#define JOIN_MASK_MOV (1 << 2)750#define JOIN_MASK_TEX (1 << 3)751752class GCRA753{754public:755GCRA(Function *, SpillCodeInserter&, MergedDefs&);756~GCRA();757758bool allocateRegisters(ArrayList& insns);759760void printNodeInfo() const;761762private:763class RIG_Node : public Graph::Node764{765public:766RIG_Node();767768void init(const RegisterSet&, LValue *);769770void addInterference(RIG_Node *);771void addRegPreference(RIG_Node *);772773inline LValue *getValue() const774{775return reinterpret_cast<LValue *>(data);776}777inline void setValue(LValue *lval) { data = lval; }778779inline uint8_t getCompMask() const780{781return ((1 << colors) - 1) << (reg & 7);782}783784static inline RIG_Node *get(const Graph::EdgeIterator& ei)785{786return static_cast<RIG_Node *>(ei.getNode());787}788789public:790uint32_t degree;791uint16_t degreeLimit; // if deg < degLimit, node is trivially colourable792uint16_t maxReg;793uint16_t colors;794795DataFile f;796int32_t reg;797798float weight;799800// list pointers for simplify() phase801RIG_Node *next;802RIG_Node *prev;803804// union of the live intervals of all coalesced values (we want to retain805// the separate intervals for testing interference of compound values)806Interval livei;807808std::list<RIG_Node *> prefRegs;809};810811private:812inline RIG_Node *getNode(const LValue *v) const { return &nodes[v->id]; }813814void buildRIG(ArrayList&);815bool coalesce(ArrayList&);816bool doCoalesce(ArrayList&, unsigned int mask);817void calculateSpillWeights();818bool simplify();819bool selectRegisters();820void cleanup(const bool success);821822void simplifyEdge(RIG_Node *, RIG_Node *);823void simplifyNode(RIG_Node *);824825bool coalesceValues(Value *, Value *, bool force);826void resolveSplitsAndMerges();827void makeCompound(Instruction *, bool isSplit);828829inline void checkInterference(const RIG_Node *, Graph::EdgeIterator&);830831inline void insertOrderedTail(std::list<RIG_Node *>&, RIG_Node *);832void checkList(std::list<RIG_Node *>&);833834private:835std::stack<uint32_t> stack;836837// list headers for simplify() phase838RIG_Node lo[2];839RIG_Node hi;840841Graph RIG;842RIG_Node *nodes;843unsigned int nodeCount;844845Function *func;846Program *prog;847848struct RelDegree {849uint8_t data[17][17];850851RelDegree() {852for (int i = 1; i <= 16; ++i)853for (int j = 1; j <= 16; ++j)854data[i][j] = j * ((i + j - 1) / j);855}856857const uint8_t* operator[](std::size_t i) const {858return data[i];859}860};861862static const RelDegree relDegree;863864RegisterSet regs;865866// need to fixup register id for participants of OP_MERGE/SPLIT867std::list<Instruction *> merges;868std::list<Instruction *> splits;869870SpillCodeInserter& spill;871std::list<ValuePair> mustSpill;872873MergedDefs &mergedDefs;874};875876const GCRA::RelDegree GCRA::relDegree;877878GCRA::RIG_Node::RIG_Node() : Node(NULL), degree(0), degreeLimit(0), maxReg(0),879colors(0), f(FILE_NULL), reg(0), weight(0), next(this), prev(this)880{881}882883void884GCRA::printNodeInfo() const885{886for (unsigned int i = 0; i < nodeCount; ++i) {887if (!nodes[i].colors)888continue;889INFO("RIG_Node[%%%i]($[%u]%i): %u colors, weight %f, deg %u/%u\n X",890i,891nodes[i].f,nodes[i].reg,nodes[i].colors,892nodes[i].weight,893nodes[i].degree, nodes[i].degreeLimit);894895for (Graph::EdgeIterator ei = nodes[i].outgoing(); !ei.end(); ei.next())896INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);897for (Graph::EdgeIterator ei = nodes[i].incident(); !ei.end(); ei.next())898INFO(" %%%i", RIG_Node::get(ei)->getValue()->id);899INFO("\n");900}901}902903static bool904isShortRegOp(Instruction *insn)905{906// Immediates are always in src1 (except zeroes, which end up getting907// replaced with a zero reg). Every other situation can be resolved by908// using a long encoding.909return insn->srcExists(1) && insn->src(1).getFile() == FILE_IMMEDIATE &&910insn->getSrc(1)->reg.data.u64;911}912913// Check if this LValue is ever used in an instruction that can't be encoded914// with long registers (i.e. > r63)915static bool916isShortRegVal(LValue *lval)917{918if (lval->getInsn() == NULL)919return false;920for (Value::DefCIterator def = lval->defs.begin();921def != lval->defs.end(); ++def)922if (isShortRegOp((*def)->getInsn()))923return true;924for (Value::UseCIterator use = lval->uses.begin();925use != lval->uses.end(); ++use)926if (isShortRegOp((*use)->getInsn()))927return true;928return false;929}930931void932GCRA::RIG_Node::init(const RegisterSet& regs, LValue *lval)933{934setValue(lval);935if (lval->reg.data.id >= 0)936lval->noSpill = lval->fixedReg = 1;937938colors = regs.units(lval->reg.file, lval->reg.size);939f = lval->reg.file;940reg = -1;941if (lval->reg.data.id >= 0)942reg = regs.idToUnits(lval);943944weight = std::numeric_limits<float>::infinity();945degree = 0;946maxReg = regs.getFileSize(f);947// On nv50, we lose a bit of gpr encoding when there's an embedded948// immediate.949if (regs.restrictedGPR16Range && f == FILE_GPR && (lval->reg.size == 2 || isShortRegVal(lval)))950maxReg /= 2;951degreeLimit = maxReg;952degreeLimit -= relDegree[1][colors] - 1;953954livei.insert(lval->livei);955}956957bool958GCRA::coalesceValues(Value *dst, Value *src, bool force)959{960LValue *rep = dst->join->asLValue();961LValue *val = src->join->asLValue();962963if (!force && val->reg.data.id >= 0) {964rep = src->join->asLValue();965val = dst->join->asLValue();966}967RIG_Node *nRep = &nodes[rep->id];968RIG_Node *nVal = &nodes[val->id];969970if (src->reg.file != dst->reg.file) {971if (!force)972return false;973WARN("forced coalescing of values in different files !\n");974}975if (!force && dst->reg.size != src->reg.size)976return false;977978if ((rep->reg.data.id >= 0) && (rep->reg.data.id != val->reg.data.id)) {979if (force) {980if (val->reg.data.id >= 0)981WARN("forced coalescing of values in different fixed regs !\n");982} else {983if (val->reg.data.id >= 0)984return false;985// make sure that there is no overlap with the fixed register of rep986for (ArrayList::Iterator it = func->allLValues.iterator();987!it.end(); it.next()) {988Value *reg = reinterpret_cast<Value *>(it.get())->asLValue();989assert(reg);990if (reg->interfers(rep) && reg->livei.overlaps(nVal->livei))991return false;992}993}994}995996if (!force && nRep->livei.overlaps(nVal->livei))997return false;998999INFO_DBG(prog->dbgFlags, REG_ALLOC, "joining %%%i($%i) <- %%%i\n",1000rep->id, rep->reg.data.id, val->id);10011002// set join pointer of all values joined with val1003const std::list<ValueDef *> &defs = mergedDefs(val);1004for (ValueDef *def : defs)1005def->get()->join = rep;1006assert(rep->join == rep && val->join == rep);10071008// add val's definitions to rep and extend the live interval of its RIG node1009mergedDefs.add(rep, defs);1010nRep->livei.unify(nVal->livei);1011nRep->degreeLimit = MIN2(nRep->degreeLimit, nVal->degreeLimit);1012nRep->maxReg = MIN2(nRep->maxReg, nVal->maxReg);1013return true;1014}10151016bool1017GCRA::coalesce(ArrayList& insns)1018{1019bool ret = doCoalesce(insns, JOIN_MASK_PHI);1020if (!ret)1021return false;1022switch (func->getProgram()->getTarget()->getChipset() & ~0xf) {1023case 0x50:1024case 0x80:1025case 0x90:1026case 0xa0:1027ret = doCoalesce(insns, JOIN_MASK_UNION | JOIN_MASK_TEX);1028break;1029case 0xc0:1030case 0xd0:1031case 0xe0:1032case 0xf0:1033case 0x100:1034case 0x110:1035case 0x120:1036case 0x130:1037case 0x140:1038case 0x160:1039ret = doCoalesce(insns, JOIN_MASK_UNION);1040break;1041default:1042break;1043}1044if (!ret)1045return false;1046return doCoalesce(insns, JOIN_MASK_MOV);1047}10481049static inline uint8_t makeCompMask(int compSize, int base, int size)1050{1051uint8_t m = ((1 << size) - 1) << base;10521053switch (compSize) {1054case 1:1055return 0xff;1056case 2:1057m |= (m << 2);1058return (m << 4) | m;1059case 3:1060case 4:1061return (m << 4) | m;1062default:1063assert(compSize <= 8);1064return m;1065}1066}10671068// Used when coalescing moves. The non-compound value will become one, e.g.:1069// mov b32 $r0 $r2 / merge b64 $r0d { $r0 $r1 }1070// split b64 { $r0 $r1 } $r0d / mov b64 $r0d f64 $r2d1071static inline void copyCompound(Value *dst, Value *src)1072{1073LValue *ldst = dst->asLValue();1074LValue *lsrc = src->asLValue();10751076if (ldst->compound && !lsrc->compound) {1077LValue *swap = lsrc;1078lsrc = ldst;1079ldst = swap;1080}10811082ldst->compound = lsrc->compound;1083ldst->compMask = lsrc->compMask;1084}10851086void1087GCRA::makeCompound(Instruction *insn, bool split)1088{1089LValue *rep = (split ? insn->getSrc(0) : insn->getDef(0))->asLValue();10901091if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC) {1092INFO("makeCompound(split = %i): ", split);1093insn->print();1094}10951096const unsigned int size = getNode(rep)->colors;1097unsigned int base = 0;10981099if (!rep->compound)1100rep->compMask = 0xff;1101rep->compound = 1;11021103for (int c = 0; split ? insn->defExists(c) : insn->srcExists(c); ++c) {1104LValue *val = (split ? insn->getDef(c) : insn->getSrc(c))->asLValue();11051106val->compound = 1;1107if (!val->compMask)1108val->compMask = 0xff;1109val->compMask &= makeCompMask(size, base, getNode(val)->colors);1110assert(val->compMask);11111112INFO_DBG(prog->dbgFlags, REG_ALLOC, "compound: %%%i:%02x <- %%%i:%02x\n",1113rep->id, rep->compMask, val->id, val->compMask);11141115base += getNode(val)->colors;1116}1117assert(base == size);1118}11191120bool1121GCRA::doCoalesce(ArrayList& insns, unsigned int mask)1122{1123int c, n;11241125for (n = 0; n < insns.getSize(); ++n) {1126Instruction *i;1127Instruction *insn = reinterpret_cast<Instruction *>(insns.get(n));11281129switch (insn->op) {1130case OP_PHI:1131if (!(mask & JOIN_MASK_PHI))1132break;1133for (c = 0; insn->srcExists(c); ++c)1134if (!coalesceValues(insn->getDef(0), insn->getSrc(c), false)) {1135// this is bad1136ERROR("failed to coalesce phi operands\n");1137return false;1138}1139break;1140case OP_UNION:1141case OP_MERGE:1142if (!(mask & JOIN_MASK_UNION))1143break;1144for (c = 0; insn->srcExists(c); ++c)1145coalesceValues(insn->getDef(0), insn->getSrc(c), true);1146if (insn->op == OP_MERGE) {1147merges.push_back(insn);1148if (insn->srcExists(1))1149makeCompound(insn, false);1150}1151break;1152case OP_SPLIT:1153if (!(mask & JOIN_MASK_UNION))1154break;1155splits.push_back(insn);1156for (c = 0; insn->defExists(c); ++c)1157coalesceValues(insn->getSrc(0), insn->getDef(c), true);1158makeCompound(insn, true);1159break;1160case OP_MOV:1161if (!(mask & JOIN_MASK_MOV))1162break;1163i = NULL;1164if (!insn->getDef(0)->uses.empty())1165i = (*insn->getDef(0)->uses.begin())->getInsn();1166// if this is a contraint-move there will only be a single use1167if (i && i->op == OP_MERGE) // do we really still need this ?1168break;1169i = insn->getSrc(0)->getUniqueInsn();1170if (i && !i->constrainedDefs()) {1171if (coalesceValues(insn->getDef(0), insn->getSrc(0), false))1172copyCompound(insn->getSrc(0), insn->getDef(0));1173}1174break;1175case OP_TEX:1176case OP_TXB:1177case OP_TXL:1178case OP_TXF:1179case OP_TXQ:1180case OP_TXD:1181case OP_TXG:1182case OP_TXLQ:1183case OP_TEXCSAA:1184case OP_TEXPREP:1185if (!(mask & JOIN_MASK_TEX))1186break;1187for (c = 0; insn->srcExists(c) && c != insn->predSrc; ++c)1188coalesceValues(insn->getDef(c), insn->getSrc(c), true);1189break;1190default:1191break;1192}1193}1194return true;1195}11961197void1198GCRA::RIG_Node::addInterference(RIG_Node *node)1199{1200this->degree += relDegree[node->colors][colors];1201node->degree += relDegree[colors][node->colors];12021203this->attach(node, Graph::Edge::CROSS);1204}12051206void1207GCRA::RIG_Node::addRegPreference(RIG_Node *node)1208{1209prefRegs.push_back(node);1210}12111212GCRA::GCRA(Function *fn, SpillCodeInserter& spill, MergedDefs& mergedDefs) :1213nodes(NULL),1214nodeCount(0),1215func(fn),1216regs(fn->getProgram()->getTarget()),1217spill(spill),1218mergedDefs(mergedDefs)1219{1220prog = func->getProgram();1221}12221223GCRA::~GCRA()1224{1225if (nodes)1226delete[] nodes;1227}12281229void1230GCRA::checkList(std::list<RIG_Node *>& lst)1231{1232GCRA::RIG_Node *prev = NULL;12331234for (std::list<RIG_Node *>::iterator it = lst.begin();1235it != lst.end();1236++it) {1237assert((*it)->getValue()->join == (*it)->getValue());1238if (prev)1239assert(prev->livei.begin() <= (*it)->livei.begin());1240prev = *it;1241}1242}12431244void1245GCRA::insertOrderedTail(std::list<RIG_Node *>& list, RIG_Node *node)1246{1247if (node->livei.isEmpty())1248return;1249// only the intervals of joined values don't necessarily arrive in order1250std::list<RIG_Node *>::iterator prev, it;1251for (it = list.end(); it != list.begin(); it = prev) {1252prev = it;1253--prev;1254if ((*prev)->livei.begin() <= node->livei.begin())1255break;1256}1257list.insert(it, node);1258}12591260void1261GCRA::buildRIG(ArrayList& insns)1262{1263std::list<RIG_Node *> values, active;12641265for (std::deque<ValueDef>::iterator it = func->ins.begin();1266it != func->ins.end(); ++it)1267insertOrderedTail(values, getNode(it->get()->asLValue()));12681269for (int i = 0; i < insns.getSize(); ++i) {1270Instruction *insn = reinterpret_cast<Instruction *>(insns.get(i));1271for (int d = 0; insn->defExists(d); ++d)1272if (insn->getDef(d)->reg.file <= LAST_REGISTER_FILE &&1273insn->getDef(d)->rep() == insn->getDef(d))1274insertOrderedTail(values, getNode(insn->getDef(d)->asLValue()));1275}1276checkList(values);12771278while (!values.empty()) {1279RIG_Node *cur = values.front();12801281for (std::list<RIG_Node *>::iterator it = active.begin();1282it != active.end();) {1283RIG_Node *node = *it;12841285if (node->livei.end() <= cur->livei.begin()) {1286it = active.erase(it);1287} else {1288if (node->f == cur->f && node->livei.overlaps(cur->livei))1289cur->addInterference(node);1290++it;1291}1292}1293values.pop_front();1294active.push_back(cur);1295}1296}12971298void1299GCRA::calculateSpillWeights()1300{1301for (unsigned int i = 0; i < nodeCount; ++i) {1302RIG_Node *const n = &nodes[i];1303if (!nodes[i].colors || nodes[i].livei.isEmpty())1304continue;1305if (nodes[i].reg >= 0) {1306// update max reg1307regs.occupy(n->f, n->reg, n->colors);1308continue;1309}1310LValue *val = nodes[i].getValue();13111312if (!val->noSpill) {1313int rc = 0;1314for (ValueDef *def : mergedDefs(val))1315rc += def->get()->refCount();13161317nodes[i].weight =1318(float)rc * (float)rc / (float)nodes[i].livei.extent();1319}13201321if (nodes[i].degree < nodes[i].degreeLimit) {1322int l = 0;1323if (val->reg.size > 4)1324l = 1;1325DLLIST_ADDHEAD(&lo[l], &nodes[i]);1326} else {1327DLLIST_ADDHEAD(&hi, &nodes[i]);1328}1329}1330if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)1331printNodeInfo();1332}13331334void1335GCRA::simplifyEdge(RIG_Node *a, RIG_Node *b)1336{1337bool move = b->degree >= b->degreeLimit;13381339INFO_DBG(prog->dbgFlags, REG_ALLOC,1340"edge: (%%%i, deg %u/%u) >-< (%%%i, deg %u/%u)\n",1341a->getValue()->id, a->degree, a->degreeLimit,1342b->getValue()->id, b->degree, b->degreeLimit);13431344b->degree -= relDegree[a->colors][b->colors];13451346move = move && b->degree < b->degreeLimit;1347if (move && !DLLIST_EMPTY(b)) {1348int l = (b->getValue()->reg.size > 4) ? 1 : 0;1349DLLIST_DEL(b);1350DLLIST_ADDTAIL(&lo[l], b);1351}1352}13531354void1355GCRA::simplifyNode(RIG_Node *node)1356{1357for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())1358simplifyEdge(node, RIG_Node::get(ei));13591360for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())1361simplifyEdge(node, RIG_Node::get(ei));13621363DLLIST_DEL(node);1364stack.push(node->getValue()->id);13651366INFO_DBG(prog->dbgFlags, REG_ALLOC, "SIMPLIFY: pushed %%%i%s\n",1367node->getValue()->id,1368(node->degree < node->degreeLimit) ? "" : "(spill)");1369}13701371bool1372GCRA::simplify()1373{1374for (;;) {1375if (!DLLIST_EMPTY(&lo[0])) {1376do {1377simplifyNode(lo[0].next);1378} while (!DLLIST_EMPTY(&lo[0]));1379} else1380if (!DLLIST_EMPTY(&lo[1])) {1381simplifyNode(lo[1].next);1382} else1383if (!DLLIST_EMPTY(&hi)) {1384RIG_Node *best = hi.next;1385unsigned bestMaxReg = best->maxReg;1386float bestScore = best->weight / (float)best->degree;1387// Spill candidate. First go through the ones with the highest max1388// register, then the ones with lower. That way the ones with the1389// lowest requirement will be allocated first, since it's a stack.1390for (RIG_Node *it = best->next; it != &hi; it = it->next) {1391float score = it->weight / (float)it->degree;1392if (score < bestScore || it->maxReg > bestMaxReg) {1393best = it;1394bestScore = score;1395bestMaxReg = it->maxReg;1396}1397}1398if (isinf(bestScore)) {1399ERROR("no viable spill candidates left\n");1400return false;1401}1402simplifyNode(best);1403} else {1404return true;1405}1406}1407}14081409void1410GCRA::checkInterference(const RIG_Node *node, Graph::EdgeIterator& ei)1411{1412const RIG_Node *intf = RIG_Node::get(ei);14131414if (intf->reg < 0)1415return;1416LValue *vA = node->getValue();1417LValue *vB = intf->getValue();14181419const uint8_t intfMask = ((1 << intf->colors) - 1) << (intf->reg & 7);14201421if (vA->compound | vB->compound) {1422// NOTE: this only works for >aligned< register tuples !1423for (const ValueDef *D : mergedDefs(vA)) {1424for (const ValueDef *d : mergedDefs(vB)) {1425const LValue *vD = D->get()->asLValue();1426const LValue *vd = d->get()->asLValue();14271428if (!vD->livei.overlaps(vd->livei)) {1429INFO_DBG(prog->dbgFlags, REG_ALLOC, "(%%%i) X (%%%i): no overlap\n",1430vD->id, vd->id);1431continue;1432}14331434uint8_t mask = vD->compound ? vD->compMask : ~0;1435if (vd->compound) {1436assert(vB->compound);1437mask &= vd->compMask & vB->compMask;1438} else {1439mask &= intfMask;1440}14411442INFO_DBG(prog->dbgFlags, REG_ALLOC,1443"(%%%i)%02x X (%%%i)%02x & %02x: $r%i.%02x\n",1444vD->id,1445vD->compound ? vD->compMask : 0xff,1446vd->id,1447vd->compound ? vd->compMask : intfMask,1448vB->compMask, intf->reg & ~7, mask);1449if (mask)1450regs.occupyMask(node->f, intf->reg & ~7, mask);1451}1452}1453} else {1454INFO_DBG(prog->dbgFlags, REG_ALLOC,1455"(%%%i) X (%%%i): $r%i + %u\n",1456vA->id, vB->id, intf->reg, intf->colors);1457regs.occupy(node->f, intf->reg, intf->colors);1458}1459}14601461bool1462GCRA::selectRegisters()1463{1464INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nSELECT phase\n");14651466while (!stack.empty()) {1467RIG_Node *node = &nodes[stack.top()];1468stack.pop();14691470regs.reset(node->f);14711472INFO_DBG(prog->dbgFlags, REG_ALLOC, "\nNODE[%%%i, %u colors]\n",1473node->getValue()->id, node->colors);14741475for (Graph::EdgeIterator ei = node->outgoing(); !ei.end(); ei.next())1476checkInterference(node, ei);1477for (Graph::EdgeIterator ei = node->incident(); !ei.end(); ei.next())1478checkInterference(node, ei);14791480if (!node->prefRegs.empty()) {1481for (std::list<RIG_Node *>::const_iterator it = node->prefRegs.begin();1482it != node->prefRegs.end();1483++it) {1484if ((*it)->reg >= 0 &&1485regs.testOccupy(node->f, (*it)->reg, node->colors)) {1486node->reg = (*it)->reg;1487break;1488}1489}1490}1491if (node->reg >= 0)1492continue;1493LValue *lval = node->getValue();1494if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)1495regs.print(node->f);1496bool ret = regs.assign(node->reg, node->f, node->colors, node->maxReg);1497if (ret) {1498INFO_DBG(prog->dbgFlags, REG_ALLOC, "assigned reg %i\n", node->reg);1499lval->compMask = node->getCompMask();1500} else {1501INFO_DBG(prog->dbgFlags, REG_ALLOC, "must spill: %%%i (size %u)\n",1502lval->id, lval->reg.size);1503Symbol *slot = NULL;1504if (lval->reg.file == FILE_GPR)1505slot = spill.assignSlot(node->livei, lval->reg.size);1506mustSpill.push_back(ValuePair(lval, slot));1507}1508}1509if (!mustSpill.empty())1510return false;1511for (unsigned int i = 0; i < nodeCount; ++i) {1512LValue *lval = nodes[i].getValue();1513if (nodes[i].reg >= 0 && nodes[i].colors > 0)1514lval->reg.data.id =1515regs.unitsToId(nodes[i].f, nodes[i].reg, lval->reg.size);1516}1517return true;1518}15191520bool1521GCRA::allocateRegisters(ArrayList& insns)1522{1523bool ret;15241525INFO_DBG(prog->dbgFlags, REG_ALLOC,1526"allocateRegisters to %u instructions\n", insns.getSize());15271528nodeCount = func->allLValues.getSize();1529nodes = new RIG_Node[nodeCount];1530if (!nodes)1531return false;1532for (unsigned int i = 0; i < nodeCount; ++i) {1533LValue *lval = reinterpret_cast<LValue *>(func->allLValues.get(i));1534if (lval) {1535nodes[i].init(regs, lval);1536RIG.insert(&nodes[i]);15371538if (lval->inFile(FILE_GPR) && lval->getInsn() != NULL) {1539Instruction *insn = lval->getInsn();1540if (insn->op != OP_MAD && insn->op != OP_FMA && insn->op != OP_SAD)1541continue;1542// For both of the cases below, we only want to add the preference1543// if all arguments are in registers.1544if (insn->src(0).getFile() != FILE_GPR ||1545insn->src(1).getFile() != FILE_GPR ||1546insn->src(2).getFile() != FILE_GPR)1547continue;1548if (prog->getTarget()->getChipset() < 0xc0) {1549// Outputting a flag is not supported with short encodings nor1550// with immediate arguments.1551// See handleMADforNV50.1552if (insn->flagsDef >= 0)1553continue;1554} else {1555// We can only fold immediate arguments if dst == src2. This1556// only matters if one of the first two arguments is an1557// immediate. This form is also only supported for floats.1558// See handleMADforNVC0.1559ImmediateValue imm;1560if (insn->dType != TYPE_F32)1561continue;1562if (!insn->src(0).getImmediate(imm) &&1563!insn->src(1).getImmediate(imm))1564continue;1565}15661567nodes[i].addRegPreference(getNode(insn->getSrc(2)->asLValue()));1568}1569}1570}15711572// coalesce first, we use only 1 RIG node for a group of joined values1573ret = coalesce(insns);1574if (!ret)1575goto out;15761577if (func->getProgram()->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)1578func->printLiveIntervals();15791580buildRIG(insns);1581calculateSpillWeights();1582ret = simplify();1583if (!ret)1584goto out;15851586ret = selectRegisters();1587if (!ret) {1588INFO_DBG(prog->dbgFlags, REG_ALLOC,1589"selectRegisters failed, inserting spill code ...\n");1590regs.reset(FILE_GPR, true);1591spill.run(mustSpill);1592if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)1593func->print();1594} else {1595mergedDefs.merge();1596prog->maxGPR = std::max(prog->maxGPR, regs.getMaxAssigned(FILE_GPR));1597}15981599out:1600cleanup(ret);1601return ret;1602}16031604void1605GCRA::cleanup(const bool success)1606{1607mustSpill.clear();16081609for (ArrayList::Iterator it = func->allLValues.iterator();1610!it.end(); it.next()) {1611LValue *lval = reinterpret_cast<LValue *>(it.get());16121613lval->livei.clear();16141615lval->compound = 0;1616lval->compMask = 0;16171618if (lval->join == lval)1619continue;16201621if (success)1622lval->reg.data.id = lval->join->reg.data.id;1623else1624lval->join = lval;1625}16261627if (success)1628resolveSplitsAndMerges();1629splits.clear(); // avoid duplicate entries on next coalesce pass1630merges.clear();16311632delete[] nodes;1633nodes = NULL;1634hi.next = hi.prev = &hi;1635lo[0].next = lo[0].prev = &lo[0];1636lo[1].next = lo[1].prev = &lo[1];1637}16381639Symbol *1640SpillCodeInserter::assignSlot(const Interval &livei, const unsigned int size)1641{1642SpillSlot slot;1643int32_t offsetBase = stackSize;1644int32_t offset;1645std::list<SpillSlot>::iterator pos = slots.end(), it = slots.begin();16461647if (offsetBase % size)1648offsetBase += size - (offsetBase % size);16491650slot.sym = NULL;16511652for (offset = offsetBase; offset < stackSize; offset += size) {1653const int32_t entryEnd = offset + size;1654while (it != slots.end() && it->offset < offset)1655++it;1656if (it == slots.end()) // no slots left1657break;1658std::list<SpillSlot>::iterator bgn = it;16591660while (it != slots.end() && it->offset < entryEnd) {1661it->occup.print();1662if (it->occup.overlaps(livei))1663break;1664++it;1665}1666if (it == slots.end() || it->offset >= entryEnd) {1667// fits1668for (; bgn != slots.end() && bgn->offset < entryEnd; ++bgn) {1669bgn->occup.insert(livei);1670if (bgn->size() == size)1671slot.sym = bgn->sym;1672}1673break;1674}1675}1676if (!slot.sym) {1677stackSize = offset + size;1678slot.offset = offset;1679slot.sym = new_Symbol(func->getProgram(), FILE_MEMORY_LOCAL);1680if (!func->stackPtr)1681offset += func->tlsBase;1682slot.sym->setAddress(NULL, offset);1683slot.sym->reg.size = size;1684slots.insert(pos, slot)->occup.insert(livei);1685}1686return slot.sym;1687}16881689Value *1690SpillCodeInserter::offsetSlot(Value *base, const LValue *lval)1691{1692if (!lval->compound || (lval->compMask & 0x1))1693return base;1694Value *slot = cloneShallow(func, base);16951696slot->reg.data.offset += (ffs(lval->compMask) - 1) * lval->reg.size;1697slot->reg.size = lval->reg.size;16981699return slot;1700}17011702void1703SpillCodeInserter::spill(Instruction *defi, Value *slot, LValue *lval)1704{1705const DataType ty = typeOfSize(lval->reg.size);17061707slot = offsetSlot(slot, lval);17081709Instruction *st;1710if (slot->reg.file == FILE_MEMORY_LOCAL) {1711lval->noSpill = 1;1712if (ty != TYPE_B96) {1713st = new_Instruction(func, OP_STORE, ty);1714st->setSrc(0, slot);1715st->setSrc(1, lval);1716} else {1717st = new_Instruction(func, OP_SPLIT, ty);1718st->setSrc(0, lval);1719for (int d = 0; d < lval->reg.size / 4; ++d)1720st->setDef(d, new_LValue(func, FILE_GPR));17211722for (int d = lval->reg.size / 4 - 1; d >= 0; --d) {1723Value *tmp = cloneShallow(func, slot);1724tmp->reg.size = 4;1725tmp->reg.data.offset += 4 * d;17261727Instruction *s = new_Instruction(func, OP_STORE, TYPE_U32);1728s->setSrc(0, tmp);1729s->setSrc(1, st->getDef(d));1730defi->bb->insertAfter(defi, s);1731}1732}1733} else {1734st = new_Instruction(func, OP_CVT, ty);1735st->setDef(0, slot);1736st->setSrc(0, lval);1737if (lval->reg.file == FILE_FLAGS)1738st->flagsSrc = 0;1739}1740defi->bb->insertAfter(defi, st);1741}17421743LValue *1744SpillCodeInserter::unspill(Instruction *usei, LValue *lval, Value *slot)1745{1746const DataType ty = typeOfSize(lval->reg.size);17471748slot = offsetSlot(slot, lval);1749lval = cloneShallow(func, lval);17501751Instruction *ld;1752if (slot->reg.file == FILE_MEMORY_LOCAL) {1753lval->noSpill = 1;1754if (ty != TYPE_B96) {1755ld = new_Instruction(func, OP_LOAD, ty);1756} else {1757ld = new_Instruction(func, OP_MERGE, ty);1758for (int d = 0; d < lval->reg.size / 4; ++d) {1759Value *tmp = cloneShallow(func, slot);1760LValue *val;1761tmp->reg.size = 4;1762tmp->reg.data.offset += 4 * d;17631764Instruction *l = new_Instruction(func, OP_LOAD, TYPE_U32);1765l->setDef(0, (val = new_LValue(func, FILE_GPR)));1766l->setSrc(0, tmp);1767usei->bb->insertBefore(usei, l);1768ld->setSrc(d, val);1769val->noSpill = 1;1770}1771ld->setDef(0, lval);1772usei->bb->insertBefore(usei, ld);1773return lval;1774}1775} else {1776ld = new_Instruction(func, OP_CVT, ty);1777}1778ld->setDef(0, lval);1779ld->setSrc(0, slot);1780if (lval->reg.file == FILE_FLAGS)1781ld->flagsDef = 0;17821783usei->bb->insertBefore(usei, ld);1784return lval;1785}17861787static bool1788value_cmp(ValueRef *a, ValueRef *b) {1789Instruction *ai = a->getInsn(), *bi = b->getInsn();1790if (ai->bb != bi->bb)1791return ai->bb->getId() < bi->bb->getId();1792return ai->serial < bi->serial;1793}17941795// For each value that is to be spilled, go through all its definitions.1796// A value can have multiple definitions if it has been coalesced before.1797// For each definition, first go through all its uses and insert an unspill1798// instruction before it, then replace the use with the temporary register.1799// Unspill can be either a load from memory or simply a move to another1800// register file.1801// For "Pseudo" instructions (like PHI, SPLIT, MERGE) we can erase the use1802// if we have spilled to a memory location, or simply with the new register.1803// No load or conversion instruction should be needed.1804bool1805SpillCodeInserter::run(const std::list<ValuePair>& lst)1806{1807for (std::list<ValuePair>::const_iterator it = lst.begin(); it != lst.end();1808++it) {1809LValue *lval = it->first->asLValue();1810Symbol *mem = it->second ? it->second->asSym() : NULL;18111812// Keep track of which instructions to delete later. Deleting them1813// inside the loop is unsafe since a single instruction may have1814// multiple destinations that all need to be spilled (like OP_SPLIT).1815unordered_set<Instruction *> to_del;18161817std::list<ValueDef *> &defs = mergedDefs(lval);1818for (Value::DefIterator d = defs.begin(); d != defs.end();1819++d) {1820Value *slot = mem ?1821static_cast<Value *>(mem) : new_LValue(func, FILE_GPR);1822Value *tmp = NULL;1823Instruction *last = NULL;18241825LValue *dval = (*d)->get()->asLValue();1826Instruction *defi = (*d)->getInsn();18271828// Sort all the uses by BB/instruction so that we don't unspill1829// multiple times in a row, and also remove a source of1830// non-determinism.1831std::vector<ValueRef *> refs(dval->uses.begin(), dval->uses.end());1832std::sort(refs.begin(), refs.end(), value_cmp);18331834// Unspill at each use *before* inserting spill instructions,1835// we don't want to have the spill instructions in the use list here.1836for (std::vector<ValueRef*>::const_iterator it = refs.begin();1837it != refs.end(); ++it) {1838ValueRef *u = *it;1839Instruction *usei = u->getInsn();1840assert(usei);1841if (usei->isPseudo()) {1842tmp = (slot->reg.file == FILE_MEMORY_LOCAL) ? NULL : slot;1843last = NULL;1844} else {1845if (!last || (usei != last->next && usei != last))1846tmp = unspill(usei, dval, slot);1847last = usei;1848}1849u->set(tmp);1850}18511852assert(defi);1853if (defi->isPseudo()) {1854d = defs.erase(d);1855--d;1856if (slot->reg.file == FILE_MEMORY_LOCAL)1857to_del.insert(defi);1858else1859defi->setDef(0, slot);1860} else {1861spill(defi, slot, dval);1862}1863}18641865for (unordered_set<Instruction *>::const_iterator it = to_del.begin();1866it != to_del.end(); ++it) {1867mergedDefs.removeDefsOfInstruction(*it);1868delete_Instruction(func->getProgram(), *it);1869}1870}18711872// TODO: We're not trying to reuse old slots in a potential next iteration.1873// We have to update the slots' livei intervals to be able to do that.1874stackBase = stackSize;1875slots.clear();1876return true;1877}18781879bool1880RegAlloc::exec()1881{1882for (IteratorRef it = prog->calls.iteratorDFS(false);1883!it->end(); it->next()) {1884func = Function::get(reinterpret_cast<Graph::Node *>(it->get()));18851886func->tlsBase = prog->tlsSize;1887if (!execFunc())1888return false;1889prog->tlsSize += func->tlsSize;1890}1891return true;1892}18931894bool1895RegAlloc::execFunc()1896{1897MergedDefs mergedDefs;1898InsertConstraintsPass insertConstr;1899PhiMovesPass insertPhiMoves;1900ArgumentMovesPass insertArgMoves;1901BuildIntervalsPass buildIntervals;1902SpillCodeInserter insertSpills(func, mergedDefs);19031904GCRA gcra(func, insertSpills, mergedDefs);19051906unsigned int i, retries;1907bool ret;19081909if (!func->ins.empty()) {1910// Insert a nop at the entry so inputs only used by the first instruction1911// don't count as having an empty live range.1912Instruction *nop = new_Instruction(func, OP_NOP, TYPE_NONE);1913BasicBlock::get(func->cfg.getRoot())->insertHead(nop);1914}19151916ret = insertConstr.exec(func);1917if (!ret)1918goto out;19191920ret = insertPhiMoves.run(func);1921if (!ret)1922goto out;19231924ret = insertArgMoves.run(func);1925if (!ret)1926goto out;19271928// TODO: need to fix up spill slot usage ranges to support > 1 retry1929for (retries = 0; retries < 3; ++retries) {1930if (retries && (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC))1931INFO("Retry: %i\n", retries);1932if (prog->dbgFlags & NV50_IR_DEBUG_REG_ALLOC)1933func->print();19341935// spilling to registers may add live ranges, need to rebuild everything1936ret = true;1937for (sequence = func->cfg.nextSequence(), i = 0;1938ret && i <= func->loopNestingBound;1939sequence = func->cfg.nextSequence(), ++i)1940ret = buildLiveSets(BasicBlock::get(func->cfg.getRoot()));1941// reset marker1942for (ArrayList::Iterator bi = func->allBBlocks.iterator();1943!bi.end(); bi.next())1944BasicBlock::get(bi)->liveSet.marker = false;1945if (!ret)1946break;1947func->orderInstructions(this->insns);19481949ret = buildIntervals.run(func);1950if (!ret)1951break;1952ret = gcra.allocateRegisters(insns);1953if (ret)1954break; // success1955}1956INFO_DBG(prog->dbgFlags, REG_ALLOC, "RegAlloc done: %i\n", ret);19571958func->tlsSize = insertSpills.getStackSize();1959out:1960return ret;1961}19621963// TODO: check if modifying Instruction::join here breaks anything1964void1965GCRA::resolveSplitsAndMerges()1966{1967for (std::list<Instruction *>::iterator it = splits.begin();1968it != splits.end();1969++it) {1970Instruction *split = *it;1971unsigned int reg = regs.idToBytes(split->getSrc(0));1972for (int d = 0; split->defExists(d); ++d) {1973Value *v = split->getDef(d);1974v->reg.data.id = regs.bytesToId(v, reg);1975v->join = v;1976reg += v->reg.size;1977}1978}1979splits.clear();19801981for (std::list<Instruction *>::iterator it = merges.begin();1982it != merges.end();1983++it) {1984Instruction *merge = *it;1985unsigned int reg = regs.idToBytes(merge->getDef(0));1986for (int s = 0; merge->srcExists(s); ++s) {1987Value *v = merge->getSrc(s);1988v->reg.data.id = regs.bytesToId(v, reg);1989v->join = v;1990// If the value is defined by a phi/union node, we also need to1991// perform the same fixup on that node's sources, since after RA1992// their registers should be identical.1993if (v->getInsn()->op == OP_PHI || v->getInsn()->op == OP_UNION) {1994Instruction *phi = v->getInsn();1995for (int phis = 0; phi->srcExists(phis); ++phis) {1996phi->getSrc(phis)->join = v;1997phi->getSrc(phis)->reg.data.id = v->reg.data.id;1998}1999}2000reg += v->reg.size;2001}2002}2003merges.clear();2004}20052006bool Program::registerAllocation()2007{2008RegAlloc ra(this);2009return ra.exec();2010}20112012bool2013RegAlloc::InsertConstraintsPass::exec(Function *ir)2014{2015constrList.clear();20162017bool ret = run(ir, true, true);2018if (ret)2019ret = insertConstraintMoves();2020return ret;2021}20222023// TODO: make part of texture insn2024void2025RegAlloc::InsertConstraintsPass::textureMask(TexInstruction *tex)2026{2027Value *def[4];2028int c, k, d;2029uint8_t mask = 0;20302031for (d = 0, k = 0, c = 0; c < 4; ++c) {2032if (!(tex->tex.mask & (1 << c)))2033continue;2034if (tex->getDef(k)->refCount()) {2035mask |= 1 << c;2036def[d++] = tex->getDef(k);2037}2038++k;2039}2040tex->tex.mask = mask;20412042for (c = 0; c < d; ++c)2043tex->setDef(c, def[c]);2044for (; c < 4; ++c)2045tex->setDef(c, NULL);2046}20472048bool2049RegAlloc::InsertConstraintsPass::detectConflict(Instruction *cst, int s)2050{2051Value *v = cst->getSrc(s);20522053// current register allocation can't handle it if a value participates in2054// multiple constraints2055for (Value::UseIterator it = v->uses.begin(); it != v->uses.end(); ++it) {2056if (cst != (*it)->getInsn())2057return true;2058}20592060// can start at s + 1 because detectConflict is called on all sources2061for (int c = s + 1; cst->srcExists(c); ++c)2062if (v == cst->getSrc(c))2063return true;20642065Instruction *defi = v->getInsn();20662067return (!defi || defi->constrainedDefs());2068}20692070void2071RegAlloc::InsertConstraintsPass::addConstraint(Instruction *i, int s, int n)2072{2073Instruction *cst;2074int d;20752076// first, look for an existing identical constraint op2077for (std::list<Instruction *>::iterator it = constrList.begin();2078it != constrList.end();2079++it) {2080cst = (*it);2081if (!i->bb->dominatedBy(cst->bb))2082break;2083for (d = 0; d < n; ++d)2084if (cst->getSrc(d) != i->getSrc(d + s))2085break;2086if (d >= n) {2087for (d = 0; d < n; ++d, ++s)2088i->setSrc(s, cst->getDef(d));2089return;2090}2091}2092cst = new_Instruction(func, OP_CONSTRAINT, i->dType);20932094for (d = 0; d < n; ++s, ++d) {2095cst->setDef(d, new_LValue(func, FILE_GPR));2096cst->setSrc(d, i->getSrc(s));2097i->setSrc(s, cst->getDef(d));2098}2099i->bb->insertBefore(i, cst);21002101constrList.push_back(cst);2102}21032104// Add a dummy use of the pointer source of >= 8 byte loads after the load2105// to prevent it from being assigned a register which overlapping the load's2106// destination, which would produce random corruptions.2107void2108RegAlloc::InsertConstraintsPass::addHazard(Instruction *i, const ValueRef *src)2109{2110Instruction *hzd = new_Instruction(func, OP_NOP, TYPE_NONE);2111hzd->setSrc(0, src->get());2112i->bb->insertAfter(i, hzd);21132114}21152116// b32 { %r0 %r1 %r2 %r3 } -> b128 %r0q2117void2118RegAlloc::InsertConstraintsPass::condenseDefs(Instruction *insn)2119{2120int n;2121for (n = 0; insn->defExists(n) && insn->def(n).getFile() == FILE_GPR; ++n);2122condenseDefs(insn, 0, n - 1);2123}21242125void2126RegAlloc::InsertConstraintsPass::condenseDefs(Instruction *insn,2127const int a, const int b)2128{2129uint8_t size = 0;2130if (a >= b)2131return;2132for (int s = a; s <= b; ++s)2133size += insn->getDef(s)->reg.size;2134if (!size)2135return;21362137LValue *lval = new_LValue(func, FILE_GPR);2138lval->reg.size = size;21392140Instruction *split = new_Instruction(func, OP_SPLIT, typeOfSize(size));2141split->setSrc(0, lval);2142for (int d = a; d <= b; ++d) {2143split->setDef(d - a, insn->getDef(d));2144insn->setDef(d, NULL);2145}2146insn->setDef(a, lval);21472148for (int k = a + 1, d = b + 1; insn->defExists(d); ++d, ++k) {2149insn->setDef(k, insn->getDef(d));2150insn->setDef(d, NULL);2151}2152// carry over predicate if any (mainly for OP_UNION uses)2153split->setPredicate(insn->cc, insn->getPredicate());21542155insn->bb->insertAfter(insn, split);2156constrList.push_back(split);2157}21582159void2160RegAlloc::InsertConstraintsPass::condenseSrcs(Instruction *insn,2161const int a, const int b)2162{2163uint8_t size = 0;2164if (a >= b)2165return;2166for (int s = a; s <= b; ++s)2167size += insn->getSrc(s)->reg.size;2168if (!size)2169return;2170LValue *lval = new_LValue(func, FILE_GPR);2171lval->reg.size = size;21722173Value *save[3];2174insn->takeExtraSources(0, save);21752176Instruction *merge = new_Instruction(func, OP_MERGE, typeOfSize(size));2177merge->setDef(0, lval);2178for (int s = a, i = 0; s <= b; ++s, ++i) {2179merge->setSrc(i, insn->getSrc(s));2180}2181insn->moveSources(b + 1, a - b);2182insn->setSrc(a, lval);2183insn->bb->insertBefore(insn, merge);21842185insn->putExtraSources(0, save);21862187constrList.push_back(merge);2188}21892190bool2191RegAlloc::InsertConstraintsPass::isScalarTexGM107(TexInstruction *tex)2192{2193if (tex->tex.sIndirectSrc >= 0 ||2194tex->tex.rIndirectSrc >= 0 ||2195tex->tex.derivAll)2196return false;21972198if (tex->tex.mask == 5 || tex->tex.mask == 6)2199return false;22002201switch (tex->op) {2202case OP_TEX:2203case OP_TXF:2204case OP_TXG:2205case OP_TXL:2206break;2207default:2208return false;2209}22102211// legal variants:2212// TEXS.1D.LZ2213// TEXS.2D2214// TEXS.2D.LZ2215// TEXS.2D.LL2216// TEXS.2D.DC2217// TEXS.2D.LL.DC2218// TEXS.2D.LZ.DC2219// TEXS.A2D2220// TEXS.A2D.LZ2221// TEXS.A2D.LZ.DC2222// TEXS.3D2223// TEXS.3D.LZ2224// TEXS.CUBE2225// TEXS.CUBE.LL22262227// TLDS.1D.LZ2228// TLDS.1D.LL2229// TLDS.2D.LZ2230// TLSD.2D.LZ.AOFFI2231// TLDS.2D.LZ.MZ2232// TLDS.2D.LL2233// TLDS.2D.LL.AOFFI2234// TLDS.A2D.LZ2235// TLDS.3D.LZ22362237// TLD4S: all 2D/RECT variants and only offset22382239switch (tex->op) {2240case OP_TEX:2241if (tex->tex.useOffsets)2242return false;22432244switch (tex->tex.target.getEnum()) {2245case TEX_TARGET_1D:2246case TEX_TARGET_2D_ARRAY_SHADOW:2247return tex->tex.levelZero;2248case TEX_TARGET_CUBE:2249return !tex->tex.levelZero;2250case TEX_TARGET_2D:2251case TEX_TARGET_2D_ARRAY:2252case TEX_TARGET_2D_SHADOW:2253case TEX_TARGET_3D:2254case TEX_TARGET_RECT:2255case TEX_TARGET_RECT_SHADOW:2256return true;2257default:2258return false;2259}22602261case OP_TXL:2262if (tex->tex.useOffsets)2263return false;22642265switch (tex->tex.target.getEnum()) {2266case TEX_TARGET_2D:2267case TEX_TARGET_2D_SHADOW:2268case TEX_TARGET_RECT:2269case TEX_TARGET_RECT_SHADOW:2270case TEX_TARGET_CUBE:2271return true;2272default:2273return false;2274}22752276case OP_TXF:2277switch (tex->tex.target.getEnum()) {2278case TEX_TARGET_1D:2279return !tex->tex.useOffsets;2280case TEX_TARGET_2D:2281case TEX_TARGET_RECT:2282return true;2283case TEX_TARGET_2D_ARRAY:2284case TEX_TARGET_2D_MS:2285case TEX_TARGET_3D:2286return !tex->tex.useOffsets && tex->tex.levelZero;2287default:2288return false;2289}22902291case OP_TXG:2292if (tex->tex.useOffsets > 1)2293return false;2294if (tex->tex.mask != 0x3 && tex->tex.mask != 0xf)2295return false;22962297switch (tex->tex.target.getEnum()) {2298case TEX_TARGET_2D:2299case TEX_TARGET_2D_MS:2300case TEX_TARGET_2D_SHADOW:2301case TEX_TARGET_RECT:2302case TEX_TARGET_RECT_SHADOW:2303return true;2304default:2305return false;2306}23072308default:2309return false;2310}2311}23122313void2314RegAlloc::InsertConstraintsPass::handleScalarTexGM107(TexInstruction *tex)2315{2316int defCount = tex->defCount(0xff);2317int srcCount = tex->srcCount(0xff);23182319tex->tex.scalar = true;23202321// 1. handle defs2322if (defCount > 3)2323condenseDefs(tex, 2, 3);2324if (defCount > 1)2325condenseDefs(tex, 0, 1);23262327// 2. handle srcs2328// special case for TXF.A2D2329if (tex->op == OP_TXF && tex->tex.target == TEX_TARGET_2D_ARRAY) {2330assert(srcCount >= 3);2331condenseSrcs(tex, 1, 2);2332} else {2333if (srcCount > 3)2334condenseSrcs(tex, 2, 3);2335// only if we have more than 2 sources2336if (srcCount > 2)2337condenseSrcs(tex, 0, 1);2338}23392340assert(!tex->defExists(2) && !tex->srcExists(2));2341}23422343void2344RegAlloc::InsertConstraintsPass::texConstraintGM107(TexInstruction *tex)2345{2346int n, s;23472348if (isTextureOp(tex->op))2349textureMask(tex);23502351if (targ->getChipset() < NVISA_GV100_CHIPSET) {2352if (isScalarTexGM107(tex)) {2353handleScalarTexGM107(tex);2354return;2355}23562357assert(!tex->tex.scalar);2358condenseDefs(tex);2359} else {2360if (isTextureOp(tex->op)) {2361int defCount = tex->defCount(0xff);2362if (defCount > 3)2363condenseDefs(tex, 2, 3);2364if (defCount > 1)2365condenseDefs(tex, 0, 1);2366} else {2367condenseDefs(tex);2368}2369}23702371if (isSurfaceOp(tex->op)) {2372int s = tex->tex.target.getDim() +2373(tex->tex.target.isArray() || tex->tex.target.isCube());2374int n = 0;23752376switch (tex->op) {2377case OP_SUSTB:2378case OP_SUSTP:2379n = 4;2380break;2381case OP_SUREDB:2382case OP_SUREDP:2383if (tex->subOp == NV50_IR_SUBOP_ATOM_CAS)2384n = 2;2385break;2386default:2387break;2388}23892390if (s > 1)2391condenseSrcs(tex, 0, s - 1);2392if (n > 1)2393condenseSrcs(tex, 1, n); // do not condense the tex handle2394} else2395if (isTextureOp(tex->op)) {2396if (tex->op != OP_TXQ) {2397s = tex->tex.target.getArgCount() - tex->tex.target.isMS();2398if (tex->op == OP_TXD) {2399// Indirect handle belongs in the first arg2400if (tex->tex.rIndirectSrc >= 0)2401s++;2402if (!tex->tex.target.isArray() && tex->tex.useOffsets)2403s++;2404}2405n = tex->srcCount(0xff, true) - s;2406// TODO: Is this necessary? Perhaps just has to be aligned to the2407// level that the first arg is, not necessarily to 4. This2408// requirement has not been rigorously verified, as it has been on2409// Kepler.2410if (n > 0 && n < 3) {2411if (tex->srcExists(n + s)) // move potential predicate out of the way2412tex->moveSources(n + s, 3 - n);2413while (n < 3)2414tex->setSrc(s + n++, new_LValue(func, FILE_GPR));2415}2416} else {2417s = tex->srcCount(0xff, true);2418n = 0;2419}24202421if (s > 1)2422condenseSrcs(tex, 0, s - 1);2423if (n > 1) // NOTE: first call modified positions already2424condenseSrcs(tex, 1, n);2425}2426}24272428void2429RegAlloc::InsertConstraintsPass::texConstraintNVE0(TexInstruction *tex)2430{2431if (isTextureOp(tex->op))2432textureMask(tex);2433condenseDefs(tex);24342435if (tex->op == OP_SUSTB || tex->op == OP_SUSTP) {2436condenseSrcs(tex, 3, 6);2437} else2438if (isTextureOp(tex->op)) {2439int n = tex->srcCount(0xff, true);2440int s = n > 4 ? 4 : n;2441if (n > 4 && n < 7) {2442if (tex->srcExists(n)) // move potential predicate out of the way2443tex->moveSources(n, 7 - n);24442445while (n < 7)2446tex->setSrc(n++, new_LValue(func, FILE_GPR));2447}2448if (s > 1)2449condenseSrcs(tex, 0, s - 1);2450if (n > 4)2451condenseSrcs(tex, 1, n - s);2452}2453}24542455void2456RegAlloc::InsertConstraintsPass::texConstraintNVC0(TexInstruction *tex)2457{2458int n, s;24592460if (isTextureOp(tex->op))2461textureMask(tex);24622463if (tex->op == OP_TXQ) {2464s = tex->srcCount(0xff);2465n = 0;2466} else if (isSurfaceOp(tex->op)) {2467s = tex->tex.target.getDim() + (tex->tex.target.isArray() || tex->tex.target.isCube());2468if (tex->op == OP_SUSTB || tex->op == OP_SUSTP)2469n = 4;2470else2471n = 0;2472} else {2473s = tex->tex.target.getArgCount() - tex->tex.target.isMS();2474if (!tex->tex.target.isArray() &&2475(tex->tex.rIndirectSrc >= 0 || tex->tex.sIndirectSrc >= 0))2476++s;2477if (tex->op == OP_TXD && tex->tex.useOffsets)2478++s;2479n = tex->srcCount(0xff) - s;2480assert(n <= 4);2481}24822483if (s > 1)2484condenseSrcs(tex, 0, s - 1);2485if (n > 1) // NOTE: first call modified positions already2486condenseSrcs(tex, 1, n);24872488condenseDefs(tex);2489}24902491void2492RegAlloc::InsertConstraintsPass::texConstraintNV50(TexInstruction *tex)2493{2494Value *pred = tex->getPredicate();2495if (pred)2496tex->setPredicate(tex->cc, NULL);24972498textureMask(tex);24992500assert(tex->defExists(0) && tex->srcExists(0));2501// make src and def count match2502int c;2503for (c = 0; tex->srcExists(c) || tex->defExists(c); ++c) {2504if (!tex->srcExists(c))2505tex->setSrc(c, new_LValue(func, tex->getSrc(0)->asLValue()));2506else2507insertConstraintMove(tex, c);2508if (!tex->defExists(c))2509tex->setDef(c, new_LValue(func, tex->getDef(0)->asLValue()));2510}2511if (pred)2512tex->setPredicate(tex->cc, pred);2513condenseDefs(tex);2514condenseSrcs(tex, 0, c - 1);2515}25162517// Insert constraint markers for instructions whose multiple sources must be2518// located in consecutive registers.2519bool2520RegAlloc::InsertConstraintsPass::visit(BasicBlock *bb)2521{2522TexInstruction *tex;2523Instruction *next;2524int s, size;25252526targ = bb->getProgram()->getTarget();25272528for (Instruction *i = bb->getEntry(); i; i = next) {2529next = i->next;25302531if ((tex = i->asTex())) {2532switch (targ->getChipset() & ~0xf) {2533case 0x50:2534case 0x80:2535case 0x90:2536case 0xa0:2537texConstraintNV50(tex);2538break;2539case 0xc0:2540case 0xd0:2541texConstraintNVC0(tex);2542break;2543case 0xe0:2544case 0xf0:2545case 0x100:2546texConstraintNVE0(tex);2547break;2548case 0x110:2549case 0x120:2550case 0x130:2551case 0x140:2552case 0x160:2553texConstraintGM107(tex);2554break;2555default:2556break;2557}2558} else2559if (i->op == OP_EXPORT || i->op == OP_STORE) {2560for (size = typeSizeof(i->dType), s = 1; size > 0; ++s) {2561assert(i->srcExists(s));2562size -= i->getSrc(s)->reg.size;2563}2564condenseSrcs(i, 1, s - 1);2565} else2566if (i->op == OP_LOAD || i->op == OP_VFETCH) {2567condenseDefs(i);2568if (i->src(0).isIndirect(0) && typeSizeof(i->dType) >= 8)2569addHazard(i, i->src(0).getIndirect(0));2570if (i->src(0).isIndirect(1) && typeSizeof(i->dType) >= 8)2571addHazard(i, i->src(0).getIndirect(1));2572if (i->op == OP_LOAD && i->fixed && targ->getChipset() < 0xc0) {2573// Add a hazard to make sure we keep the op around. These are used2574// for membars.2575Instruction *nop = new_Instruction(func, OP_NOP, i->dType);2576nop->setSrc(0, i->getDef(0));2577i->bb->insertAfter(i, nop);2578}2579} else2580if (i->op == OP_UNION ||2581i->op == OP_MERGE ||2582i->op == OP_SPLIT) {2583constrList.push_back(i);2584} else2585if (i->op == OP_ATOM && i->subOp == NV50_IR_SUBOP_ATOM_CAS &&2586targ->getChipset() < 0xc0) {2587// Like a hazard, but for a def.2588Instruction *nop = new_Instruction(func, OP_NOP, i->dType);2589nop->setSrc(0, i->getDef(0));2590i->bb->insertAfter(i, nop);2591}2592}2593return true;2594}25952596void2597RegAlloc::InsertConstraintsPass::insertConstraintMove(Instruction *cst, int s)2598{2599const uint8_t size = cst->src(s).getSize();26002601assert(cst->getSrc(s)->defs.size() == 1); // still SSA26022603Instruction *defi = cst->getSrc(s)->defs.front()->getInsn();26042605bool imm = defi->op == OP_MOV &&2606defi->src(0).getFile() == FILE_IMMEDIATE;2607bool load = defi->op == OP_LOAD &&2608defi->src(0).getFile() == FILE_MEMORY_CONST &&2609!defi->src(0).isIndirect(0);2610// catch some cases where don't really need MOVs2611if (cst->getSrc(s)->refCount() == 1 && !defi->constrainedDefs()) {2612if (imm || load) {2613// Move the defi right before the cst. No point in expanding2614// the range.2615defi->bb->remove(defi);2616cst->bb->insertBefore(cst, defi);2617}2618return;2619}26202621LValue *lval = new_LValue(func, cst->src(s).getFile());2622lval->reg.size = size;26232624Instruction *mov = new_Instruction(func, OP_MOV, typeOfSize(size));2625mov->setDef(0, lval);2626mov->setSrc(0, cst->getSrc(s));26272628if (load) {2629mov->op = OP_LOAD;2630mov->setSrc(0, defi->getSrc(0));2631} else if (imm) {2632mov->setSrc(0, defi->getSrc(0));2633}26342635if (defi->getPredicate())2636mov->setPredicate(defi->cc, defi->getPredicate());26372638cst->setSrc(s, mov->getDef(0));2639cst->bb->insertBefore(cst, mov);26402641cst->getDef(0)->asLValue()->noSpill = 1; // doesn't help2642}26432644// Insert extra moves so that, if multiple register constraints on a value are2645// in conflict, these conflicts can be resolved.2646bool2647RegAlloc::InsertConstraintsPass::insertConstraintMoves()2648{2649for (std::list<Instruction *>::iterator it = constrList.begin();2650it != constrList.end();2651++it) {2652Instruction *cst = *it;2653Instruction *mov;26542655if (cst->op == OP_SPLIT && 0) {2656// spilling splits is annoying, just make sure they're separate2657for (int d = 0; cst->defExists(d); ++d) {2658if (!cst->getDef(d)->refCount())2659continue;2660LValue *lval = new_LValue(func, cst->def(d).getFile());2661const uint8_t size = cst->def(d).getSize();2662lval->reg.size = size;26632664mov = new_Instruction(func, OP_MOV, typeOfSize(size));2665mov->setSrc(0, lval);2666mov->setDef(0, cst->getDef(d));2667cst->setDef(d, mov->getSrc(0));2668cst->bb->insertAfter(cst, mov);26692670cst->getSrc(0)->asLValue()->noSpill = 1;2671mov->getSrc(0)->asLValue()->noSpill = 1;2672}2673} else2674if (cst->op == OP_MERGE || cst->op == OP_UNION) {2675for (int s = 0; cst->srcExists(s); ++s) {2676const uint8_t size = cst->src(s).getSize();26772678if (!cst->getSrc(s)->defs.size()) {2679mov = new_Instruction(func, OP_NOP, typeOfSize(size));2680mov->setDef(0, cst->getSrc(s));2681cst->bb->insertBefore(cst, mov);2682continue;2683}26842685insertConstraintMove(cst, s);2686}2687}2688}26892690return true;2691}26922693} // namespace nv50_ir269426952696