RegAllocFast.cpp 40 KB

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