LocalStackSlotAllocation.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. //===- LocalStackSlotAllocation.cpp - Pre-allocate locals to stack slots --===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass assigns local frame indices to stack slots relative to one another
  10. // and allocates additional base registers to access them when the target
  11. // estimates they are likely to be out of range of stack pointer and frame
  12. // pointer relative addressing.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/CodeGen/MachineBasicBlock.h"
  20. #include "llvm/CodeGen/MachineFrameInfo.h"
  21. #include "llvm/CodeGen/MachineFunction.h"
  22. #include "llvm/CodeGen/MachineFunctionPass.h"
  23. #include "llvm/CodeGen/MachineInstr.h"
  24. #include "llvm/CodeGen/MachineOperand.h"
  25. #include "llvm/CodeGen/MachineRegisterInfo.h"
  26. #include "llvm/CodeGen/TargetFrameLowering.h"
  27. #include "llvm/CodeGen/TargetOpcodes.h"
  28. #include "llvm/CodeGen/TargetRegisterInfo.h"
  29. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  30. #include "llvm/Pass.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <algorithm>
  35. #include <cassert>
  36. #include <cstdint>
  37. #include <tuple>
  38. using namespace llvm;
  39. #define DEBUG_TYPE "localstackalloc"
  40. STATISTIC(NumAllocations, "Number of frame indices allocated into local block");
  41. STATISTIC(NumBaseRegisters, "Number of virtual frame base registers allocated");
  42. STATISTIC(NumReplacements, "Number of frame indices references replaced");
  43. namespace {
  44. class FrameRef {
  45. MachineBasicBlock::iterator MI; // Instr referencing the frame
  46. int64_t LocalOffset; // Local offset of the frame idx referenced
  47. int FrameIdx; // The frame index
  48. // Order reference instruction appears in program. Used to ensure
  49. // deterministic order when multiple instructions may reference the same
  50. // location.
  51. unsigned Order;
  52. public:
  53. FrameRef(MachineInstr *I, int64_t Offset, int Idx, unsigned Ord) :
  54. MI(I), LocalOffset(Offset), FrameIdx(Idx), Order(Ord) {}
  55. bool operator<(const FrameRef &RHS) const {
  56. return std::tie(LocalOffset, FrameIdx, Order) <
  57. std::tie(RHS.LocalOffset, RHS.FrameIdx, RHS.Order);
  58. }
  59. MachineBasicBlock::iterator getMachineInstr() const { return MI; }
  60. int64_t getLocalOffset() const { return LocalOffset; }
  61. int getFrameIndex() const { return FrameIdx; }
  62. };
  63. class LocalStackSlotPass: public MachineFunctionPass {
  64. SmallVector<int64_t, 16> LocalOffsets;
  65. /// StackObjSet - A set of stack object indexes
  66. using StackObjSet = SmallSetVector<int, 8>;
  67. void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, int64_t &Offset,
  68. bool StackGrowsDown, unsigned &MaxAlign);
  69. void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
  70. SmallSet<int, 16> &ProtectedObjs,
  71. MachineFrameInfo &MFI, bool StackGrowsDown,
  72. int64_t &Offset, unsigned &MaxAlign);
  73. void calculateFrameObjectOffsets(MachineFunction &Fn);
  74. bool insertFrameReferenceRegisters(MachineFunction &Fn);
  75. public:
  76. static char ID; // Pass identification, replacement for typeid
  77. explicit LocalStackSlotPass() : MachineFunctionPass(ID) {
  78. initializeLocalStackSlotPassPass(*PassRegistry::getPassRegistry());
  79. }
  80. bool runOnMachineFunction(MachineFunction &MF) override;
  81. void getAnalysisUsage(AnalysisUsage &AU) const override {
  82. AU.setPreservesCFG();
  83. MachineFunctionPass::getAnalysisUsage(AU);
  84. }
  85. };
  86. } // end anonymous namespace
  87. char LocalStackSlotPass::ID = 0;
  88. char &llvm::LocalStackSlotAllocationID = LocalStackSlotPass::ID;
  89. INITIALIZE_PASS(LocalStackSlotPass, DEBUG_TYPE,
  90. "Local Stack Slot Allocation", false, false)
  91. bool LocalStackSlotPass::runOnMachineFunction(MachineFunction &MF) {
  92. MachineFrameInfo &MFI = MF.getFrameInfo();
  93. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  94. unsigned LocalObjectCount = MFI.getObjectIndexEnd();
  95. // If the target doesn't want/need this pass, or if there are no locals
  96. // to consider, early exit.
  97. if (!TRI->requiresVirtualBaseRegisters(MF) || LocalObjectCount == 0)
  98. return true;
  99. // Make sure we have enough space to store the local offsets.
  100. LocalOffsets.resize(MFI.getObjectIndexEnd());
  101. // Lay out the local blob.
  102. calculateFrameObjectOffsets(MF);
  103. // Insert virtual base registers to resolve frame index references.
  104. bool UsedBaseRegs = insertFrameReferenceRegisters(MF);
  105. // Tell MFI whether any base registers were allocated. PEI will only
  106. // want to use the local block allocations from this pass if there were any.
  107. // Otherwise, PEI can do a bit better job of getting the alignment right
  108. // without a hole at the start since it knows the alignment of the stack
  109. // at the start of local allocation, and this pass doesn't.
  110. MFI.setUseLocalStackAllocationBlock(UsedBaseRegs);
  111. return true;
  112. }
  113. /// AdjustStackOffset - Helper function used to adjust the stack frame offset.
  114. void LocalStackSlotPass::AdjustStackOffset(MachineFrameInfo &MFI,
  115. int FrameIdx, int64_t &Offset,
  116. bool StackGrowsDown,
  117. unsigned &MaxAlign) {
  118. // If the stack grows down, add the object size to find the lowest address.
  119. if (StackGrowsDown)
  120. Offset += MFI.getObjectSize(FrameIdx);
  121. unsigned Align = MFI.getObjectAlignment(FrameIdx);
  122. // If the alignment of this object is greater than that of the stack, then
  123. // increase the stack alignment to match.
  124. MaxAlign = std::max(MaxAlign, Align);
  125. // Adjust to alignment boundary.
  126. Offset = (Offset + Align - 1) / Align * Align;
  127. int64_t LocalOffset = StackGrowsDown ? -Offset : Offset;
  128. LLVM_DEBUG(dbgs() << "Allocate FI(" << FrameIdx << ") to local offset "
  129. << LocalOffset << "\n");
  130. // Keep the offset available for base register allocation
  131. LocalOffsets[FrameIdx] = LocalOffset;
  132. // And tell MFI about it for PEI to use later
  133. MFI.mapLocalFrameObject(FrameIdx, LocalOffset);
  134. if (!StackGrowsDown)
  135. Offset += MFI.getObjectSize(FrameIdx);
  136. ++NumAllocations;
  137. }
  138. /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
  139. /// those required to be close to the Stack Protector) to stack offsets.
  140. void LocalStackSlotPass::AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
  141. SmallSet<int, 16> &ProtectedObjs,
  142. MachineFrameInfo &MFI,
  143. bool StackGrowsDown, int64_t &Offset,
  144. unsigned &MaxAlign) {
  145. for (StackObjSet::const_iterator I = UnassignedObjs.begin(),
  146. E = UnassignedObjs.end(); I != E; ++I) {
  147. int i = *I;
  148. AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
  149. ProtectedObjs.insert(i);
  150. }
  151. }
  152. /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
  153. /// abstract stack objects.
  154. void LocalStackSlotPass::calculateFrameObjectOffsets(MachineFunction &Fn) {
  155. // Loop over all of the stack objects, assigning sequential addresses...
  156. MachineFrameInfo &MFI = Fn.getFrameInfo();
  157. const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering();
  158. bool StackGrowsDown =
  159. TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
  160. int64_t Offset = 0;
  161. unsigned MaxAlign = 0;
  162. // Make sure that the stack protector comes before the local variables on the
  163. // stack.
  164. SmallSet<int, 16> ProtectedObjs;
  165. if (MFI.hasStackProtectorIndex()) {
  166. int StackProtectorFI = MFI.getStackProtectorIndex();
  167. // We need to make sure we didn't pre-allocate the stack protector when
  168. // doing this.
  169. // If we already have a stack protector, this will re-assign it to a slot
  170. // that is **not** covering the protected objects.
  171. assert(!MFI.isObjectPreAllocated(StackProtectorFI) &&
  172. "Stack protector pre-allocated in LocalStackSlotAllocation");
  173. StackObjSet LargeArrayObjs;
  174. StackObjSet SmallArrayObjs;
  175. StackObjSet AddrOfObjs;
  176. AdjustStackOffset(MFI, StackProtectorFI, Offset, StackGrowsDown, MaxAlign);
  177. // Assign large stack objects first.
  178. for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
  179. if (MFI.isDeadObjectIndex(i))
  180. continue;
  181. if (StackProtectorFI == (int)i)
  182. continue;
  183. switch (MFI.getObjectSSPLayout(i)) {
  184. case MachineFrameInfo::SSPLK_None:
  185. continue;
  186. case MachineFrameInfo::SSPLK_SmallArray:
  187. SmallArrayObjs.insert(i);
  188. continue;
  189. case MachineFrameInfo::SSPLK_AddrOf:
  190. AddrOfObjs.insert(i);
  191. continue;
  192. case MachineFrameInfo::SSPLK_LargeArray:
  193. LargeArrayObjs.insert(i);
  194. continue;
  195. }
  196. llvm_unreachable("Unexpected SSPLayoutKind.");
  197. }
  198. AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
  199. Offset, MaxAlign);
  200. AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
  201. Offset, MaxAlign);
  202. AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
  203. Offset, MaxAlign);
  204. }
  205. // Then assign frame offsets to stack objects that are not used to spill
  206. // callee saved registers.
  207. for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
  208. if (MFI.isDeadObjectIndex(i))
  209. continue;
  210. if (MFI.getStackProtectorIndex() == (int)i)
  211. continue;
  212. if (ProtectedObjs.count(i))
  213. continue;
  214. AdjustStackOffset(MFI, i, Offset, StackGrowsDown, MaxAlign);
  215. }
  216. // Remember how big this blob of stack space is
  217. MFI.setLocalFrameSize(Offset);
  218. MFI.setLocalFrameMaxAlign(assumeAligned(MaxAlign));
  219. }
  220. static inline bool
  221. lookupCandidateBaseReg(unsigned BaseReg,
  222. int64_t BaseOffset,
  223. int64_t FrameSizeAdjust,
  224. int64_t LocalFrameOffset,
  225. const MachineInstr &MI,
  226. const TargetRegisterInfo *TRI) {
  227. // Check if the relative offset from the where the base register references
  228. // to the target address is in range for the instruction.
  229. int64_t Offset = FrameSizeAdjust + LocalFrameOffset - BaseOffset;
  230. return TRI->isFrameOffsetLegal(&MI, BaseReg, Offset);
  231. }
  232. bool LocalStackSlotPass::insertFrameReferenceRegisters(MachineFunction &Fn) {
  233. // Scan the function's instructions looking for frame index references.
  234. // For each, ask the target if it wants a virtual base register for it
  235. // based on what we can tell it about where the local will end up in the
  236. // stack frame. If it wants one, re-use a suitable one we've previously
  237. // allocated, or if there isn't one that fits the bill, allocate a new one
  238. // and ask the target to create a defining instruction for it.
  239. bool UsedBaseReg = false;
  240. MachineFrameInfo &MFI = Fn.getFrameInfo();
  241. const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo();
  242. const TargetFrameLowering &TFI = *Fn.getSubtarget().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. unsigned Order = 0;
  251. for (MachineBasicBlock &BB : Fn) {
  252. for (MachineInstr &MI : BB) {
  253. // Debug value, stackmap and patchpoint instructions can't be out of
  254. // range, so they don't need any updates.
  255. if (MI.isDebugInstr() || MI.getOpcode() == TargetOpcode::STATEPOINT ||
  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.push_back(FrameRef(&MI, LocalOffset, Idx, Order++));
  277. break;
  278. }
  279. }
  280. }
  281. }
  282. // Sort the frame references by local offset.
  283. // Use frame index as a tie-breaker in case MI's have the same offset.
  284. llvm::sort(FrameReferenceInsns);
  285. MachineBasicBlock *Entry = &Fn.front();
  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. MachineInstr &MI = *FR.getMachineInstr();
  292. int64_t LocalOffset = FR.getLocalOffset();
  293. int FrameIdx = FR.getFrameIndex();
  294. assert(MFI.isObjectPreAllocated(FrameIdx) &&
  295. "Only pre-allocated locals expected!");
  296. // We need to keep the references to the stack protector slot through frame
  297. // index operands so that it gets resolved by PEI rather than this pass.
  298. // This avoids accesses to the stack protector though virtual base
  299. // registers, and forces PEI to address it using fp/sp/bp.
  300. if (MFI.hasStackProtectorIndex() &&
  301. FrameIdx == MFI.getStackProtectorIndex())
  302. continue;
  303. LLVM_DEBUG(dbgs() << "Considering: " << MI);
  304. unsigned idx = 0;
  305. for (unsigned f = MI.getNumOperands(); idx != f; ++idx) {
  306. if (!MI.getOperand(idx).isFI())
  307. continue;
  308. if (FrameIdx == MI.getOperand(idx).getIndex())
  309. break;
  310. }
  311. assert(idx < MI.getNumOperands() && "Cannot find FI operand");
  312. int64_t Offset = 0;
  313. int64_t FrameSizeAdjust = StackGrowsDown ? MFI.getLocalFrameSize() : 0;
  314. LLVM_DEBUG(dbgs() << " Replacing FI in: " << MI);
  315. // If we have a suitable base register available, use it; otherwise
  316. // create a new one. Note that any offset encoded in the
  317. // instruction itself will be taken into account by the target,
  318. // so we don't have to adjust for it here when reusing a base
  319. // register.
  320. if (UsedBaseReg &&
  321. lookupCandidateBaseReg(BaseReg, BaseOffset, FrameSizeAdjust,
  322. LocalOffset, MI, TRI)) {
  323. LLVM_DEBUG(dbgs() << " Reusing base register " << BaseReg << "\n");
  324. // We found a register to reuse.
  325. Offset = FrameSizeAdjust + LocalOffset - BaseOffset;
  326. } else {
  327. // No previously defined register was in range, so create a new one.
  328. int64_t InstrOffset = TRI->getFrameIndexInstrOffset(&MI, idx);
  329. int64_t PrevBaseOffset = BaseOffset;
  330. BaseOffset = FrameSizeAdjust + LocalOffset + InstrOffset;
  331. // We'd like to avoid creating single-use virtual base registers.
  332. // Because the FrameRefs are in sorted order, and we've already
  333. // processed all FrameRefs before this one, just check whether or not
  334. // the next FrameRef will be able to reuse this new register. If not,
  335. // then don't bother creating it.
  336. if (ref + 1 >= e ||
  337. !lookupCandidateBaseReg(
  338. BaseReg, BaseOffset, FrameSizeAdjust,
  339. FrameReferenceInsns[ref + 1].getLocalOffset(),
  340. *FrameReferenceInsns[ref + 1].getMachineInstr(), TRI)) {
  341. BaseOffset = PrevBaseOffset;
  342. continue;
  343. }
  344. const MachineFunction *MF = MI.getMF();
  345. const TargetRegisterClass *RC = TRI->getPointerRegClass(*MF);
  346. BaseReg = Fn.getRegInfo().createVirtualRegister(RC);
  347. LLVM_DEBUG(dbgs() << " Materializing base register " << BaseReg
  348. << " at frame local offset "
  349. << LocalOffset + InstrOffset << "\n");
  350. // Tell the target to insert the instruction to initialize
  351. // the base register.
  352. // MachineBasicBlock::iterator InsertionPt = Entry->begin();
  353. TRI->materializeFrameBaseRegister(Entry, BaseReg, FrameIdx,
  354. InstrOffset);
  355. // The base register already includes any offset specified
  356. // by the instruction, so account for that so it doesn't get
  357. // applied twice.
  358. Offset = -InstrOffset;
  359. ++NumBaseRegisters;
  360. UsedBaseReg = true;
  361. }
  362. assert(BaseReg != 0 && "Unable to allocate virtual base register!");
  363. // Modify the instruction to use the new base register rather
  364. // than the frame index operand.
  365. TRI->resolveFrameIndex(MI, BaseReg, Offset);
  366. LLVM_DEBUG(dbgs() << "Resolved: " << MI);
  367. ++NumReplacements;
  368. }
  369. return UsedBaseReg;
  370. }