RegAllocFast.cpp 41 KB

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