LocalStackSlotAllocation.cpp 17 KB

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