xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp (revision 53b9af02c8437c03508f5fb34d5902352300bf9a)
1 //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
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 defines the WebAssembly-specific subclass of TargetMachine.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "WebAssembly.h"
16 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
17 #include "WebAssemblyTargetMachine.h"
18 #include "WebAssemblyTargetObjectFile.h"
19 #include "WebAssemblyTargetTransformInfo.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Transforms/Scalar.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "wasm"
31 
32 // Emscripten's asm.js-style exception handling
33 static cl::opt<bool> EnableEmExceptionHandling(
34     "enable-emscripten-cxx-exceptions",
35     cl::desc("WebAssembly Emscripten-style exception handling"),
36     cl::init(false));
37 
38 extern "C" void LLVMInitializeWebAssemblyTarget() {
39   // Register the target.
40   RegisterTargetMachine<WebAssemblyTargetMachine> X(TheWebAssemblyTarget32);
41   RegisterTargetMachine<WebAssemblyTargetMachine> Y(TheWebAssemblyTarget64);
42 
43   // Register exception handling pass to opt
44   initializeWebAssemblyLowerEmscriptenExceptionsPass(
45       *PassRegistry::getPassRegistry());
46 }
47 
48 //===----------------------------------------------------------------------===//
49 // WebAssembly Lowering public interface.
50 //===----------------------------------------------------------------------===//
51 
52 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
53   if (!RM.hasValue())
54     return Reloc::PIC_;
55   return *RM;
56 }
57 
58 /// Create an WebAssembly architecture model.
59 ///
60 WebAssemblyTargetMachine::WebAssemblyTargetMachine(
61     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
62     const TargetOptions &Options, Optional<Reloc::Model> RM,
63     CodeModel::Model CM, CodeGenOpt::Level OL)
64     : LLVMTargetMachine(T,
65                         TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
66                                          : "e-m:e-p:32:32-i64:64-n32:64-S128",
67                         TT, CPU, FS, Options, getEffectiveRelocModel(RM),
68                         CM, OL),
69       TLOF(make_unique<WebAssemblyTargetObjectFile>()) {
70   // WebAssembly type-checks expressions, but a noreturn function with a return
71   // type that doesn't match the context will cause a check failure. So we lower
72   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
73   // 'unreachable' expression which is meant for that case.
74   this->Options.TrapUnreachable = true;
75 
76   initAsmInfo();
77 
78   // Note that we don't use setRequiresStructuredCFG(true). It disables
79   // optimizations than we're ok with, and want, such as critical edge
80   // splitting and tail merging.
81 }
82 
83 WebAssemblyTargetMachine::~WebAssemblyTargetMachine() {}
84 
85 const WebAssemblySubtarget *
86 WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
87   Attribute CPUAttr = F.getFnAttribute("target-cpu");
88   Attribute FSAttr = F.getFnAttribute("target-features");
89 
90   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
91                         ? CPUAttr.getValueAsString().str()
92                         : TargetCPU;
93   std::string FS = !FSAttr.hasAttribute(Attribute::None)
94                        ? FSAttr.getValueAsString().str()
95                        : TargetFS;
96 
97   auto &I = SubtargetMap[CPU + FS];
98   if (!I) {
99     // This needs to be done before we create a new subtarget since any
100     // creation will depend on the TM and the code generation flags on the
101     // function that reside in TargetOptions.
102     resetTargetOptions(F);
103     I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
104   }
105   return I.get();
106 }
107 
108 namespace {
109 /// WebAssembly Code Generator Pass Configuration Options.
110 class WebAssemblyPassConfig final : public TargetPassConfig {
111 public:
112   WebAssemblyPassConfig(WebAssemblyTargetMachine *TM, PassManagerBase &PM)
113       : TargetPassConfig(TM, PM) {}
114 
115   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
116     return getTM<WebAssemblyTargetMachine>();
117   }
118 
119   FunctionPass *createTargetRegisterAllocator(bool) override;
120 
121   void addIRPasses() override;
122   bool addInstSelector() override;
123   void addPostRegAlloc() override;
124   bool addGCPasses() override { return false; }
125   void addPreEmitPass() override;
126 };
127 } // end anonymous namespace
128 
129 TargetIRAnalysis WebAssemblyTargetMachine::getTargetIRAnalysis() {
130   return TargetIRAnalysis([this](const Function &F) {
131     return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
132   });
133 }
134 
135 TargetPassConfig *
136 WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
137   return new WebAssemblyPassConfig(this, PM);
138 }
139 
140 FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
141   return nullptr; // No reg alloc
142 }
143 
144 //===----------------------------------------------------------------------===//
145 // The following functions are called from lib/CodeGen/Passes.cpp to modify
146 // the CodeGen pass sequence.
147 //===----------------------------------------------------------------------===//
148 
149 void WebAssemblyPassConfig::addIRPasses() {
150   if (TM->Options.ThreadModel == ThreadModel::Single)
151     // In "single" mode, atomics get lowered to non-atomics.
152     addPass(createLowerAtomicPass());
153   else
154     // Expand some atomic operations. WebAssemblyTargetLowering has hooks which
155     // control specifically what gets lowered.
156     addPass(createAtomicExpandPass(TM));
157 
158   // Optimize "returned" function attributes.
159   if (getOptLevel() != CodeGenOpt::None)
160     addPass(createWebAssemblyOptimizeReturned());
161 
162   // Handle exceptions.
163   if (EnableEmExceptionHandling)
164     addPass(createWebAssemblyLowerEmscriptenExceptions());
165 
166   TargetPassConfig::addIRPasses();
167 }
168 
169 bool WebAssemblyPassConfig::addInstSelector() {
170   (void)TargetPassConfig::addInstSelector();
171   addPass(
172       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
173   // Run the argument-move pass immediately after the ScheduleDAG scheduler
174   // so that we can fix up the ARGUMENT instructions before anything else
175   // sees them in the wrong place.
176   addPass(createWebAssemblyArgumentMove());
177   // Set the p2align operands. This information is present during ISel, however
178   // it's inconvenient to collect. Collect it now, and update the immediate
179   // operands.
180   addPass(createWebAssemblySetP2AlignOperands());
181   return false;
182 }
183 
184 void WebAssemblyPassConfig::addPostRegAlloc() {
185   // TODO: The following CodeGen passes don't currently support code containing
186   // virtual registers. Consider removing their restrictions and re-enabling
187   // them.
188 
189   // Has no asserts of its own, but was not written to handle virtual regs.
190   disablePass(&ShrinkWrapID);
191 
192   // These functions all require the AllVRegsAllocated property.
193   disablePass(&MachineCopyPropagationID);
194   disablePass(&PostRASchedulerID);
195   disablePass(&FuncletLayoutID);
196   disablePass(&StackMapLivenessID);
197   disablePass(&LiveDebugValuesID);
198   disablePass(&PatchableFunctionID);
199 
200   TargetPassConfig::addPostRegAlloc();
201 }
202 
203 void WebAssemblyPassConfig::addPreEmitPass() {
204   TargetPassConfig::addPreEmitPass();
205 
206   // Now that we have a prologue and epilogue and all frame indices are
207   // rewritten, eliminate SP and FP. This allows them to be stackified,
208   // colored, and numbered with the rest of the registers.
209   addPass(createWebAssemblyReplacePhysRegs());
210 
211   if (getOptLevel() != CodeGenOpt::None) {
212     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
213     addPass(createWebAssemblyPrepareForLiveIntervals());
214 
215     // Depend on LiveIntervals and perform some optimizations on it.
216     addPass(createWebAssemblyOptimizeLiveIntervals());
217 
218     // Prepare store instructions for register stackifying.
219     addPass(createWebAssemblyStoreResults());
220 
221     // Mark registers as representing wasm's expression stack. This is a key
222     // code-compression technique in WebAssembly. We run this pass (and
223     // StoreResults above) very late, so that it sees as much code as possible,
224     // including code emitted by PEI and expanded by late tail duplication.
225     addPass(createWebAssemblyRegStackify());
226 
227     // Run the register coloring pass to reduce the total number of registers.
228     // This runs after stackification so that it doesn't consider registers
229     // that become stackified.
230     addPass(createWebAssemblyRegColoring());
231   }
232 
233   // Eliminate multiple-entry loops.
234   addPass(createWebAssemblyFixIrreducibleControlFlow());
235 
236   // Put the CFG in structured form; insert BLOCK and LOOP markers.
237   addPass(createWebAssemblyCFGStackify());
238 
239   // Lower br_unless into br_if.
240   addPass(createWebAssemblyLowerBrUnless());
241 
242   // Perform the very last peephole optimizations on the code.
243   if (getOptLevel() != CodeGenOpt::None)
244     addPass(createWebAssemblyPeephole());
245 
246   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
247   addPass(createWebAssemblyRegNumbering());
248 }
249