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