RegAllocFast.cpp 42 KB

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