PrologEpilogInserter.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. // This pass provides an optional shrink wrapping variant of prolog/epilog
  18. // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #define DEBUG_TYPE "pei"
  22. #include "PrologEpilogInserter.h"
  23. #include "llvm/InlineAsm.h"
  24. #include "llvm/CodeGen/MachineDominators.h"
  25. #include "llvm/CodeGen/MachineLoopInfo.h"
  26. #include "llvm/CodeGen/MachineInstr.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/RegisterScavenging.h"
  30. #include "llvm/Target/TargetMachine.h"
  31. #include "llvm/Target/TargetOptions.h"
  32. #include "llvm/Target/TargetRegisterInfo.h"
  33. #include "llvm/Target/TargetFrameLowering.h"
  34. #include "llvm/Target/TargetInstrInfo.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Compiler.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/ADT/IndexedMap.h"
  39. #include "llvm/ADT/SmallSet.h"
  40. #include "llvm/ADT/Statistic.h"
  41. #include "llvm/ADT/STLExtras.h"
  42. #include <climits>
  43. using namespace llvm;
  44. char PEI::ID = 0;
  45. char &llvm::PrologEpilogCodeInserterID = PEI::ID;
  46. INITIALIZE_PASS_BEGIN(PEI, "prologepilog",
  47. "Prologue/Epilogue Insertion", false, false)
  48. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  49. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  50. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  51. INITIALIZE_PASS_END(PEI, "prologepilog",
  52. "Prologue/Epilogue Insertion & Frame Finalization",
  53. false, false)
  54. STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered");
  55. STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged");
  56. STATISTIC(NumBytesStackSpace,
  57. "Number of bytes used for stack in all functions");
  58. /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
  59. /// frame indexes with appropriate references.
  60. ///
  61. bool PEI::runOnMachineFunction(MachineFunction &Fn) {
  62. const Function* F = Fn.getFunction();
  63. const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
  64. const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
  65. RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL;
  66. FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn);
  67. // Calculate the MaxCallFrameSize and AdjustsStack variables for the
  68. // function's frame information. Also eliminates call frame pseudo
  69. // instructions.
  70. calculateCallsInformation(Fn);
  71. // Allow the target machine to make some adjustments to the function
  72. // e.g. UsedPhysRegs before calculateCalleeSavedRegisters.
  73. TFI->processFunctionBeforeCalleeSavedScan(Fn, RS);
  74. // Scan the function for modified callee saved registers and insert spill code
  75. // for any callee saved registers that are modified.
  76. calculateCalleeSavedRegisters(Fn);
  77. // Determine placement of CSR spill/restore code:
  78. // - With shrink wrapping, place spills and restores to tightly
  79. // enclose regions in the Machine CFG of the function where
  80. // they are used.
  81. // - Without shink wrapping (default), place all spills in the
  82. // entry block, all restores in return blocks.
  83. placeCSRSpillsAndRestores(Fn);
  84. // Add the code to save and restore the callee saved registers
  85. if (!F->hasFnAttr(Attribute::Naked))
  86. insertCSRSpillsAndRestores(Fn);
  87. // Allow the target machine to make final modifications to the function
  88. // before the frame layout is finalized.
  89. TFI->processFunctionBeforeFrameFinalized(Fn);
  90. // Calculate actual frame offsets for all abstract stack objects...
  91. calculateFrameObjectOffsets(Fn);
  92. // Add prolog and epilog code to the function. This function is required
  93. // to align the stack frame as necessary for any stack variables or
  94. // called functions. Because of this, calculateCalleeSavedRegisters()
  95. // must be called before this function in order to set the AdjustsStack
  96. // and MaxCallFrameSize variables.
  97. if (!F->hasFnAttr(Attribute::Naked))
  98. insertPrologEpilogCode(Fn);
  99. // Replace all MO_FrameIndex operands with physical register references
  100. // and actual offsets.
  101. //
  102. replaceFrameIndices(Fn);
  103. // If register scavenging is needed, as we've enabled doing it as a
  104. // post-pass, scavenge the virtual registers that frame index elimiation
  105. // inserted.
  106. if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging)
  107. scavengeFrameVirtualRegs(Fn);
  108. delete RS;
  109. clearAllSets();
  110. return true;
  111. }
  112. #if 0
  113. void PEI::getAnalysisUsage(AnalysisUsage &AU) const {
  114. AU.setPreservesCFG();
  115. if (ShrinkWrapping || ShrinkWrapFunc != "") {
  116. AU.addRequired<MachineLoopInfo>();
  117. AU.addRequired<MachineDominatorTree>();
  118. }
  119. AU.addPreserved<MachineLoopInfo>();
  120. AU.addPreserved<MachineDominatorTree>();
  121. MachineFunctionPass::getAnalysisUsage(AU);
  122. }
  123. #endif
  124. /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack
  125. /// variables for the function's frame information and eliminate call frame
  126. /// pseudo instructions.
  127. void PEI::calculateCallsInformation(MachineFunction &Fn) {
  128. const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
  129. const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
  130. const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
  131. MachineFrameInfo *MFI = Fn.getFrameInfo();
  132. unsigned MaxCallFrameSize = 0;
  133. bool AdjustsStack = MFI->adjustsStack();
  134. // Get the function call frame set-up and tear-down instruction opcode
  135. int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  136. int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  137. // Early exit for targets which have no call frame setup/destroy pseudo
  138. // instructions.
  139. if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1)
  140. return;
  141. std::vector<MachineBasicBlock::iterator> FrameSDOps;
  142. for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB)
  143. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I)
  144. if (I->getOpcode() == FrameSetupOpcode ||
  145. I->getOpcode() == FrameDestroyOpcode) {
  146. assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo"
  147. " instructions should have a single immediate argument!");
  148. unsigned Size = I->getOperand(0).getImm();
  149. if (Size > MaxCallFrameSize) MaxCallFrameSize = Size;
  150. AdjustsStack = true;
  151. FrameSDOps.push_back(I);
  152. } else if (I->isInlineAsm()) {
  153. // Some inline asm's need a stack frame, as indicated by operand 1.
  154. unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  155. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  156. AdjustsStack = true;
  157. }
  158. MFI->setAdjustsStack(AdjustsStack);
  159. MFI->setMaxCallFrameSize(MaxCallFrameSize);
  160. for (std::vector<MachineBasicBlock::iterator>::iterator
  161. i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) {
  162. MachineBasicBlock::iterator I = *i;
  163. // If call frames are not being included as part of the stack frame, and
  164. // the target doesn't indicate otherwise, remove the call frame pseudos
  165. // here. The sub/add sp instruction pairs are still inserted, but we don't
  166. // need to track the SP adjustment for frame index elimination.
  167. if (TFI->canSimplifyCallFramePseudos(Fn))
  168. RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I);
  169. }
  170. }
  171. /// calculateCalleeSavedRegisters - Scan the function for modified callee saved
  172. /// registers.
  173. void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) {
  174. const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
  175. const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
  176. MachineFrameInfo *MFI = Fn.getFrameInfo();
  177. // Get the callee saved register list...
  178. const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn);
  179. // These are used to keep track the callee-save area. Initialize them.
  180. MinCSFrameIndex = INT_MAX;
  181. MaxCSFrameIndex = 0;
  182. // Early exit for targets which have no callee saved registers.
  183. if (CSRegs == 0 || CSRegs[0] == 0)
  184. return;
  185. // In Naked functions we aren't going to save any registers.
  186. if (Fn.getFunction()->hasFnAttr(Attribute::Naked))
  187. return;
  188. std::vector<CalleeSavedInfo> CSI;
  189. for (unsigned i = 0; CSRegs[i]; ++i) {
  190. unsigned Reg = CSRegs[i];
  191. if (Fn.getRegInfo().isPhysRegOrOverlapUsed(Reg)) {
  192. // If the reg is modified, save it!
  193. CSI.push_back(CalleeSavedInfo(Reg));
  194. }
  195. }
  196. if (CSI.empty())
  197. return; // Early exit if no callee saved registers are modified!
  198. unsigned NumFixedSpillSlots;
  199. const TargetFrameLowering::SpillSlot *FixedSpillSlots =
  200. TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
  201. // Now that we know which registers need to be saved and restored, allocate
  202. // stack slots for them.
  203. for (std::vector<CalleeSavedInfo>::iterator
  204. I = CSI.begin(), E = CSI.end(); I != E; ++I) {
  205. unsigned Reg = I->getReg();
  206. const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
  207. int FrameIdx;
  208. if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) {
  209. I->setFrameIdx(FrameIdx);
  210. continue;
  211. }
  212. // Check to see if this physreg must be spilled to a particular stack slot
  213. // on this target.
  214. const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
  215. while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots &&
  216. FixedSlot->Reg != Reg)
  217. ++FixedSlot;
  218. if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
  219. // Nope, just spill it anywhere convenient.
  220. unsigned Align = RC->getAlignment();
  221. unsigned StackAlign = TFI->getStackAlignment();
  222. // We may not be able to satisfy the desired alignment specification of
  223. // the TargetRegisterClass if the stack alignment is smaller. Use the
  224. // min.
  225. Align = std::min(Align, StackAlign);
  226. FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true);
  227. if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx;
  228. if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx;
  229. } else {
  230. // Spill it to the stack where we must.
  231. FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true);
  232. }
  233. I->setFrameIdx(FrameIdx);
  234. }
  235. MFI->setCalleeSavedInfo(CSI);
  236. }
  237. /// insertCSRSpillsAndRestores - Insert spill and restore code for
  238. /// callee saved registers used in the function, handling shrink wrapping.
  239. ///
  240. void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) {
  241. // Get callee saved register information.
  242. MachineFrameInfo *MFI = Fn.getFrameInfo();
  243. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  244. MFI->setCalleeSavedInfoValid(true);
  245. // Early exit if no callee saved registers are modified!
  246. if (CSI.empty())
  247. return;
  248. const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
  249. const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering();
  250. const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
  251. MachineBasicBlock::iterator I;
  252. if (! ShrinkWrapThisFunction) {
  253. // Spill using target interface.
  254. I = EntryBlock->begin();
  255. if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) {
  256. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  257. // Add the callee-saved register as live-in.
  258. // It's killed at the spill.
  259. EntryBlock->addLiveIn(CSI[i].getReg());
  260. // Insert the spill to the stack frame.
  261. unsigned Reg = CSI[i].getReg();
  262. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  263. TII.storeRegToStackSlot(*EntryBlock, I, Reg, true,
  264. CSI[i].getFrameIdx(), RC, TRI);
  265. }
  266. }
  267. // Restore using target interface.
  268. for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) {
  269. MachineBasicBlock* MBB = ReturnBlocks[ri];
  270. I = MBB->end(); --I;
  271. // Skip over all terminator instructions, which are part of the return
  272. // sequence.
  273. MachineBasicBlock::iterator I2 = I;
  274. while (I2 != MBB->begin() && (--I2)->isTerminator())
  275. I = I2;
  276. bool AtStart = I == MBB->begin();
  277. MachineBasicBlock::iterator BeforeI = I;
  278. if (!AtStart)
  279. --BeforeI;
  280. // Restore all registers immediately before the return and any
  281. // terminators that precede it.
  282. if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) {
  283. for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
  284. unsigned Reg = CSI[i].getReg();
  285. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  286. TII.loadRegFromStackSlot(*MBB, I, Reg,
  287. CSI[i].getFrameIdx(),
  288. RC, TRI);
  289. assert(I != MBB->begin() &&
  290. "loadRegFromStackSlot didn't insert any code!");
  291. // Insert in reverse order. loadRegFromStackSlot can insert
  292. // multiple instructions.
  293. if (AtStart)
  294. I = MBB->begin();
  295. else {
  296. I = BeforeI;
  297. ++I;
  298. }
  299. }
  300. }
  301. }
  302. return;
  303. }
  304. // Insert spills.
  305. std::vector<CalleeSavedInfo> blockCSI;
  306. for (CSRegBlockMap::iterator BI = CSRSave.begin(),
  307. BE = CSRSave.end(); BI != BE; ++BI) {
  308. MachineBasicBlock* MBB = BI->first;
  309. CSRegSet save = BI->second;
  310. if (save.empty())
  311. continue;
  312. blockCSI.clear();
  313. for (CSRegSet::iterator RI = save.begin(),
  314. RE = save.end(); RI != RE; ++RI) {
  315. blockCSI.push_back(CSI[*RI]);
  316. }
  317. assert(blockCSI.size() > 0 &&
  318. "Could not collect callee saved register info");
  319. I = MBB->begin();
  320. // When shrink wrapping, use stack slot stores/loads.
  321. for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
  322. // Add the callee-saved register as live-in.
  323. // It's killed at the spill.
  324. MBB->addLiveIn(blockCSI[i].getReg());
  325. // Insert the spill to the stack frame.
  326. unsigned Reg = blockCSI[i].getReg();
  327. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  328. TII.storeRegToStackSlot(*MBB, I, Reg,
  329. true,
  330. blockCSI[i].getFrameIdx(),
  331. RC, TRI);
  332. }
  333. }
  334. for (CSRegBlockMap::iterator BI = CSRRestore.begin(),
  335. BE = CSRRestore.end(); BI != BE; ++BI) {
  336. MachineBasicBlock* MBB = BI->first;
  337. CSRegSet restore = BI->second;
  338. if (restore.empty())
  339. continue;
  340. blockCSI.clear();
  341. for (CSRegSet::iterator RI = restore.begin(),
  342. RE = restore.end(); RI != RE; ++RI) {
  343. blockCSI.push_back(CSI[*RI]);
  344. }
  345. assert(blockCSI.size() > 0 &&
  346. "Could not find callee saved register info");
  347. // If MBB is empty and needs restores, insert at the _beginning_.
  348. if (MBB->empty()) {
  349. I = MBB->begin();
  350. } else {
  351. I = MBB->end();
  352. --I;
  353. // Skip over all terminator instructions, which are part of the
  354. // return sequence.
  355. if (! I->isTerminator()) {
  356. ++I;
  357. } else {
  358. MachineBasicBlock::iterator I2 = I;
  359. while (I2 != MBB->begin() && (--I2)->isTerminator())
  360. I = I2;
  361. }
  362. }
  363. bool AtStart = I == MBB->begin();
  364. MachineBasicBlock::iterator BeforeI = I;
  365. if (!AtStart)
  366. --BeforeI;
  367. // Restore all registers immediately before the return and any
  368. // terminators that precede it.
  369. for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) {
  370. unsigned Reg = blockCSI[i].getReg();
  371. const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
  372. TII.loadRegFromStackSlot(*MBB, I, Reg,
  373. blockCSI[i].getFrameIdx(),
  374. RC, TRI);
  375. assert(I != MBB->begin() &&
  376. "loadRegFromStackSlot didn't insert any code!");
  377. // Insert in reverse order. loadRegFromStackSlot can insert
  378. // multiple instructions.
  379. if (AtStart)
  380. I = MBB->begin();
  381. else {
  382. I = BeforeI;
  383. ++I;
  384. }
  385. }
  386. }
  387. }
  388. /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
  389. static inline void
  390. AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx,
  391. bool StackGrowsDown, int64_t &Offset,
  392. unsigned &MaxAlign) {
  393. // If the stack grows down, add the object size to find the lowest address.
  394. if (StackGrowsDown)
  395. Offset += MFI->getObjectSize(FrameIdx);
  396. unsigned Align = MFI->getObjectAlignment(FrameIdx);
  397. // If the alignment of this object is greater than that of the stack, then
  398. // increase the stack alignment to match.
  399. MaxAlign = std::max(MaxAlign, Align);
  400. // Adjust to alignment boundary.
  401. Offset = (Offset + Align - 1) / Align * Align;
  402. if (StackGrowsDown) {
  403. DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n");
  404. MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset
  405. } else {
  406. DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n");
  407. MFI->setObjectOffset(FrameIdx, Offset);
  408. Offset += MFI->getObjectSize(FrameIdx);
  409. }
  410. }
  411. /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
  412. /// abstract stack objects.
  413. ///
  414. void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) {
  415. const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
  416. bool StackGrowsDown =
  417. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  418. // Loop over all of the stack objects, assigning sequential addresses...
  419. MachineFrameInfo *MFI = Fn.getFrameInfo();
  420. // Start at the beginning of the local area.
  421. // The Offset is the distance from the stack top in the direction
  422. // of stack growth -- so it's always nonnegative.
  423. int LocalAreaOffset = TFI.getOffsetOfLocalArea();
  424. if (StackGrowsDown)
  425. LocalAreaOffset = -LocalAreaOffset;
  426. assert(LocalAreaOffset >= 0
  427. && "Local area offset should be in direction of stack growth");
  428. int64_t Offset = LocalAreaOffset;
  429. // If there are fixed sized objects that are preallocated in the local area,
  430. // non-fixed objects can't be allocated right at the start of local area.
  431. // We currently don't support filling in holes in between fixed sized
  432. // objects, so we adjust 'Offset' to point to the end of last fixed sized
  433. // preallocated object.
  434. for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) {
  435. int64_t FixedOff;
  436. if (StackGrowsDown) {
  437. // The maximum distance from the stack pointer is at lower address of
  438. // the object -- which is given by offset. For down growing stack
  439. // the offset is negative, so we negate the offset to get the distance.
  440. FixedOff = -MFI->getObjectOffset(i);
  441. } else {
  442. // The maximum distance from the start pointer is at the upper
  443. // address of the object.
  444. FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i);
  445. }
  446. if (FixedOff > Offset) Offset = FixedOff;
  447. }
  448. // First assign frame offsets to stack objects that are used to spill
  449. // callee saved registers.
  450. if (StackGrowsDown) {
  451. for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) {
  452. // If the stack grows down, we need to add the size to find the lowest
  453. // address of the object.
  454. Offset += MFI->getObjectSize(i);
  455. unsigned Align = MFI->getObjectAlignment(i);
  456. // Adjust to alignment boundary
  457. Offset = (Offset+Align-1)/Align*Align;
  458. MFI->setObjectOffset(i, -Offset); // Set the computed offset
  459. }
  460. } else {
  461. int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex;
  462. for (int i = MaxCSFI; i >= MinCSFI ; --i) {
  463. unsigned Align = MFI->getObjectAlignment(i);
  464. // Adjust to alignment boundary
  465. Offset = (Offset+Align-1)/Align*Align;
  466. MFI->setObjectOffset(i, Offset);
  467. Offset += MFI->getObjectSize(i);
  468. }
  469. }
  470. unsigned MaxAlign = MFI->getMaxAlignment();
  471. // Make sure the special register scavenging spill slot is closest to the
  472. // frame pointer if a frame pointer is required.
  473. const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo();
  474. if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) &&
  475. !RegInfo->needsStackRealignment(Fn)) {
  476. int SFI = RS->getScavengingFrameIndex();
  477. if (SFI >= 0)
  478. AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
  479. }
  480. // FIXME: Once this is working, then enable flag will change to a target
  481. // check for whether the frame is large enough to want to use virtual
  482. // frame index registers. Functions which don't want/need this optimization
  483. // will continue to use the existing code path.
  484. if (MFI->getUseLocalStackAllocationBlock()) {
  485. unsigned Align = MFI->getLocalFrameMaxAlign();
  486. // Adjust to alignment boundary.
  487. Offset = (Offset + Align - 1) / Align * Align;
  488. DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
  489. // Resolve offsets for objects in the local block.
  490. for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) {
  491. std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i);
  492. int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
  493. DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" <<
  494. FIOffset << "]\n");
  495. MFI->setObjectOffset(Entry.first, FIOffset);
  496. }
  497. // Allocate the local block
  498. Offset += MFI->getLocalFrameSize();
  499. MaxAlign = std::max(Align, MaxAlign);
  500. }
  501. // Make sure that the stack protector comes before the local variables on the
  502. // stack.
  503. SmallSet<int, 16> LargeStackObjs;
  504. if (MFI->getStackProtectorIndex() >= 0) {
  505. AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown,
  506. Offset, MaxAlign);
  507. // Assign large stack objects first.
  508. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  509. if (MFI->isObjectPreAllocated(i) &&
  510. MFI->getUseLocalStackAllocationBlock())
  511. continue;
  512. if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
  513. continue;
  514. if (RS && (int)i == RS->getScavengingFrameIndex())
  515. continue;
  516. if (MFI->isDeadObjectIndex(i))
  517. continue;
  518. if (MFI->getStackProtectorIndex() == (int)i)
  519. continue;
  520. if (!MFI->MayNeedStackProtector(i))
  521. continue;
  522. AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
  523. LargeStackObjs.insert(i);
  524. }
  525. }
  526. // Then assign frame offsets to stack objects that are not used to spill
  527. // callee saved registers.
  528. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  529. if (MFI->isObjectPreAllocated(i) &&
  530. MFI->getUseLocalStackAllocationBlock())
  531. continue;
  532. if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex)
  533. continue;
  534. if (RS && (int)i == RS->getScavengingFrameIndex())
  535. continue;
  536. if (MFI->isDeadObjectIndex(i))
  537. continue;
  538. if (MFI->getStackProtectorIndex() == (int)i)
  539. continue;
  540. if (LargeStackObjs.count(i))
  541. continue;
  542. AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
  543. }
  544. // Make sure the special register scavenging spill slot is closest to the
  545. // stack pointer.
  546. if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) ||
  547. !RegInfo->useFPForScavengingIndex(Fn))) {
  548. int SFI = RS->getScavengingFrameIndex();
  549. if (SFI >= 0)
  550. AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
  551. }
  552. if (!TFI.targetHandlesStackFrameRounding()) {
  553. // If we have reserved argument space for call sites in the function
  554. // immediately on entry to the current function, count it as part of the
  555. // overall stack size.
  556. if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn))
  557. Offset += MFI->getMaxCallFrameSize();
  558. // Round up the size to a multiple of the alignment. If the function has
  559. // any calls or alloca's, align to the target's StackAlignment value to
  560. // ensure that the callee's frame or the alloca data is suitably aligned;
  561. // otherwise, for leaf functions, align to the TransientStackAlignment
  562. // value.
  563. unsigned StackAlign;
  564. if (MFI->adjustsStack() || MFI->hasVarSizedObjects() ||
  565. (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0))
  566. StackAlign = TFI.getStackAlignment();
  567. else
  568. StackAlign = TFI.getTransientStackAlignment();
  569. // If the frame pointer is eliminated, all frame offsets will be relative to
  570. // SP not FP. Align to MaxAlign so this works.
  571. StackAlign = std::max(StackAlign, MaxAlign);
  572. unsigned AlignMask = StackAlign - 1;
  573. Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
  574. }
  575. // Update frame info to pretend that this is part of the stack...
  576. int64_t StackSize = Offset - LocalAreaOffset;
  577. MFI->setStackSize(StackSize);
  578. NumBytesStackSpace += StackSize;
  579. }
  580. /// insertPrologEpilogCode - Scan the function for modified callee saved
  581. /// registers, insert spill code for these callee saved registers, then add
  582. /// prolog and epilog code to the function.
  583. ///
  584. void PEI::insertPrologEpilogCode(MachineFunction &Fn) {
  585. const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
  586. // Add prologue to the function...
  587. TFI.emitPrologue(Fn);
  588. // Add epilogue to restore the callee-save registers in each exiting block
  589. for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
  590. // If last instruction is a return instruction, add an epilogue
  591. if (!I->empty() && I->back().isReturn())
  592. TFI.emitEpilogue(Fn, *I);
  593. }
  594. // Emit additional code that is required to support segmented stacks, if
  595. // we've been asked for it. This, when linked with a runtime with support
  596. // for segmented stacks (libgcc is one), will result in allocating stack
  597. // space in small chunks instead of one large contiguous block.
  598. if (Fn.getTarget().Options.EnableSegmentedStacks)
  599. TFI.adjustForSegmentedStacks(Fn);
  600. }
  601. /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
  602. /// register references and actual offsets.
  603. ///
  604. void PEI::replaceFrameIndices(MachineFunction &Fn) {
  605. if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do?
  606. const TargetMachine &TM = Fn.getTarget();
  607. assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!");
  608. const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo();
  609. const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
  610. const TargetFrameLowering *TFI = TM.getFrameLowering();
  611. bool StackGrowsDown =
  612. TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  613. int FrameSetupOpcode = TII.getCallFrameSetupOpcode();
  614. int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
  615. for (MachineFunction::iterator BB = Fn.begin(),
  616. E = Fn.end(); BB != E; ++BB) {
  617. #ifndef NDEBUG
  618. int SPAdjCount = 0; // frame setup / destroy count.
  619. #endif
  620. int SPAdj = 0; // SP offset due to call frame setup / destroy.
  621. if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB);
  622. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
  623. if (I->getOpcode() == FrameSetupOpcode ||
  624. I->getOpcode() == FrameDestroyOpcode) {
  625. #ifndef NDEBUG
  626. // Track whether we see even pairs of them
  627. SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1;
  628. #endif
  629. // Remember how much SP has been adjusted to create the call
  630. // frame.
  631. int Size = I->getOperand(0).getImm();
  632. if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) ||
  633. (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode))
  634. Size = -Size;
  635. SPAdj += Size;
  636. MachineBasicBlock::iterator PrevI = BB->end();
  637. if (I != BB->begin()) PrevI = prior(I);
  638. TRI.eliminateCallFramePseudoInstr(Fn, *BB, I);
  639. // Visit the instructions created by eliminateCallFramePseudoInstr().
  640. if (PrevI == BB->end())
  641. I = BB->begin(); // The replaced instr was the first in the block.
  642. else
  643. I = llvm::next(PrevI);
  644. continue;
  645. }
  646. MachineInstr *MI = I;
  647. bool DoIncr = true;
  648. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
  649. if (MI->getOperand(i).isFI()) {
  650. // Some instructions (e.g. inline asm instructions) can have
  651. // multiple frame indices and/or cause eliminateFrameIndex
  652. // to insert more than one instruction. We need the register
  653. // scavenger to go through all of these instructions so that
  654. // it can update its register information. We keep the
  655. // iterator at the point before insertion so that we can
  656. // revisit them in full.
  657. bool AtBeginning = (I == BB->begin());
  658. if (!AtBeginning) --I;
  659. // If this instruction has a FrameIndex operand, we need to
  660. // use that target machine register info object to eliminate
  661. // it.
  662. TRI.eliminateFrameIndex(MI, SPAdj,
  663. FrameIndexVirtualScavenging ? NULL : RS);
  664. // Reset the iterator if we were at the beginning of the BB.
  665. if (AtBeginning) {
  666. I = BB->begin();
  667. DoIncr = false;
  668. }
  669. MI = 0;
  670. break;
  671. }
  672. if (DoIncr && I != BB->end()) ++I;
  673. // Update register states.
  674. if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI);
  675. }
  676. // If we have evenly matched pairs of frame setup / destroy instructions,
  677. // make sure the adjustments come out to zero. If we don't have matched
  678. // pairs, we can't be sure the missing bit isn't in another basic block
  679. // due to a custom inserter playing tricks, so just asserting SPAdj==0
  680. // isn't sufficient. See tMOVCC on Thumb1, for example.
  681. assert((SPAdjCount || SPAdj == 0) &&
  682. "Unbalanced call frame setup / destroy pairs?");
  683. }
  684. }
  685. /// scavengeFrameVirtualRegs - Replace all frame index virtual registers
  686. /// with physical registers. Use the register scavenger to find an
  687. /// appropriate register to use.
  688. void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) {
  689. // Run through the instructions and find any virtual registers.
  690. for (MachineFunction::iterator BB = Fn.begin(),
  691. E = Fn.end(); BB != E; ++BB) {
  692. RS->enterBasicBlock(BB);
  693. unsigned VirtReg = 0;
  694. unsigned ScratchReg = 0;
  695. int SPAdj = 0;
  696. // The instruction stream may change in the loop, so check BB->end()
  697. // directly.
  698. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
  699. MachineInstr *MI = I;
  700. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  701. if (MI->getOperand(i).isReg()) {
  702. MachineOperand &MO = MI->getOperand(i);
  703. unsigned Reg = MO.getReg();
  704. if (Reg == 0)
  705. continue;
  706. if (!TargetRegisterInfo::isVirtualRegister(Reg))
  707. continue;
  708. ++NumVirtualFrameRegs;
  709. // Have we already allocated a scratch register for this virtual?
  710. if (Reg != VirtReg) {
  711. // When we first encounter a new virtual register, it
  712. // must be a definition.
  713. assert(MI->getOperand(i).isDef() &&
  714. "frame index virtual missing def!");
  715. // Scavenge a new scratch register
  716. VirtReg = Reg;
  717. const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg);
  718. ScratchReg = RS->scavengeRegister(RC, I, SPAdj);
  719. ++NumScavengedRegs;
  720. }
  721. // Replace this reference to the virtual register with the
  722. // scratch register.
  723. assert (ScratchReg && "Missing scratch register!");
  724. MI->getOperand(i).setReg(ScratchReg);
  725. }
  726. }
  727. RS->forward(I);
  728. ++I;
  729. }
  730. }
  731. }