RegAllocFast.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  1. //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This register allocator allocates registers to a basic block at a time,
  11. // attempting to keep values in registers and reusing registers as appropriate.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/Passes.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/IndexedMap.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/SparseSet.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/CodeGen/MachineFrameInfo.h"
  23. #include "llvm/CodeGen/MachineFunctionPass.h"
  24. #include "llvm/CodeGen/MachineInstr.h"
  25. #include "llvm/CodeGen/MachineInstrBuilder.h"
  26. #include "llvm/CodeGen/MachineRegisterInfo.h"
  27. #include "llvm/CodeGen/RegAllocRegistry.h"
  28. #include "llvm/CodeGen/RegisterClassInfo.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/Support/CommandLine.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/Target/TargetInstrInfo.h"
  35. #include "llvm/Target/TargetSubtargetInfo.h"
  36. #include <algorithm>
  37. using namespace llvm;
  38. #define DEBUG_TYPE "regalloc"
  39. STATISTIC(NumStores, "Number of stores added");
  40. STATISTIC(NumLoads , "Number of loads added");
  41. STATISTIC(NumCopies, "Number of copies coalesced");
  42. static RegisterRegAlloc
  43. fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
  44. namespace {
  45. class RAFast : public MachineFunctionPass {
  46. public:
  47. static char ID;
  48. RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
  49. isBulkSpilling(false) {}
  50. private:
  51. MachineFunction *MF;
  52. MachineRegisterInfo *MRI;
  53. const TargetRegisterInfo *TRI;
  54. const TargetInstrInfo *TII;
  55. RegisterClassInfo RegClassInfo;
  56. // Basic block currently being allocated.
  57. MachineBasicBlock *MBB;
  58. // StackSlotForVirtReg - Maps virtual regs to the frame index where these
  59. // values are spilled.
  60. IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
  61. // Everything we know about a live virtual register.
  62. struct LiveReg {
  63. MachineInstr *LastUse; // Last instr to use reg.
  64. unsigned VirtReg; // Virtual register number.
  65. unsigned PhysReg; // Currently held here.
  66. unsigned short LastOpNum; // OpNum on LastUse.
  67. bool Dirty; // Register needs spill.
  68. explicit LiveReg(unsigned v)
  69. : LastUse(nullptr), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false){}
  70. unsigned getSparseSetIndex() const {
  71. return TargetRegisterInfo::virtReg2Index(VirtReg);
  72. }
  73. };
  74. typedef SparseSet<LiveReg> LiveRegMap;
  75. // LiveVirtRegs - This map contains entries for each virtual register
  76. // that is currently available in a physical register.
  77. LiveRegMap LiveVirtRegs;
  78. DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
  79. // RegState - Track the state of a physical register.
  80. enum RegState {
  81. // A disabled register is not available for allocation, but an alias may
  82. // be in use. A register can only be moved out of the disabled state if
  83. // all aliases are disabled.
  84. regDisabled,
  85. // A free register is not currently in use and can be allocated
  86. // immediately without checking aliases.
  87. regFree,
  88. // A reserved register has been assigned explicitly (e.g., setting up a
  89. // call parameter), and it remains reserved until it is used.
  90. regReserved
  91. // A register state may also be a virtual register number, indication that
  92. // the physical register is currently allocated to a virtual register. In
  93. // that case, LiveVirtRegs contains the inverse mapping.
  94. };
  95. // PhysRegState - One of the RegState enums, or a virtreg.
  96. std::vector<unsigned> PhysRegState;
  97. // Set of register units.
  98. typedef SparseSet<unsigned> UsedInInstrSet;
  99. // Set of register units that are used in the current instruction, and so
  100. // cannot be allocated.
  101. UsedInInstrSet UsedInInstr;
  102. // Mark a physreg as used in this instruction.
  103. void markRegUsedInInstr(unsigned PhysReg) {
  104. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  105. UsedInInstr.insert(*Units);
  106. }
  107. // Check if a physreg or any of its aliases are used in this instruction.
  108. bool isRegUsedInInstr(unsigned PhysReg) const {
  109. for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
  110. if (UsedInInstr.count(*Units))
  111. return true;
  112. return false;
  113. }
  114. // SkippedInstrs - Descriptors of instructions whose clobber list was
  115. // ignored because all registers were spilled. It is still necessary to
  116. // mark all the clobbered registers as used by the function.
  117. SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
  118. // isBulkSpilling - This flag is set when LiveRegMap will be cleared
  119. // completely after spilling all live registers. LiveRegMap entries should
  120. // not be erased.
  121. bool isBulkSpilling;
  122. enum : unsigned {
  123. spillClean = 1,
  124. spillDirty = 100,
  125. spillImpossible = ~0u
  126. };
  127. public:
  128. const char *getPassName() const override {
  129. return "Fast Register Allocator";
  130. }
  131. void getAnalysisUsage(AnalysisUsage &AU) const override {
  132. AU.setPreservesCFG();
  133. MachineFunctionPass::getAnalysisUsage(AU);
  134. }
  135. private:
  136. bool runOnMachineFunction(MachineFunction &Fn) override;
  137. void AllocateBasicBlock();
  138. void handleThroughOperands(MachineInstr *MI,
  139. SmallVectorImpl<unsigned> &VirtDead);
  140. int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
  141. bool isLastUseOfLocalReg(MachineOperand&);
  142. void addKillFlag(const LiveReg&);
  143. void killVirtReg(LiveRegMap::iterator);
  144. void killVirtReg(unsigned VirtReg);
  145. void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
  146. void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
  147. void usePhysReg(MachineOperand&);
  148. void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
  149. unsigned calcSpillCost(unsigned PhysReg) const;
  150. void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
  151. LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
  152. return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
  153. }
  154. LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
  155. return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
  156. }
  157. LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
  158. LiveRegMap::iterator allocVirtReg(MachineInstr *MI, LiveRegMap::iterator,
  159. unsigned Hint);
  160. LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
  161. unsigned VirtReg, unsigned Hint);
  162. LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
  163. unsigned VirtReg, unsigned Hint);
  164. void spillAll(MachineBasicBlock::iterator MI);
  165. bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
  166. };
  167. char RAFast::ID = 0;
  168. }
  169. /// getStackSpaceFor - This allocates space for the specified virtual register
  170. /// to be held on the stack.
  171. int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
  172. // Find the location Reg would belong...
  173. int SS = StackSlotForVirtReg[VirtReg];
  174. if (SS != -1)
  175. return SS; // Already has space allocated?
  176. // Allocate a new stack object for this spill location...
  177. int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
  178. RC->getAlignment());
  179. // Assign the slot.
  180. StackSlotForVirtReg[VirtReg] = FrameIdx;
  181. return FrameIdx;
  182. }
  183. /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
  184. /// its virtual register, and it is guaranteed to be a block-local register.
  185. ///
  186. bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
  187. // If the register has ever been spilled or reloaded, we conservatively assume
  188. // it is a global register used in multiple blocks.
  189. if (StackSlotForVirtReg[MO.getReg()] != -1)
  190. return false;
  191. // Check that the use/def chain has exactly one operand - MO.
  192. MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
  193. if (&*I != &MO)
  194. return false;
  195. return ++I == MRI->reg_nodbg_end();
  196. }
  197. /// addKillFlag - Set kill flags on last use of a virtual register.
  198. void RAFast::addKillFlag(const LiveReg &LR) {
  199. if (!LR.LastUse) return;
  200. MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
  201. if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
  202. if (MO.getReg() == LR.PhysReg)
  203. MO.setIsKill();
  204. else
  205. LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
  206. }
  207. }
  208. /// killVirtReg - Mark virtreg as no longer available.
  209. void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
  210. addKillFlag(*LRI);
  211. assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
  212. "Broken RegState mapping");
  213. PhysRegState[LRI->PhysReg] = regFree;
  214. // Erase from LiveVirtRegs unless we're spilling in bulk.
  215. if (!isBulkSpilling)
  216. LiveVirtRegs.erase(LRI);
  217. }
  218. /// killVirtReg - Mark virtreg as no longer available.
  219. void RAFast::killVirtReg(unsigned VirtReg) {
  220. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  221. "killVirtReg needs a virtual register");
  222. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  223. if (LRI != LiveVirtRegs.end())
  224. killVirtReg(LRI);
  225. }
  226. /// spillVirtReg - This method spills the value specified by VirtReg into the
  227. /// corresponding stack slot if needed.
  228. void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
  229. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  230. "Spilling a physical register is illegal!");
  231. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  232. assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
  233. spillVirtReg(MI, LRI);
  234. }
  235. /// spillVirtReg - Do the actual work of spilling.
  236. void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
  237. LiveRegMap::iterator LRI) {
  238. LiveReg &LR = *LRI;
  239. assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
  240. if (LR.Dirty) {
  241. // If this physreg is used by the instruction, we want to kill it on the
  242. // instruction, not on the spill.
  243. bool SpillKill = LR.LastUse != MI;
  244. LR.Dirty = false;
  245. DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
  246. << " in " << PrintReg(LR.PhysReg, TRI));
  247. const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
  248. int FI = getStackSpaceFor(LRI->VirtReg, RC);
  249. DEBUG(dbgs() << " to stack slot #" << FI << "\n");
  250. TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
  251. ++NumStores; // Update statistics
  252. // If this register is used by DBG_VALUE then insert new DBG_VALUE to
  253. // identify spilled location as the place to find corresponding variable's
  254. // value.
  255. SmallVectorImpl<MachineInstr *> &LRIDbgValues =
  256. LiveDbgValueMap[LRI->VirtReg];
  257. for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
  258. MachineInstr *DBG = LRIDbgValues[li];
  259. const MDNode *Var = DBG->getDebugVariable();
  260. const MDNode *Expr = DBG->getDebugExpression();
  261. bool IsIndirect = DBG->isIndirectDebugValue();
  262. uint64_t Offset = IsIndirect ? DBG->getOperand(1).getImm() : 0;
  263. DebugLoc DL = DBG->getDebugLoc();
  264. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  265. "Expected inlined-at fields to agree");
  266. MachineInstr *NewDV =
  267. BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::DBG_VALUE))
  268. .addFrameIndex(FI)
  269. .addImm(Offset)
  270. .addMetadata(Var)
  271. .addMetadata(Expr);
  272. assert(NewDV->getParent() == MBB && "dangling parent pointer");
  273. (void)NewDV;
  274. DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
  275. }
  276. // Now this register is spilled there is should not be any DBG_VALUE
  277. // pointing to this register because they are all pointing to spilled value
  278. // now.
  279. LRIDbgValues.clear();
  280. if (SpillKill)
  281. LR.LastUse = nullptr; // Don't kill register again
  282. }
  283. killVirtReg(LRI);
  284. }
  285. /// spillAll - Spill all dirty virtregs without killing them.
  286. void RAFast::spillAll(MachineBasicBlock::iterator MI) {
  287. if (LiveVirtRegs.empty()) return;
  288. isBulkSpilling = true;
  289. // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
  290. // of spilling here is deterministic, if arbitrary.
  291. for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
  292. i != e; ++i)
  293. spillVirtReg(MI, i);
  294. LiveVirtRegs.clear();
  295. isBulkSpilling = false;
  296. }
  297. /// usePhysReg - Handle the direct use of a physical register.
  298. /// Check that the register is not used by a virtreg.
  299. /// Kill the physreg, marking it free.
  300. /// This may add implicit kills to MO->getParent() and invalidate MO.
  301. void RAFast::usePhysReg(MachineOperand &MO) {
  302. unsigned PhysReg = MO.getReg();
  303. assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
  304. "Bad usePhysReg operand");
  305. markRegUsedInInstr(PhysReg);
  306. switch (PhysRegState[PhysReg]) {
  307. case regDisabled:
  308. break;
  309. case regReserved:
  310. PhysRegState[PhysReg] = regFree;
  311. // Fall through
  312. case regFree:
  313. MO.setIsKill();
  314. return;
  315. default:
  316. // The physreg was allocated to a virtual register. That means the value we
  317. // wanted has been clobbered.
  318. llvm_unreachable("Instruction uses an allocated register");
  319. }
  320. // Maybe a superregister is reserved?
  321. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  322. unsigned Alias = *AI;
  323. switch (PhysRegState[Alias]) {
  324. case regDisabled:
  325. break;
  326. case regReserved:
  327. // Either PhysReg is a subregister of Alias and we mark the
  328. // whole register as free, or PhysReg is the superregister of
  329. // Alias and we mark all the aliases as disabled before freeing
  330. // PhysReg.
  331. // In the latter case, since PhysReg was disabled, this means that
  332. // its value is defined only by physical sub-registers. This check
  333. // is performed by the assert of the default case in this loop.
  334. // Note: The value of the superregister may only be partial
  335. // defined, that is why regDisabled is a valid state for aliases.
  336. assert((TRI->isSuperRegister(PhysReg, Alias) ||
  337. TRI->isSuperRegister(Alias, PhysReg)) &&
  338. "Instruction is not using a subregister of a reserved register");
  339. // Fall through.
  340. case regFree:
  341. if (TRI->isSuperRegister(PhysReg, Alias)) {
  342. // Leave the superregister in the working set.
  343. PhysRegState[Alias] = regFree;
  344. MO.getParent()->addRegisterKilled(Alias, TRI, true);
  345. return;
  346. }
  347. // Some other alias was in the working set - clear it.
  348. PhysRegState[Alias] = regDisabled;
  349. break;
  350. default:
  351. llvm_unreachable("Instruction uses an alias of an allocated register");
  352. }
  353. }
  354. // All aliases are disabled, bring register into working set.
  355. PhysRegState[PhysReg] = regFree;
  356. MO.setIsKill();
  357. }
  358. /// definePhysReg - Mark PhysReg as reserved or free after spilling any
  359. /// virtregs. This is very similar to defineVirtReg except the physreg is
  360. /// reserved instead of allocated.
  361. void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
  362. RegState NewState) {
  363. markRegUsedInInstr(PhysReg);
  364. switch (unsigned VirtReg = PhysRegState[PhysReg]) {
  365. case regDisabled:
  366. break;
  367. default:
  368. spillVirtReg(MI, VirtReg);
  369. // Fall through.
  370. case regFree:
  371. case regReserved:
  372. PhysRegState[PhysReg] = NewState;
  373. return;
  374. }
  375. // This is a disabled register, disable all aliases.
  376. PhysRegState[PhysReg] = NewState;
  377. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  378. unsigned Alias = *AI;
  379. switch (unsigned VirtReg = PhysRegState[Alias]) {
  380. case regDisabled:
  381. break;
  382. default:
  383. spillVirtReg(MI, VirtReg);
  384. // Fall through.
  385. case regFree:
  386. case regReserved:
  387. PhysRegState[Alias] = regDisabled;
  388. if (TRI->isSuperRegister(PhysReg, Alias))
  389. return;
  390. break;
  391. }
  392. }
  393. }
  394. // calcSpillCost - Return the cost of spilling clearing out PhysReg and
  395. // aliases so it is free for allocation.
  396. // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
  397. // can be allocated directly.
  398. // Returns spillImpossible when PhysReg or an alias can't be spilled.
  399. unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
  400. if (isRegUsedInInstr(PhysReg)) {
  401. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
  402. return spillImpossible;
  403. }
  404. switch (unsigned VirtReg = PhysRegState[PhysReg]) {
  405. case regDisabled:
  406. break;
  407. case regFree:
  408. return 0;
  409. case regReserved:
  410. DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
  411. << PrintReg(PhysReg, TRI) << " is reserved already.\n");
  412. return spillImpossible;
  413. default: {
  414. LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
  415. assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
  416. return I->Dirty ? spillDirty : spillClean;
  417. }
  418. }
  419. // This is a disabled register, add up cost of aliases.
  420. DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
  421. unsigned Cost = 0;
  422. for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
  423. unsigned Alias = *AI;
  424. switch (unsigned VirtReg = PhysRegState[Alias]) {
  425. case regDisabled:
  426. break;
  427. case regFree:
  428. ++Cost;
  429. break;
  430. case regReserved:
  431. return spillImpossible;
  432. default: {
  433. LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
  434. assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
  435. Cost += I->Dirty ? spillDirty : spillClean;
  436. break;
  437. }
  438. }
  439. }
  440. return Cost;
  441. }
  442. /// assignVirtToPhysReg - This method updates local state so that we know
  443. /// that PhysReg is the proper container for VirtReg now. The physical
  444. /// register must not be used for anything else when this is called.
  445. ///
  446. void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
  447. DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
  448. << PrintReg(PhysReg, TRI) << "\n");
  449. PhysRegState[PhysReg] = LR.VirtReg;
  450. assert(!LR.PhysReg && "Already assigned a physreg");
  451. LR.PhysReg = PhysReg;
  452. }
  453. RAFast::LiveRegMap::iterator
  454. RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
  455. LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
  456. assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
  457. assignVirtToPhysReg(*LRI, PhysReg);
  458. return LRI;
  459. }
  460. /// allocVirtReg - Allocate a physical register for VirtReg.
  461. RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
  462. LiveRegMap::iterator LRI,
  463. unsigned Hint) {
  464. const unsigned VirtReg = LRI->VirtReg;
  465. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  466. "Can only allocate virtual registers");
  467. const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
  468. // Ignore invalid hints.
  469. if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
  470. !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
  471. Hint = 0;
  472. // Take hint when possible.
  473. if (Hint) {
  474. // Ignore the hint if we would have to spill a dirty register.
  475. unsigned Cost = calcSpillCost(Hint);
  476. if (Cost < spillDirty) {
  477. if (Cost)
  478. definePhysReg(MI, Hint, regFree);
  479. // definePhysReg may kill virtual registers and modify LiveVirtRegs.
  480. // That invalidates LRI, so run a new lookup for VirtReg.
  481. return assignVirtToPhysReg(VirtReg, Hint);
  482. }
  483. }
  484. ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
  485. // First try to find a completely free register.
  486. for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
  487. unsigned PhysReg = *I;
  488. if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
  489. assignVirtToPhysReg(*LRI, PhysReg);
  490. return LRI;
  491. }
  492. }
  493. DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
  494. << TRI->getRegClassName(RC) << "\n");
  495. unsigned BestReg = 0, BestCost = spillImpossible;
  496. for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
  497. unsigned Cost = calcSpillCost(*I);
  498. DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
  499. DEBUG(dbgs() << "\tCost: " << Cost << "\n");
  500. DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
  501. // Cost is 0 when all aliases are already disabled.
  502. if (Cost == 0) {
  503. assignVirtToPhysReg(*LRI, *I);
  504. return LRI;
  505. }
  506. if (Cost < BestCost)
  507. BestReg = *I, BestCost = Cost;
  508. }
  509. if (BestReg) {
  510. definePhysReg(MI, BestReg, regFree);
  511. // definePhysReg may kill virtual registers and modify LiveVirtRegs.
  512. // That invalidates LRI, so run a new lookup for VirtReg.
  513. return assignVirtToPhysReg(VirtReg, BestReg);
  514. }
  515. // Nothing we can do. Report an error and keep going with a bad allocation.
  516. if (MI->isInlineAsm())
  517. MI->emitError("inline assembly requires more registers than available");
  518. else
  519. MI->emitError("ran out of registers during register allocation");
  520. definePhysReg(MI, *AO.begin(), regFree);
  521. return assignVirtToPhysReg(VirtReg, *AO.begin());
  522. }
  523. /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
  524. RAFast::LiveRegMap::iterator
  525. RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
  526. unsigned VirtReg, unsigned Hint) {
  527. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  528. "Not a virtual register");
  529. LiveRegMap::iterator LRI;
  530. bool New;
  531. std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
  532. if (New) {
  533. // If there is no hint, peek at the only use of this register.
  534. if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
  535. MRI->hasOneNonDBGUse(VirtReg)) {
  536. const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
  537. // It's a copy, use the destination register as a hint.
  538. if (UseMI.isCopyLike())
  539. Hint = UseMI.getOperand(0).getReg();
  540. }
  541. LRI = allocVirtReg(MI, LRI, Hint);
  542. } else if (LRI->LastUse) {
  543. // Redefining a live register - kill at the last use, unless it is this
  544. // instruction defining VirtReg multiple times.
  545. if (LRI->LastUse != MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
  546. addKillFlag(*LRI);
  547. }
  548. assert(LRI->PhysReg && "Register not assigned");
  549. LRI->LastUse = MI;
  550. LRI->LastOpNum = OpNum;
  551. LRI->Dirty = true;
  552. markRegUsedInInstr(LRI->PhysReg);
  553. return LRI;
  554. }
  555. /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
  556. RAFast::LiveRegMap::iterator
  557. RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
  558. unsigned VirtReg, unsigned Hint) {
  559. assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
  560. "Not a virtual register");
  561. LiveRegMap::iterator LRI;
  562. bool New;
  563. std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
  564. MachineOperand &MO = MI->getOperand(OpNum);
  565. if (New) {
  566. LRI = allocVirtReg(MI, LRI, Hint);
  567. const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
  568. int FrameIndex = getStackSpaceFor(VirtReg, RC);
  569. DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
  570. << PrintReg(LRI->PhysReg, TRI) << "\n");
  571. TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
  572. ++NumLoads;
  573. } else if (LRI->Dirty) {
  574. if (isLastUseOfLocalReg(MO)) {
  575. DEBUG(dbgs() << "Killing last use: " << MO << "\n");
  576. if (MO.isUse())
  577. MO.setIsKill();
  578. else
  579. MO.setIsDead();
  580. } else if (MO.isKill()) {
  581. DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
  582. MO.setIsKill(false);
  583. } else if (MO.isDead()) {
  584. DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
  585. MO.setIsDead(false);
  586. }
  587. } else if (MO.isKill()) {
  588. // We must remove kill flags from uses of reloaded registers because the
  589. // register would be killed immediately, and there might be a second use:
  590. // %foo = OR %x<kill>, %x
  591. // This would cause a second reload of %x into a different register.
  592. DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
  593. MO.setIsKill(false);
  594. } else if (MO.isDead()) {
  595. DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
  596. MO.setIsDead(false);
  597. }
  598. assert(LRI->PhysReg && "Register not assigned");
  599. LRI->LastUse = MI;
  600. LRI->LastOpNum = OpNum;
  601. markRegUsedInInstr(LRI->PhysReg);
  602. return LRI;
  603. }
  604. // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
  605. // subregs. This may invalidate any operand pointers.
  606. // Return true if the operand kills its register.
  607. bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
  608. MachineOperand &MO = MI->getOperand(OpNum);
  609. bool Dead = MO.isDead();
  610. if (!MO.getSubReg()) {
  611. MO.setReg(PhysReg);
  612. return MO.isKill() || Dead;
  613. }
  614. // Handle subregister index.
  615. MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
  616. MO.setSubReg(0);
  617. // A kill flag implies killing the full register. Add corresponding super
  618. // register kill.
  619. if (MO.isKill()) {
  620. MI->addRegisterKilled(PhysReg, TRI, true);
  621. return true;
  622. }
  623. // A <def,read-undef> of a sub-register requires an implicit def of the full
  624. // register.
  625. if (MO.isDef() && MO.isUndef())
  626. MI->addRegisterDefined(PhysReg, TRI);
  627. return Dead;
  628. }
  629. // Handle special instruction operand like early clobbers and tied ops when
  630. // there are additional physreg defines.
  631. void RAFast::handleThroughOperands(MachineInstr *MI,
  632. SmallVectorImpl<unsigned> &VirtDead) {
  633. DEBUG(dbgs() << "Scanning for through registers:");
  634. SmallSet<unsigned, 8> ThroughRegs;
  635. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  636. MachineOperand &MO = MI->getOperand(i);
  637. if (!MO.isReg()) continue;
  638. unsigned Reg = MO.getReg();
  639. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  640. continue;
  641. if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
  642. (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
  643. if (ThroughRegs.insert(Reg).second)
  644. DEBUG(dbgs() << ' ' << PrintReg(Reg));
  645. }
  646. }
  647. // If any physreg defines collide with preallocated through registers,
  648. // we must spill and reallocate.
  649. DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
  650. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  651. MachineOperand &MO = MI->getOperand(i);
  652. if (!MO.isReg() || !MO.isDef()) continue;
  653. unsigned Reg = MO.getReg();
  654. if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  655. markRegUsedInInstr(Reg);
  656. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
  657. if (ThroughRegs.count(PhysRegState[*AI]))
  658. definePhysReg(MI, *AI, regFree);
  659. }
  660. }
  661. SmallVector<unsigned, 8> PartialDefs;
  662. DEBUG(dbgs() << "Allocating tied uses.\n");
  663. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  664. MachineOperand &MO = MI->getOperand(i);
  665. if (!MO.isReg()) continue;
  666. unsigned Reg = MO.getReg();
  667. if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
  668. if (MO.isUse()) {
  669. unsigned DefIdx = 0;
  670. if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
  671. DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
  672. << DefIdx << ".\n");
  673. LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
  674. unsigned PhysReg = LRI->PhysReg;
  675. setPhysReg(MI, i, PhysReg);
  676. // Note: we don't update the def operand yet. That would cause the normal
  677. // def-scan to attempt spilling.
  678. } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
  679. DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
  680. // Reload the register, but don't assign to the operand just yet.
  681. // That would confuse the later phys-def processing pass.
  682. LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
  683. PartialDefs.push_back(LRI->PhysReg);
  684. }
  685. }
  686. DEBUG(dbgs() << "Allocating early clobbers.\n");
  687. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  688. MachineOperand &MO = MI->getOperand(i);
  689. if (!MO.isReg()) continue;
  690. unsigned Reg = MO.getReg();
  691. if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
  692. if (!MO.isEarlyClobber())
  693. continue;
  694. // Note: defineVirtReg may invalidate MO.
  695. LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
  696. unsigned PhysReg = LRI->PhysReg;
  697. if (setPhysReg(MI, i, PhysReg))
  698. VirtDead.push_back(Reg);
  699. }
  700. // Restore UsedInInstr to a state usable for allocating normal virtual uses.
  701. UsedInInstr.clear();
  702. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  703. MachineOperand &MO = MI->getOperand(i);
  704. if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
  705. unsigned Reg = MO.getReg();
  706. if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  707. DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
  708. << " as used in instr\n");
  709. markRegUsedInInstr(Reg);
  710. }
  711. // Also mark PartialDefs as used to avoid reallocation.
  712. for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
  713. markRegUsedInInstr(PartialDefs[i]);
  714. }
  715. void RAFast::AllocateBasicBlock() {
  716. DEBUG(dbgs() << "\nAllocating " << *MBB);
  717. PhysRegState.assign(TRI->getNumRegs(), regDisabled);
  718. assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
  719. MachineBasicBlock::iterator MII = MBB->begin();
  720. // Add live-in registers as live.
  721. for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
  722. E = MBB->livein_end(); I != E; ++I)
  723. if (MRI->isAllocatable(*I))
  724. definePhysReg(MII, *I, regReserved);
  725. SmallVector<unsigned, 8> VirtDead;
  726. SmallVector<MachineInstr*, 32> Coalesced;
  727. // Otherwise, sequentially allocate each instruction in the MBB.
  728. while (MII != MBB->end()) {
  729. MachineInstr *MI = MII++;
  730. const MCInstrDesc &MCID = MI->getDesc();
  731. DEBUG({
  732. dbgs() << "\n>> " << *MI << "Regs:";
  733. for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
  734. if (PhysRegState[Reg] == regDisabled) continue;
  735. dbgs() << " " << TRI->getName(Reg);
  736. switch(PhysRegState[Reg]) {
  737. case regFree:
  738. break;
  739. case regReserved:
  740. dbgs() << "*";
  741. break;
  742. default: {
  743. dbgs() << '=' << PrintReg(PhysRegState[Reg]);
  744. LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
  745. assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
  746. if (I->Dirty)
  747. dbgs() << "*";
  748. assert(I->PhysReg == Reg && "Bad inverse map");
  749. break;
  750. }
  751. }
  752. }
  753. dbgs() << '\n';
  754. // Check that LiveVirtRegs is the inverse.
  755. for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
  756. e = LiveVirtRegs.end(); i != e; ++i) {
  757. assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
  758. "Bad map key");
  759. assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
  760. "Bad map value");
  761. assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
  762. }
  763. });
  764. // Debug values are not allowed to change codegen in any way.
  765. if (MI->isDebugValue()) {
  766. bool ScanDbgValue = true;
  767. while (ScanDbgValue) {
  768. ScanDbgValue = false;
  769. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  770. MachineOperand &MO = MI->getOperand(i);
  771. if (!MO.isReg()) continue;
  772. unsigned Reg = MO.getReg();
  773. if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
  774. LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
  775. if (LRI != LiveVirtRegs.end())
  776. setPhysReg(MI, i, LRI->PhysReg);
  777. else {
  778. int SS = StackSlotForVirtReg[Reg];
  779. if (SS == -1) {
  780. // We can't allocate a physreg for a DebugValue, sorry!
  781. DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
  782. MO.setReg(0);
  783. }
  784. else {
  785. // Modify DBG_VALUE now that the value is in a spill slot.
  786. bool IsIndirect = MI->isIndirectDebugValue();
  787. uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
  788. const MDNode *Var = MI->getDebugVariable();
  789. const MDNode *Expr = MI->getDebugExpression();
  790. DebugLoc DL = MI->getDebugLoc();
  791. MachineBasicBlock *MBB = MI->getParent();
  792. assert(
  793. cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  794. "Expected inlined-at fields to agree");
  795. MachineInstr *NewDV = BuildMI(*MBB, MBB->erase(MI), DL,
  796. TII->get(TargetOpcode::DBG_VALUE))
  797. .addFrameIndex(SS)
  798. .addImm(Offset)
  799. .addMetadata(Var)
  800. .addMetadata(Expr);
  801. DEBUG(dbgs() << "Modifying debug info due to spill:"
  802. << "\t" << *NewDV);
  803. // Scan NewDV operands from the beginning.
  804. MI = NewDV;
  805. ScanDbgValue = true;
  806. break;
  807. }
  808. }
  809. LiveDbgValueMap[Reg].push_back(MI);
  810. }
  811. }
  812. // Next instruction.
  813. continue;
  814. }
  815. // If this is a copy, we may be able to coalesce.
  816. unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
  817. if (MI->isCopy()) {
  818. CopyDst = MI->getOperand(0).getReg();
  819. CopySrc = MI->getOperand(1).getReg();
  820. CopyDstSub = MI->getOperand(0).getSubReg();
  821. CopySrcSub = MI->getOperand(1).getSubReg();
  822. }
  823. // Track registers used by instruction.
  824. UsedInInstr.clear();
  825. // First scan.
  826. // Mark physreg uses and early clobbers as used.
  827. // Find the end of the virtreg operands
  828. unsigned VirtOpEnd = 0;
  829. bool hasTiedOps = false;
  830. bool hasEarlyClobbers = false;
  831. bool hasPartialRedefs = false;
  832. bool hasPhysDefs = false;
  833. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  834. MachineOperand &MO = MI->getOperand(i);
  835. // Make sure MRI knows about registers clobbered by regmasks.
  836. if (MO.isRegMask()) {
  837. MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
  838. continue;
  839. }
  840. if (!MO.isReg()) continue;
  841. unsigned Reg = MO.getReg();
  842. if (!Reg) continue;
  843. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  844. VirtOpEnd = i+1;
  845. if (MO.isUse()) {
  846. hasTiedOps = hasTiedOps ||
  847. MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
  848. } else {
  849. if (MO.isEarlyClobber())
  850. hasEarlyClobbers = true;
  851. if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
  852. hasPartialRedefs = true;
  853. }
  854. continue;
  855. }
  856. if (!MRI->isAllocatable(Reg)) continue;
  857. if (MO.isUse()) {
  858. usePhysReg(MO);
  859. } else if (MO.isEarlyClobber()) {
  860. definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
  861. regFree : regReserved);
  862. hasEarlyClobbers = true;
  863. } else
  864. hasPhysDefs = true;
  865. }
  866. // The instruction may have virtual register operands that must be allocated
  867. // the same register at use-time and def-time: early clobbers and tied
  868. // operands. If there are also physical defs, these registers must avoid
  869. // both physical defs and uses, making them more constrained than normal
  870. // operands.
  871. // Similarly, if there are multiple defs and tied operands, we must make
  872. // sure the same register is allocated to uses and defs.
  873. // We didn't detect inline asm tied operands above, so just make this extra
  874. // pass for all inline asm.
  875. if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
  876. (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
  877. handleThroughOperands(MI, VirtDead);
  878. // Don't attempt coalescing when we have funny stuff going on.
  879. CopyDst = 0;
  880. // Pretend we have early clobbers so the use operands get marked below.
  881. // This is not necessary for the common case of a single tied use.
  882. hasEarlyClobbers = true;
  883. }
  884. // Second scan.
  885. // Allocate virtreg uses.
  886. for (unsigned i = 0; i != VirtOpEnd; ++i) {
  887. MachineOperand &MO = MI->getOperand(i);
  888. if (!MO.isReg()) continue;
  889. unsigned Reg = MO.getReg();
  890. if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
  891. if (MO.isUse()) {
  892. LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
  893. unsigned PhysReg = LRI->PhysReg;
  894. CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
  895. if (setPhysReg(MI, i, PhysReg))
  896. killVirtReg(LRI);
  897. }
  898. }
  899. // Track registers defined by instruction - early clobbers and tied uses at
  900. // this point.
  901. UsedInInstr.clear();
  902. if (hasEarlyClobbers) {
  903. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  904. MachineOperand &MO = MI->getOperand(i);
  905. if (!MO.isReg()) continue;
  906. unsigned Reg = MO.getReg();
  907. if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  908. // Look for physreg defs and tied uses.
  909. if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
  910. markRegUsedInInstr(Reg);
  911. }
  912. }
  913. unsigned DefOpEnd = MI->getNumOperands();
  914. if (MI->isCall()) {
  915. // Spill all virtregs before a call. This serves two purposes: 1. If an
  916. // exception is thrown, the landing pad is going to expect to find
  917. // registers in their spill slots, and 2. we don't have to wade through
  918. // all the <imp-def> operands on the call instruction.
  919. DefOpEnd = VirtOpEnd;
  920. DEBUG(dbgs() << " Spilling remaining registers before call.\n");
  921. spillAll(MI);
  922. // The imp-defs are skipped below, but we still need to mark those
  923. // registers as used by the function.
  924. SkippedInstrs.insert(&MCID);
  925. }
  926. // Third scan.
  927. // Allocate defs and collect dead defs.
  928. for (unsigned i = 0; i != DefOpEnd; ++i) {
  929. MachineOperand &MO = MI->getOperand(i);
  930. if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
  931. continue;
  932. unsigned Reg = MO.getReg();
  933. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  934. if (!MRI->isAllocatable(Reg)) continue;
  935. definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
  936. continue;
  937. }
  938. LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
  939. unsigned PhysReg = LRI->PhysReg;
  940. if (setPhysReg(MI, i, PhysReg)) {
  941. VirtDead.push_back(Reg);
  942. CopyDst = 0; // cancel coalescing;
  943. } else
  944. CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
  945. }
  946. // Kill dead defs after the scan to ensure that multiple defs of the same
  947. // register are allocated identically. We didn't need to do this for uses
  948. // because we are crerating our own kill flags, and they are always at the
  949. // last use.
  950. for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
  951. killVirtReg(VirtDead[i]);
  952. VirtDead.clear();
  953. if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
  954. DEBUG(dbgs() << "-- coalescing: " << *MI);
  955. Coalesced.push_back(MI);
  956. } else {
  957. DEBUG(dbgs() << "<< " << *MI);
  958. }
  959. }
  960. // Spill all physical registers holding virtual registers now.
  961. DEBUG(dbgs() << "Spilling live registers at end of block.\n");
  962. spillAll(MBB->getFirstTerminator());
  963. // Erase all the coalesced copies. We are delaying it until now because
  964. // LiveVirtRegs might refer to the instrs.
  965. for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
  966. MBB->erase(Coalesced[i]);
  967. NumCopies += Coalesced.size();
  968. DEBUG(MBB->dump());
  969. }
  970. /// runOnMachineFunction - Register allocate the whole function
  971. ///
  972. bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
  973. DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
  974. << "********** Function: " << Fn.getName() << '\n');
  975. MF = &Fn;
  976. MRI = &MF->getRegInfo();
  977. TRI = MF->getSubtarget().getRegisterInfo();
  978. TII = MF->getSubtarget().getInstrInfo();
  979. MRI->freezeReservedRegs(Fn);
  980. RegClassInfo.runOnMachineFunction(Fn);
  981. UsedInInstr.clear();
  982. UsedInInstr.setUniverse(TRI->getNumRegUnits());
  983. assert(!MRI->isSSA() && "regalloc requires leaving SSA");
  984. // initialize the virtual->physical register map to have a 'null'
  985. // mapping for all virtual registers
  986. StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
  987. LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
  988. // Loop over all of the basic blocks, eliminating virtual register references
  989. for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
  990. MBBi != MBBe; ++MBBi) {
  991. MBB = &*MBBi;
  992. AllocateBasicBlock();
  993. }
  994. // All machine operands and other references to virtual registers have been
  995. // replaced. Remove the virtual registers.
  996. MRI->clearVirtRegs();
  997. SkippedInstrs.clear();
  998. StackSlotForVirtReg.clear();
  999. LiveDbgValueMap.clear();
  1000. return true;
  1001. }
  1002. FunctionPass *llvm::createFastRegisterAllocator() {
  1003. return new RAFast();
  1004. }