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 /// \brief 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 "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/Support/Debug.h"
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "wasm-frame-info"
36 
37 // TODO: wasm64
38 // TODO: Emit TargetOpcode::CFI_INSTRUCTION instructions
39 
40 /// Return true if the specified function should have a dedicated frame pointer
41 /// register.
42 bool WebAssemblyFrameLowering::hasFP(const MachineFunction &MF) const {
43   const MachineFrameInfo *MFI = MF.getFrameInfo();
44   const auto *RegInfo =
45       MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
46   return MFI->isFrameAddressTaken() || MFI->hasVarSizedObjects() ||
47          MFI->hasStackMap() || MFI->hasPatchPoint() ||
48          RegInfo->needsStackRealignment(MF);
49 }
50 
51 /// Under normal circumstances, when a frame pointer is not required, we reserve
52 /// argument space for call sites in the function immediately on entry to the
53 /// current function. This eliminates the need for add/sub sp brackets around
54 /// call sites. Returns true if the call frame is included as part of the stack
55 /// frame.
56 bool WebAssemblyFrameLowering::hasReservedCallFrame(
57     const MachineFunction &MF) const {
58   return !MF.getFrameInfo()->hasVarSizedObjects();
59 }
60 
61 
62 /// Returns true if this function needs a local user-space stack pointer.
63 /// Unlike a machine stack pointer, the wasm user stack pointer is a global
64 /// variable, so it is loaded into a register in the prolog.
65 bool WebAssemblyFrameLowering::needsSP(const MachineFunction &MF,
66                                        const MachineFrameInfo &MFI) const {
67   return MFI.getStackSize() || MFI.adjustsStack() || hasFP(MF);
68 }
69 
70 /// Returns true if the local user-space stack pointer needs to be written back
71 /// to memory by this function (this is not meaningful if needsSP is false). If
72 /// false, the stack red zone can be used and only a local SP is needed.
73 bool WebAssemblyFrameLowering::needsSPWriteback(
74     const MachineFunction &MF, const MachineFrameInfo &MFI) const {
75   return MFI.getStackSize() > RedZoneSize || MFI.hasCalls() ||
76          MF.getFunction()->hasFnAttribute(Attribute::NoRedZone);
77 }
78 
79 static void writeSPToMemory(unsigned SrcReg, MachineFunction &MF,
80                             MachineBasicBlock &MBB,
81                             MachineBasicBlock::iterator &InsertPt,
82                             DebugLoc DL) {
83   auto *SPSymbol = MF.createExternalSymbolName("__stack_pointer");
84   unsigned SPAddr =
85       MF.getRegInfo().createVirtualRegister(&WebAssembly::I32RegClass);
86   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
87 
88   BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), SPAddr)
89       .addExternalSymbol(SPSymbol);
90   auto *MMO = new MachineMemOperand(MachinePointerInfo(),
91                                     MachineMemOperand::MOStore, 4, 4);
92   BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::STORE_I32),
93           WebAssembly::SP32)
94       .addImm(0)
95       .addReg(SPAddr)
96       .addImm(2)  // p2align
97       .addReg(SrcReg)
98       .addMemOperand(MMO);
99   MF.getInfo<WebAssemblyFunctionInfo>()->stackifyVReg(SPAddr);
100 }
101 
102 void WebAssemblyFrameLowering::eliminateCallFramePseudoInstr(
103     MachineFunction &MF, MachineBasicBlock &MBB,
104     MachineBasicBlock::iterator I) const {
105   assert(!I->getOperand(0).getImm() && hasFP(MF) &&
106          "Call frame pseudos should only be used for dynamic stack adjustment");
107   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
108   if (I->getOpcode() == TII->getCallFrameDestroyOpcode() &&
109       needsSPWriteback(MF, *MF.getFrameInfo())) {
110     DebugLoc DL = I->getDebugLoc();
111     writeSPToMemory(WebAssembly::SP32, MF, MBB, I, DL);
112   }
113   MBB.erase(I);
114 }
115 
116 void WebAssemblyFrameLowering::emitPrologue(MachineFunction &MF,
117                                             MachineBasicBlock &MBB) const {
118   // TODO: Do ".setMIFlag(MachineInstr::FrameSetup)" on emitted instructions
119   auto *MFI = MF.getFrameInfo();
120   assert(MFI->getCalleeSavedInfo().empty() &&
121          "WebAssembly should not have callee-saved registers");
122   auto *WFI = MF.getInfo<WebAssemblyFunctionInfo>();
123 
124   if (!needsSP(MF, *MFI)) return;
125   uint64_t StackSize = MFI->getStackSize();
126 
127   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
128   auto &MRI = MF.getRegInfo();
129 
130   auto InsertPt = MBB.begin();
131   DebugLoc DL;
132 
133   unsigned SPAddr = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
134   unsigned SPReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
135   auto *SPSymbol = MF.createExternalSymbolName("__stack_pointer");
136   BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), SPAddr)
137       .addExternalSymbol(SPSymbol);
138   // This MachinePointerInfo should reference __stack_pointer as well but
139   // doesn't because MachinePointerInfo() takes a GV which we don't have for
140   // __stack_pointer. TODO: check if PseudoSourceValue::ExternalSymbolCallEntry
141   // is appropriate instead. (likewise for EmitEpologue below)
142   auto *LoadMMO = new MachineMemOperand(MachinePointerInfo(),
143                                         MachineMemOperand::MOLoad, 4, 4);
144   // Load the SP value.
145   BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::LOAD_I32),
146           StackSize ? SPReg : (unsigned)WebAssembly::SP32)
147       .addImm(0)       // offset
148       .addReg(SPAddr)  // addr
149       .addImm(2)       // p2align
150       .addMemOperand(LoadMMO);
151   WFI->stackifyVReg(SPAddr);
152 
153   if (StackSize) {
154     // Subtract the frame size
155     unsigned OffsetReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
156     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), OffsetReg)
157         .addImm(StackSize);
158     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::SUB_I32),
159             WebAssembly::SP32)
160         .addReg(SPReg)
161         .addReg(OffsetReg);
162     WFI->stackifyVReg(OffsetReg);
163     WFI->stackifyVReg(SPReg);
164   }
165   if (hasFP(MF)) {
166     // Unlike most conventional targets (where FP points to the saved FP),
167     // FP points to the bottom of the fixed-size locals, so we can use positive
168     // offsets in load/store instructions.
169     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY_LOCAL_I32),
170             WebAssembly::FP32)
171         .addReg(WebAssembly::SP32);
172   }
173   if (StackSize && needsSPWriteback(MF, *MFI)) {
174     writeSPToMemory(WebAssembly::SP32, MF, MBB, InsertPt, DL);
175   }
176 }
177 
178 void WebAssemblyFrameLowering::emitEpilogue(MachineFunction &MF,
179                                             MachineBasicBlock &MBB) const {
180   auto *MFI = MF.getFrameInfo();
181   uint64_t StackSize = MFI->getStackSize();
182   if (!needsSP(MF, *MFI) || !needsSPWriteback(MF, *MFI)) return;
183   auto *WFI = MF.getInfo<WebAssemblyFunctionInfo>();
184   const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
185   auto &MRI = MF.getRegInfo();
186   auto InsertPt = MBB.getFirstTerminator();
187   DebugLoc DL;
188 
189   if (InsertPt != MBB.end()) {
190     DL = InsertPt->getDebugLoc();
191   }
192 
193   // Restore the stack pointer. If we had fixed-size locals, add the offset
194   // subtracted in the prolog.
195   if (StackSize) {
196     unsigned OffsetReg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
197     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::CONST_I32), OffsetReg)
198         .addImm(StackSize);
199     BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::ADD_I32),
200             WebAssembly::SP32)
201         .addReg(hasFP(MF) ? WebAssembly::FP32 : WebAssembly::SP32)
202         .addReg(OffsetReg);
203     WFI->stackifyVReg(OffsetReg);
204   }
205 
206   writeSPToMemory(
207       (!StackSize && hasFP(MF)) ? WebAssembly::FP32 : WebAssembly::SP32, MF,
208       MBB, InsertPt, DL);
209 }
210