1 //===-- WebAssemblyFrameLowering.cpp - WebAssembly Frame Lowering ----------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file contains the WebAssembly implementation of
12 /// TargetFrameLowering class.
14 /// On WebAssembly, there aren't a lot of things to do here. There are no
15 /// callee-saved registers to save, and no spill slots.
17 /// The stack grows downward.
19 //===----------------------------------------------------------------------===//
21 #include "WebAssemblyFrameLowering.h"
22 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
23 #include "WebAssemblyInstrInfo.h"
24 #include "WebAssemblyMachineFunctionInfo.h"
25 #include "WebAssemblySubtarget.h"
26 #include "WebAssemblyTargetMachine.h"
27 #include "WebAssemblyUtilities.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/Support/Debug.h"
36 #define DEBUG_TYPE "wasm-frame-info"
39 // TODO: Emit TargetOpcode::CFI_INSTRUCTION instructions
41 /// We need a base pointer in the case of having items on the stack that
42 /// require stricter alignment than the stack pointer itself. Because we need
43 /// to shift the stack pointer by some unknown amount to force the alignment,
44 /// we need to record the value of the stack pointer on entry to the function.
45 bool WebAssemblyFrameLowering::hasBP(
46 const MachineFunction &MF) const {
48 MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
49 return RegInfo->needsStackRealignment(MF);
52 /// Return true if the specified function should have a dedicated frame pointer
54 bool WebAssemblyFrameLowering::hasFP(const MachineFunction &MF) const {
55 const MachineFrameInfo &MFI = MF.getFrameInfo();
57 // When we have var-sized objects, we move the stack pointer by an unknown
58 // amount, and need to emit a frame pointer to restore the stack to where we
59 // were on function entry.
60 // If we already need a base pointer, we use that to fix up the stack pointer.
61 // If there are no fixed-size objects, we would have no use of a frame
62 // pointer, and thus should not emit one.
63 bool HasFixedSizedObjects = MFI.getStackSize() > 0;
64 bool NeedsFixedReference = !hasBP(MF) || HasFixedSizedObjects;
66 return MFI.isFrameAddressTaken() ||
67 (MFI.hasVarSizedObjects() && NeedsFixedReference) ||
68 MFI.hasStackMap() || MFI.hasPatchPoint();
71 /// Under normal circumstances, when a frame pointer is not required, we reserve
72 /// argument space for call sites in the function immediately on entry to the
73 /// current function. This eliminates the need for add/sub sp brackets around
74 /// call sites. Returns true if the call frame is included as part of the stack
76 bool WebAssemblyFrameLowering::hasReservedCallFrame(
77 const MachineFunction &MF) const {
78 return !MF.getFrameInfo().hasVarSizedObjects();
82 /// Returns true if this function needs a local user-space stack pointer.
83 /// Unlike a machine stack pointer, the wasm user stack pointer is a global
84 /// variable, so it is loaded into a register in the prolog.
85 bool WebAssemblyFrameLowering::needsSP(const MachineFunction &MF,
86 const MachineFrameInfo &MFI) const {
87 return MFI.getStackSize() || MFI.adjustsStack() || hasFP(MF);
90 /// Returns true if the local user-space stack pointer needs to be written back
91 /// to memory by this function (this is not meaningful if needsSP is false). If
92 /// false, the stack red zone can be used and only a local SP is needed.
93 bool WebAssemblyFrameLowering::needsSPWriteback(
94 const MachineFunction &MF, const MachineFrameInfo &MFI) const {
95 assert(needsSP(MF, MFI));
96 return MFI.getStackSize() > RedZoneSize || MFI.hasCalls() ||
97 MF.getFunction()->hasFnAttribute(Attribute::NoRedZone);
100 static void writeSPToMemory(unsigned SrcReg, MachineFunction &MF,
101 MachineBasicBlock &MBB,
102 MachineBasicBlock::iterator &InsertAddr,
103 MachineBasicBlock::iterator &InsertStore,
104 const DebugLoc &DL) {
105 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
107 if (MF.getSubtarget<WebAssemblySubtarget>()
108 .getTargetTriple().isOSBinFormatELF()) {
109 const char *ES = "__stack_pointer";
110 auto *SPSymbol = MF.createExternalSymbolName(ES);
111 MachineRegisterInfo &MRI = MF.getRegInfo();
112 const TargetRegisterClass *PtrRC =
113 MRI.getTargetRegisterInfo()->getPointerRegClass(MF);
114 unsigned Zero = MRI.createVirtualRegister(PtrRC);
116 BuildMI(MBB, InsertAddr, DL, TII->get(WebAssembly::CONST_I32), Zero)
118 MachineMemOperand *MMO = MF.getMachineMemOperand(
119 MachinePointerInfo(MF.getPSVManager().getExternalSymbolCallEntry(ES)),
120 MachineMemOperand::MOStore, 4, 4);
121 BuildMI(MBB, InsertStore, DL, TII->get(WebAssembly::STORE_I32))
122 .addImm(2) // p2align
123 .addExternalSymbol(SPSymbol)
128 MachineModuleInfoWasm &MMIW =
129 MF.getMMI().getObjFileInfo<MachineModuleInfoWasm>();
130 BuildMI(MBB, InsertStore, DL, TII->get(WebAssembly::SET_GLOBAL_I32))
131 .addImm(MMIW.getStackPointerGlobal())
136 MachineBasicBlock::iterator
137 WebAssemblyFrameLowering::eliminateCallFramePseudoInstr(
138 MachineFunction &MF, MachineBasicBlock &MBB,
139 MachineBasicBlock::iterator I) const {
140 assert(!I->getOperand(0).getImm() && (hasFP(MF) || hasBP(MF)) &&
141 "Call frame pseudos should only be used for dynamic stack adjustment");
142 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
143 if (I->getOpcode() == TII->getCallFrameDestroyOpcode() &&
144 needsSPWriteback(MF, MF.getFrameInfo())) {
145 DebugLoc DL = I->getDebugLoc();
146 writeSPToMemory(WebAssembly::SP32, MF, MBB, I, I, DL);
151 void WebAssemblyFrameLowering::emitPrologue(MachineFunction &MF,
152 MachineBasicBlock &MBB) const {
153 // TODO: Do ".setMIFlag(MachineInstr::FrameSetup)" on emitted instructions
154 auto &MFI = MF.getFrameInfo();
155 assert(MFI.getCalleeSavedInfo().empty() &&
156 "WebAssembly should not have callee-saved registers");
158 if (!needsSP(MF, MFI)) return;
159 uint64_t StackSize = MFI.getStackSize();
161 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
162 auto &MRI = MF.getRegInfo();
164 auto InsertPt = MBB.begin();
165 while (InsertPt != MBB.end() && WebAssembly::isArgument(*InsertPt))
169 const TargetRegisterClass *PtrRC =
170 MRI.getTargetRegisterInfo()->getPointerRegClass(MF);
171 unsigned SPReg = WebAssembly::SP32;
173 SPReg = MRI.createVirtualRegister(PtrRC);
174 if (MF.getSubtarget<WebAssemblySubtarget>()
175 .getTargetTriple().isOSBinFormatELF()) {
176 const char *ES = "__stack_pointer";
177 auto *SPSymbol = MF.createExternalSymbolName(ES);
178 unsigned Zero = MRI.createVirtualRegister(PtrRC);
180 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), Zero)
182 MachineMemOperand *LoadMMO = MF.getMachineMemOperand(
183 MachinePointerInfo(MF.getPSVManager().getExternalSymbolCallEntry(ES)),
184 MachineMemOperand::MOLoad, 4, 4);
185 // Load the SP value.
186 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::LOAD_I32), SPReg)
187 .addImm(2) // p2align
188 .addExternalSymbol(SPSymbol)
189 .addReg(Zero) // addr
190 .addMemOperand(LoadMMO);
192 auto &MMIW = MF.getMMI().getObjFileInfo<MachineModuleInfoWasm>();
193 if (!MMIW.hasStackPointerGlobal()) {
194 MMIW.setStackPointerGlobal(MMIW.getGlobals().size());
196 // Create the stack-pointer global. For now, just use the
197 // Emscripten/Binaryen ABI names.
199 G.Type = wasm::ValType::I32;
202 G.InitialModule = "env";
203 G.InitialName = "STACKTOP";
206 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::GET_GLOBAL_I32), SPReg)
207 .addImm(MMIW.getStackPointerGlobal());
210 bool HasBP = hasBP(MF);
212 auto FI = MF.getInfo<WebAssemblyFunctionInfo>();
213 unsigned BasePtr = MRI.createVirtualRegister(PtrRC);
214 FI->setBasePointerVreg(BasePtr);
215 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY), BasePtr)
219 // Subtract the frame size
220 unsigned OffsetReg = MRI.createVirtualRegister(PtrRC);
221 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), OffsetReg)
223 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::SUB_I32),
229 unsigned BitmaskReg = MRI.createVirtualRegister(PtrRC);
230 unsigned Alignment = MFI.getMaxAlignment();
231 assert((1u << countTrailingZeros(Alignment)) == Alignment &&
232 "Alignment must be a power of 2");
233 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), BitmaskReg)
234 .addImm((int)~(Alignment - 1));
235 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::AND_I32),
237 .addReg(WebAssembly::SP32)
241 // Unlike most conventional targets (where FP points to the saved FP),
242 // FP points to the bottom of the fixed-size locals, so we can use positive
243 // offsets in load/store instructions.
244 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY),
246 .addReg(WebAssembly::SP32);
248 if (StackSize && needsSPWriteback(MF, MFI)) {
249 writeSPToMemory(WebAssembly::SP32, MF, MBB, InsertPt, InsertPt, DL);
253 void WebAssemblyFrameLowering::emitEpilogue(MachineFunction &MF,
254 MachineBasicBlock &MBB) const {
255 auto &MFI = MF.getFrameInfo();
256 uint64_t StackSize = MFI.getStackSize();
257 if (!needsSP(MF, MFI) || !needsSPWriteback(MF, MFI)) return;
258 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
259 auto &MRI = MF.getRegInfo();
260 auto InsertPt = MBB.getFirstTerminator();
263 if (InsertPt != MBB.end())
264 DL = InsertPt->getDebugLoc();
266 // Restore the stack pointer. If we had fixed-size locals, add the offset
267 // subtracted in the prolog.
269 MachineBasicBlock::iterator InsertAddr = InsertPt;
271 auto FI = MF.getInfo<WebAssemblyFunctionInfo>();
272 SPReg = FI->getBasePointerVreg();
273 } else if (StackSize) {
274 const TargetRegisterClass *PtrRC =
275 MRI.getTargetRegisterInfo()->getPointerRegClass(MF);
276 unsigned OffsetReg = MRI.createVirtualRegister(PtrRC);
278 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), OffsetReg)
280 // In the epilog we don't need to write the result back to the SP32 physreg
281 // because it won't be used again. We can use a stackified register instead.
282 SPReg = MRI.createVirtualRegister(PtrRC);
283 BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::ADD_I32), SPReg)
284 .addReg(hasFP(MF) ? WebAssembly::FP32 : WebAssembly::SP32)
287 SPReg = hasFP(MF) ? WebAssembly::FP32 : WebAssembly::SP32;
290 writeSPToMemory(SPReg, MF, MBB, InsertAddr, InsertPt, DL);