LocalStackSlotAllocation.cpp 17 KB

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