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