RegAllocFast.cpp 41 KB

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