xref: /llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp (revision f3b4f99007cdcb3306484c9a39d31addc20aaa69)
1 //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file defines the WebAssembly-specific subclass of TargetMachine.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "WebAssemblyTargetMachine.h"
15 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
16 #include "WebAssembly.h"
17 #include "WebAssemblyTargetObjectFile.h"
18 #include "WebAssemblyTargetTransformInfo.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/RegAllocRegistry.h"
22 #include "llvm/CodeGen/TargetPassConfig.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/Support/TargetRegistry.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Transforms/Utils.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> EnableEmException(
34     "enable-emscripten-cxx-exceptions",
35     cl::desc("WebAssembly Emscripten-style exception handling"),
36     cl::init(false));
37 
38 // Emscripten's asm.js-style setjmp/longjmp handling
39 static cl::opt<bool> EnableEmSjLj(
40     "enable-emscripten-sjlj",
41     cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
42     cl::init(false));
43 
44 extern "C" void LLVMInitializeWebAssemblyTarget() {
45   // Register the target.
46   RegisterTargetMachine<WebAssemblyTargetMachine> X(
47       getTheWebAssemblyTarget32());
48   RegisterTargetMachine<WebAssemblyTargetMachine> Y(
49       getTheWebAssemblyTarget64());
50 
51   // Register backend passes
52   auto &PR = *PassRegistry::getPassRegistry();
53   initializeWebAssemblyAddMissingPrototypesPass(PR);
54   initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
55   initializeLowerGlobalDtorsPass(PR);
56   initializeFixFunctionBitcastsPass(PR);
57   initializeOptimizeReturnedPass(PR);
58   initializeWebAssemblyArgumentMovePass(PR);
59   initializeWebAssemblySetP2AlignOperandsPass(PR);
60   initializeWebAssemblyReplacePhysRegsPass(PR);
61   initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
62   initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
63   initializeWebAssemblyMemIntrinsicResultsPass(PR);
64   initializeWebAssemblyRegStackifyPass(PR);
65   initializeWebAssemblyRegColoringPass(PR);
66   initializeWebAssemblyExplicitLocalsPass(PR);
67   initializeWebAssemblyFixIrreducibleControlFlowPass(PR);
68   initializeWebAssemblyLateEHPreparePass(PR);
69   initializeWebAssemblyExceptionInfoPass(PR);
70   initializeWebAssemblyCFGSortPass(PR);
71   initializeWebAssemblyCFGStackifyPass(PR);
72   initializeWebAssemblyLowerBrUnlessPass(PR);
73   initializeWebAssemblyRegNumberingPass(PR);
74   initializeWebAssemblyPeepholePass(PR);
75   initializeWebAssemblyCallIndirectFixupPass(PR);
76 }
77 
78 //===----------------------------------------------------------------------===//
79 // WebAssembly Lowering public interface.
80 //===----------------------------------------------------------------------===//
81 
82 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
83   if (!RM.hasValue()) {
84     // Default to static relocation model.  This should always be more optimial
85     // than PIC since the static linker can determine all global addresses and
86     // assume direct function calls.
87     return Reloc::Static;
88   }
89   return *RM;
90 }
91 
92 /// Create an WebAssembly architecture model.
93 ///
94 WebAssemblyTargetMachine::WebAssemblyTargetMachine(
95     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
96     const TargetOptions &Options, Optional<Reloc::Model> RM,
97     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
98     : LLVMTargetMachine(T,
99                         TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
100                                          : "e-m:e-p:32:32-i64:64-n32:64-S128",
101                         TT, CPU, FS, Options, getEffectiveRelocModel(RM),
102                         getEffectiveCodeModel(CM, CodeModel::Large), OL),
103       TLOF(new WebAssemblyTargetObjectFile()) {
104   // WebAssembly type-checks instructions, but a noreturn function with a return
105   // type that doesn't match the context will cause a check failure. So we lower
106   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
107   // 'unreachable' instructions which is meant for that case.
108   this->Options.TrapUnreachable = true;
109 
110   // WebAssembly treats each function as an independent unit. Force
111   // -ffunction-sections, effectively, so that we can emit them independently.
112   this->Options.FunctionSections = true;
113   this->Options.DataSections = true;
114   this->Options.UniqueSectionNames = true;
115 
116   initAsmInfo();
117 
118   // Create a subtarget using the unmodified target machine features to
119   // initialize the used feature set with explicitly enabled features.
120   getSubtargetImpl(getTargetCPU(), getTargetFeatureString());
121 
122   // Note that we don't use setRequiresStructuredCFG(true). It disables
123   // optimizations than we're ok with, and want, such as critical edge
124   // splitting and tail merging.
125 }
126 
127 WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
128 
129 const WebAssemblySubtarget *
130 WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
131                                            std::string FS) const {
132   auto &I = SubtargetMap[CPU + FS];
133   if (!I) {
134     I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
135     UsedFeatures |= I->getFeatureBits();
136   }
137   return I.get();
138 }
139 
140 const WebAssemblySubtarget *
141 WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
142   Attribute CPUAttr = F.getFnAttribute("target-cpu");
143   Attribute FSAttr = F.getFnAttribute("target-features");
144 
145   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
146                         ? CPUAttr.getValueAsString().str()
147                         : TargetCPU;
148   std::string FS = !FSAttr.hasAttribute(Attribute::None)
149                        ? FSAttr.getValueAsString().str()
150                        : TargetFS;
151 
152   // This needs to be done before we create a new subtarget since any
153   // creation will depend on the TM and the code generation flags on the
154   // function that reside in TargetOptions.
155   resetTargetOptions(F);
156 
157   return getSubtargetImpl(CPU, FS);
158 }
159 
160 namespace {
161 class StripThreadLocal final : public ModulePass {
162   // The default thread model for wasm is single, where thread-local variables
163   // are identical to regular globals and should be treated the same. So this
164   // pass just converts all GlobalVariables to NotThreadLocal
165   static char ID;
166 
167 public:
168   StripThreadLocal() : ModulePass(ID) {}
169   bool runOnModule(Module &M) override {
170     for (auto &GV : M.globals())
171       GV.setThreadLocalMode(GlobalValue::ThreadLocalMode::NotThreadLocal);
172     return true;
173   }
174 };
175 char StripThreadLocal::ID = 0;
176 
177 /// WebAssembly Code Generator Pass Configuration Options.
178 class WebAssemblyPassConfig final : public TargetPassConfig {
179 public:
180   WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
181       : TargetPassConfig(TM, PM) {}
182 
183   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
184     return getTM<WebAssemblyTargetMachine>();
185   }
186 
187   FunctionPass *createTargetRegisterAllocator(bool) override;
188 
189   void addIRPasses() override;
190   bool addInstSelector() override;
191   void addPostRegAlloc() override;
192   bool addGCPasses() override { return false; }
193   void addPreEmitPass() override;
194 };
195 } // end anonymous namespace
196 
197 TargetTransformInfo
198 WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
199   return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
200 }
201 
202 TargetPassConfig *
203 WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
204   return new WebAssemblyPassConfig(*this, PM);
205 }
206 
207 FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
208   return nullptr; // No reg alloc
209 }
210 
211 //===----------------------------------------------------------------------===//
212 // The following functions are called from lib/CodeGen/Passes.cpp to modify
213 // the CodeGen pass sequence.
214 //===----------------------------------------------------------------------===//
215 
216 void WebAssemblyPassConfig::addIRPasses() {
217   if (static_cast<WebAssemblyTargetMachine *>(TM)
218           ->getUsedFeatures()[WebAssembly::FeatureAtomics]) {
219     // Expand some atomic operations. WebAssemblyTargetLowering has hooks which
220     // control specifically what gets lowered.
221     addPass(createAtomicExpandPass());
222   } else {
223     // If atomics are not enabled, they get lowered to non-atomics.
224     addPass(createLowerAtomicPass());
225     addPass(new StripThreadLocal());
226   }
227 
228   // Add signatures to prototype-less function declarations
229   addPass(createWebAssemblyAddMissingPrototypes());
230 
231   // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
232   addPass(createWebAssemblyLowerGlobalDtors());
233 
234   // Fix function bitcasts, as WebAssembly requires caller and callee signatures
235   // to match.
236   addPass(createWebAssemblyFixFunctionBitcasts());
237 
238   // Optimize "returned" function attributes.
239   if (getOptLevel() != CodeGenOpt::None)
240     addPass(createWebAssemblyOptimizeReturned());
241 
242   // If exception handling is not enabled and setjmp/longjmp handling is
243   // enabled, we lower invokes into calls and delete unreachable landingpad
244   // blocks. Lowering invokes when there is no EH support is done in
245   // TargetPassConfig::addPassesToHandleExceptions, but this runs after this
246   // function and SjLj handling expects all invokes to be lowered before.
247   if (!EnableEmException &&
248       TM->Options.ExceptionModel == ExceptionHandling::None) {
249     addPass(createLowerInvokePass());
250     // The lower invoke pass may create unreachable code. Remove it in order not
251     // to process dead blocks in setjmp/longjmp handling.
252     addPass(createUnreachableBlockEliminationPass());
253   }
254 
255   // Handle exceptions and setjmp/longjmp if enabled.
256   if (EnableEmException || EnableEmSjLj)
257     addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException,
258                                                    EnableEmSjLj));
259 
260   TargetPassConfig::addIRPasses();
261 }
262 
263 bool WebAssemblyPassConfig::addInstSelector() {
264   (void)TargetPassConfig::addInstSelector();
265   addPass(
266       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
267   // Run the argument-move pass immediately after the ScheduleDAG scheduler
268   // so that we can fix up the ARGUMENT instructions before anything else
269   // sees them in the wrong place.
270   addPass(createWebAssemblyArgumentMove());
271   // Set the p2align operands. This information is present during ISel, however
272   // it's inconvenient to collect. Collect it now, and update the immediate
273   // operands.
274   addPass(createWebAssemblySetP2AlignOperands());
275   return false;
276 }
277 
278 void WebAssemblyPassConfig::addPostRegAlloc() {
279   // TODO: The following CodeGen passes don't currently support code containing
280   // virtual registers. Consider removing their restrictions and re-enabling
281   // them.
282 
283   // These functions all require the NoVRegs property.
284   disablePass(&MachineCopyPropagationID);
285   disablePass(&PostRAMachineSinkingID);
286   disablePass(&PostRASchedulerID);
287   disablePass(&FuncletLayoutID);
288   disablePass(&StackMapLivenessID);
289   disablePass(&LiveDebugValuesID);
290   disablePass(&PatchableFunctionID);
291   disablePass(&ShrinkWrapID);
292 
293   TargetPassConfig::addPostRegAlloc();
294 }
295 
296 void WebAssemblyPassConfig::addPreEmitPass() {
297   TargetPassConfig::addPreEmitPass();
298 
299   // Rewrite pseudo call_indirect instructions as real instructions.
300   // This needs to run before register stackification, because we change the
301   // order of the arguments.
302   addPass(createWebAssemblyCallIndirectFixup());
303 
304   // Eliminate multiple-entry loops.
305   addPass(createWebAssemblyFixIrreducibleControlFlow());
306 
307   // Do various transformations for exception handling.
308   // Every CFG-changing optimizations should come before this.
309   addPass(createWebAssemblyLateEHPrepare());
310 
311   // Now that we have a prologue and epilogue and all frame indices are
312   // rewritten, eliminate SP and FP. This allows them to be stackified,
313   // colored, and numbered with the rest of the registers.
314   addPass(createWebAssemblyReplacePhysRegs());
315 
316   // Preparations and optimizations related to register stackification.
317   if (getOptLevel() != CodeGenOpt::None) {
318     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
319     addPass(createWebAssemblyPrepareForLiveIntervals());
320 
321     // Depend on LiveIntervals and perform some optimizations on it.
322     addPass(createWebAssemblyOptimizeLiveIntervals());
323 
324     // Prepare memory intrinsic calls for register stackifying.
325     addPass(createWebAssemblyMemIntrinsicResults());
326 
327     // Mark registers as representing wasm's value stack. This is a key
328     // code-compression technique in WebAssembly. We run this pass (and
329     // MemIntrinsicResults above) very late, so that it sees as much code as
330     // possible, including code emitted by PEI and expanded by late tail
331     // duplication.
332     addPass(createWebAssemblyRegStackify());
333 
334     // Run the register coloring pass to reduce the total number of registers.
335     // This runs after stackification so that it doesn't consider registers
336     // that become stackified.
337     addPass(createWebAssemblyRegColoring());
338   }
339 
340   // Insert explicit local.get and local.set operators.
341   addPass(createWebAssemblyExplicitLocals());
342 
343   // Sort the blocks of the CFG into topological order, a prerequisite for
344   // BLOCK and LOOP markers.
345   addPass(createWebAssemblyCFGSort());
346 
347   // Insert BLOCK and LOOP markers.
348   addPass(createWebAssemblyCFGStackify());
349 
350   // Lower br_unless into br_if.
351   addPass(createWebAssemblyLowerBrUnless());
352 
353   // Perform the very last peephole optimizations on the code.
354   if (getOptLevel() != CodeGenOpt::None)
355     addPass(createWebAssemblyPeephole());
356 
357   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
358   addPass(createWebAssemblyRegNumbering());
359 }
360