X86DynAllocaExpander.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. //===----- X86DynAllocaExpander.cpp - Expand DynAlloca pseudo instruction -===//
  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 file defines a pass that expands DynAlloca pseudo-instructions.
  10. //
  11. // It performs a conservative analysis to determine whether each allocation
  12. // falls within a region of the stack that is safe to use, or whether stack
  13. // probes must be emitted.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "X86.h"
  17. #include "X86InstrBuilder.h"
  18. #include "X86InstrInfo.h"
  19. #include "X86MachineFunctionInfo.h"
  20. #include "X86Subtarget.h"
  21. #include "llvm/ADT/MapVector.h"
  22. #include "llvm/ADT/PostOrderIterator.h"
  23. #include "llvm/CodeGen/MachineFunctionPass.h"
  24. #include "llvm/CodeGen/MachineInstrBuilder.h"
  25. #include "llvm/CodeGen/MachineRegisterInfo.h"
  26. #include "llvm/CodeGen/Passes.h"
  27. #include "llvm/CodeGen/TargetInstrInfo.h"
  28. #include "llvm/IR/Function.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. using namespace llvm;
  31. namespace {
  32. class X86DynAllocaExpander : public MachineFunctionPass {
  33. public:
  34. X86DynAllocaExpander() : MachineFunctionPass(ID) {}
  35. bool runOnMachineFunction(MachineFunction &MF) override;
  36. private:
  37. /// Strategies for lowering a DynAlloca.
  38. enum Lowering { TouchAndSub, Sub, Probe };
  39. /// Deterministic-order map from DynAlloca instruction to desired lowering.
  40. typedef MapVector<MachineInstr*, Lowering> LoweringMap;
  41. /// Compute which lowering to use for each DynAlloca instruction.
  42. void computeLowerings(MachineFunction &MF, LoweringMap& Lowerings);
  43. /// Get the appropriate lowering based on current offset and amount.
  44. Lowering getLowering(int64_t CurrentOffset, int64_t AllocaAmount);
  45. /// Lower a DynAlloca instruction.
  46. void lower(MachineInstr* MI, Lowering L);
  47. MachineRegisterInfo *MRI = nullptr;
  48. const X86Subtarget *STI = nullptr;
  49. const TargetInstrInfo *TII = nullptr;
  50. const X86RegisterInfo *TRI = nullptr;
  51. unsigned StackPtr = 0;
  52. unsigned SlotSize = 0;
  53. int64_t StackProbeSize = 0;
  54. bool NoStackArgProbe = false;
  55. StringRef getPassName() const override { return "X86 DynAlloca Expander"; }
  56. static char ID;
  57. };
  58. char X86DynAllocaExpander::ID = 0;
  59. } // end anonymous namespace
  60. FunctionPass *llvm::createX86DynAllocaExpander() {
  61. return new X86DynAllocaExpander();
  62. }
  63. /// Return the allocation amount for a DynAlloca instruction, or -1 if unknown.
  64. static int64_t getDynAllocaAmount(MachineInstr *MI, MachineRegisterInfo *MRI) {
  65. assert(MI->getOpcode() == X86::DYN_ALLOCA_32 ||
  66. MI->getOpcode() == X86::DYN_ALLOCA_64);
  67. assert(MI->getOperand(0).isReg());
  68. Register AmountReg = MI->getOperand(0).getReg();
  69. MachineInstr *Def = MRI->getUniqueVRegDef(AmountReg);
  70. if (!Def ||
  71. (Def->getOpcode() != X86::MOV32ri && Def->getOpcode() != X86::MOV64ri) ||
  72. !Def->getOperand(1).isImm())
  73. return -1;
  74. return Def->getOperand(1).getImm();
  75. }
  76. X86DynAllocaExpander::Lowering
  77. X86DynAllocaExpander::getLowering(int64_t CurrentOffset,
  78. int64_t AllocaAmount) {
  79. // For a non-constant amount or a large amount, we have to probe.
  80. if (AllocaAmount < 0 || AllocaAmount > StackProbeSize)
  81. return Probe;
  82. // If it fits within the safe region of the stack, just subtract.
  83. if (CurrentOffset + AllocaAmount <= StackProbeSize)
  84. return Sub;
  85. // Otherwise, touch the current tip of the stack, then subtract.
  86. return TouchAndSub;
  87. }
  88. static bool isPushPop(const MachineInstr &MI) {
  89. switch (MI.getOpcode()) {
  90. case X86::PUSH32i8:
  91. case X86::PUSH32r:
  92. case X86::PUSH32rmm:
  93. case X86::PUSH32rmr:
  94. case X86::PUSHi32:
  95. case X86::PUSH64i8:
  96. case X86::PUSH64r:
  97. case X86::PUSH64rmm:
  98. case X86::PUSH64rmr:
  99. case X86::PUSH64i32:
  100. case X86::POP32r:
  101. case X86::POP64r:
  102. return true;
  103. default:
  104. return false;
  105. }
  106. }
  107. void X86DynAllocaExpander::computeLowerings(MachineFunction &MF,
  108. LoweringMap &Lowerings) {
  109. // Do a one-pass reverse post-order walk of the CFG to conservatively estimate
  110. // the offset between the stack pointer and the lowest touched part of the
  111. // stack, and use that to decide how to lower each DynAlloca instruction.
  112. // Initialize OutOffset[B], the stack offset at exit from B, to something big.
  113. DenseMap<MachineBasicBlock *, int64_t> OutOffset;
  114. for (MachineBasicBlock &MBB : MF)
  115. OutOffset[&MBB] = INT32_MAX;
  116. // Note: we don't know the offset at the start of the entry block since the
  117. // prologue hasn't been inserted yet, and how much that will adjust the stack
  118. // pointer depends on register spills, which have not been computed yet.
  119. // Compute the reverse post-order.
  120. ReversePostOrderTraversal<MachineFunction*> RPO(&MF);
  121. for (MachineBasicBlock *MBB : RPO) {
  122. int64_t Offset = -1;
  123. for (MachineBasicBlock *Pred : MBB->predecessors())
  124. Offset = std::max(Offset, OutOffset[Pred]);
  125. if (Offset == -1) Offset = INT32_MAX;
  126. for (MachineInstr &MI : *MBB) {
  127. if (MI.getOpcode() == X86::DYN_ALLOCA_32 ||
  128. MI.getOpcode() == X86::DYN_ALLOCA_64) {
  129. // A DynAlloca moves StackPtr, and potentially touches it.
  130. int64_t Amount = getDynAllocaAmount(&MI, MRI);
  131. Lowering L = getLowering(Offset, Amount);
  132. Lowerings[&MI] = L;
  133. switch (L) {
  134. case Sub:
  135. Offset += Amount;
  136. break;
  137. case TouchAndSub:
  138. Offset = Amount;
  139. break;
  140. case Probe:
  141. Offset = 0;
  142. break;
  143. }
  144. } else if (MI.isCall() || isPushPop(MI)) {
  145. // Calls, pushes and pops touch the tip of the stack.
  146. Offset = 0;
  147. } else if (MI.getOpcode() == X86::ADJCALLSTACKUP32 ||
  148. MI.getOpcode() == X86::ADJCALLSTACKUP64) {
  149. Offset -= MI.getOperand(0).getImm();
  150. } else if (MI.getOpcode() == X86::ADJCALLSTACKDOWN32 ||
  151. MI.getOpcode() == X86::ADJCALLSTACKDOWN64) {
  152. Offset += MI.getOperand(0).getImm();
  153. } else if (MI.modifiesRegister(StackPtr, TRI)) {
  154. // Any other modification of SP means we've lost track of it.
  155. Offset = INT32_MAX;
  156. }
  157. }
  158. OutOffset[MBB] = Offset;
  159. }
  160. }
  161. static unsigned getSubOpcode(bool Is64Bit, int64_t Amount) {
  162. if (Is64Bit)
  163. return isInt<8>(Amount) ? X86::SUB64ri8 : X86::SUB64ri32;
  164. return isInt<8>(Amount) ? X86::SUB32ri8 : X86::SUB32ri;
  165. }
  166. void X86DynAllocaExpander::lower(MachineInstr *MI, Lowering L) {
  167. const DebugLoc &DL = MI->getDebugLoc();
  168. MachineBasicBlock *MBB = MI->getParent();
  169. MachineBasicBlock::iterator I = *MI;
  170. int64_t Amount = getDynAllocaAmount(MI, MRI);
  171. if (Amount == 0) {
  172. MI->eraseFromParent();
  173. return;
  174. }
  175. // These two variables differ on x32, which is a 64-bit target with a
  176. // 32-bit alloca.
  177. bool Is64Bit = STI->is64Bit();
  178. bool Is64BitAlloca = MI->getOpcode() == X86::DYN_ALLOCA_64;
  179. assert(SlotSize == 4 || SlotSize == 8);
  180. std::optional<MachineFunction::DebugInstrOperandPair> InstrNum;
  181. if (unsigned Num = MI->peekDebugInstrNum()) {
  182. // Operand 2 of DYN_ALLOCAs contains the stack def.
  183. InstrNum = {Num, 2};
  184. }
  185. switch (L) {
  186. case TouchAndSub: {
  187. assert(Amount >= SlotSize);
  188. // Use a push to touch the top of the stack.
  189. unsigned RegA = Is64Bit ? X86::RAX : X86::EAX;
  190. BuildMI(*MBB, I, DL, TII->get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
  191. .addReg(RegA, RegState::Undef);
  192. Amount -= SlotSize;
  193. if (!Amount)
  194. break;
  195. // Fall through to make any remaining adjustment.
  196. [[fallthrough]];
  197. }
  198. case Sub:
  199. assert(Amount > 0);
  200. if (Amount == SlotSize) {
  201. // Use push to save size.
  202. unsigned RegA = Is64Bit ? X86::RAX : X86::EAX;
  203. BuildMI(*MBB, I, DL, TII->get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
  204. .addReg(RegA, RegState::Undef);
  205. } else {
  206. // Sub.
  207. BuildMI(*MBB, I, DL,
  208. TII->get(getSubOpcode(Is64BitAlloca, Amount)), StackPtr)
  209. .addReg(StackPtr)
  210. .addImm(Amount);
  211. }
  212. break;
  213. case Probe:
  214. if (!NoStackArgProbe) {
  215. // The probe lowering expects the amount in RAX/EAX.
  216. unsigned RegA = Is64BitAlloca ? X86::RAX : X86::EAX;
  217. BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::COPY), RegA)
  218. .addReg(MI->getOperand(0).getReg());
  219. // Do the probe.
  220. STI->getFrameLowering()->emitStackProbe(*MBB->getParent(), *MBB, MI, DL,
  221. /*InProlog=*/false, InstrNum);
  222. } else {
  223. // Sub
  224. BuildMI(*MBB, I, DL,
  225. TII->get(Is64BitAlloca ? X86::SUB64rr : X86::SUB32rr), StackPtr)
  226. .addReg(StackPtr)
  227. .addReg(MI->getOperand(0).getReg());
  228. }
  229. break;
  230. }
  231. Register AmountReg = MI->getOperand(0).getReg();
  232. MI->eraseFromParent();
  233. // Delete the definition of AmountReg.
  234. if (MRI->use_empty(AmountReg))
  235. if (MachineInstr *AmountDef = MRI->getUniqueVRegDef(AmountReg))
  236. AmountDef->eraseFromParent();
  237. }
  238. bool X86DynAllocaExpander::runOnMachineFunction(MachineFunction &MF) {
  239. if (!MF.getInfo<X86MachineFunctionInfo>()->hasDynAlloca())
  240. return false;
  241. MRI = &MF.getRegInfo();
  242. STI = &MF.getSubtarget<X86Subtarget>();
  243. TII = STI->getInstrInfo();
  244. TRI = STI->getRegisterInfo();
  245. StackPtr = TRI->getStackRegister();
  246. SlotSize = TRI->getSlotSize();
  247. StackProbeSize = STI->getTargetLowering()->getStackProbeSize(MF);
  248. NoStackArgProbe = MF.getFunction().hasFnAttribute("no-stack-arg-probe");
  249. if (NoStackArgProbe)
  250. StackProbeSize = INT64_MAX;
  251. LoweringMap Lowerings;
  252. computeLowerings(MF, Lowerings);
  253. for (auto &P : Lowerings)
  254. lower(P.first, P.second);
  255. return true;
  256. }