LocalStackSlotAllocation.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
  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 assigns local frame indices to stack slots relative to one another
  11. // and allocates additional base registers to access them when the target
  12. // estimates they are likely to be out of range of stack pointer and frame
  13. // pointer relative addressing.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #define DEBUG_TYPE "localstackalloc"
  17. #include "llvm/Constants.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/Intrinsics.h"
  21. #include "llvm/LLVMContext.h"
  22. #include "llvm/Module.h"
  23. #include "llvm/Pass.h"
  24. #include "llvm/ADT/SmallSet.h"
  25. #include "llvm/ADT/Statistic.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/CodeGen/MachineFrameInfo.h"
  28. #include "llvm/CodeGen/MachineFunction.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/MachineRegisterInfo.h"
  31. #include "llvm/CodeGen/Passes.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Target/TargetRegisterInfo.h"
  36. #include "llvm/Target/TargetFrameLowering.h"
  37. using namespace llvm;
  38. STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
  39. STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
  40. STATISTIC(NumReplacements, "Number of frame indices references replaced");
  41. namespace {
  42. class FrameRef {
  43. MachineBasicBlock::iterator MI; // Instr referencing the frame
  44. int64_t LocalOffset; // Local offset of the frame idx referenced
  45. public:
  46. FrameRef(MachineBasicBlock::iterator I, int64_t Offset) :
  47. MI(I), LocalOffset(Offset) {}
  48. bool operator<(const FrameRef &RHS) const {
  49. return LocalOffset < RHS.LocalOffset;
  50. }
  51. MachineBasicBlock::iterator getMachineInstr() { return MI; }
  52. };
  53. class LocalStackSlotPass: public MachineFunctionPass {
  54. SmallVector<int64_t,16> LocalOffsets;
  55. void AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx, int64_t &Offset,
  56. bool StackGrowsDown, unsigned &MaxAlign);
  57. void calculateFrameObjectOffsets(MachineFunction &Fn);
  58. bool insertFrameReferenceRegisters(MachineFunction &Fn);
  59. public:
  60. static char ID; // Pass identification, replacement for typeid
  61. explicit LocalStackSlotPass() : MachineFunctionPass(ID) { }
  62. bool runOnMachineFunction(MachineFunction &MF);
  63. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  64. AU.setPreservesCFG();
  65. MachineFunctionPass::getAnalysisUsage(AU);
  66. }
  67. private:
  68. };
  69. } // end anonymous namespace
  70. char LocalStackSlotPass::ID = 0;
  71. char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
  72. INITIALIZE_PASS(LocalStackSlotPass, "localstackalloc",
  73. "Local Stack Slot Allocation", false, false)
  74. bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
  75. MachineFrameInfo *MFI = MF.getFrameInfo();
  76. const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
  77. unsigned LocalObjectCount = MFI->getObjectIndexEnd();
  78. // If the target doesn't want/need this pass, or if there are no locals
  79. // to consider, early exit.
  80. if (!TRI->requiresVirtualBaseRegisters(MF) || LocalObjectCount == 0)
  81. return true;
  82. // Make sure we have enough space to store the local offsets.
  83. LocalOffsets.resize(MFI->getObjectIndexEnd());
  84. // Lay out the local blob.
  85. calculateFrameObjectOffsets(MF);
  86. // Insert virtual base registers to resolve frame index references.
  87. bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
  88. // Tell MFI whether any base registers were allocated. PEI will only
  89. // want to use the local block allocations from this pass if there were any.
  90. // Otherwise, PEI can do a bit better job of getting the alignment right
  91. // without a hole at the start since it knows the alignment of the stack
  92. // at the start of local allocation, and this pass doesn't.
  93. MFI->setUseLocalStackAllocationBlock(UsedBaseRegs);
  94. return true;
  95. }
  96. /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
  97. void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo *MFI,
  98. int FrameIdx, int64_t &Offset,
  99. bool StackGrowsDown,
  100. unsigned &MaxAlign) {
  101. // If the stack grows down, add the object size to find the lowest address.
  102. if (StackGrowsDown)
  103. Offset += MFI->getObjectSize(FrameIdx);
  104. unsigned Align = MFI->getObjectAlignment(FrameIdx);
  105. // If the alignment of this object is greater than that of the stack, then
  106. // increase the stack alignment to match.
  107. MaxAlign = std::max(MaxAlign, Align);
  108. // Adjust to alignment boundary.
  109. Offset = (Offset + Align - 1) / Align * Align;
  110. int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
  111. DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
  112. << LocalOffset << "\n");
  113. // Keep the offset available for base register allocation
  114. LocalOffsets[FrameIdx] = LocalOffset;
  115. // And tell MFI about it for PEI to use later
  116. MFI->mapLocalFrameObject(FrameIdx, LocalOffset);
  117. if (!StackGrowsDown)
  118. Offset += MFI->getObjectSize(FrameIdx);
  119. ++NumAllocations;
  120. }
  121. /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
  122. /// abstract stack objects.
  123. ///
  124. void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
  125. // Loop over all of the stack objects, assigning sequential addresses...
  126. MachineFrameInfo *MFI = Fn.getFrameInfo();
  127. const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
  128. bool StackGrowsDown =
  129. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  130. int64_t Offset = 0;
  131. unsigned MaxAlign = 0;
  132. // Make sure that the stack protector comes before the local variables on the
  133. // stack.
  134. SmallSet<int, 16> LargeStackObjs;
  135. if (MFI->getStackProtectorIndex() >= 0) {
  136. AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), Offset,
  137. StackGrowsDown, MaxAlign);
  138. // Assign large stack objects first.
  139. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  140. if (MFI->isDeadObjectIndex(i))
  141. continue;
  142. if (MFI->getStackProtectorIndex() == (int)i)
  143. continue;
  144. if (!MFI->MayNeedStackProtector(i))
  145. continue;
  146. AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
  147. LargeStackObjs.insert(i);
  148. }
  149. }
  150. // Then assign frame offsets to stack objects that are not used to spill
  151. // callee saved registers.
  152. for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) {
  153. if (MFI->isDeadObjectIndex(i))
  154. continue;
  155. if (MFI->getStackProtectorIndex() == (int)i)
  156. continue;
  157. if (LargeStackObjs.count(i))
  158. continue;
  159. AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
  160. }
  161. // Remember how big this blob of stack space is
  162. MFI->setLocalFrameSize(Offset);
  163. MFI->setLocalFrameMaxAlign(MaxAlign);
  164. }
  165. static inline bool
  166. lookupCandidateBaseReg(const SmallVector<std::pair<unsigned, int64_t>, 8> &Regs,
  167. std::pair<unsigned, int64_t> &RegOffset,
  168. int64_t FrameSizeAdjust,
  169. int64_t LocalFrameOffset,
  170. const MachineInstr *MI,
  171. const TargetRegisterInfo *TRI) {
  172. unsigned e = Regs.size();
  173. for (unsigned i = 0; i < e; ++i) {
  174. RegOffset = Regs[i];
  175. // Check if the relative offset from the where the base register references
  176. // to the target address is in range for the instruction.
  177. int64_t Offset = FrameSizeAdjust + LocalFrameOffset - RegOffset.second;
  178. if (TRI->isFrameOffsetLegal(MI, Offset))
  179. return true;
  180. }
  181. return false;
  182. }
  183. bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
  184. // Scan the function's instructions looking for frame index references.
  185. // For each, ask the target if it wants a virtual base register for it
  186. // based on what we can tell it about where the local will end up in the
  187. // stack frame. If it wants one, re-use a suitable one we've previously
  188. // allocated, or if there isn't one that fits the bill, allocate a new one
  189. // and ask the target to create a defining instruction for it.
  190. bool UsedBaseReg = false;
  191. MachineFrameInfo *MFI = Fn.getFrameInfo();
  192. const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo();
  193. const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering();
  194. bool StackGrowsDown =
  195. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  196. // Collect all of the instructions in the block that reference
  197. // a frame index. Also store the frame index referenced to ease later
  198. // lookup. (For any insn that has more than one FI reference, we arbitrarily
  199. // choose the first one).
  200. SmallVector<FrameRef, 64> FrameReferenceInsns;
  201. // A base register definition is a register + offset pair.
  202. SmallVector<std::pair<unsigned, int64_t>, 8> BaseRegisters;
  203. for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
  204. for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
  205. MachineInstr *MI = I;
  206. // Debug value instructions can't be out of range, so they don't need
  207. // any updates.
  208. if (MI->isDebugValue())
  209. continue;
  210. // For now, allocate the base register(s) within the basic block
  211. // where they're used, and don't try to keep them around outside
  212. // of that. It may be beneficial to try sharing them more broadly
  213. // than that, but the increased register pressure makes that a
  214. // tricky thing to balance. Investigate if re-materializing these
  215. // becomes an issue.
  216. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  217. // Consider replacing all frame index operands that reference
  218. // an object allocated in the local block.
  219. if (MI->getOperand(i).isFI()) {
  220. // Don't try this with values not in the local block.
  221. if (!MFI->isObjectPreAllocated(MI->getOperand(i).getIndex()))
  222. break;
  223. FrameReferenceInsns.
  224. push_back(FrameRef(MI, LocalOffsets[MI->getOperand(i).getIndex()]));
  225. break;
  226. }
  227. }
  228. }
  229. }
  230. // Sort the frame references by local offset
  231. array_pod_sort(FrameReferenceInsns.begin(), FrameReferenceInsns.end());
  232. MachineBasicBlock *Entry = Fn.begin();
  233. // Loop through the frame references and allocate for them as necessary.
  234. for (int ref = 0, e = FrameReferenceInsns.size(); ref < e ; ++ref) {
  235. MachineBasicBlock::iterator I =
  236. FrameReferenceInsns[ref].getMachineInstr();
  237. MachineInstr *MI = I;
  238. for (unsigned idx = 0, e = MI->getNumOperands(); idx != e; ++idx) {
  239. // Consider replacing all frame index operands that reference
  240. // an object allocated in the local block.
  241. if (MI->getOperand(idx).isFI()) {
  242. int FrameIdx = MI->getOperand(idx).getIndex();
  243. assert(MFI->isObjectPreAllocated(FrameIdx) &&
  244. "Only pre-allocated locals expected!");
  245. DEBUG(dbgs() << "Considering: " << *MI);
  246. if (TRI->needsFrameBaseReg(MI, LocalOffsets[FrameIdx])) {
  247. unsigned BaseReg = 0;
  248. int64_t Offset = 0;
  249. int64_t FrameSizeAdjust =
  250. StackGrowsDown ? MFI->getLocalFrameSize() : 0;
  251. DEBUG(dbgs() << " Replacing FI in: " << *MI);
  252. // If we have a suitable base register available, use it; otherwise
  253. // create a new one. Note that any offset encoded in the
  254. // instruction itself will be taken into account by the target,
  255. // so we don't have to adjust for it here when reusing a base
  256. // register.
  257. std::pair<unsigned, int64_t> RegOffset;
  258. if (lookupCandidateBaseReg(BaseRegisters, RegOffset,
  259. FrameSizeAdjust,
  260. LocalOffsets[FrameIdx],
  261. MI, TRI)) {
  262. DEBUG(dbgs() << " Reusing base register " <<
  263. RegOffset.first << "\n");
  264. // We found a register to reuse.
  265. BaseReg = RegOffset.first;
  266. Offset = FrameSizeAdjust + LocalOffsets[FrameIdx] -
  267. RegOffset.second;
  268. } else {
  269. // No previously defined register was in range, so create a
  270. // new one.
  271. int64_t InstrOffset = TRI->getFrameIndexInstrOffset(MI, idx);
  272. const TargetRegisterClass *RC = TRI->getPointerRegClass();
  273. BaseReg = Fn.getRegInfo().createVirtualRegister(RC);
  274. DEBUG(dbgs() << " Materializing base register " << BaseReg <<
  275. " at frame local offset " <<
  276. LocalOffsets[FrameIdx] + InstrOffset << "\n");
  277. // Tell the target to insert the instruction to initialize
  278. // the base register.
  279. // MachineBasicBlock::iterator InsertionPt = Entry->begin();
  280. TRI->materializeFrameBaseRegister(Entry, BaseReg, FrameIdx,
  281. InstrOffset);
  282. // The base register already includes any offset specified
  283. // by the instruction, so account for that so it doesn't get
  284. // applied twice.
  285. Offset = -InstrOffset;
  286. int64_t BaseOffset = FrameSizeAdjust + LocalOffsets[FrameIdx] +
  287. InstrOffset;
  288. BaseRegisters.push_back(
  289. std::pair<unsigned, int64_t>(BaseReg, BaseOffset));
  290. ++NumBaseRegisters;
  291. UsedBaseReg = true;
  292. }
  293. assert(BaseReg != 0 && "Unable to allocate virtual base register!");
  294. // Modify the instruction to use the new base register rather
  295. // than the frame index operand.
  296. TRI->resolveFrameIndex(I, BaseReg, Offset);
  297. DEBUG(dbgs() << "Resolved: " << *MI);
  298. ++NumReplacements;
  299. }
  300. }
  301. }
  302. }
  303. return UsedBaseReg;
  304. }