1 //===-- WebAssemblyFrameLowering.cpp - WebAssembly Frame Lowering ----------==//
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 /// \file
11 /// This file contains the WebAssembly implementation of
12 /// TargetFrameLowering class.
13 ///
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.
16 ///
17 /// The stack grows downward.
18 ///
19 //===----------------------------------------------------------------------===//
20 
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/MC/MCAsmInfo.h"
34 #include "llvm/Support/Debug.h"
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "wasm-frame-info"
38 
39 // TODO: wasm64
40 // TODO: Emit TargetOpcode::CFI_INSTRUCTION instructions
41 
42 /// We need a base pointer in the case of having items on the stack that
43 /// require stricter alignment than the stack pointer itself.  Because we need
44 /// to shift the stack pointer by some unknown amount to force the alignment,
45 /// we need to record the value of the stack pointer on entry to the function.
46 bool WebAssemblyFrameLowering::hasBP(
47     const MachineFunction &MF) const {
48   const auto *RegInfo =
49       MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
50   return RegInfo->needsStackRealignment(MF);
51 }
52 
53 /// Return true if the specified function should have a dedicated frame pointer
54 /// register.
55 bool WebAssemblyFrameLowering::hasFP(const MachineFunction &MF) const {
56   const MachineFrameInfo &MFI = MF.getFrameInfo();
57 
58   // When we have var-sized objects, we move the stack pointer by an unknown
59   // amount, and need to emit a frame pointer to restore the stack to where we
60   // were on function entry.
61   // If we already need a base pointer, we use that to fix up the stack pointer.
62   // If there are no fixed-size objects, we would have no use of a frame
63   // pointer, and thus should not emit one.
64   bool HasFixedSizedObjects = MFI.getStackSize() > 0;
65   bool NeedsFixedReference = !hasBP(MF) || HasFixedSizedObjects;
66 
67   return MFI.isFrameAddressTaken() ||
68          (MFI.hasVarSizedObjects() && NeedsFixedReference) ||
69          MFI.hasStackMap() || MFI.hasPatchPoint();
70 }
71 
72 /// Under normal circumstances, when a frame pointer is not required, we reserve
73 /// argument space for call sites in the function immediately on entry to the
74 /// current function. This eliminates the need for add/sub sp brackets around
75 /// call sites. Returns true if the call frame is included as part of the stack
76 /// frame.
77 bool WebAssemblyFrameLowering::hasReservedCallFrame(
78     const MachineFunction &MF) const {
79   return !MF.getFrameInfo().hasVarSizedObjects();
80 }
81 
82 // In function with EH pads, we need to make a copy of the value of
83 // __stack_pointer global in SP32 register, in order to use it when restoring
84 // __stack_pointer after an exception is caught.
85 bool WebAssemblyFrameLowering::needsPrologForEH(
86     const MachineFunction &MF) const {
87   auto EHType = MF.getTarget().getMCAsmInfo()->getExceptionHandlingType();
88   return EHType == ExceptionHandling::Wasm &&
89          MF.getFunction().hasPersonalityFn() && MF.getFrameInfo().hasCalls();
90 }
91 
92 /// Returns true if this function needs a local user-space stack pointer.
93 /// Unlike a machine stack pointer, the wasm user stack pointer is a global
94 /// variable, so it is loaded into a register in the prolog.
95 bool WebAssemblyFrameLowering::needsSP(const MachineFunction &MF,
96                                        const MachineFrameInfo &MFI) const {
97   return MFI.getStackSize() || MFI.adjustsStack() || hasFP(MF) ||
98          needsPrologForEH(MF);
99 }
100 
101 /// Returns true if the local user-space stack pointer needs to be written back
102 /// to __stack_pointer global by this function (this is not meaningful if
103 /// needsSP is false). If false, the stack red zone can be used and only a local
104 /// SP is needed.
105 bool WebAssemblyFrameLowering::needsSPWriteback(
106     const MachineFunction &MF, const MachineFrameInfo &MFI) const {
107   assert(needsSP(MF, MFI));
108   return MFI.getStackSize() > RedZoneSize || MFI.hasCalls() ||
109          MF.getFunction().hasFnAttribute(Attribute::NoRedZone);
110 }
111 
112 void WebAssemblyFrameLowering::writeSPToGlobal(
113     unsigned SrcReg, MachineFunction &MF, MachineBasicBlock &MBB,
114     MachineBasicBlock::iterator &InsertStore, const DebugLoc &DL) const {
115   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
116 
117   const char *ES = "__stack_pointer";
118   auto *SPSymbol = MF.createExternalSymbolName(ES);
119   BuildMI(MBB, InsertStore, DL, TII->get(WebAssembly::SET_GLOBAL_I32))
120       .addExternalSymbol(SPSymbol, WebAssemblyII::MO_SYMBOL_GLOBAL)
121       .addReg(SrcReg);
122 }
123 
124 MachineBasicBlock::iterator
125 WebAssemblyFrameLowering::eliminateCallFramePseudoInstr(
126     MachineFunction &MF, MachineBasicBlock &MBB,
127     MachineBasicBlock::iterator I) const {
128   assert(!I->getOperand(0).getImm() && (hasFP(MF) || hasBP(MF)) &&
129          "Call frame pseudos should only be used for dynamic stack adjustment");
130   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
131   if (I->getOpcode() == TII->getCallFrameDestroyOpcode() &&
132       needsSPWriteback(MF, MF.getFrameInfo())) {
133     DebugLoc DL = I->getDebugLoc();
134     writeSPToGlobal(WebAssembly::SP32, MF, MBB, I, DL);
135   }
136   return MBB.erase(I);
137 }
138 
139 void WebAssemblyFrameLowering::emitPrologue(MachineFunction &MF,
140                                             MachineBasicBlock &MBB) const {
141   // TODO: Do ".setMIFlag(MachineInstr::FrameSetup)" on emitted instructions
142   auto &MFI = MF.getFrameInfo();
143   assert(MFI.getCalleeSavedInfo().empty() &&
144          "WebAssembly should not have callee-saved registers");
145 
146   if (!needsSP(MF, MFI)) return;
147   uint64_t StackSize = MFI.getStackSize();
148 
149   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
150   auto &MRI = MF.getRegInfo();
151 
152   auto InsertPt = MBB.begin();
153   while (InsertPt != MBB.end() && WebAssembly::isArgument(*InsertPt))
154     ++InsertPt;
155   DebugLoc DL;
156 
157   const TargetRegisterClass *PtrRC =
158       MRI.getTargetRegisterInfo()->getPointerRegClass(MF);
159   unsigned SPReg = WebAssembly::SP32;
160   if (StackSize)
161     SPReg = MRI.createVirtualRegister(PtrRC);
162 
163   const char *ES = "__stack_pointer";
164   auto *SPSymbol = MF.createExternalSymbolName(ES);
165   BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::GET_GLOBAL_I32), SPReg)
166       .addExternalSymbol(SPSymbol, WebAssemblyII::MO_SYMBOL_GLOBAL);
167 
168   bool HasBP = hasBP(MF);
169   if (HasBP) {
170     auto FI = MF.getInfo<WebAssemblyFunctionInfo>();
171     unsigned BasePtr = MRI.createVirtualRegister(PtrRC);
172     FI->setBasePointerVreg(BasePtr);
173     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY), BasePtr)
174         .addReg(SPReg);
175   }
176   if (StackSize) {
177     // Subtract the frame size
178     unsigned OffsetReg = MRI.createVirtualRegister(PtrRC);
179     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), OffsetReg)
180         .addImm(StackSize);
181     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::SUB_I32),
182             WebAssembly::SP32)
183         .addReg(SPReg)
184         .addReg(OffsetReg);
185   }
186   if (HasBP) {
187     unsigned BitmaskReg = MRI.createVirtualRegister(PtrRC);
188     unsigned Alignment = MFI.getMaxAlignment();
189     assert((1u << countTrailingZeros(Alignment)) == Alignment &&
190       "Alignment must be a power of 2");
191     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), BitmaskReg)
192         .addImm((int)~(Alignment - 1));
193     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::AND_I32),
194             WebAssembly::SP32)
195         .addReg(WebAssembly::SP32)
196         .addReg(BitmaskReg);
197   }
198   if (hasFP(MF)) {
199     // Unlike most conventional targets (where FP points to the saved FP),
200     // FP points to the bottom of the fixed-size locals, so we can use positive
201     // offsets in load/store instructions.
202     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY),
203             WebAssembly::FP32)
204         .addReg(WebAssembly::SP32);
205   }
206   if (StackSize && needsSPWriteback(MF, MFI)) {
207     writeSPToGlobal(WebAssembly::SP32, MF, MBB, InsertPt, DL);
208   }
209 }
210 
211 void WebAssemblyFrameLowering::emitEpilogue(MachineFunction &MF,
212                                             MachineBasicBlock &MBB) const {
213   auto &MFI = MF.getFrameInfo();
214   uint64_t StackSize = MFI.getStackSize();
215   if (!needsSP(MF, MFI) || !needsSPWriteback(MF, MFI)) return;
216   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
217   auto &MRI = MF.getRegInfo();
218   auto InsertPt = MBB.getFirstTerminator();
219   DebugLoc DL;
220 
221   if (InsertPt != MBB.end())
222     DL = InsertPt->getDebugLoc();
223 
224   // Restore the stack pointer. If we had fixed-size locals, add the offset
225   // subtracted in the prolog.
226   unsigned SPReg = 0;
227   if (hasBP(MF)) {
228     auto FI = MF.getInfo<WebAssemblyFunctionInfo>();
229     SPReg = FI->getBasePointerVreg();
230   } else if (StackSize) {
231     const TargetRegisterClass *PtrRC =
232         MRI.getTargetRegisterInfo()->getPointerRegClass(MF);
233     unsigned OffsetReg = MRI.createVirtualRegister(PtrRC);
234     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), OffsetReg)
235         .addImm(StackSize);
236     // In the epilog we don't need to write the result back to the SP32 physreg
237     // because it won't be used again. We can use a stackified register instead.
238     SPReg = MRI.createVirtualRegister(PtrRC);
239     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::ADD_I32), SPReg)
240         .addReg(hasFP(MF) ? WebAssembly::FP32 : WebAssembly::SP32)
241         .addReg(OffsetReg);
242   } else {
243     SPReg = hasFP(MF) ? WebAssembly::FP32 : WebAssembly::SP32;
244   }
245 
246   writeSPToGlobal(SPReg, MF, MBB, InsertPt, DL);
247 }
248