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 // Returns true if this function needs a local user-space stack pointer for its
83 // local frame (not for exception handling).
84 bool WebAssemblyFrameLowering::needsSPForLocalFrame(
85     const MachineFunction &MF) const {
86   auto &MFI = MF.getFrameInfo();
87   return MFI.getStackSize() || MFI.adjustsStack() || hasFP(MF);
88 }
89 
90 // In function with EH pads, we need to make a copy of the value of
91 // __stack_pointer global in SP32 register, in order to use it when restoring
92 // __stack_pointer after an exception is caught.
93 bool WebAssemblyFrameLowering::needsPrologForEH(
94     const MachineFunction &MF) const {
95   auto EHType = MF.getTarget().getMCAsmInfo()->getExceptionHandlingType();
96   return EHType == ExceptionHandling::Wasm &&
97          MF.getFunction().hasPersonalityFn() && MF.getFrameInfo().hasCalls();
98 }
99 
100 /// Returns true if this function needs a local user-space stack pointer.
101 /// Unlike a machine stack pointer, the wasm user stack pointer is a global
102 /// variable, so it is loaded into a register in the prolog.
103 bool WebAssemblyFrameLowering::needsSP(const MachineFunction &MF) const {
104   return needsSPForLocalFrame(MF) || needsPrologForEH(MF);
105 }
106 
107 /// Returns true if the local user-space stack pointer needs to be written back
108 /// to __stack_pointer global by this function (this is not meaningful if
109 /// needsSP is false). If false, the stack red zone can be used and only a local
110 /// SP is needed.
111 bool WebAssemblyFrameLowering::needsSPWriteback(
112     const MachineFunction &MF) const {
113   auto &MFI = MF.getFrameInfo();
114   assert(needsSP(MF));
115   // When we don't need a local stack pointer for its local frame but only to
116   // support EH, we don't need to write SP back in the epilog, because we don't
117   // bump down the stack pointer in the prolog. We need to write SP back in the
118   // epilog only if
119   // 1. We need SP not only for EH support but also because we actually use
120   // stack or we have a frame address taken.
121   // 2. We cannot use the red zone.
122   bool CanUseRedZone = MFI.getStackSize() <= RedZoneSize && !MFI.hasCalls() &&
123                        !MF.getFunction().hasFnAttribute(Attribute::NoRedZone);
124   return needsSPForLocalFrame(MF) && !CanUseRedZone;
125 }
126 
127 void WebAssemblyFrameLowering::writeSPToGlobal(
128     unsigned SrcReg, MachineFunction &MF, MachineBasicBlock &MBB,
129     MachineBasicBlock::iterator &InsertStore, const DebugLoc &DL) const {
130   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
131 
132   const char *ES = "__stack_pointer";
133   auto *SPSymbol = MF.createExternalSymbolName(ES);
134   BuildMI(MBB, InsertStore, DL, TII->get(WebAssembly::SET_GLOBAL_I32))
135       .addExternalSymbol(SPSymbol, WebAssemblyII::MO_SYMBOL_GLOBAL)
136       .addReg(SrcReg);
137 }
138 
139 MachineBasicBlock::iterator
140 WebAssemblyFrameLowering::eliminateCallFramePseudoInstr(
141     MachineFunction &MF, MachineBasicBlock &MBB,
142     MachineBasicBlock::iterator I) const {
143   assert(!I->getOperand(0).getImm() && (hasFP(MF) || hasBP(MF)) &&
144          "Call frame pseudos should only be used for dynamic stack adjustment");
145   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
146   if (I->getOpcode() == TII->getCallFrameDestroyOpcode() &&
147       needsSPWriteback(MF)) {
148     DebugLoc DL = I->getDebugLoc();
149     writeSPToGlobal(WebAssembly::SP32, MF, MBB, I, DL);
150   }
151   return MBB.erase(I);
152 }
153 
154 void WebAssemblyFrameLowering::emitPrologue(MachineFunction &MF,
155                                             MachineBasicBlock &MBB) const {
156   // TODO: Do ".setMIFlag(MachineInstr::FrameSetup)" on emitted instructions
157   auto &MFI = MF.getFrameInfo();
158   assert(MFI.getCalleeSavedInfo().empty() &&
159          "WebAssembly should not have callee-saved registers");
160 
161   if (!needsSP(MF)) return;
162   uint64_t StackSize = MFI.getStackSize();
163 
164   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
165   auto &MRI = MF.getRegInfo();
166 
167   auto InsertPt = MBB.begin();
168   while (InsertPt != MBB.end() && WebAssembly::isArgument(*InsertPt))
169     ++InsertPt;
170   DebugLoc DL;
171 
172   const TargetRegisterClass *PtrRC =
173       MRI.getTargetRegisterInfo()->getPointerRegClass(MF);
174   unsigned SPReg = WebAssembly::SP32;
175   if (StackSize)
176     SPReg = MRI.createVirtualRegister(PtrRC);
177 
178   const char *ES = "__stack_pointer";
179   auto *SPSymbol = MF.createExternalSymbolName(ES);
180   BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::GET_GLOBAL_I32), SPReg)
181       .addExternalSymbol(SPSymbol, WebAssemblyII::MO_SYMBOL_GLOBAL);
182 
183   bool HasBP = hasBP(MF);
184   if (HasBP) {
185     auto FI = MF.getInfo<WebAssemblyFunctionInfo>();
186     unsigned BasePtr = MRI.createVirtualRegister(PtrRC);
187     FI->setBasePointerVreg(BasePtr);
188     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY), BasePtr)
189         .addReg(SPReg);
190   }
191   if (StackSize) {
192     // Subtract the frame size
193     unsigned OffsetReg = MRI.createVirtualRegister(PtrRC);
194     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), OffsetReg)
195         .addImm(StackSize);
196     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::SUB_I32),
197             WebAssembly::SP32)
198         .addReg(SPReg)
199         .addReg(OffsetReg);
200   }
201   if (HasBP) {
202     unsigned BitmaskReg = MRI.createVirtualRegister(PtrRC);
203     unsigned Alignment = MFI.getMaxAlignment();
204     assert((1u << countTrailingZeros(Alignment)) == Alignment &&
205       "Alignment must be a power of 2");
206     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), BitmaskReg)
207         .addImm((int)~(Alignment - 1));
208     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::AND_I32),
209             WebAssembly::SP32)
210         .addReg(WebAssembly::SP32)
211         .addReg(BitmaskReg);
212   }
213   if (hasFP(MF)) {
214     // Unlike most conventional targets (where FP points to the saved FP),
215     // FP points to the bottom of the fixed-size locals, so we can use positive
216     // offsets in load/store instructions.
217     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY),
218             WebAssembly::FP32)
219         .addReg(WebAssembly::SP32);
220   }
221   if (StackSize && needsSPWriteback(MF)) {
222     writeSPToGlobal(WebAssembly::SP32, MF, MBB, InsertPt, DL);
223   }
224 }
225 
226 void WebAssemblyFrameLowering::emitEpilogue(MachineFunction &MF,
227                                             MachineBasicBlock &MBB) const {
228   uint64_t StackSize = MF.getFrameInfo().getStackSize();
229   if (!needsSP(MF) || !needsSPWriteback(MF)) return;
230   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
231   auto &MRI = MF.getRegInfo();
232   auto InsertPt = MBB.getFirstTerminator();
233   DebugLoc DL;
234 
235   if (InsertPt != MBB.end())
236     DL = InsertPt->getDebugLoc();
237 
238   // Restore the stack pointer. If we had fixed-size locals, add the offset
239   // subtracted in the prolog.
240   unsigned SPReg = 0;
241   if (hasBP(MF)) {
242     auto FI = MF.getInfo<WebAssemblyFunctionInfo>();
243     SPReg = FI->getBasePointerVreg();
244   } else if (StackSize) {
245     const TargetRegisterClass *PtrRC =
246         MRI.getTargetRegisterInfo()->getPointerRegClass(MF);
247     unsigned OffsetReg = MRI.createVirtualRegister(PtrRC);
248     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), OffsetReg)
249         .addImm(StackSize);
250     // In the epilog we don't need to write the result back to the SP32 physreg
251     // because it won't be used again. We can use a stackified register instead.
252     SPReg = MRI.createVirtualRegister(PtrRC);
253     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::ADD_I32), SPReg)
254         .addReg(hasFP(MF) ? WebAssembly::FP32 : WebAssembly::SP32)
255         .addReg(OffsetReg);
256   } else {
257     SPReg = hasFP(MF) ? WebAssembly::FP32 : WebAssembly::SP32;
258   }
259 
260   writeSPToGlobal(SPReg, MF, MBB, InsertPt, DL);
261 }
262