PrologEpilogInserter.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===//
  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 pass is responsible for finalizing the functions frame layout, saving
  11. // callee saved registers, and for emitting prolog & epilog code for the
  12. // function.
  13. //
  14. // This pass must be run after register allocation. After this pass is
  15. // executed, it is illegal to construct MO_FrameIndex operands.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/ADT/IndexedMap.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/ADT/SmallSet.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/CodeGen/MachineDominators.h"
  24. #include "llvm/CodeGen/MachineFrameInfo.h"
  25. #include "llvm/CodeGen/MachineInstr.h"
  26. #include "llvm/CodeGen/MachineLoopInfo.h"
  27. #include "llvm/CodeGen/MachineModuleInfo.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/Passes.h"
  30. #include "llvm/CodeGen/RegisterScavenging.h"
  31. #include "llvm/CodeGen/StackProtector.h"
  32. #include "llvm/CodeGen/WinEHFuncInfo.h"
  33. #include "llvm/IR/DiagnosticInfo.h"
  34. #include "llvm/IR/InlineAsm.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Compiler.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include "llvm/Target/TargetFrameLowering.h"
  41. #include "llvm/Target/TargetInstrInfo.h"
  42. #include "llvm/Target/TargetMachine.h"
  43. #include "llvm/Target/TargetRegisterInfo.h"
  44. #include "llvm/Target/TargetSubtargetInfo.h"
  45. #include <climits>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "pei"
  48. namespace {
  49. class PEI : public MachineFunctionPass {
  50. public:
  51. static char ID;
  52. PEI() : MachineFunctionPass(ID) {
  53. initializePEIPass(*PassRegistry::getPassRegistry());
  54. }
  55. void getAnalysisUsage(AnalysisUsage &AU) const override;
  56. /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
  57. /// frame indexes with appropriate references.
  58. ///
  59. bool runOnMachineFunction(MachineFunction &Fn) override;
  60. private:
  61. RegScavenger *RS;
  62. // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved
  63. // stack frame indexes.
  64. unsigned MinCSFrameIndex, MaxCSFrameIndex;
  65. // Save and Restore blocks of the current function.
  66. MachineBasicBlock *SaveBlock;
  67. SmallVector<MachineBasicBlock *, 4> RestoreBlocks;
  68. // Flag to control whether to use the register scavenger to resolve
  69. // frame index materialization registers. Set according to
  70. // TRI->requiresFrameIndexScavenging() for the current function.
  71. bool FrameIndexVirtualScavenging;
  72. void calculateSets(MachineFunction &Fn);
  73. void calculateCallsInformation(MachineFunction &Fn);
  74. void assignCalleeSavedSpillSlots(MachineFunction &Fn,
  75. const BitVector &SavedRegs);
  76. void insertCSRSpillsAndRestores(MachineFunction &Fn);
  77. void calculateFrameObjectOffsets(MachineFunction &Fn);
  78. void replaceFrameIndices(MachineFunction &Fn);
  79. void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
  80. int &SPAdj);
  81. void scavengeFrameVirtualRegs(MachineFunction &Fn);
  82. void insertPrologEpilogCode(MachineFunction &Fn);
  83. // Convenience for recognizing return blocks.
  84. bool isReturnBlock(const MachineBasicBlock *MBB) const;
  85. };
  86. } // namespace
  87. char PEI::ID = 0;
  88. char &llvm::PrologEpilogCodeInserterID = PEI::ID;
  89. static cl::opt<unsigned>
  90. WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1),
  91. cl::desc("Warn for stack size bigger than the given"
  92. " number"));
  93. INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
  94. "Prologue/Epilogue Insertion", false, false)
  95. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  96. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  97. INITIALIZE_PASS_DEPENDENCY(StackProtector)
  98. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  99. INITIALIZE_PASS_END(PEI, "prologepilog",
  100. "Prologue/Epilogue Insertion & Frame Finalization",
  101. false, false)
  102. STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
  103. STATISTIC(NumBytesStackSpace,
  104. "Number of bytes used for stack in all functions");
  105. void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
  106. AU.setPreservesCFG();
  107. AU.addPreserved<MachineLoopInfo>();
  108. AU.addPreserved<MachineDominatorTree>();
  109. AU.addRequired<StackProtector>();
  110. AU.addRequired<TargetPassConfig>();
  111. MachineFunctionPass::getAnalysisUsage(AU);
  112. }
  113. bool PEI::isReturnBlock(const MachineBasicBlock* MBB) const {
  114. return (MBB && !MBB->empty() && MBB->back().isReturn());
  115. }
  116. /// Compute the set of return blocks
  117. void PEI::calculateSets(MachineFunction &Fn) {
  118. const MachineFrameInfo *MFI = Fn.getFrameInfo();
  119. // Even when we do not change any CSR, we still want to insert the
  120. // prologue and epilogue of the function.
  121. // So set the save points for those.
  122. // Use the points found by shrink-wrapping, if any.
  123. if (MFI->getSavePoint()) {
  124. SaveBlock = MFI->getSavePoint();
  125. assert(MFI->getRestorePoint() && "Both restore and save must be set");
  126. MachineBasicBlock *RestoreBlock = MFI->getRestorePoint();
  127. // If RestoreBlock does not have any successor and is not a return block
  128. // then the end point is unreachable and we do not need to insert any
  129. // epilogue.
  130. if (!RestoreBlock->succ_empty() || isReturnBlock(RestoreBlock))
  131. RestoreBlocks.push_back(RestoreBlock);
  132. return;
  133. }
  134. // Save refs to entry and return blocks.
  135. SaveBlock = Fn.begin();
  136. for (MachineFunction::iterator MBB = Fn.begin(), E = Fn.end();
  137. MBB != E; ++MBB)
  138. if (isReturnBlock(MBB))
  139. RestoreBlocks.push_back(MBB);
  140. return;
  141. }
  142. /// StackObjSet - A set of stack object indexes
  143. typedef SmallSetVector<int, 8> StackObjSet;
  144. /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
  145. /// frame indexes with appropriate references.
  146. ///
  147. bool PEI::runOnMachineFunction(MachineFunction &Fn) {
  148. const Function* F = Fn.getFunction();
  149. const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
  150. const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
  151. assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs");
  152. RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr;
  153. FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
  154. // Calculate the MaxCallFrameSize and AdjustsStack variables for the
  155. // function's frame information. Also eliminates call frame pseudo
  156. // instructions.
  157. calculateCallsInformation(Fn);
  158. // Determine which of the registers in the callee save list should be saved.
  159. BitVector SavedRegs;
  160. TFI->determineCalleeSaves(Fn, SavedRegs, RS);
  161. // Insert spill code for any callee saved registers that are modified.
  162. assignCalleeSavedSpillSlots(Fn, SavedRegs);
  163. // Determine placement of CSR spill/restore code:
  164. // place all spills in the entry block, all restores in return blocks.
  165. calculateSets(Fn);
  166. // Add the code to save and restore the callee saved registers
  167. if (!F->hasFnAttribute(Attribute::Naked))
  168. insertCSRSpillsAndRestores(Fn);
  169. // Allow the target machine to make final modifications to the function
  170. // before the frame layout is finalized.
  171. TFI->processFunctionBeforeFrameFinalized(Fn, RS);
  172. // Calculate actual frame offsets for all abstract stack objects...
  173. calculateFrameObjectOffsets(Fn);
  174. // Add prolog and epilog code to the function. This function is required
  175. // to align the stack frame as necessary for any stack variables or
  176. // called functions. Because of this, calculateCalleeSavedRegisters()
  177. // must be called before this function in order to set the AdjustsStack
  178. // and MaxCallFrameSize variables.
  179. if (!F->hasFnAttribute(Attribute::Naked))
  180. insertPrologEpilogCode(Fn);
  181. // Replace all MO_FrameIndex operands with physical register references
  182. // and actual offsets.
  183. //
  184. replaceFrameIndices(Fn);
  185. // If register scavenging is needed, as we've enabled doing it as a
  186. // post-pass, scavenge the virtual registers that frame index elimination
  187. // inserted.
  188. if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
  189. scavengeFrameVirtualRegs(Fn);
  190. // Clear any vregs created by virtual scavenging.
  191. Fn.getRegInfo().clearVirtRegs();
  192. // Warn on stack size when we exceeds the given limit.
  193. MachineFrameInfo *MFI = Fn.getFrameInfo();
  194. uint64_t StackSize = MFI->getStackSize();
  195. if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) {
  196. DiagnosticInfoStackSize DiagStackSize(*F, StackSize);
  197. F->getContext().diagnose(DiagStackSize);
  198. }
  199. delete RS;
  200. RestoreBlocks.clear();
  201. return true;
  202. }
  203. /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
  204. /// variables for the function's frame information and eliminate call frame
  205. /// pseudo instructions.
  206. void PEI::calculateCallsInformation(MachineFunction &Fn) {
  207. const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
  208. const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
  209. MachineFrameInfo *MFI = Fn.getFrameInfo();
  210. unsigned MaxCallFrameSize = 0;
  211. bool AdjustsStack = MFI->adjustsStack();
  212. // Get the function call frame set-up and tear-down instruction opcode
  213. unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  214. unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  215. // Early exit for targets which have no call frame setup/destroy pseudo
  216. // instructions.
  217. if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
  218. return;
  219. std::vector<MachineBasicBlock::iterator> FrameSDOps;
  220. for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
  221. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
  222. if (I->getOpcode() == FrameSetupOpcode ||
  223. I->getOpcode() == FrameDestroyOpcode) {
  224. assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
  225. " instructions should have a single immediate argument!");
  226. unsigned Size = I->getOperand(0).getImm();
  227. if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
  228. AdjustsStack = true;
  229. FrameSDOps.push_back(I);
  230. } else if (I->isInlineAsm()) {
  231. // Some inline asm's need a stack frame, as indicated by operand 1.
  232. unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  233. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  234. AdjustsStack = true;
  235. }
  236. MFI->setAdjustsStack(AdjustsStack);
  237. MFI->setMaxCallFrameSize(MaxCallFrameSize);
  238. for (std::vector<MachineBasicBlock::iterator>::iterator
  239. i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
  240. MachineBasicBlock::iterator I = *i;
  241. // If call frames are not being included as part of the stack frame, and
  242. // the target doesn't indicate otherwise, remove the call frame pseudos
  243. // here. The sub/add sp instruction pairs are still inserted, but we don't
  244. // need to track the SP adjustment for frame index elimination.
  245. if (TFI->canSimplifyCallFramePseudos(Fn))
  246. TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
  247. }
  248. }
  249. void PEI::assignCalleeSavedSpillSlots(MachineFunction &F,
  250. const BitVector &SavedRegs) {
  251. // These are used to keep track the callee-save area. Initialize them.
  252. MinCSFrameIndex = INT_MAX;
  253. MaxCSFrameIndex = 0;
  254. if (SavedRegs.empty())
  255. return;
  256. const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
  257. const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F);
  258. std::vector<CalleeSavedInfo> CSI;
  259. for (unsigned i = 0; CSRegs[i]; ++i) {
  260. unsigned Reg = CSRegs[i];
  261. if (SavedRegs.test(Reg))
  262. CSI.push_back(CalleeSavedInfo(Reg));
  263. }
  264. const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
  265. MachineFrameInfo *MFI = F.getFrameInfo();
  266. if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
  267. // If target doesn't implement this, use generic code.
  268. if (CSI.empty())
  269. return; // Early exit if no callee saved registers are modified!
  270. unsigned NumFixedSpillSlots;
  271. const TargetFrameLowering::SpillSlot *FixedSpillSlots =
  272. TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
  273. // Now that we know which registers need to be saved and restored, allocate
  274. // stack slots for them.
  275. for (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end();
  276. I != E; ++I) {
  277. unsigned Reg = I->getReg();
  278. const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
  279. int FrameIdx;
  280. if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
  281. I->setFrameIdx(FrameIdx);
  282. continue;
  283. }
  284. // Check to see if this physreg must be spilled to a particular stack slot
  285. // on this target.
  286. const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
  287. while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
  288. FixedSlot->Reg != Reg)
  289. ++FixedSlot;
  290. if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
  291. // Nope, just spill it anywhere convenient.
  292. unsigned Align = RC->getAlignment();
  293. unsigned StackAlign = TFI->getStackAlignment();
  294. // We may not be able to satisfy the desired alignment specification of
  295. // the TargetRegisterClass if the stack alignment is smaller. Use the
  296. // min.
  297. Align = std::min(Align, StackAlign);
  298. FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
  299. if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
  300. if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
  301. } else {
  302. // Spill it to the stack where we must.
  303. FrameIdx =
  304. MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset);
  305. }
  306. I->setFrameIdx(FrameIdx);
  307. }
  308. }
  309. MFI->setCalleeSavedInfo(CSI);
  310. }
  311. /// Helper function to update the liveness information for the callee-saved
  312. /// registers.
  313. static void updateLiveness(MachineFunction &MF) {
  314. MachineFrameInfo *MFI = MF.getFrameInfo();
  315. // Visited will contain all the basic blocks that are in the region
  316. // where the callee saved registers are alive:
  317. // - Anything that is not Save or Restore -> LiveThrough.
  318. // - Save -> LiveIn.
  319. // - Restore -> LiveOut.
  320. // The live-out is not attached to the block, so no need to keep
  321. // Restore in this set.
  322. SmallPtrSet<MachineBasicBlock *, 8> Visited;
  323. SmallVector<MachineBasicBlock *, 8> WorkList;
  324. MachineBasicBlock *Entry = &MF.front();
  325. MachineBasicBlock *Save = MFI->getSavePoint();
  326. if (!Save)
  327. Save = Entry;
  328. if (Entry != Save) {
  329. WorkList.push_back(Entry);
  330. Visited.insert(Entry);
  331. }
  332. Visited.insert(Save);
  333. MachineBasicBlock *Restore = MFI->getRestorePoint();
  334. if (Restore)
  335. // By construction Restore cannot be visited, otherwise it
  336. // means there exists a path to Restore that does not go
  337. // through Save.
  338. WorkList.push_back(Restore);
  339. while (!WorkList.empty()) {
  340. const MachineBasicBlock *CurBB = WorkList.pop_back_val();
  341. // By construction, the region that is after the save point is
  342. // dominated by the Save and post-dominated by the Restore.
  343. if (CurBB == Save)
  344. continue;
  345. // Enqueue all the successors not already visited.
  346. // Those are by construction either before Save or after Restore.
  347. for (MachineBasicBlock *SuccBB : CurBB->successors())
  348. if (Visited.insert(SuccBB).second)
  349. WorkList.push_back(SuccBB);
  350. }
  351. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  352. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  353. for (MachineBasicBlock *MBB : Visited)
  354. // Add the callee-saved register as live-in.
  355. // It's killed at the spill.
  356. MBB->addLiveIn(CSI[i].getReg());
  357. }
  358. }
  359. /// insertCSRSpillsAndRestores - Insert spill and restore code for
  360. /// callee saved registers used in the function.
  361. ///
  362. void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
  363. // Get callee saved register information.
  364. MachineFrameInfo *MFI = Fn.getFrameInfo();
  365. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  366. MFI->setCalleeSavedInfoValid(true);
  367. // Early exit if no callee saved registers are modified!
  368. if (CSI.empty())
  369. return;
  370. const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
  371. const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
  372. const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
  373. MachineBasicBlock::iterator I;
  374. // Spill using target interface.
  375. I = SaveBlock->begin();
  376. if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) {
  377. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  378. // Insert the spill to the stack frame.
  379. unsigned Reg = CSI[i].getReg();
  380. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  381. TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(),
  382. RC, TRI);
  383. }
  384. }
  385. // Update the live-in information of all the blocks up to the save point.
  386. updateLiveness(Fn);
  387. // Restore using target interface.
  388. for (MachineBasicBlock *MBB : RestoreBlocks) {
  389. I = MBB->end();
  390. // Skip over all terminator instructions, which are part of the return
  391. // sequence.
  392. MachineBasicBlock::iterator I2 = I;
  393. while (I2 != MBB->begin() && (--I2)->isTerminator())
  394. I = I2;
  395. bool AtStart = I == MBB->begin();
  396. MachineBasicBlock::iterator BeforeI = I;
  397. if (!AtStart)
  398. --BeforeI;
  399. // Restore all registers immediately before the return and any
  400. // terminators that precede it.
  401. if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
  402. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  403. unsigned Reg = CSI[i].getReg();
  404. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  405. TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI);
  406. assert(I != MBB->begin() &&
  407. "loadRegFromStackSlot didn't insert any code!");
  408. // Insert in reverse order. loadRegFromStackSlot can insert
  409. // multiple instructions.
  410. if (AtStart)
  411. I = MBB->begin();
  412. else {
  413. I = BeforeI;
  414. ++I;
  415. }
  416. }
  417. }
  418. }
  419. }
  420. /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
  421. static inline void
  422. AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
  423. bool StackGrowsDown, int64_t &Offset,
  424. unsigned &MaxAlign) {
  425. // If the stack grows down, add the object size to find the lowest address.
  426. if (StackGrowsDown)
  427. Offset += MFI->getObjectSize(FrameIdx);
  428. unsigned Align = MFI->getObjectAlignment(FrameIdx);
  429. // If the alignment of this object is greater than that of the stack, then
  430. // increase the stack alignment to match.
  431. MaxAlign = std::max(MaxAlign, Align);
  432. // Adjust to alignment boundary.
  433. Offset = (Offset + Align - 1) / Align * Align;
  434. if (StackGrowsDown) {
  435. DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
  436. MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
  437. } else {
  438. DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
  439. MFI->setObjectOffset(FrameIdx, Offset);
  440. Offset += MFI->getObjectSize(FrameIdx);
  441. }
  442. }
  443. /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
  444. /// those required to be close to the Stack Protector) to stack offsets.
  445. static void
  446. AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
  447. SmallSet<int, 16> &ProtectedObjs,
  448. MachineFrameInfo *MFI, bool StackGrowsDown,
  449. int64_t &Offset, unsigned &MaxAlign) {
  450. for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
  451. E = UnassignedObjs.end(); I != E; ++I) {
  452. int i = *I;
  453. AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
  454. ProtectedObjs.insert(i);
  455. }
  456. }
  457. /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
  458. /// abstract stack objects.
  459. ///
  460. void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
  461. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  462. StackProtector *SP = &getAnalysis<StackProtector>();
  463. bool StackGrowsDown =
  464. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  465. // Loop over all of the stack objects, assigning sequential addresses...
  466. MachineFrameInfo *MFI = Fn.getFrameInfo();
  467. // Start at the beginning of the local area.
  468. // The Offset is the distance from the stack top in the direction
  469. // of stack growth -- so it's always nonnegative.
  470. int LocalAreaOffset = TFI.getOffsetOfLocalArea();
  471. if (StackGrowsDown)
  472. LocalAreaOffset = -LocalAreaOffset;
  473. assert(LocalAreaOffset >= 0
  474. && "Local area offset should be in direction of stack growth");
  475. int64_t Offset = LocalAreaOffset;
  476. // If there are fixed sized objects that are preallocated in the local area,
  477. // non-fixed objects can't be allocated right at the start of local area.
  478. // We currently don't support filling in holes in between fixed sized
  479. // objects, so we adjust 'Offset' to point to the end of last fixed sized
  480. // preallocated object.
  481. for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
  482. int64_t FixedOff;
  483. if (StackGrowsDown) {
  484. // The maximum distance from the stack pointer is at lower address of
  485. // the object -- which is given by offset. For down growing stack
  486. // the offset is negative, so we negate the offset to get the distance.
  487. FixedOff = -MFI->getObjectOffset(i);
  488. } else {
  489. // The maximum distance from the start pointer is at the upper
  490. // address of the object.
  491. FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
  492. }
  493. if (FixedOff > Offset) Offset = FixedOff;
  494. }
  495. // First assign frame offsets to stack objects that are used to spill
  496. // callee saved registers.
  497. if (StackGrowsDown) {
  498. for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
  499. // If the stack grows down, we need to add the size to find the lowest
  500. // address of the object.
  501. Offset += MFI->getObjectSize(i);
  502. unsigned Align = MFI->getObjectAlignment(i);
  503. // Adjust to alignment boundary
  504. Offset = RoundUpToAlignment(Offset, Align);
  505. MFI->setObjectOffset(i, -Offset); // Set the computed offset
  506. }
  507. } else {
  508. int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
  509. for (int i = MaxCSFI; i >= MinCSFI ; --i) {
  510. unsigned Align = MFI->getObjectAlignment(i);
  511. // Adjust to alignment boundary
  512. Offset = RoundUpToAlignment(Offset, Align);
  513. MFI->setObjectOffset(i, Offset);
  514. Offset += MFI->getObjectSize(i);
  515. }
  516. }
  517. unsigned MaxAlign = MFI->getMaxAlignment();
  518. // Make sure the special register scavenging spill slot is closest to the
  519. // incoming stack pointer if a frame pointer is required and is closer
  520. // to the incoming rather than the final stack pointer.
  521. const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo();
  522. bool EarlyScavengingSlots = (TFI.hasFP(Fn) &&
  523. TFI.isFPCloseToIncomingSP() &&
  524. RegInfo->useFPForScavengingIndex(Fn) &&
  525. !RegInfo->needsStackRealignment(Fn));
  526. if (RS && EarlyScavengingSlots) {
  527. SmallVector<int, 2> SFIs;
  528. RS->getScavengingFrameIndices(SFIs);
  529. for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
  530. IE = SFIs.end(); I != IE; ++I)
  531. AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
  532. }
  533. // FIXME: Once this is working, then enable flag will change to a target
  534. // check for whether the frame is large enough to want to use virtual
  535. // frame index registers. Functions which don't want/need this optimization
  536. // will continue to use the existing code path.
  537. if (MFI->getUseLocalStackAllocationBlock()) {
  538. unsigned Align = MFI->getLocalFrameMaxAlign();
  539. // Adjust to alignment boundary.
  540. Offset = RoundUpToAlignment(Offset, Align);
  541. DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
  542. // Resolve offsets for objects in the local block.
  543. for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
  544. std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
  545. int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
  546. DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
  547. FIOffset << "]\n");
  548. MFI->setObjectOffset(Entry.first, FIOffset);
  549. }
  550. // Allocate the local block
  551. Offset += MFI->getLocalFrameSize();
  552. MaxAlign = std::max(Align, MaxAlign);
  553. }
  554. // Make sure that the stack protector comes before the local variables on the
  555. // stack.
  556. SmallSet<int, 16> ProtectedObjs;
  557. if (MFI->getStackProtectorIndex() >= 0) {
  558. StackObjSet LargeArrayObjs;
  559. StackObjSet SmallArrayObjs;
  560. StackObjSet AddrOfObjs;
  561. AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
  562. Offset, MaxAlign);
  563. // Assign large stack objects first.
  564. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  565. if (MFI->isObjectPreAllocated(i) &&
  566. MFI->getUseLocalStackAllocationBlock())
  567. continue;
  568. if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
  569. continue;
  570. if (RS && RS->isScavengingFrameIndex((int)i))
  571. continue;
  572. if (MFI->isDeadObjectIndex(i))
  573. continue;
  574. if (MFI->getStackProtectorIndex() == (int)i)
  575. continue;
  576. switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) {
  577. case StackProtector::SSPLK_None:
  578. continue;
  579. case StackProtector::SSPLK_SmallArray:
  580. SmallArrayObjs.insert(i);
  581. continue;
  582. case StackProtector::SSPLK_AddrOf:
  583. AddrOfObjs.insert(i);
  584. continue;
  585. case StackProtector::SSPLK_LargeArray:
  586. LargeArrayObjs.insert(i);
  587. continue;
  588. }
  589. llvm_unreachable("Unexpected SSPLayoutKind.");
  590. }
  591. AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
  592. Offset, MaxAlign);
  593. AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
  594. Offset, MaxAlign);
  595. AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
  596. Offset, MaxAlign);
  597. }
  598. // Then assign frame offsets to stack objects that are not used to spill
  599. // callee saved registers.
  600. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  601. if (MFI->isObjectPreAllocated(i) &&
  602. MFI->getUseLocalStackAllocationBlock())
  603. continue;
  604. if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
  605. continue;
  606. if (RS && RS->isScavengingFrameIndex((int)i))
  607. continue;
  608. if (MFI->isDeadObjectIndex(i))
  609. continue;
  610. if (MFI->getStackProtectorIndex() == (int)i)
  611. continue;
  612. if (ProtectedObjs.count(i))
  613. continue;
  614. AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
  615. }
  616. // Make sure the special register scavenging spill slot is closest to the
  617. // stack pointer.
  618. if (RS && !EarlyScavengingSlots) {
  619. SmallVector<int, 2> SFIs;
  620. RS->getScavengingFrameIndices(SFIs);
  621. for (SmallVectorImpl<int>::iterator I = SFIs.begin(),
  622. IE = SFIs.end(); I != IE; ++I)
  623. AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign);
  624. }
  625. if (!TFI.targetHandlesStackFrameRounding()) {
  626. // If we have reserved argument space for call sites in the function
  627. // immediately on entry to the current function, count it as part of the
  628. // overall stack size.
  629. if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
  630. Offset += MFI->getMaxCallFrameSize();
  631. // Round up the size to a multiple of the alignment. If the function has
  632. // any calls or alloca's, align to the target's StackAlignment value to
  633. // ensure that the callee's frame or the alloca data is suitably aligned;
  634. // otherwise, for leaf functions, align to the TransientStackAlignment
  635. // value.
  636. unsigned StackAlign;
  637. if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
  638. (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
  639. StackAlign = TFI.getStackAlignment();
  640. else
  641. StackAlign = TFI.getTransientStackAlignment();
  642. // If the frame pointer is eliminated, all frame offsets will be relative to
  643. // SP not FP. Align to MaxAlign so this works.
  644. StackAlign = std::max(StackAlign, MaxAlign);
  645. Offset = RoundUpToAlignment(Offset, StackAlign);
  646. }
  647. // Update frame info to pretend that this is part of the stack...
  648. int64_t StackSize = Offset - LocalAreaOffset;
  649. MFI->setStackSize(StackSize);
  650. NumBytesStackSpace += StackSize;
  651. }
  652. /// insertPrologEpilogCode - Scan the function for modified callee saved
  653. /// registers, insert spill code for these callee saved registers, then add
  654. /// prolog and epilog code to the function.
  655. ///
  656. void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
  657. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  658. // Add prologue to the function...
  659. TFI.emitPrologue(Fn, *SaveBlock);
  660. // Add epilogue to restore the callee-save registers in each exiting block.
  661. for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
  662. TFI.emitEpilogue(Fn, *RestoreBlock);
  663. // Emit additional code that is required to support segmented stacks, if
  664. // we've been asked for it. This, when linked with a runtime with support
  665. // for segmented stacks (libgcc is one), will result in allocating stack
  666. // space in small chunks instead of one large contiguous block.
  667. if (Fn.shouldSplitStack())
  668. TFI.adjustForSegmentedStacks(Fn, *SaveBlock);
  669. // Emit additional code that is required to explicitly handle the stack in
  670. // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
  671. // approach is rather similar to that of Segmented Stacks, but it uses a
  672. // different conditional check and another BIF for allocating more stack
  673. // space.
  674. if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE)
  675. TFI.adjustForHiPEPrologue(Fn, *SaveBlock);
  676. }
  677. /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
  678. /// register references and actual offsets.
  679. ///
  680. void PEI::replaceFrameIndices(MachineFunction &Fn) {
  681. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  682. if (!TFI.needsFrameIndexResolution(Fn)) return;
  683. MachineModuleInfo &MMI = Fn.getMMI();
  684. const Function *F = Fn.getFunction();
  685. const Function *ParentF = MMI.getWinEHParent(F);
  686. unsigned FrameReg;
  687. if (F == ParentF) {
  688. WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
  689. // FIXME: This should be unconditional but we have bugs in the preparation
  690. // pass.
  691. if (FuncInfo.UnwindHelpFrameIdx != INT_MAX)
  692. FuncInfo.UnwindHelpFrameOffset = TFI.getFrameIndexReferenceFromSP(
  693. Fn, FuncInfo.UnwindHelpFrameIdx, FrameReg);
  694. } else if (MMI.hasWinEHFuncInfo(F)) {
  695. WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction());
  696. auto I = FuncInfo.CatchHandlerParentFrameObjIdx.find(F);
  697. if (I != FuncInfo.CatchHandlerParentFrameObjIdx.end())
  698. FuncInfo.CatchHandlerParentFrameObjOffset[F] =
  699. TFI.getFrameIndexReferenceFromSP(Fn, I->second, FrameReg);
  700. }
  701. // Store SPAdj at exit of a basic block.
  702. SmallVector<int, 8> SPState;
  703. SPState.resize(Fn.getNumBlockIDs());
  704. SmallPtrSet<MachineBasicBlock*, 8> Reachable;
  705. // Iterate over the reachable blocks in DFS order.
  706. for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable);
  707. DFI != DFE; ++DFI) {
  708. int SPAdj = 0;
  709. // Check the exit state of the DFS stack predecessor.
  710. if (DFI.getPathLength() >= 2) {
  711. MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2);
  712. assert(Reachable.count(StackPred) &&
  713. "DFS stack predecessor is already visited.\n");
  714. SPAdj = SPState[StackPred->getNumber()];
  715. }
  716. MachineBasicBlock *BB = *DFI;
  717. replaceFrameIndices(BB, Fn, SPAdj);
  718. SPState[BB->getNumber()] = SPAdj;
  719. }
  720. // Handle the unreachable blocks.
  721. for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
  722. if (Reachable.count(BB))
  723. // Already handled in DFS traversal.
  724. continue;
  725. int SPAdj = 0;
  726. replaceFrameIndices(BB, Fn, SPAdj);
  727. }
  728. }
  729. void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn,
  730. int &SPAdj) {
  731. assert(Fn.getSubtarget().getRegisterInfo() &&
  732. "getRegisterInfo() must be implemented!");
  733. const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo();
  734. const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo();
  735. const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering();
  736. unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  737. unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  738. if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
  739. bool InsideCallSequence = false;
  740. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
  741. if (I->getOpcode() == FrameSetupOpcode ||
  742. I->getOpcode() == FrameDestroyOpcode) {
  743. InsideCallSequence = (I->getOpcode() == FrameSetupOpcode);
  744. SPAdj += TII.getSPAdjust(I);
  745. MachineBasicBlock::iterator PrevI = BB->end();
  746. if (I != BB->begin()) PrevI = std::prev(I);
  747. TFI->eliminateCallFramePseudoInstr(Fn, *BB, I);
  748. // Visit the instructions created by eliminateCallFramePseudoInstr().
  749. if (PrevI == BB->end())
  750. I = BB->begin(); // The replaced instr was the first in the block.
  751. else
  752. I = std::next(PrevI);
  753. continue;
  754. }
  755. MachineInstr *MI = I;
  756. bool DoIncr = true;
  757. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  758. if (!MI->getOperand(i).isFI())
  759. continue;
  760. // Frame indicies in debug values are encoded in a target independent
  761. // way with simply the frame index and offset rather than any
  762. // target-specific addressing mode.
  763. if (MI->isDebugValue()) {
  764. assert(i == 0 && "Frame indicies can only appear as the first "
  765. "operand of a DBG_VALUE machine instruction");
  766. unsigned Reg;
  767. MachineOperand &Offset = MI->getOperand(1);
  768. Offset.setImm(Offset.getImm() +
  769. TFI->getFrameIndexReference(
  770. Fn, MI->getOperand(0).getIndex(), Reg));
  771. MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/);
  772. continue;
  773. }
  774. // TODO: This code should be commoned with the code for
  775. // PATCHPOINT. There's no good reason for the difference in
  776. // implementation other than historical accident. The only
  777. // remaining difference is the unconditional use of the stack
  778. // pointer as the base register.
  779. if (MI->getOpcode() == TargetOpcode::STATEPOINT) {
  780. assert((!MI->isDebugValue() || i == 0) &&
  781. "Frame indicies can only appear as the first operand of a "
  782. "DBG_VALUE machine instruction");
  783. unsigned Reg;
  784. MachineOperand &Offset = MI->getOperand(i + 1);
  785. const unsigned refOffset =
  786. TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(),
  787. Reg);
  788. Offset.setImm(Offset.getImm() + refOffset);
  789. MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/);
  790. continue;
  791. }
  792. // Some instructions (e.g. inline asm instructions) can have
  793. // multiple frame indices and/or cause eliminateFrameIndex
  794. // to insert more than one instruction. We need the register
  795. // scavenger to go through all of these instructions so that
  796. // it can update its register information. We keep the
  797. // iterator at the point before insertion so that we can
  798. // revisit them in full.
  799. bool AtBeginning = (I == BB->begin());
  800. if (!AtBeginning) --I;
  801. // If this instruction has a FrameIndex operand, we need to
  802. // use that target machine register info object to eliminate
  803. // it.
  804. TRI.eliminateFrameIndex(MI, SPAdj, i,
  805. FrameIndexVirtualScavenging ? nullptr : RS);
  806. // Reset the iterator if we were at the beginning of the BB.
  807. if (AtBeginning) {
  808. I = BB->begin();
  809. DoIncr = false;
  810. }
  811. MI = nullptr;
  812. break;
  813. }
  814. // If we are looking at a call sequence, we need to keep track of
  815. // the SP adjustment made by each instruction in the sequence.
  816. // This includes both the frame setup/destroy pseudos (handled above),
  817. // as well as other instructions that have side effects w.r.t the SP.
  818. // Note that this must come after eliminateFrameIndex, because
  819. // if I itself referred to a frame index, we shouldn't count its own
  820. // adjustment.
  821. if (MI && InsideCallSequence)
  822. SPAdj += TII.getSPAdjust(MI);
  823. if (DoIncr && I != BB->end()) ++I;
  824. // Update register states.
  825. if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
  826. }
  827. }
  828. /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
  829. /// with physical registers. Use the register scavenger to find an
  830. /// appropriate register to use.
  831. ///
  832. /// FIXME: Iterating over the instruction stream is unnecessary. We can simply
  833. /// iterate over the vreg use list, which at this point only contains machine
  834. /// operands for which eliminateFrameIndex need a new scratch reg.
  835. void
  836. PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
  837. // Run through the instructions and find any virtual registers.
  838. for (MachineFunction::iterator BB = Fn.begin(),
  839. E = Fn.end(); BB != E; ++BB) {
  840. RS->enterBasicBlock(BB);
  841. int SPAdj = 0;
  842. // The instruction stream may change in the loop, so check BB->end()
  843. // directly.
  844. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
  845. // We might end up here again with a NULL iterator if we scavenged a
  846. // register for which we inserted spill code for definition by what was
  847. // originally the first instruction in BB.
  848. if (I == MachineBasicBlock::iterator(nullptr))
  849. I = BB->begin();
  850. MachineInstr *MI = I;
  851. MachineBasicBlock::iterator J = std::next(I);
  852. MachineBasicBlock::iterator P =
  853. I == BB->begin() ? MachineBasicBlock::iterator(nullptr)
  854. : std::prev(I);
  855. // RS should process this instruction before we might scavenge at this
  856. // location. This is because we might be replacing a virtual register
  857. // defined by this instruction, and if so, registers killed by this
  858. // instruction are available, and defined registers are not.
  859. RS->forward(I);
  860. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  861. if (MI->getOperand(i).isReg()) {
  862. MachineOperand &MO = MI->getOperand(i);
  863. unsigned Reg = MO.getReg();
  864. if (Reg == 0)
  865. continue;
  866. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  867. continue;
  868. // When we first encounter a new virtual register, it
  869. // must be a definition.
  870. assert(MI->getOperand(i).isDef() &&
  871. "frame index virtual missing def!");
  872. // Scavenge a new scratch register
  873. const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
  874. unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj);
  875. ++NumScavengedRegs;
  876. // Replace this reference to the virtual register with the
  877. // scratch register.
  878. assert (ScratchReg && "Missing scratch register!");
  879. MachineRegisterInfo &MRI = Fn.getRegInfo();
  880. Fn.getRegInfo().replaceRegWith(Reg, ScratchReg);
  881. // Make sure MRI now accounts this register as used.
  882. MRI.setPhysRegUsed(ScratchReg);
  883. // Because this instruction was processed by the RS before this
  884. // register was allocated, make sure that the RS now records the
  885. // register as being used.
  886. RS->setRegUsed(ScratchReg);
  887. }
  888. }
  889. // If the scavenger needed to use one of its spill slots, the
  890. // spill code will have been inserted in between I and J. This is a
  891. // problem because we need the spill code before I: Move I to just
  892. // prior to J.
  893. if (I != std::prev(J)) {
  894. BB->splice(J, BB, I);
  895. // Before we move I, we need to prepare the RS to visit I again.
  896. // Specifically, RS will assert if it sees uses of registers that
  897. // it believes are undefined. Because we have already processed
  898. // register kills in I, when it visits I again, it will believe that
  899. // those registers are undefined. To avoid this situation, unprocess
  900. // the instruction I.
  901. assert(RS->getCurrentPosition() == I &&
  902. "The register scavenger has an unexpected position");
  903. I = P;
  904. RS->unprocess(P);
  905. } else
  906. ++I;
  907. }
  908. }
  909. }