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 "TargetInfo/WebAssemblyTargetInfo.h"
17 #include "WebAssembly.h"
18 #include "WebAssemblyMachineFunctionInfo.h"
19 #include "WebAssemblyTargetObjectFile.h"
20 #include "WebAssemblyTargetTransformInfo.h"
21 #include "llvm/CodeGen/MIRParser/MIParser.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Scalar/LowerAtomic.h"
31 #include "llvm/Transforms/Utils.h"
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "wasm"
35 
36 // Emscripten's asm.js-style exception handling
37 cl::opt<bool> EnableEmException(
38     "enable-emscripten-cxx-exceptions",
39     cl::desc("WebAssembly Emscripten-style exception handling"),
40     cl::init(false));
41 
42 // Emscripten's asm.js-style setjmp/longjmp handling
43 cl::opt<bool> EnableEmSjLj(
44     "enable-emscripten-sjlj",
45     cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
46     cl::init(false));
47 
48 // A command-line option to keep implicit locals
49 // for the purpose of testing with lit/llc ONLY.
50 // This produces output which is not valid WebAssembly, and is not supported
51 // by assemblers/disassemblers and other MC based tools.
52 static cl::opt<bool> WasmDisableExplicitLocals(
53     "wasm-disable-explicit-locals", cl::Hidden,
54     cl::desc("WebAssembly: output implicit locals in"
55              " instruction output for test purposes only."),
56     cl::init(false));
57 
58 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyTarget() {
59   // Register the target.
60   RegisterTargetMachine<WebAssemblyTargetMachine> X(
61       getTheWebAssemblyTarget32());
62   RegisterTargetMachine<WebAssemblyTargetMachine> Y(
63       getTheWebAssemblyTarget64());
64 
65   // Register backend passes
66   auto &PR = *PassRegistry::getPassRegistry();
67   initializeWebAssemblyAddMissingPrototypesPass(PR);
68   initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
69   initializeLowerGlobalDtorsPass(PR);
70   initializeFixFunctionBitcastsPass(PR);
71   initializeOptimizeReturnedPass(PR);
72   initializeWebAssemblyArgumentMovePass(PR);
73   initializeWebAssemblySetP2AlignOperandsPass(PR);
74   initializeWebAssemblyReplacePhysRegsPass(PR);
75   initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
76   initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
77   initializeWebAssemblyMemIntrinsicResultsPass(PR);
78   initializeWebAssemblyRegStackifyPass(PR);
79   initializeWebAssemblyRegColoringPass(PR);
80   initializeWebAssemblyNullifyDebugValueListsPass(PR);
81   initializeWebAssemblyFixIrreducibleControlFlowPass(PR);
82   initializeWebAssemblyLateEHPreparePass(PR);
83   initializeWebAssemblyExceptionInfoPass(PR);
84   initializeWebAssemblyCFGSortPass(PR);
85   initializeWebAssemblyCFGStackifyPass(PR);
86   initializeWebAssemblyExplicitLocalsPass(PR);
87   initializeWebAssemblyLowerBrUnlessPass(PR);
88   initializeWebAssemblyRegNumberingPass(PR);
89   initializeWebAssemblyDebugFixupPass(PR);
90   initializeWebAssemblyPeepholePass(PR);
91 }
92 
93 //===----------------------------------------------------------------------===//
94 // WebAssembly Lowering public interface.
95 //===----------------------------------------------------------------------===//
96 
97 static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM,
98                                            const Triple &TT) {
99   if (!RM.hasValue()) {
100     // Default to static relocation model.  This should always be more optimial
101     // than PIC since the static linker can determine all global addresses and
102     // assume direct function calls.
103     return Reloc::Static;
104   }
105 
106   if (!TT.isOSEmscripten()) {
107     // Relocation modes other than static are currently implemented in a way
108     // that only works for Emscripten, so disable them if we aren't targeting
109     // Emscripten.
110     return Reloc::Static;
111   }
112 
113   return *RM;
114 }
115 
116 // Check for reference types in Feature String, in order to extend target
117 // description string
118 static bool hasReferenceTypes(const StringRef &FS) {
119   return FS.find("+reference-types") != StringRef::npos;
120 }
121 
122 /// Create an WebAssembly architecture model.
123 ///
124 WebAssemblyTargetMachine::WebAssemblyTargetMachine(
125     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
126     const TargetOptions &Options, Optional<Reloc::Model> RM,
127     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
128     : LLVMTargetMachine(T,
129                         TT.isArch64Bit()
130                             ? (hasReferenceTypes(FS)
131                                    ? "e-m:e-p:64:64-i64:64-n32:64-S128-ni:1:10:20"
132                                    : "e-m:e-p:64:64-i64:64-n32:64-S128-ni:1")
133                             : (hasReferenceTypes(FS)
134                                    ? "e-m:e-p:32:32-i64:64-n32:64-S128-ni:1:10:20"
135                                    : "e-m:e-p:32:32-i64:64-n32:64-S128-ni:1"),
136                         TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT),
137                         getEffectiveCodeModel(CM, CodeModel::Large), OL),
138       TLOF(new WebAssemblyTargetObjectFile()) {
139   // WebAssembly type-checks instructions, but a noreturn function with a return
140   // type that doesn't match the context will cause a check failure. So we lower
141   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
142   // 'unreachable' instructions which is meant for that case.
143   this->Options.TrapUnreachable = true;
144 
145   // WebAssembly treats each function as an independent unit. Force
146   // -ffunction-sections, effectively, so that we can emit them independently.
147   this->Options.FunctionSections = true;
148   this->Options.DataSections = true;
149   this->Options.UniqueSectionNames = true;
150 
151   initAsmInfo();
152 
153   // Note that we don't use setRequiresStructuredCFG(true). It disables
154   // optimizations than we're ok with, and want, such as critical edge
155   // splitting and tail merging.
156 }
157 
158 WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
159 
160 const WebAssemblySubtarget *WebAssemblyTargetMachine::getSubtargetImpl() const {
161   return getSubtargetImpl(std::string(getTargetCPU()),
162                           std::string(getTargetFeatureString()));
163 }
164 
165 const WebAssemblySubtarget *
166 WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
167                                            std::string FS) const {
168   auto &I = SubtargetMap[CPU + FS];
169   if (!I) {
170     I = std::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
171   }
172   return I.get();
173 }
174 
175 const WebAssemblySubtarget *
176 WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
177   Attribute CPUAttr = F.getFnAttribute("target-cpu");
178   Attribute FSAttr = F.getFnAttribute("target-features");
179 
180   std::string CPU =
181       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
182   std::string FS =
183       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
184 
185   // This needs to be done before we create a new subtarget since any
186   // creation will depend on the TM and the code generation flags on the
187   // function that reside in TargetOptions.
188   resetTargetOptions(F);
189 
190   return getSubtargetImpl(CPU, FS);
191 }
192 
193 namespace {
194 
195 class CoalesceFeaturesAndStripAtomics final : public ModulePass {
196   // Take the union of all features used in the module and use it for each
197   // function individually, since having multiple feature sets in one module
198   // currently does not make sense for WebAssembly. If atomics are not enabled,
199   // also strip atomic operations and thread local storage.
200   static char ID;
201   WebAssemblyTargetMachine *WasmTM;
202 
203 public:
204   CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM)
205       : ModulePass(ID), WasmTM(WasmTM) {}
206 
207   bool runOnModule(Module &M) override {
208     FeatureBitset Features = coalesceFeatures(M);
209 
210     std::string FeatureStr = getFeatureString(Features);
211     WasmTM->setTargetFeatureString(FeatureStr);
212     for (auto &F : M)
213       replaceFeatures(F, FeatureStr);
214 
215     bool StrippedAtomics = false;
216     bool StrippedTLS = false;
217 
218     if (!Features[WebAssembly::FeatureAtomics])
219       StrippedAtomics = stripAtomics(M);
220 
221     if (!Features[WebAssembly::FeatureBulkMemory])
222       StrippedTLS = stripThreadLocals(M);
223 
224     if (StrippedAtomics && !StrippedTLS)
225       stripThreadLocals(M);
226     else if (StrippedTLS && !StrippedAtomics)
227       stripAtomics(M);
228 
229     recordFeatures(M, Features, StrippedAtomics || StrippedTLS);
230 
231     // Conservatively assume we have made some change
232     return true;
233   }
234 
235 private:
236   FeatureBitset coalesceFeatures(const Module &M) {
237     FeatureBitset Features =
238         WasmTM
239             ->getSubtargetImpl(std::string(WasmTM->getTargetCPU()),
240                                std::string(WasmTM->getTargetFeatureString()))
241             ->getFeatureBits();
242     for (auto &F : M)
243       Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits();
244     return Features;
245   }
246 
247   std::string getFeatureString(const FeatureBitset &Features) {
248     std::string Ret;
249     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
250       if (Features[KV.Value])
251         Ret += (StringRef("+") + KV.Key + ",").str();
252     }
253     return Ret;
254   }
255 
256   void replaceFeatures(Function &F, const std::string &Features) {
257     F.removeFnAttr("target-features");
258     F.removeFnAttr("target-cpu");
259     F.addFnAttr("target-features", Features);
260   }
261 
262   bool stripAtomics(Module &M) {
263     // Detect whether any atomics will be lowered, since there is no way to tell
264     // whether the LowerAtomic pass lowers e.g. stores.
265     bool Stripped = false;
266     for (auto &F : M) {
267       for (auto &B : F) {
268         for (auto &I : B) {
269           if (I.isAtomic()) {
270             Stripped = true;
271             goto done;
272           }
273         }
274       }
275     }
276 
277   done:
278     if (!Stripped)
279       return false;
280 
281     LowerAtomicPass Lowerer;
282     FunctionAnalysisManager FAM;
283     for (auto &F : M)
284       Lowerer.run(F, FAM);
285 
286     return true;
287   }
288 
289   bool stripThreadLocals(Module &M) {
290     bool Stripped = false;
291     for (auto &GV : M.globals()) {
292       if (GV.isThreadLocal()) {
293         Stripped = true;
294         GV.setThreadLocal(false);
295       }
296     }
297     return Stripped;
298   }
299 
300   void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) {
301     for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) {
302       if (Features[KV.Value]) {
303         // Mark features as used
304         std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str();
305         M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey,
306                         wasm::WASM_FEATURE_PREFIX_USED);
307       }
308     }
309     // Code compiled without atomics or bulk-memory may have had its atomics or
310     // thread-local data lowered to nonatomic operations or non-thread-local
311     // data. In that case, we mark the pseudo-feature "shared-mem" as disallowed
312     // to tell the linker that it would be unsafe to allow this code ot be used
313     // in a module with shared memory.
314     if (Stripped) {
315       M.addModuleFlag(Module::ModFlagBehavior::Error, "wasm-feature-shared-mem",
316                       wasm::WASM_FEATURE_PREFIX_DISALLOWED);
317     }
318   }
319 };
320 char CoalesceFeaturesAndStripAtomics::ID = 0;
321 
322 /// WebAssembly Code Generator Pass Configuration Options.
323 class WebAssemblyPassConfig final : public TargetPassConfig {
324 public:
325   WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
326       : TargetPassConfig(TM, PM) {}
327 
328   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
329     return getTM<WebAssemblyTargetMachine>();
330   }
331 
332   FunctionPass *createTargetRegisterAllocator(bool) override;
333 
334   void addIRPasses() override;
335   bool addInstSelector() override;
336   void addPostRegAlloc() override;
337   bool addGCPasses() override { return false; }
338   void addPreEmitPass() override;
339 
340   // No reg alloc
341   bool addRegAssignAndRewriteFast() override { return false; }
342 
343   // No reg alloc
344   bool addRegAssignAndRewriteOptimized() override { return false; }
345 };
346 } // end anonymous namespace
347 
348 TargetTransformInfo
349 WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
350   return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
351 }
352 
353 TargetPassConfig *
354 WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
355   return new WebAssemblyPassConfig(*this, PM);
356 }
357 
358 FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
359   return nullptr; // No reg alloc
360 }
361 
362 //===----------------------------------------------------------------------===//
363 // The following functions are called from lib/CodeGen/Passes.cpp to modify
364 // the CodeGen pass sequence.
365 //===----------------------------------------------------------------------===//
366 
367 void WebAssemblyPassConfig::addIRPasses() {
368   // Lower atomics and TLS if necessary
369   addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine()));
370 
371   // This is a no-op if atomics are not used in the module
372   addPass(createAtomicExpandPass());
373 
374   // Add signatures to prototype-less function declarations
375   addPass(createWebAssemblyAddMissingPrototypes());
376 
377   // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
378   addPass(createWebAssemblyLowerGlobalDtors());
379 
380   // Fix function bitcasts, as WebAssembly requires caller and callee signatures
381   // to match.
382   addPass(createWebAssemblyFixFunctionBitcasts());
383 
384   // Optimize "returned" function attributes.
385   if (getOptLevel() != CodeGenOpt::None)
386     addPass(createWebAssemblyOptimizeReturned());
387 
388   // If exception handling is not enabled and setjmp/longjmp handling is
389   // enabled, we lower invokes into calls and delete unreachable landingpad
390   // blocks. Lowering invokes when there is no EH support is done in
391   // TargetPassConfig::addPassesToHandleExceptions, but this runs after this
392   // function and SjLj handling expects all invokes to be lowered before.
393   if (!EnableEmException &&
394       TM->Options.ExceptionModel == ExceptionHandling::None) {
395     addPass(createLowerInvokePass());
396     // The lower invoke pass may create unreachable code. Remove it in order not
397     // to process dead blocks in setjmp/longjmp handling.
398     addPass(createUnreachableBlockEliminationPass());
399   }
400 
401   // Handle exceptions and setjmp/longjmp if enabled.
402   if (EnableEmException || EnableEmSjLj)
403     addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException,
404                                                    EnableEmSjLj));
405 
406   // Expand indirectbr instructions to switches.
407   addPass(createIndirectBrExpandPass());
408 
409   TargetPassConfig::addIRPasses();
410 }
411 
412 bool WebAssemblyPassConfig::addInstSelector() {
413   (void)TargetPassConfig::addInstSelector();
414   addPass(
415       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
416   // Run the argument-move pass immediately after the ScheduleDAG scheduler
417   // so that we can fix up the ARGUMENT instructions before anything else
418   // sees them in the wrong place.
419   addPass(createWebAssemblyArgumentMove());
420   // Set the p2align operands. This information is present during ISel, however
421   // it's inconvenient to collect. Collect it now, and update the immediate
422   // operands.
423   addPass(createWebAssemblySetP2AlignOperands());
424 
425   // Eliminate range checks and add default targets to br_table instructions.
426   addPass(createWebAssemblyFixBrTableDefaults());
427 
428   return false;
429 }
430 
431 void WebAssemblyPassConfig::addPostRegAlloc() {
432   // TODO: The following CodeGen passes don't currently support code containing
433   // virtual registers. Consider removing their restrictions and re-enabling
434   // them.
435 
436   // These functions all require the NoVRegs property.
437   disablePass(&MachineCopyPropagationID);
438   disablePass(&PostRAMachineSinkingID);
439   disablePass(&PostRASchedulerID);
440   disablePass(&FuncletLayoutID);
441   disablePass(&StackMapLivenessID);
442   disablePass(&LiveDebugValuesID);
443   disablePass(&PatchableFunctionID);
444   disablePass(&ShrinkWrapID);
445 
446   // This pass hurts code size for wasm because it can generate irreducible
447   // control flow.
448   disablePass(&MachineBlockPlacementID);
449 
450   TargetPassConfig::addPostRegAlloc();
451 }
452 
453 void WebAssemblyPassConfig::addPreEmitPass() {
454   TargetPassConfig::addPreEmitPass();
455 
456   // Nullify DBG_VALUE_LISTs that we cannot handle.
457   addPass(createWebAssemblyNullifyDebugValueLists());
458 
459   // Eliminate multiple-entry loops.
460   addPass(createWebAssemblyFixIrreducibleControlFlow());
461 
462   // Do various transformations for exception handling.
463   // Every CFG-changing optimizations should come before this.
464   if (TM->Options.ExceptionModel == ExceptionHandling::Wasm)
465     addPass(createWebAssemblyLateEHPrepare());
466 
467   // Now that we have a prologue and epilogue and all frame indices are
468   // rewritten, eliminate SP and FP. This allows them to be stackified,
469   // colored, and numbered with the rest of the registers.
470   addPass(createWebAssemblyReplacePhysRegs());
471 
472   // Preparations and optimizations related to register stackification.
473   if (getOptLevel() != CodeGenOpt::None) {
474     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
475     addPass(createWebAssemblyPrepareForLiveIntervals());
476 
477     // Depend on LiveIntervals and perform some optimizations on it.
478     addPass(createWebAssemblyOptimizeLiveIntervals());
479 
480     // Prepare memory intrinsic calls for register stackifying.
481     addPass(createWebAssemblyMemIntrinsicResults());
482 
483     // Mark registers as representing wasm's value stack. This is a key
484     // code-compression technique in WebAssembly. We run this pass (and
485     // MemIntrinsicResults above) very late, so that it sees as much code as
486     // possible, including code emitted by PEI and expanded by late tail
487     // duplication.
488     addPass(createWebAssemblyRegStackify());
489 
490     // Run the register coloring pass to reduce the total number of registers.
491     // This runs after stackification so that it doesn't consider registers
492     // that become stackified.
493     addPass(createWebAssemblyRegColoring());
494   }
495 
496   // Sort the blocks of the CFG into topological order, a prerequisite for
497   // BLOCK and LOOP markers.
498   addPass(createWebAssemblyCFGSort());
499 
500   // Insert BLOCK and LOOP markers.
501   addPass(createWebAssemblyCFGStackify());
502 
503   // Insert explicit local.get and local.set operators.
504   if (!WasmDisableExplicitLocals)
505     addPass(createWebAssemblyExplicitLocals());
506 
507   // Lower br_unless into br_if.
508   addPass(createWebAssemblyLowerBrUnless());
509 
510   // Perform the very last peephole optimizations on the code.
511   if (getOptLevel() != CodeGenOpt::None)
512     addPass(createWebAssemblyPeephole());
513 
514   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
515   addPass(createWebAssemblyRegNumbering());
516 
517   // Fix debug_values whose defs have been stackified.
518   if (!WasmDisableExplicitLocals)
519     addPass(createWebAssemblyDebugFixup());
520 }
521 
522 yaml::MachineFunctionInfo *
523 WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
524   return new yaml::WebAssemblyFunctionInfo();
525 }
526 
527 yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
528     const MachineFunction &MF) const {
529   const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
530   return new yaml::WebAssemblyFunctionInfo(*MFI);
531 }
532 
533 bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
534     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
535     SMDiagnostic &Error, SMRange &SourceRange) const {
536   const auto &YamlMFI =
537       reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
538   MachineFunction &MF = PFS.MF;
539   MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
540   return false;
541 }
542