PrologEpilogInserter.cpp 32 KB

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