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" 16c6c42137SRichard Trieu #include "TargetInfo/WebAssemblyTargetInfo.h" 176bda14b3SChandler Carruth #include "WebAssembly.h" 1852221d56SHeejin Ahn #include "WebAssemblyMachineFunctionInfo.h" 195bf22fc8SDan Gohman #include "WebAssemblyTargetObjectFile.h" 2010e730a2SDan Gohman #include "WebAssemblyTargetTransformInfo.h" 2152221d56SHeejin Ahn #include "llvm/CodeGen/MIRParser/MIParser.h" 2210e730a2SDan Gohman #include "llvm/CodeGen/MachineFunctionPass.h" 2310e730a2SDan Gohman #include "llvm/CodeGen/Passes.h" 2410e730a2SDan Gohman #include "llvm/CodeGen/RegAllocRegistry.h" 2531d19d43SMatthias Braun #include "llvm/CodeGen/TargetPassConfig.h" 2610e730a2SDan Gohman #include "llvm/IR/Function.h" 27*89b57061SReid Kleckner #include "llvm/MC/TargetRegistry.h" 2810e730a2SDan Gohman #include "llvm/Target/TargetOptions.h" 2903855df1SJF Bastien #include "llvm/Transforms/Scalar.h" 303f34e1b8SThomas Lively #include "llvm/Transforms/Scalar/LowerAtomic.h" 31a373d18eSDavid Blaikie #include "llvm/Transforms/Utils.h" 3210e730a2SDan Gohman using namespace llvm; 3310e730a2SDan Gohman 3410e730a2SDan Gohman #define DEBUG_TYPE "wasm" 3510e730a2SDan Gohman 36f41f67d3SDerek Schuff // Emscripten's asm.js-style exception handling 3777b921b8SHeejin Ahn cl::opt<bool> 3877b921b8SHeejin Ahn WasmEnableEmEH("enable-emscripten-cxx-exceptions", 39f41f67d3SDerek Schuff cl::desc("WebAssembly Emscripten-style exception handling"), 40f41f67d3SDerek Schuff cl::init(false)); 41f41f67d3SDerek Schuff 42ccdceda1SDerek Schuff // Emscripten's asm.js-style setjmp/longjmp handling 439bd02c43SHeejin Ahn cl::opt<bool> WasmEnableEmSjLj( 44ccdceda1SDerek Schuff "enable-emscripten-sjlj", 45ccdceda1SDerek Schuff cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"), 46ccdceda1SDerek Schuff cl::init(false)); 47ccdceda1SDerek Schuff 4877b921b8SHeejin Ahn // Exception handling using wasm EH instructions 4977b921b8SHeejin Ahn cl::opt<bool> WasmEnableEH("wasm-enable-eh", 5077b921b8SHeejin Ahn cl::desc("WebAssembly exception handling"), 5177b921b8SHeejin Ahn cl::init(false)); 5277b921b8SHeejin Ahn 5377b921b8SHeejin Ahn // setjmp/longjmp handling using wasm EH instrutions 5477b921b8SHeejin Ahn cl::opt<bool> WasmEnableSjLj("wasm-enable-sjlj", 5577b921b8SHeejin Ahn cl::desc("WebAssembly setjmp/longjmp handling"), 5677b921b8SHeejin Ahn cl::init(false)); 5777b921b8SHeejin Ahn 582b7fe086SWouter van Oortmerssen // A command-line option to keep implicit locals 592b7fe086SWouter van Oortmerssen // for the purpose of testing with lit/llc ONLY. 602b7fe086SWouter van Oortmerssen // This produces output which is not valid WebAssembly, and is not supported 612b7fe086SWouter van Oortmerssen // by assemblers/disassemblers and other MC based tools. 622b7fe086SWouter van Oortmerssen static cl::opt<bool> WasmDisableExplicitLocals( 632b7fe086SWouter van Oortmerssen "wasm-disable-explicit-locals", cl::Hidden, 642b7fe086SWouter van Oortmerssen cl::desc("WebAssembly: output implicit locals in" 652b7fe086SWouter van Oortmerssen " instruction output for test purposes only."), 662b7fe086SWouter van Oortmerssen cl::init(false)); 672b7fe086SWouter van Oortmerssen 680dbcb363STom Stellard extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeWebAssemblyTarget() { 6910e730a2SDan Gohman // Register the target. 70f42454b9SMehdi Amini RegisterTargetMachine<WebAssemblyTargetMachine> X( 71f42454b9SMehdi Amini getTheWebAssemblyTarget32()); 72f42454b9SMehdi Amini RegisterTargetMachine<WebAssemblyTargetMachine> Y( 73f42454b9SMehdi Amini getTheWebAssemblyTarget64()); 74f41f67d3SDerek Schuff 7540926451SJacob Gravelle // Register backend passes 7640926451SJacob Gravelle auto &PR = *PassRegistry::getPassRegistry(); 7792617559SSam Clegg initializeWebAssemblyAddMissingPrototypesPass(PR); 7840926451SJacob Gravelle initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR); 7940926451SJacob Gravelle initializeLowerGlobalDtorsPass(PR); 8040926451SJacob Gravelle initializeFixFunctionBitcastsPass(PR); 8140926451SJacob Gravelle initializeOptimizeReturnedPass(PR); 8240926451SJacob Gravelle initializeWebAssemblyArgumentMovePass(PR); 8340926451SJacob Gravelle initializeWebAssemblySetP2AlignOperandsPass(PR); 8440926451SJacob Gravelle initializeWebAssemblyReplacePhysRegsPass(PR); 8540926451SJacob Gravelle initializeWebAssemblyPrepareForLiveIntervalsPass(PR); 8640926451SJacob Gravelle initializeWebAssemblyOptimizeLiveIntervalsPass(PR); 87321d5220SHeejin Ahn initializeWebAssemblyMemIntrinsicResultsPass(PR); 8840926451SJacob Gravelle initializeWebAssemblyRegStackifyPass(PR); 8940926451SJacob Gravelle initializeWebAssemblyRegColoringPass(PR); 90a64ebb86SHeejin Ahn initializeWebAssemblyNullifyDebugValueListsPass(PR); 9140926451SJacob Gravelle initializeWebAssemblyFixIrreducibleControlFlowPass(PR); 924934f76bSHeejin Ahn initializeWebAssemblyLateEHPreparePass(PR); 9304c48949SHeejin Ahn initializeWebAssemblyExceptionInfoPass(PR); 9440926451SJacob Gravelle initializeWebAssemblyCFGSortPass(PR); 9540926451SJacob Gravelle initializeWebAssemblyCFGStackifyPass(PR); 96e9fd9073SHeejin Ahn initializeWebAssemblyExplicitLocalsPass(PR); 9740926451SJacob Gravelle initializeWebAssemblyLowerBrUnlessPass(PR); 9840926451SJacob Gravelle initializeWebAssemblyRegNumberingPass(PR); 992b7fe086SWouter van Oortmerssen initializeWebAssemblyDebugFixupPass(PR); 10040926451SJacob Gravelle initializeWebAssemblyPeepholePass(PR); 1019647a6f7SWouter van Oortmerssen initializeWebAssemblyMCLowerPrePassPass(PR); 10210e730a2SDan Gohman } 10310e730a2SDan Gohman 10410e730a2SDan Gohman //===----------------------------------------------------------------------===// 10510e730a2SDan Gohman // WebAssembly Lowering public interface. 10610e730a2SDan Gohman //===----------------------------------------------------------------------===// 10710e730a2SDan Gohman 10853572d04SDan Gohman static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM, 10953572d04SDan Gohman const Triple &TT) { 11074f5fd4eSSam Clegg if (!RM.hasValue()) { 11174f5fd4eSSam Clegg // Default to static relocation model. This should always be more optimial 11274f5fd4eSSam Clegg // than PIC since the static linker can determine all global addresses and 11374f5fd4eSSam Clegg // assume direct function calls. 11474f5fd4eSSam Clegg return Reloc::Static; 11574f5fd4eSSam Clegg } 11653572d04SDan Gohman 11753572d04SDan Gohman if (!TT.isOSEmscripten()) { 11853572d04SDan Gohman // Relocation modes other than static are currently implemented in a way 11953572d04SDan Gohman // that only works for Emscripten, so disable them if we aren't targeting 12053572d04SDan Gohman // Emscripten. 12153572d04SDan Gohman return Reloc::Static; 12253572d04SDan Gohman } 12353572d04SDan Gohman 12441133a3eSDan Gohman return *RM; 12541133a3eSDan Gohman } 12641133a3eSDan Gohman 12710e730a2SDan Gohman /// Create an WebAssembly architecture model. 12810e730a2SDan Gohman /// 12910e730a2SDan Gohman WebAssemblyTargetMachine::WebAssemblyTargetMachine( 13010e730a2SDan Gohman const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 13141133a3eSDan Gohman const TargetOptions &Options, Optional<Reloc::Model> RM, 132314ed201SDaniel Jasper Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT) 133ac02baabSDerek Schuff : LLVMTargetMachine( 134ac02baabSDerek Schuff T, 135d7086af2SPaulo Matos TT.isArch64Bit() 136ac02baabSDerek Schuff ? (TT.isOSEmscripten() 13746667a10SPaulo Matos ? "e-m:e-p:64:64-i64:64-f128:64-n32:64-S128-ni:1:10:20" 13846667a10SPaulo Matos : "e-m:e-p:64:64-i64:64-n32:64-S128-ni:1:10:20") 139ac02baabSDerek Schuff : (TT.isOSEmscripten() 14046667a10SPaulo Matos ? "e-m:e-p:32:32-i64:64-f128:64-n32:64-S128-ni:1:10:20" 14146667a10SPaulo Matos : "e-m:e-p:32:32-i64:64-n32:64-S128-ni:1:10:20"), 14253572d04SDan Gohman TT, CPU, FS, Options, getEffectiveRelocModel(RM, TT), 143ca29c271SDavid Green getEffectiveCodeModel(CM, CodeModel::Large), OL), 144cf2a9e28SSam Clegg TLOF(new WebAssemblyTargetObjectFile()) { 145e040533eSDan Gohman // WebAssembly type-checks instructions, but a noreturn function with a return 146ffa143ceSDerek Schuff // type that doesn't match the context will cause a check failure. So we lower 147ffa143ceSDerek Schuff // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's 148e040533eSDan Gohman // 'unreachable' instructions which is meant for that case. 149ffa143ceSDerek Schuff this->Options.TrapUnreachable = true; 150ffa143ceSDerek Schuff 151d934cb88SDan Gohman // WebAssembly treats each function as an independent unit. Force 152d934cb88SDan Gohman // -ffunction-sections, effectively, so that we can emit them independently. 153d934cb88SDan Gohman this->Options.FunctionSections = true; 154d934cb88SDan Gohman this->Options.DataSections = true; 155d934cb88SDan Gohman this->Options.UniqueSectionNames = true; 156d934cb88SDan Gohman 15710e730a2SDan Gohman initAsmInfo(); 15810e730a2SDan Gohman 159d85ab7fcSDan Gohman // Note that we don't use setRequiresStructuredCFG(true). It disables 160d85ab7fcSDan Gohman // optimizations than we're ok with, and want, such as critical edge 161d85ab7fcSDan Gohman // splitting and tail merging. 16210e730a2SDan Gohman } 16310e730a2SDan Gohman 16418c56a07SHeejin Ahn WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor. 16510e730a2SDan Gohman 16689fe083cSThomas Lively const WebAssemblySubtarget *WebAssemblyTargetMachine::getSubtargetImpl() const { 16789fe083cSThomas Lively return getSubtargetImpl(std::string(getTargetCPU()), 16889fe083cSThomas Lively std::string(getTargetFeatureString())); 16989fe083cSThomas Lively } 17089fe083cSThomas Lively 17110e730a2SDan Gohman const WebAssemblySubtarget * 172f3b4f990SThomas Lively WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU, 173f3b4f990SThomas Lively std::string FS) const { 174f3b4f990SThomas Lively auto &I = SubtargetMap[CPU + FS]; 175f3b4f990SThomas Lively if (!I) { 1760eaee545SJonas Devlieghere I = std::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this); 177f3b4f990SThomas Lively } 178f3b4f990SThomas Lively return I.get(); 179f3b4f990SThomas Lively } 180f3b4f990SThomas Lively 181f3b4f990SThomas Lively const WebAssemblySubtarget * 18210e730a2SDan Gohman WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const { 18310e730a2SDan Gohman Attribute CPUAttr = F.getFnAttribute("target-cpu"); 18410e730a2SDan Gohman Attribute FSAttr = F.getFnAttribute("target-features"); 18510e730a2SDan Gohman 186aab90384SCraig Topper std::string CPU = 187aab90384SCraig Topper CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU; 188aab90384SCraig Topper std::string FS = 189aab90384SCraig Topper FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS; 19010e730a2SDan Gohman 19110e730a2SDan Gohman // This needs to be done before we create a new subtarget since any 19210e730a2SDan Gohman // creation will depend on the TM and the code generation flags on the 19310e730a2SDan Gohman // function that reside in TargetOptions. 19410e730a2SDan Gohman resetTargetOptions(F); 195f3b4f990SThomas Lively 196f3b4f990SThomas Lively return getSubtargetImpl(CPU, FS); 19710e730a2SDan Gohman } 19810e730a2SDan Gohman 19910e730a2SDan Gohman namespace { 2003f34e1b8SThomas Lively 2013f34e1b8SThomas Lively class CoalesceFeaturesAndStripAtomics final : public ModulePass { 2023f34e1b8SThomas Lively // Take the union of all features used in the module and use it for each 2033f34e1b8SThomas Lively // function individually, since having multiple feature sets in one module 2043f34e1b8SThomas Lively // currently does not make sense for WebAssembly. If atomics are not enabled, 2053f34e1b8SThomas Lively // also strip atomic operations and thread local storage. 20639b5367cSDerek Schuff static char ID; 2073f34e1b8SThomas Lively WebAssemblyTargetMachine *WasmTM; 20839b5367cSDerek Schuff 20939b5367cSDerek Schuff public: 2103f34e1b8SThomas Lively CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM) 2113f34e1b8SThomas Lively : ModulePass(ID), WasmTM(WasmTM) {} 2123f34e1b8SThomas Lively 21339b5367cSDerek Schuff bool runOnModule(Module &M) override { 2143f34e1b8SThomas Lively FeatureBitset Features = coalesceFeatures(M); 2153f34e1b8SThomas Lively 2163f34e1b8SThomas Lively std::string FeatureStr = getFeatureString(Features); 21789fe083cSThomas Lively WasmTM->setTargetFeatureString(FeatureStr); 2183f34e1b8SThomas Lively for (auto &F : M) 2193f34e1b8SThomas Lively replaceFeatures(F, FeatureStr); 2203f34e1b8SThomas Lively 22142bba4b8SGuanzhong Chen bool StrippedAtomics = false; 22242bba4b8SGuanzhong Chen bool StrippedTLS = false; 2233f34e1b8SThomas Lively 22442bba4b8SGuanzhong Chen if (!Features[WebAssembly::FeatureAtomics]) 22542bba4b8SGuanzhong Chen StrippedAtomics = stripAtomics(M); 22642bba4b8SGuanzhong Chen 22742bba4b8SGuanzhong Chen if (!Features[WebAssembly::FeatureBulkMemory]) 22842bba4b8SGuanzhong Chen StrippedTLS = stripThreadLocals(M); 22942bba4b8SGuanzhong Chen 23042bba4b8SGuanzhong Chen if (StrippedAtomics && !StrippedTLS) 23142bba4b8SGuanzhong Chen stripThreadLocals(M); 23242bba4b8SGuanzhong Chen else if (StrippedTLS && !StrippedAtomics) 23342bba4b8SGuanzhong Chen stripAtomics(M); 23442bba4b8SGuanzhong Chen 23542bba4b8SGuanzhong Chen recordFeatures(M, Features, StrippedAtomics || StrippedTLS); 2363f34e1b8SThomas Lively 2373f34e1b8SThomas Lively // Conservatively assume we have made some change 23839b5367cSDerek Schuff return true; 23939b5367cSDerek Schuff } 2403f34e1b8SThomas Lively 2413f34e1b8SThomas Lively private: 2423f34e1b8SThomas Lively FeatureBitset coalesceFeatures(const Module &M) { 2433f34e1b8SThomas Lively FeatureBitset Features = 2443f34e1b8SThomas Lively WasmTM 245adcd0268SBenjamin Kramer ->getSubtargetImpl(std::string(WasmTM->getTargetCPU()), 246adcd0268SBenjamin Kramer std::string(WasmTM->getTargetFeatureString())) 2473f34e1b8SThomas Lively ->getFeatureBits(); 2483f34e1b8SThomas Lively for (auto &F : M) 2493f34e1b8SThomas Lively Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits(); 2503f34e1b8SThomas Lively return Features; 2513f34e1b8SThomas Lively } 2523f34e1b8SThomas Lively 2533f34e1b8SThomas Lively std::string getFeatureString(const FeatureBitset &Features) { 2543f34e1b8SThomas Lively std::string Ret; 2553f34e1b8SThomas Lively for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 2563f34e1b8SThomas Lively if (Features[KV.Value]) 2573f34e1b8SThomas Lively Ret += (StringRef("+") + KV.Key + ",").str(); 2583f34e1b8SThomas Lively } 2593f34e1b8SThomas Lively return Ret; 2603f34e1b8SThomas Lively } 2613f34e1b8SThomas Lively 2623f34e1b8SThomas Lively void replaceFeatures(Function &F, const std::string &Features) { 2633f34e1b8SThomas Lively F.removeFnAttr("target-features"); 2643f34e1b8SThomas Lively F.removeFnAttr("target-cpu"); 2653f34e1b8SThomas Lively F.addFnAttr("target-features", Features); 2663f34e1b8SThomas Lively } 2673f34e1b8SThomas Lively 2683f34e1b8SThomas Lively bool stripAtomics(Module &M) { 2693f34e1b8SThomas Lively // Detect whether any atomics will be lowered, since there is no way to tell 2703f34e1b8SThomas Lively // whether the LowerAtomic pass lowers e.g. stores. 2713f34e1b8SThomas Lively bool Stripped = false; 2723f34e1b8SThomas Lively for (auto &F : M) { 2733f34e1b8SThomas Lively for (auto &B : F) { 2743f34e1b8SThomas Lively for (auto &I : B) { 2753f34e1b8SThomas Lively if (I.isAtomic()) { 2763f34e1b8SThomas Lively Stripped = true; 2773f34e1b8SThomas Lively goto done; 2783f34e1b8SThomas Lively } 2793f34e1b8SThomas Lively } 2803f34e1b8SThomas Lively } 2813f34e1b8SThomas Lively } 2823f34e1b8SThomas Lively 2833f34e1b8SThomas Lively done: 2843f34e1b8SThomas Lively if (!Stripped) 2853f34e1b8SThomas Lively return false; 2863f34e1b8SThomas Lively 2873f34e1b8SThomas Lively LowerAtomicPass Lowerer; 2883f34e1b8SThomas Lively FunctionAnalysisManager FAM; 2893f34e1b8SThomas Lively for (auto &F : M) 2903f34e1b8SThomas Lively Lowerer.run(F, FAM); 2913f34e1b8SThomas Lively 2923f34e1b8SThomas Lively return true; 2933f34e1b8SThomas Lively } 2943f34e1b8SThomas Lively 2953f34e1b8SThomas Lively bool stripThreadLocals(Module &M) { 2963f34e1b8SThomas Lively bool Stripped = false; 2973f34e1b8SThomas Lively for (auto &GV : M.globals()) { 298a28a4662SSam Clegg if (GV.isThreadLocal()) { 2993f34e1b8SThomas Lively Stripped = true; 300a28a4662SSam Clegg GV.setThreadLocal(false); 3013f34e1b8SThomas Lively } 3023f34e1b8SThomas Lively } 3033f34e1b8SThomas Lively return Stripped; 3043f34e1b8SThomas Lively } 3053f34e1b8SThomas Lively 3063f34e1b8SThomas Lively void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) { 3073f34e1b8SThomas Lively for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 308a1ae9566SThomas Lively if (Features[KV.Value]) { 309a1ae9566SThomas Lively // Mark features as used 3103f34e1b8SThomas Lively std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str(); 3113f34e1b8SThomas Lively M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey, 3123f34e1b8SThomas Lively wasm::WASM_FEATURE_PREFIX_USED); 3133f34e1b8SThomas Lively } 3143f34e1b8SThomas Lively } 315a1ae9566SThomas Lively // Code compiled without atomics or bulk-memory may have had its atomics or 316a1ae9566SThomas Lively // thread-local data lowered to nonatomic operations or non-thread-local 317a1ae9566SThomas Lively // data. In that case, we mark the pseudo-feature "shared-mem" as disallowed 318a1ae9566SThomas Lively // to tell the linker that it would be unsafe to allow this code ot be used 319a1ae9566SThomas Lively // in a module with shared memory. 320a1ae9566SThomas Lively if (Stripped) { 321a1ae9566SThomas Lively M.addModuleFlag(Module::ModFlagBehavior::Error, "wasm-feature-shared-mem", 322a1ae9566SThomas Lively wasm::WASM_FEATURE_PREFIX_DISALLOWED); 323a1ae9566SThomas Lively } 3243f34e1b8SThomas Lively } 32539b5367cSDerek Schuff }; 3263f34e1b8SThomas Lively char CoalesceFeaturesAndStripAtomics::ID = 0; 32739b5367cSDerek Schuff 32810e730a2SDan Gohman /// WebAssembly Code Generator Pass Configuration Options. 32910e730a2SDan Gohman class WebAssemblyPassConfig final : public TargetPassConfig { 33010e730a2SDan Gohman public: 3315e394c3dSMatthias Braun WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM) 33210e730a2SDan Gohman : TargetPassConfig(TM, PM) {} 33310e730a2SDan Gohman 33410e730a2SDan Gohman WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const { 33510e730a2SDan Gohman return getTM<WebAssemblyTargetMachine>(); 33610e730a2SDan Gohman } 33710e730a2SDan Gohman 33810e730a2SDan Gohman FunctionPass *createTargetRegisterAllocator(bool) override; 33910e730a2SDan Gohman 34010e730a2SDan Gohman void addIRPasses() override; 34110e730a2SDan Gohman bool addInstSelector() override; 34210e730a2SDan Gohman void addPostRegAlloc() override; 343ad154c83SDerek Schuff bool addGCPasses() override { return false; } 34410e730a2SDan Gohman void addPreEmitPass() override; 345d3a0a65bSPaulo Matos bool addPreISel() override; 346cf55a657SMatt Arsenault 347cf55a657SMatt Arsenault // No reg alloc 348c9122ddeSMatt Arsenault bool addRegAssignAndRewriteFast() override { return false; } 349cf55a657SMatt Arsenault 350cf55a657SMatt Arsenault // No reg alloc 351c9122ddeSMatt Arsenault bool addRegAssignAndRewriteOptimized() override { return false; } 35210e730a2SDan Gohman }; 35310e730a2SDan Gohman } // end anonymous namespace 35410e730a2SDan Gohman 35526d11ca4SSanjoy Das TargetTransformInfo 35626d11ca4SSanjoy Das WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) { 35710e730a2SDan Gohman return TargetTransformInfo(WebAssemblyTTIImpl(this, F)); 35810e730a2SDan Gohman } 35910e730a2SDan Gohman 36010e730a2SDan Gohman TargetPassConfig * 36110e730a2SDan Gohman WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) { 3625e394c3dSMatthias Braun return new WebAssemblyPassConfig(*this, PM); 36310e730a2SDan Gohman } 36410e730a2SDan Gohman 36510e730a2SDan Gohman FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) { 36610e730a2SDan Gohman return nullptr; // No reg alloc 36710e730a2SDan Gohman } 36810e730a2SDan Gohman 36977b921b8SHeejin Ahn static void checkSanityForEHAndSjLj(const TargetMachine *TM) { 37077b921b8SHeejin Ahn // Sanity checking related to -exception-model 37177b921b8SHeejin Ahn if (TM->Options.ExceptionModel != ExceptionHandling::None && 37277b921b8SHeejin Ahn TM->Options.ExceptionModel != ExceptionHandling::Wasm) 37377b921b8SHeejin Ahn report_fatal_error("-exception-model should be either 'none' or 'wasm'"); 37477b921b8SHeejin Ahn if (WasmEnableEmEH && TM->Options.ExceptionModel == ExceptionHandling::Wasm) 37577b921b8SHeejin Ahn report_fatal_error("-exception-model=wasm not allowed with " 37677b921b8SHeejin Ahn "-enable-emscripten-cxx-exceptions"); 37777b921b8SHeejin Ahn if (WasmEnableEH && TM->Options.ExceptionModel != ExceptionHandling::Wasm) 37877b921b8SHeejin Ahn report_fatal_error( 37977b921b8SHeejin Ahn "-wasm-enable-eh only allowed with -exception-model=wasm"); 38077b921b8SHeejin Ahn if (WasmEnableSjLj && TM->Options.ExceptionModel != ExceptionHandling::Wasm) 38177b921b8SHeejin Ahn report_fatal_error( 38277b921b8SHeejin Ahn "-wasm-enable-sjlj only allowed with -exception-model=wasm"); 38377b921b8SHeejin Ahn if ((!WasmEnableEH && !WasmEnableSjLj) && 38477b921b8SHeejin Ahn TM->Options.ExceptionModel == ExceptionHandling::Wasm) 38577b921b8SHeejin Ahn report_fatal_error( 38677b921b8SHeejin Ahn "-exception-model=wasm only allowed with at least one of " 38777b921b8SHeejin Ahn "-wasm-enable-eh or -wasm-enable-sjj"); 38877b921b8SHeejin Ahn 38977b921b8SHeejin Ahn // You can't enable two modes of EH at the same time 39077b921b8SHeejin Ahn if (WasmEnableEmEH && WasmEnableEH) 39177b921b8SHeejin Ahn report_fatal_error( 39277b921b8SHeejin Ahn "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-eh"); 39377b921b8SHeejin Ahn // You can't enable two modes of SjLj at the same time 39477b921b8SHeejin Ahn if (WasmEnableEmSjLj && WasmEnableSjLj) 39577b921b8SHeejin Ahn report_fatal_error( 39677b921b8SHeejin Ahn "-enable-emscripten-sjlj not allowed with -wasm-enable-sjlj"); 39777b921b8SHeejin Ahn // You can't mix Emscripten EH with Wasm SjLj. 39877b921b8SHeejin Ahn if (WasmEnableEmEH && WasmEnableSjLj) 39977b921b8SHeejin Ahn report_fatal_error( 40077b921b8SHeejin Ahn "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-sjlj"); 40177b921b8SHeejin Ahn // Currently it is allowed to mix Wasm EH with Emscripten SjLj as an interim 40277b921b8SHeejin Ahn // measure, but some code will error out at compile time in this combination. 40377b921b8SHeejin Ahn // See WebAssemblyLowerEmscriptenEHSjLj pass for details. 40477b921b8SHeejin Ahn } 40577b921b8SHeejin Ahn 40610e730a2SDan Gohman //===----------------------------------------------------------------------===// 40710e730a2SDan Gohman // The following functions are called from lib/CodeGen/Passes.cpp to modify 40810e730a2SDan Gohman // the CodeGen pass sequence. 40910e730a2SDan Gohman //===----------------------------------------------------------------------===// 41010e730a2SDan Gohman 41110e730a2SDan Gohman void WebAssemblyPassConfig::addIRPasses() { 41289fe083cSThomas Lively // Lower atomics and TLS if necessary 41389fe083cSThomas Lively addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine())); 41489fe083cSThomas Lively 41589fe083cSThomas Lively // This is a no-op if atomics are not used in the module 41689fe083cSThomas Lively addPass(createAtomicExpandPass()); 41789fe083cSThomas Lively 41892617559SSam Clegg // Add signatures to prototype-less function declarations 41992617559SSam Clegg addPass(createWebAssemblyAddMissingPrototypes()); 42092617559SSam Clegg 421bafe6902SSam Clegg // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls. 422bafe6902SSam Clegg addPass(createWebAssemblyLowerGlobalDtors()); 423bafe6902SSam Clegg 4241b637458SDan Gohman // Fix function bitcasts, as WebAssembly requires caller and callee signatures 4251b637458SDan Gohman // to match. 4261b637458SDan Gohman addPass(createWebAssemblyFixFunctionBitcasts()); 4271b637458SDan Gohman 42881719f85SDan Gohman // Optimize "returned" function attributes. 429b13c91f1SDan Gohman if (getOptLevel() != CodeGenOpt::None) 43081719f85SDan Gohman addPass(createWebAssemblyOptimizeReturned()); 43181719f85SDan Gohman 43277b921b8SHeejin Ahn checkSanityForEHAndSjLj(TM); 43377b921b8SHeejin Ahn 434c0f18172SHeejin Ahn // If exception handling is not enabled and setjmp/longjmp handling is 435c0f18172SHeejin Ahn // enabled, we lower invokes into calls and delete unreachable landingpad 436c0f18172SHeejin Ahn // blocks. Lowering invokes when there is no EH support is done in 43777b921b8SHeejin Ahn // TargetPassConfig::addPassesToHandleExceptions, but that runs after these IR 43877b921b8SHeejin Ahn // passes and Emscripten SjLj handling expects all invokes to be lowered 43977b921b8SHeejin Ahn // before. 44077b921b8SHeejin Ahn if (!WasmEnableEmEH && !WasmEnableEH) { 441c0f18172SHeejin Ahn addPass(createLowerInvokePass()); 442c0f18172SHeejin Ahn // The lower invoke pass may create unreachable code. Remove it in order not 443c0f18172SHeejin Ahn // to process dead blocks in setjmp/longjmp handling. 444c0f18172SHeejin Ahn addPass(createUnreachableBlockEliminationPass()); 445c0f18172SHeejin Ahn } 446c0f18172SHeejin Ahn 44777b921b8SHeejin Ahn // Handle exceptions and setjmp/longjmp if enabled. Unlike Wasm EH preparation 44877b921b8SHeejin Ahn // done in WasmEHPrepare pass, Wasm SjLj preparation shares libraries and 44977b921b8SHeejin Ahn // transformation algorithms with Emscripten SjLj, so we run 45077b921b8SHeejin Ahn // LowerEmscriptenEHSjLj pass also when Wasm SjLj is enabled. 45177b921b8SHeejin Ahn if (WasmEnableEmEH || WasmEnableEmSjLj || WasmEnableSjLj) 45277b921b8SHeejin Ahn addPass(createWebAssemblyLowerEmscriptenEHSjLj()); 453f41f67d3SDerek Schuff 454ec4be576SDerek Schuff // Expand indirectbr instructions to switches. 455ec4be576SDerek Schuff addPass(createIndirectBrExpandPass()); 456ec4be576SDerek Schuff 45710e730a2SDan Gohman TargetPassConfig::addIRPasses(); 45810e730a2SDan Gohman } 45910e730a2SDan Gohman 46010e730a2SDan Gohman bool WebAssemblyPassConfig::addInstSelector() { 461b0921ca9SDan Gohman (void)TargetPassConfig::addInstSelector(); 46210e730a2SDan Gohman addPass( 46310e730a2SDan Gohman createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel())); 4641cf96c0cSDan Gohman // Run the argument-move pass immediately after the ScheduleDAG scheduler 4651cf96c0cSDan Gohman // so that we can fix up the ARGUMENT instructions before anything else 4661cf96c0cSDan Gohman // sees them in the wrong place. 4671cf96c0cSDan Gohman addPass(createWebAssemblyArgumentMove()); 468bb372243SDan Gohman // Set the p2align operands. This information is present during ISel, however 469bb372243SDan Gohman // it's inconvenient to collect. Collect it now, and update the immediate 470bb372243SDan Gohman // operands. 471bb372243SDan Gohman addPass(createWebAssemblySetP2AlignOperands()); 4727f50c15bSThomas Lively 4737f50c15bSThomas Lively // Eliminate range checks and add default targets to br_table instructions. 4747f50c15bSThomas Lively addPass(createWebAssemblyFixBrTableDefaults()); 4757f50c15bSThomas Lively 47610e730a2SDan Gohman return false; 47710e730a2SDan Gohman } 47810e730a2SDan Gohman 479600aee98SJF Bastien void WebAssemblyPassConfig::addPostRegAlloc() { 4809c54d3b4SDan Gohman // TODO: The following CodeGen passes don't currently support code containing 4819c54d3b4SDan Gohman // virtual registers. Consider removing their restrictions and re-enabling 4829c54d3b4SDan Gohman // them. 483ad154c83SDerek Schuff 4841eb47368SMatthias Braun // These functions all require the NoVRegs property. 485600aee98SJF Bastien disablePass(&MachineCopyPropagationID); 4867ab1b32bSJun Bum Lim disablePass(&PostRAMachineSinkingID); 487ecabac62SDerek Schuff disablePass(&PostRASchedulerID); 488ecabac62SDerek Schuff disablePass(&FuncletLayoutID); 489ecabac62SDerek Schuff disablePass(&StackMapLivenessID); 490ecabac62SDerek Schuff disablePass(&LiveDebugValuesID); 491fe71ec77SSanjoy Das disablePass(&PatchableFunctionID); 4927ab1b32bSJun Bum Lim disablePass(&ShrinkWrapID); 493950a13cfSDan Gohman 494ef9d6aeaSHeejin Ahn // This pass hurts code size for wasm because it can generate irreducible 495ef9d6aeaSHeejin Ahn // control flow. 496ef9d6aeaSHeejin Ahn disablePass(&MachineBlockPlacementID); 497ef9d6aeaSHeejin Ahn 498b0921ca9SDan Gohman TargetPassConfig::addPostRegAlloc(); 499600aee98SJF Bastien } 50010e730a2SDan Gohman 501950a13cfSDan Gohman void WebAssemblyPassConfig::addPreEmitPass() { 502b0921ca9SDan Gohman TargetPassConfig::addPreEmitPass(); 503b0921ca9SDan Gohman 504a64ebb86SHeejin Ahn // Nullify DBG_VALUE_LISTs that we cannot handle. 505a64ebb86SHeejin Ahn addPass(createWebAssemblyNullifyDebugValueLists()); 506a64ebb86SHeejin Ahn 507e95056d6SHeejin Ahn // Eliminate multiple-entry loops. 508e95056d6SHeejin Ahn addPass(createWebAssemblyFixIrreducibleControlFlow()); 509e95056d6SHeejin Ahn 510e95056d6SHeejin Ahn // Do various transformations for exception handling. 511d6f48786SHeejin Ahn // Every CFG-changing optimizations should come before this. 5129e4eadebSHeejin Ahn if (TM->Options.ExceptionModel == ExceptionHandling::Wasm) 513e95056d6SHeejin Ahn addPass(createWebAssemblyLateEHPrepare()); 514e95056d6SHeejin Ahn 5150bb98650SHeejin Ahn // Now that we have a prologue and epilogue and all frame indices are 5160bb98650SHeejin Ahn // rewritten, eliminate SP and FP. This allows them to be stackified, 5170bb98650SHeejin Ahn // colored, and numbered with the rest of the registers. 5180bb98650SHeejin Ahn addPass(createWebAssemblyReplacePhysRegs()); 5190bb98650SHeejin Ahn 520d6f48786SHeejin Ahn // Preparations and optimizations related to register stackification. 5210cfb5f85SDan Gohman if (getOptLevel() != CodeGenOpt::None) { 5220cfb5f85SDan Gohman // LiveIntervals isn't commonly run this late. Re-establish preconditions. 5230cfb5f85SDan Gohman addPass(createWebAssemblyPrepareForLiveIntervals()); 5240cfb5f85SDan Gohman 5250cfb5f85SDan Gohman // Depend on LiveIntervals and perform some optimizations on it. 5260cfb5f85SDan Gohman addPass(createWebAssemblyOptimizeLiveIntervals()); 5270cfb5f85SDan Gohman 528321d5220SHeejin Ahn // Prepare memory intrinsic calls for register stackifying. 529321d5220SHeejin Ahn addPass(createWebAssemblyMemIntrinsicResults()); 5300cfb5f85SDan Gohman 531e040533eSDan Gohman // Mark registers as representing wasm's value stack. This is a key 5320cfb5f85SDan Gohman // code-compression technique in WebAssembly. We run this pass (and 533321d5220SHeejin Ahn // MemIntrinsicResults above) very late, so that it sees as much code as 534321d5220SHeejin Ahn // possible, including code emitted by PEI and expanded by late tail 535321d5220SHeejin Ahn // duplication. 5360cfb5f85SDan Gohman addPass(createWebAssemblyRegStackify()); 5370cfb5f85SDan Gohman 5380cfb5f85SDan Gohman // Run the register coloring pass to reduce the total number of registers. 5390cfb5f85SDan Gohman // This runs after stackification so that it doesn't consider registers 5400cfb5f85SDan Gohman // that become stackified. 5410cfb5f85SDan Gohman addPass(createWebAssemblyRegColoring()); 5420cfb5f85SDan Gohman } 5430cfb5f85SDan Gohman 544f52ee17aSDan Gohman // Sort the blocks of the CFG into topological order, a prerequisite for 545f52ee17aSDan Gohman // BLOCK and LOOP markers. 546f52ee17aSDan Gohman addPass(createWebAssemblyCFGSort()); 547f52ee17aSDan Gohman 548f52ee17aSDan Gohman // Insert BLOCK and LOOP markers. 549950a13cfSDan Gohman addPass(createWebAssemblyCFGStackify()); 5505941bde0SDan Gohman 551e9fd9073SHeejin Ahn // Insert explicit local.get and local.set operators. 5522b7fe086SWouter van Oortmerssen if (!WasmDisableExplicitLocals) 553e9fd9073SHeejin Ahn addPass(createWebAssemblyExplicitLocals()); 554e9fd9073SHeejin Ahn 555f0b165a7SDan Gohman // Lower br_unless into br_if. 556f0b165a7SDan Gohman addPass(createWebAssemblyLowerBrUnless()); 557f0b165a7SDan Gohman 5585941bde0SDan Gohman // Perform the very last peephole optimizations on the code. 559b13c91f1SDan Gohman if (getOptLevel() != CodeGenOpt::None) 56081719f85SDan Gohman addPass(createWebAssemblyPeephole()); 561b7c2400fSDan Gohman 562b7c2400fSDan Gohman // Create a mapping from LLVM CodeGen virtual registers to wasm registers. 563b7c2400fSDan Gohman addPass(createWebAssemblyRegNumbering()); 5642b7fe086SWouter van Oortmerssen 5652b7fe086SWouter van Oortmerssen // Fix debug_values whose defs have been stackified. 5662b7fe086SWouter van Oortmerssen if (!WasmDisableExplicitLocals) 5672b7fe086SWouter van Oortmerssen addPass(createWebAssemblyDebugFixup()); 5689647a6f7SWouter van Oortmerssen 5699647a6f7SWouter van Oortmerssen // Collect information to prepare for MC lowering / asm printing. 5709647a6f7SWouter van Oortmerssen addPass(createWebAssemblyMCLowerPrePass()); 571950a13cfSDan Gohman } 57252221d56SHeejin Ahn 573d3a0a65bSPaulo Matos bool WebAssemblyPassConfig::addPreISel() { 574d3a0a65bSPaulo Matos TargetPassConfig::addPreISel(); 575d3a0a65bSPaulo Matos addPass(createWebAssemblyLowerRefTypesIntPtrConv()); 576d3a0a65bSPaulo Matos return false; 577d3a0a65bSPaulo Matos } 578d3a0a65bSPaulo Matos 57952221d56SHeejin Ahn yaml::MachineFunctionInfo * 58052221d56SHeejin Ahn WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const { 58152221d56SHeejin Ahn return new yaml::WebAssemblyFunctionInfo(); 58252221d56SHeejin Ahn } 58352221d56SHeejin Ahn 58452221d56SHeejin Ahn yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML( 58552221d56SHeejin Ahn const MachineFunction &MF) const { 58652221d56SHeejin Ahn const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>(); 58752221d56SHeejin Ahn return new yaml::WebAssemblyFunctionInfo(*MFI); 58852221d56SHeejin Ahn } 58952221d56SHeejin Ahn 59052221d56SHeejin Ahn bool WebAssemblyTargetMachine::parseMachineFunctionInfo( 59152221d56SHeejin Ahn const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS, 59252221d56SHeejin Ahn SMDiagnostic &Error, SMRange &SourceRange) const { 59352221d56SHeejin Ahn const auto &YamlMFI = 59452221d56SHeejin Ahn reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI); 59552221d56SHeejin Ahn MachineFunction &MF = PFS.MF; 59652221d56SHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI); 59752221d56SHeejin Ahn return false; 59852221d56SHeejin Ahn } 599