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