110e730a2SDan Gohman //===- WebAssemblyTargetMachine.cpp - Define TargetMachine for WebAssembly -==//
210e730a2SDan Gohman //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
610e730a2SDan Gohman //
710e730a2SDan Gohman //===----------------------------------------------------------------------===//
810e730a2SDan Gohman ///
910e730a2SDan Gohman /// \file
105f8f34e4SAdrian Prantl /// This file defines the WebAssembly-specific subclass of TargetMachine.
1110e730a2SDan Gohman ///
1210e730a2SDan Gohman //===----------------------------------------------------------------------===//
1310e730a2SDan Gohman 
1410e730a2SDan Gohman #include "WebAssemblyTargetMachine.h"
156bda14b3SChandler Carruth #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
166bda14b3SChandler Carruth #include "WebAssembly.h"
17*52221d56SHeejin Ahn #include "WebAssemblyMachineFunctionInfo.h"
185bf22fc8SDan Gohman #include "WebAssemblyTargetObjectFile.h"
1910e730a2SDan Gohman #include "WebAssemblyTargetTransformInfo.h"
20*52221d56SHeejin Ahn #include "llvm/CodeGen/MIRParser/MIParser.h"
2110e730a2SDan Gohman #include "llvm/CodeGen/MachineFunctionPass.h"
2210e730a2SDan Gohman #include "llvm/CodeGen/Passes.h"
2310e730a2SDan Gohman #include "llvm/CodeGen/RegAllocRegistry.h"
2431d19d43SMatthias Braun #include "llvm/CodeGen/TargetPassConfig.h"
2510e730a2SDan Gohman #include "llvm/IR/Function.h"
2610e730a2SDan Gohman #include "llvm/Support/TargetRegistry.h"
2710e730a2SDan Gohman #include "llvm/Target/TargetOptions.h"
2803855df1SJF Bastien #include "llvm/Transforms/Scalar.h"
29a373d18eSDavid Blaikie #include "llvm/Transforms/Utils.h"
3010e730a2SDan Gohman using namespace llvm;
3110e730a2SDan Gohman 
3210e730a2SDan Gohman #define DEBUG_TYPE "wasm"
3310e730a2SDan Gohman 
34f41f67d3SDerek Schuff // Emscripten's asm.js-style exception handling
35ccdceda1SDerek Schuff static cl::opt<bool> EnableEmException(
3653b9af02SDerek Schuff     "enable-emscripten-cxx-exceptions",
37f41f67d3SDerek Schuff     cl::desc("WebAssembly Emscripten-style exception handling"),
38f41f67d3SDerek Schuff     cl::init(false));
39f41f67d3SDerek Schuff 
40ccdceda1SDerek Schuff // Emscripten's asm.js-style setjmp/longjmp handling
41ccdceda1SDerek Schuff static cl::opt<bool> EnableEmSjLj(
42ccdceda1SDerek Schuff     "enable-emscripten-sjlj",
43ccdceda1SDerek Schuff     cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
44ccdceda1SDerek Schuff     cl::init(false));
45ccdceda1SDerek Schuff 
4610e730a2SDan Gohman extern "C" void LLVMInitializeWebAssemblyTarget() {
4710e730a2SDan Gohman   // Register the target.
48f42454b9SMehdi Amini   RegisterTargetMachine<WebAssemblyTargetMachine> X(
49f42454b9SMehdi Amini       getTheWebAssemblyTarget32());
50f42454b9SMehdi Amini   RegisterTargetMachine<WebAssemblyTargetMachine> Y(
51f42454b9SMehdi Amini       getTheWebAssemblyTarget64());
52f41f67d3SDerek Schuff 
5340926451SJacob Gravelle   // Register backend passes
5440926451SJacob Gravelle   auto &PR = *PassRegistry::getPassRegistry();
5592617559SSam Clegg   initializeWebAssemblyAddMissingPrototypesPass(PR);
5640926451SJacob Gravelle   initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR);
5740926451SJacob Gravelle   initializeLowerGlobalDtorsPass(PR);
5840926451SJacob Gravelle   initializeFixFunctionBitcastsPass(PR);
5940926451SJacob Gravelle   initializeOptimizeReturnedPass(PR);
6040926451SJacob Gravelle   initializeWebAssemblyArgumentMovePass(PR);
6140926451SJacob Gravelle   initializeWebAssemblySetP2AlignOperandsPass(PR);
6240926451SJacob Gravelle   initializeWebAssemblyReplacePhysRegsPass(PR);
6340926451SJacob Gravelle   initializeWebAssemblyPrepareForLiveIntervalsPass(PR);
6440926451SJacob Gravelle   initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
65321d5220SHeejin Ahn   initializeWebAssemblyMemIntrinsicResultsPass(PR);
6640926451SJacob Gravelle   initializeWebAssemblyRegStackifyPass(PR);
6740926451SJacob Gravelle   initializeWebAssemblyRegColoringPass(PR);
6840926451SJacob Gravelle   initializeWebAssemblyExplicitLocalsPass(PR);
6940926451SJacob Gravelle   initializeWebAssemblyFixIrreducibleControlFlowPass(PR);
704934f76bSHeejin Ahn   initializeWebAssemblyLateEHPreparePass(PR);
7104c48949SHeejin Ahn   initializeWebAssemblyExceptionInfoPass(PR);
7240926451SJacob Gravelle   initializeWebAssemblyCFGSortPass(PR);
7340926451SJacob Gravelle   initializeWebAssemblyCFGStackifyPass(PR);
7440926451SJacob Gravelle   initializeWebAssemblyLowerBrUnlessPass(PR);
7540926451SJacob Gravelle   initializeWebAssemblyRegNumberingPass(PR);
7640926451SJacob Gravelle   initializeWebAssemblyPeepholePass(PR);
7740926451SJacob Gravelle   initializeWebAssemblyCallIndirectFixupPass(PR);
7810e730a2SDan Gohman }
7910e730a2SDan Gohman 
8010e730a2SDan Gohman //===----------------------------------------------------------------------===//
8110e730a2SDan Gohman // WebAssembly Lowering public interface.
8210e730a2SDan Gohman //===----------------------------------------------------------------------===//
8310e730a2SDan Gohman 
8441133a3eSDan Gohman static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) {
8574f5fd4eSSam Clegg   if (!RM.hasValue()) {
8674f5fd4eSSam Clegg     // Default to static relocation model.  This should always be more optimial
8774f5fd4eSSam Clegg     // than PIC since the static linker can determine all global addresses and
8874f5fd4eSSam Clegg     // assume direct function calls.
8974f5fd4eSSam Clegg     return Reloc::Static;
9074f5fd4eSSam Clegg   }
9141133a3eSDan Gohman   return *RM;
9241133a3eSDan Gohman }
9341133a3eSDan Gohman 
9410e730a2SDan Gohman /// Create an WebAssembly architecture model.
9510e730a2SDan Gohman ///
9610e730a2SDan Gohman WebAssemblyTargetMachine::WebAssemblyTargetMachine(
9710e730a2SDan Gohman     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
9841133a3eSDan Gohman     const TargetOptions &Options, Optional<Reloc::Model> RM,
99314ed201SDaniel Jasper     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
100bb8507e6SMatthias Braun     : LLVMTargetMachine(T,
101bb8507e6SMatthias Braun                         TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128"
1020c6f5ac5SDan Gohman                                          : "e-m:e-p:32:32-i64:64-n32:64-S128",
10341133a3eSDan Gohman                         TT, CPU, FS, Options, getEffectiveRelocModel(RM),
104ca29c271SDavid Green                         getEffectiveCodeModel(CM, CodeModel::Large), OL),
105cf2a9e28SSam Clegg       TLOF(new WebAssemblyTargetObjectFile()) {
106e040533eSDan Gohman   // WebAssembly type-checks instructions, but a noreturn function with a return
107ffa143ceSDerek Schuff   // type that doesn't match the context will cause a check failure. So we lower
108ffa143ceSDerek Schuff   // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
109e040533eSDan Gohman   // 'unreachable' instructions which is meant for that case.
110ffa143ceSDerek Schuff   this->Options.TrapUnreachable = true;
111ffa143ceSDerek Schuff 
112d934cb88SDan Gohman   // WebAssembly treats each function as an independent unit. Force
113d934cb88SDan Gohman   // -ffunction-sections, effectively, so that we can emit them independently.
114d934cb88SDan Gohman   this->Options.FunctionSections = true;
115d934cb88SDan Gohman   this->Options.DataSections = true;
116d934cb88SDan Gohman   this->Options.UniqueSectionNames = true;
117d934cb88SDan Gohman 
11810e730a2SDan Gohman   initAsmInfo();
11910e730a2SDan Gohman 
120f3b4f990SThomas Lively   // Create a subtarget using the unmodified target machine features to
121f3b4f990SThomas Lively   // initialize the used feature set with explicitly enabled features.
122f3b4f990SThomas Lively   getSubtargetImpl(getTargetCPU(), getTargetFeatureString());
123f3b4f990SThomas Lively 
124d85ab7fcSDan Gohman   // Note that we don't use setRequiresStructuredCFG(true). It disables
125d85ab7fcSDan Gohman   // optimizations than we're ok with, and want, such as critical edge
126d85ab7fcSDan Gohman   // splitting and tail merging.
12710e730a2SDan Gohman }
12810e730a2SDan Gohman 
12918c56a07SHeejin Ahn WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
13010e730a2SDan Gohman 
13110e730a2SDan Gohman const WebAssemblySubtarget *
132f3b4f990SThomas Lively WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
133f3b4f990SThomas Lively                                            std::string FS) const {
134f3b4f990SThomas Lively   auto &I = SubtargetMap[CPU + FS];
135f3b4f990SThomas Lively   if (!I) {
136f3b4f990SThomas Lively     I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this);
137f3b4f990SThomas Lively     UsedFeatures |= I->getFeatureBits();
138f3b4f990SThomas Lively   }
139f3b4f990SThomas Lively   return I.get();
140f3b4f990SThomas Lively }
141f3b4f990SThomas Lively 
142f3b4f990SThomas Lively const WebAssemblySubtarget *
14310e730a2SDan Gohman WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
14410e730a2SDan Gohman   Attribute CPUAttr = F.getFnAttribute("target-cpu");
14510e730a2SDan Gohman   Attribute FSAttr = F.getFnAttribute("target-features");
14610e730a2SDan Gohman 
14710e730a2SDan Gohman   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
14810e730a2SDan Gohman                         ? CPUAttr.getValueAsString().str()
14910e730a2SDan Gohman                         : TargetCPU;
15010e730a2SDan Gohman   std::string FS = !FSAttr.hasAttribute(Attribute::None)
15110e730a2SDan Gohman                        ? FSAttr.getValueAsString().str()
15210e730a2SDan Gohman                        : TargetFS;
15310e730a2SDan Gohman 
15410e730a2SDan Gohman   // This needs to be done before we create a new subtarget since any
15510e730a2SDan Gohman   // creation will depend on the TM and the code generation flags on the
15610e730a2SDan Gohman   // function that reside in TargetOptions.
15710e730a2SDan Gohman   resetTargetOptions(F);
158f3b4f990SThomas Lively 
159f3b4f990SThomas Lively   return getSubtargetImpl(CPU, FS);
16010e730a2SDan Gohman }
16110e730a2SDan Gohman 
16210e730a2SDan Gohman namespace {
16339b5367cSDerek Schuff class StripThreadLocal final : public ModulePass {
16439b5367cSDerek Schuff   // The default thread model for wasm is single, where thread-local variables
16539b5367cSDerek Schuff   // are identical to regular globals and should be treated the same. So this
16639b5367cSDerek Schuff   // pass just converts all GlobalVariables to NotThreadLocal
16739b5367cSDerek Schuff   static char ID;
16839b5367cSDerek Schuff 
16939b5367cSDerek Schuff public:
17039b5367cSDerek Schuff   StripThreadLocal() : ModulePass(ID) {}
17139b5367cSDerek Schuff   bool runOnModule(Module &M) override {
17239b5367cSDerek Schuff     for (auto &GV : M.globals())
17339b5367cSDerek Schuff       GV.setThreadLocalMode(GlobalValue::ThreadLocalMode::NotThreadLocal);
17439b5367cSDerek Schuff     return true;
17539b5367cSDerek Schuff   }
17639b5367cSDerek Schuff };
17739b5367cSDerek Schuff char StripThreadLocal::ID = 0;
17839b5367cSDerek Schuff 
17910e730a2SDan Gohman /// WebAssembly Code Generator Pass Configuration Options.
18010e730a2SDan Gohman class WebAssemblyPassConfig final : public TargetPassConfig {
18110e730a2SDan Gohman public:
1825e394c3dSMatthias Braun   WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
18310e730a2SDan Gohman       : TargetPassConfig(TM, PM) {}
18410e730a2SDan Gohman 
18510e730a2SDan Gohman   WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
18610e730a2SDan Gohman     return getTM<WebAssemblyTargetMachine>();
18710e730a2SDan Gohman   }
18810e730a2SDan Gohman 
18910e730a2SDan Gohman   FunctionPass *createTargetRegisterAllocator(bool) override;
19010e730a2SDan Gohman 
19110e730a2SDan Gohman   void addIRPasses() override;
19210e730a2SDan Gohman   bool addInstSelector() override;
19310e730a2SDan Gohman   void addPostRegAlloc() override;
194ad154c83SDerek Schuff   bool addGCPasses() override { return false; }
19510e730a2SDan Gohman   void addPreEmitPass() override;
196cf55a657SMatt Arsenault 
197cf55a657SMatt Arsenault   // No reg alloc
198cf55a657SMatt Arsenault   bool addRegAssignmentFast() override { return false; }
199cf55a657SMatt Arsenault 
200cf55a657SMatt Arsenault   // No reg alloc
201cf55a657SMatt Arsenault   bool addRegAssignmentOptimized() override { return false; }
20210e730a2SDan Gohman };
20310e730a2SDan Gohman } // end anonymous namespace
20410e730a2SDan Gohman 
20526d11ca4SSanjoy Das TargetTransformInfo
20626d11ca4SSanjoy Das WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) {
20710e730a2SDan Gohman   return TargetTransformInfo(WebAssemblyTTIImpl(this, F));
20810e730a2SDan Gohman }
20910e730a2SDan Gohman 
21010e730a2SDan Gohman TargetPassConfig *
21110e730a2SDan Gohman WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
2125e394c3dSMatthias Braun   return new WebAssemblyPassConfig(*this, PM);
21310e730a2SDan Gohman }
21410e730a2SDan Gohman 
21510e730a2SDan Gohman FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
21610e730a2SDan Gohman   return nullptr; // No reg alloc
21710e730a2SDan Gohman }
21810e730a2SDan Gohman 
21910e730a2SDan Gohman //===----------------------------------------------------------------------===//
22010e730a2SDan Gohman // The following functions are called from lib/CodeGen/Passes.cpp to modify
22110e730a2SDan Gohman // the CodeGen pass sequence.
22210e730a2SDan Gohman //===----------------------------------------------------------------------===//
22310e730a2SDan Gohman 
22410e730a2SDan Gohman void WebAssemblyPassConfig::addIRPasses() {
225f3b4f990SThomas Lively   if (static_cast<WebAssemblyTargetMachine *>(TM)
226f3b4f990SThomas Lively           ->getUsedFeatures()[WebAssembly::FeatureAtomics]) {
22710e730a2SDan Gohman     // Expand some atomic operations. WebAssemblyTargetLowering has hooks which
22810e730a2SDan Gohman     // control specifically what gets lowered.
2298b61764cSFrancis Visoiu Mistrih     addPass(createAtomicExpandPass());
230f3b4f990SThomas Lively   } else {
231f3b4f990SThomas Lively     // If atomics are not enabled, they get lowered to non-atomics.
232f3b4f990SThomas Lively     addPass(createLowerAtomicPass());
233f3b4f990SThomas Lively     addPass(new StripThreadLocal());
23439b5367cSDerek Schuff   }
23510e730a2SDan Gohman 
23692617559SSam Clegg   // Add signatures to prototype-less function declarations
23792617559SSam Clegg   addPass(createWebAssemblyAddMissingPrototypes());
23892617559SSam Clegg 
239bafe6902SSam Clegg   // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls.
240bafe6902SSam Clegg   addPass(createWebAssemblyLowerGlobalDtors());
241bafe6902SSam Clegg 
2421b637458SDan Gohman   // Fix function bitcasts, as WebAssembly requires caller and callee signatures
2431b637458SDan Gohman   // to match.
2441b637458SDan Gohman   addPass(createWebAssemblyFixFunctionBitcasts());
2451b637458SDan Gohman 
24681719f85SDan Gohman   // Optimize "returned" function attributes.
247b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
24881719f85SDan Gohman     addPass(createWebAssemblyOptimizeReturned());
24981719f85SDan Gohman 
250c0f18172SHeejin Ahn   // If exception handling is not enabled and setjmp/longjmp handling is
251c0f18172SHeejin Ahn   // enabled, we lower invokes into calls and delete unreachable landingpad
252c0f18172SHeejin Ahn   // blocks. Lowering invokes when there is no EH support is done in
253c0f18172SHeejin Ahn   // TargetPassConfig::addPassesToHandleExceptions, but this runs after this
254c0f18172SHeejin Ahn   // function and SjLj handling expects all invokes to be lowered before.
2559386bde1SHeejin Ahn   if (!EnableEmException &&
2569386bde1SHeejin Ahn       TM->Options.ExceptionModel == ExceptionHandling::None) {
257c0f18172SHeejin Ahn     addPass(createLowerInvokePass());
258c0f18172SHeejin Ahn     // The lower invoke pass may create unreachable code. Remove it in order not
259c0f18172SHeejin Ahn     // to process dead blocks in setjmp/longjmp handling.
260c0f18172SHeejin Ahn     addPass(createUnreachableBlockEliminationPass());
261c0f18172SHeejin Ahn   }
262c0f18172SHeejin Ahn 
263c0f18172SHeejin Ahn   // Handle exceptions and setjmp/longjmp if enabled.
264ccdceda1SDerek Schuff   if (EnableEmException || EnableEmSjLj)
265ccdceda1SDerek Schuff     addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException,
266ccdceda1SDerek Schuff                                                    EnableEmSjLj));
267f41f67d3SDerek Schuff 
26810e730a2SDan Gohman   TargetPassConfig::addIRPasses();
26910e730a2SDan Gohman }
27010e730a2SDan Gohman 
27110e730a2SDan Gohman bool WebAssemblyPassConfig::addInstSelector() {
272b0921ca9SDan Gohman   (void)TargetPassConfig::addInstSelector();
27310e730a2SDan Gohman   addPass(
27410e730a2SDan Gohman       createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel()));
2751cf96c0cSDan Gohman   // Run the argument-move pass immediately after the ScheduleDAG scheduler
2761cf96c0cSDan Gohman   // so that we can fix up the ARGUMENT instructions before anything else
2771cf96c0cSDan Gohman   // sees them in the wrong place.
2781cf96c0cSDan Gohman   addPass(createWebAssemblyArgumentMove());
279bb372243SDan Gohman   // Set the p2align operands. This information is present during ISel, however
280bb372243SDan Gohman   // it's inconvenient to collect. Collect it now, and update the immediate
281bb372243SDan Gohman   // operands.
282bb372243SDan Gohman   addPass(createWebAssemblySetP2AlignOperands());
28310e730a2SDan Gohman   return false;
28410e730a2SDan Gohman }
28510e730a2SDan Gohman 
286600aee98SJF Bastien void WebAssemblyPassConfig::addPostRegAlloc() {
2879c54d3b4SDan Gohman   // TODO: The following CodeGen passes don't currently support code containing
2889c54d3b4SDan Gohman   // virtual registers. Consider removing their restrictions and re-enabling
2899c54d3b4SDan Gohman   // them.
290ad154c83SDerek Schuff 
2911eb47368SMatthias Braun   // These functions all require the NoVRegs property.
292600aee98SJF Bastien   disablePass(&MachineCopyPropagationID);
2937ab1b32bSJun Bum Lim   disablePass(&PostRAMachineSinkingID);
294ecabac62SDerek Schuff   disablePass(&PostRASchedulerID);
295ecabac62SDerek Schuff   disablePass(&FuncletLayoutID);
296ecabac62SDerek Schuff   disablePass(&StackMapLivenessID);
297ecabac62SDerek Schuff   disablePass(&LiveDebugValuesID);
298fe71ec77SSanjoy Das   disablePass(&PatchableFunctionID);
2997ab1b32bSJun Bum Lim   disablePass(&ShrinkWrapID);
300950a13cfSDan Gohman 
301ef9d6aeaSHeejin Ahn   // This pass hurts code size for wasm because it can generate irreducible
302ef9d6aeaSHeejin Ahn   // control flow.
303ef9d6aeaSHeejin Ahn   disablePass(&MachineBlockPlacementID);
304ef9d6aeaSHeejin Ahn 
305b0921ca9SDan Gohman   TargetPassConfig::addPostRegAlloc();
306600aee98SJF Bastien }
30710e730a2SDan Gohman 
308950a13cfSDan Gohman void WebAssemblyPassConfig::addPreEmitPass() {
309b0921ca9SDan Gohman   TargetPassConfig::addPreEmitPass();
310b0921ca9SDan Gohman 
3116f69783fSDerek Schuff   // Rewrite pseudo call_indirect instructions as real instructions.
3126f69783fSDerek Schuff   // This needs to run before register stackification, because we change the
3136f69783fSDerek Schuff   // order of the arguments.
3146f69783fSDerek Schuff   addPass(createWebAssemblyCallIndirectFixup());
3156f69783fSDerek Schuff 
316e95056d6SHeejin Ahn   // Eliminate multiple-entry loops.
317e95056d6SHeejin Ahn   addPass(createWebAssemblyFixIrreducibleControlFlow());
318e95056d6SHeejin Ahn 
319e95056d6SHeejin Ahn   // Do various transformations for exception handling.
320d6f48786SHeejin Ahn   // Every CFG-changing optimizations should come before this.
321e95056d6SHeejin Ahn   addPass(createWebAssemblyLateEHPrepare());
322e95056d6SHeejin Ahn 
3230bb98650SHeejin Ahn   // Now that we have a prologue and epilogue and all frame indices are
3240bb98650SHeejin Ahn   // rewritten, eliminate SP and FP. This allows them to be stackified,
3250bb98650SHeejin Ahn   // colored, and numbered with the rest of the registers.
3260bb98650SHeejin Ahn   addPass(createWebAssemblyReplacePhysRegs());
3270bb98650SHeejin Ahn 
328d6f48786SHeejin Ahn   // Preparations and optimizations related to register stackification.
3290cfb5f85SDan Gohman   if (getOptLevel() != CodeGenOpt::None) {
3300cfb5f85SDan Gohman     // LiveIntervals isn't commonly run this late. Re-establish preconditions.
3310cfb5f85SDan Gohman     addPass(createWebAssemblyPrepareForLiveIntervals());
3320cfb5f85SDan Gohman 
3330cfb5f85SDan Gohman     // Depend on LiveIntervals and perform some optimizations on it.
3340cfb5f85SDan Gohman     addPass(createWebAssemblyOptimizeLiveIntervals());
3350cfb5f85SDan Gohman 
336321d5220SHeejin Ahn     // Prepare memory intrinsic calls for register stackifying.
337321d5220SHeejin Ahn     addPass(createWebAssemblyMemIntrinsicResults());
3380cfb5f85SDan Gohman 
339e040533eSDan Gohman     // Mark registers as representing wasm's value stack. This is a key
3400cfb5f85SDan Gohman     // code-compression technique in WebAssembly. We run this pass (and
341321d5220SHeejin Ahn     // MemIntrinsicResults above) very late, so that it sees as much code as
342321d5220SHeejin Ahn     // possible, including code emitted by PEI and expanded by late tail
343321d5220SHeejin Ahn     // duplication.
3440cfb5f85SDan Gohman     addPass(createWebAssemblyRegStackify());
3450cfb5f85SDan Gohman 
3460cfb5f85SDan Gohman     // Run the register coloring pass to reduce the total number of registers.
3470cfb5f85SDan Gohman     // This runs after stackification so that it doesn't consider registers
3480cfb5f85SDan Gohman     // that become stackified.
3490cfb5f85SDan Gohman     addPass(createWebAssemblyRegColoring());
3500cfb5f85SDan Gohman   }
3510cfb5f85SDan Gohman 
3526a87ddacSThomas Lively   // Insert explicit local.get and local.set operators.
353a7be3755SWouter van Oortmerssen   addPass(createWebAssemblyExplicitLocals());
354a7be3755SWouter van Oortmerssen 
355f52ee17aSDan Gohman   // Sort the blocks of the CFG into topological order, a prerequisite for
356f52ee17aSDan Gohman   // BLOCK and LOOP markers.
357f52ee17aSDan Gohman   addPass(createWebAssemblyCFGSort());
358f52ee17aSDan Gohman 
359f52ee17aSDan Gohman   // Insert BLOCK and LOOP markers.
360950a13cfSDan Gohman   addPass(createWebAssemblyCFGStackify());
3615941bde0SDan Gohman 
362f0b165a7SDan Gohman   // Lower br_unless into br_if.
363f0b165a7SDan Gohman   addPass(createWebAssemblyLowerBrUnless());
364f0b165a7SDan Gohman 
3655941bde0SDan Gohman   // Perform the very last peephole optimizations on the code.
366b13c91f1SDan Gohman   if (getOptLevel() != CodeGenOpt::None)
36781719f85SDan Gohman     addPass(createWebAssemblyPeephole());
368b7c2400fSDan Gohman 
369b7c2400fSDan Gohman   // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
370b7c2400fSDan Gohman   addPass(createWebAssemblyRegNumbering());
371950a13cfSDan Gohman }
372*52221d56SHeejin Ahn 
373*52221d56SHeejin Ahn yaml::MachineFunctionInfo *
374*52221d56SHeejin Ahn WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
375*52221d56SHeejin Ahn   return new yaml::WebAssemblyFunctionInfo();
376*52221d56SHeejin Ahn }
377*52221d56SHeejin Ahn 
378*52221d56SHeejin Ahn yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
379*52221d56SHeejin Ahn     const MachineFunction &MF) const {
380*52221d56SHeejin Ahn   const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
381*52221d56SHeejin Ahn   return new yaml::WebAssemblyFunctionInfo(*MFI);
382*52221d56SHeejin Ahn }
383*52221d56SHeejin Ahn 
384*52221d56SHeejin Ahn bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
385*52221d56SHeejin Ahn     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
386*52221d56SHeejin Ahn     SMDiagnostic &Error, SMRange &SourceRange) const {
387*52221d56SHeejin Ahn   const auto &YamlMFI =
388*52221d56SHeejin Ahn       reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
389*52221d56SHeejin Ahn   MachineFunction &MF = PFS.MF;
390*52221d56SHeejin Ahn   MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI);
391*52221d56SHeejin Ahn   return false;
392*52221d56SHeejin Ahn }
393