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