LocalStackSlotAllocation.cpp 17 KB

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