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" 1752221d56SHeejin Ahn #include "WebAssemblyMachineFunctionInfo.h" 185bf22fc8SDan Gohman #include "WebAssemblyTargetObjectFile.h" 1910e730a2SDan Gohman #include "WebAssemblyTargetTransformInfo.h" 2052221d56SHeejin 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" 29*3f34e1b8SThomas Lively #include "llvm/Transforms/Scalar/LowerAtomic.h" 30a373d18eSDavid Blaikie #include "llvm/Transforms/Utils.h" 3110e730a2SDan Gohman using namespace llvm; 3210e730a2SDan Gohman 3310e730a2SDan Gohman #define DEBUG_TYPE "wasm" 3410e730a2SDan Gohman 35f41f67d3SDerek Schuff // Emscripten's asm.js-style exception handling 36ccdceda1SDerek Schuff static cl::opt<bool> EnableEmException( 3753b9af02SDerek Schuff "enable-emscripten-cxx-exceptions", 38f41f67d3SDerek Schuff cl::desc("WebAssembly Emscripten-style exception handling"), 39f41f67d3SDerek Schuff cl::init(false)); 40f41f67d3SDerek Schuff 41ccdceda1SDerek Schuff // Emscripten's asm.js-style setjmp/longjmp handling 42ccdceda1SDerek Schuff static cl::opt<bool> EnableEmSjLj( 43ccdceda1SDerek Schuff "enable-emscripten-sjlj", 44ccdceda1SDerek Schuff cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"), 45ccdceda1SDerek Schuff cl::init(false)); 46ccdceda1SDerek Schuff 4710e730a2SDan Gohman extern "C" void LLVMInitializeWebAssemblyTarget() { 4810e730a2SDan Gohman // Register the target. 49f42454b9SMehdi Amini RegisterTargetMachine<WebAssemblyTargetMachine> X( 50f42454b9SMehdi Amini getTheWebAssemblyTarget32()); 51f42454b9SMehdi Amini RegisterTargetMachine<WebAssemblyTargetMachine> Y( 52f42454b9SMehdi Amini getTheWebAssemblyTarget64()); 53f41f67d3SDerek Schuff 5440926451SJacob Gravelle // Register backend passes 5540926451SJacob Gravelle auto &PR = *PassRegistry::getPassRegistry(); 5692617559SSam Clegg initializeWebAssemblyAddMissingPrototypesPass(PR); 5740926451SJacob Gravelle initializeWebAssemblyLowerEmscriptenEHSjLjPass(PR); 5840926451SJacob Gravelle initializeLowerGlobalDtorsPass(PR); 5940926451SJacob Gravelle initializeFixFunctionBitcastsPass(PR); 6040926451SJacob Gravelle initializeOptimizeReturnedPass(PR); 6140926451SJacob Gravelle initializeWebAssemblyArgumentMovePass(PR); 6240926451SJacob Gravelle initializeWebAssemblySetP2AlignOperandsPass(PR); 6340926451SJacob Gravelle initializeWebAssemblyReplacePhysRegsPass(PR); 6440926451SJacob Gravelle initializeWebAssemblyPrepareForLiveIntervalsPass(PR); 6540926451SJacob Gravelle initializeWebAssemblyOptimizeLiveIntervalsPass(PR); 66321d5220SHeejin Ahn initializeWebAssemblyMemIntrinsicResultsPass(PR); 6740926451SJacob Gravelle initializeWebAssemblyRegStackifyPass(PR); 6840926451SJacob Gravelle initializeWebAssemblyRegColoringPass(PR); 6940926451SJacob Gravelle initializeWebAssemblyExplicitLocalsPass(PR); 7040926451SJacob Gravelle initializeWebAssemblyFixIrreducibleControlFlowPass(PR); 714934f76bSHeejin Ahn initializeWebAssemblyLateEHPreparePass(PR); 7204c48949SHeejin Ahn initializeWebAssemblyExceptionInfoPass(PR); 7340926451SJacob Gravelle initializeWebAssemblyCFGSortPass(PR); 7440926451SJacob Gravelle initializeWebAssemblyCFGStackifyPass(PR); 7540926451SJacob Gravelle initializeWebAssemblyLowerBrUnlessPass(PR); 7640926451SJacob Gravelle initializeWebAssemblyRegNumberingPass(PR); 7740926451SJacob Gravelle initializeWebAssemblyPeepholePass(PR); 7840926451SJacob Gravelle initializeWebAssemblyCallIndirectFixupPass(PR); 7910e730a2SDan Gohman } 8010e730a2SDan Gohman 8110e730a2SDan Gohman //===----------------------------------------------------------------------===// 8210e730a2SDan Gohman // WebAssembly Lowering public interface. 8310e730a2SDan Gohman //===----------------------------------------------------------------------===// 8410e730a2SDan Gohman 8541133a3eSDan Gohman static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) { 8674f5fd4eSSam Clegg if (!RM.hasValue()) { 8774f5fd4eSSam Clegg // Default to static relocation model. This should always be more optimial 8874f5fd4eSSam Clegg // than PIC since the static linker can determine all global addresses and 8974f5fd4eSSam Clegg // assume direct function calls. 9074f5fd4eSSam Clegg return Reloc::Static; 9174f5fd4eSSam Clegg } 9241133a3eSDan Gohman return *RM; 9341133a3eSDan Gohman } 9441133a3eSDan Gohman 9510e730a2SDan Gohman /// Create an WebAssembly architecture model. 9610e730a2SDan Gohman /// 9710e730a2SDan Gohman WebAssemblyTargetMachine::WebAssemblyTargetMachine( 9810e730a2SDan Gohman const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 9941133a3eSDan Gohman const TargetOptions &Options, Optional<Reloc::Model> RM, 100314ed201SDaniel Jasper Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT) 101bb8507e6SMatthias Braun : LLVMTargetMachine(T, 102bb8507e6SMatthias Braun TT.isArch64Bit() ? "e-m:e-p:64:64-i64:64-n32:64-S128" 1030c6f5ac5SDan Gohman : "e-m:e-p:32:32-i64:64-n32:64-S128", 10441133a3eSDan Gohman TT, CPU, FS, Options, getEffectiveRelocModel(RM), 105ca29c271SDavid Green getEffectiveCodeModel(CM, CodeModel::Large), OL), 106cf2a9e28SSam Clegg TLOF(new WebAssemblyTargetObjectFile()) { 107e040533eSDan Gohman // WebAssembly type-checks instructions, but a noreturn function with a return 108ffa143ceSDerek Schuff // type that doesn't match the context will cause a check failure. So we lower 109ffa143ceSDerek Schuff // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's 110e040533eSDan Gohman // 'unreachable' instructions which is meant for that case. 111ffa143ceSDerek Schuff this->Options.TrapUnreachable = true; 112ffa143ceSDerek Schuff 113d934cb88SDan Gohman // WebAssembly treats each function as an independent unit. Force 114d934cb88SDan Gohman // -ffunction-sections, effectively, so that we can emit them independently. 115d934cb88SDan Gohman this->Options.FunctionSections = true; 116d934cb88SDan Gohman this->Options.DataSections = true; 117d934cb88SDan Gohman this->Options.UniqueSectionNames = true; 118d934cb88SDan Gohman 11910e730a2SDan Gohman initAsmInfo(); 12010e730a2SDan Gohman 121d85ab7fcSDan Gohman // Note that we don't use setRequiresStructuredCFG(true). It disables 122d85ab7fcSDan Gohman // optimizations than we're ok with, and want, such as critical edge 123d85ab7fcSDan Gohman // splitting and tail merging. 12410e730a2SDan Gohman } 12510e730a2SDan Gohman 12618c56a07SHeejin Ahn WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor. 12710e730a2SDan Gohman 12810e730a2SDan Gohman const WebAssemblySubtarget * 129f3b4f990SThomas Lively WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU, 130f3b4f990SThomas Lively std::string FS) const { 131f3b4f990SThomas Lively auto &I = SubtargetMap[CPU + FS]; 132f3b4f990SThomas Lively if (!I) { 133f3b4f990SThomas Lively I = llvm::make_unique<WebAssemblySubtarget>(TargetTriple, CPU, FS, *this); 134f3b4f990SThomas Lively } 135f3b4f990SThomas Lively return I.get(); 136f3b4f990SThomas Lively } 137f3b4f990SThomas Lively 138f3b4f990SThomas Lively const WebAssemblySubtarget * 13910e730a2SDan Gohman WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const { 14010e730a2SDan Gohman Attribute CPUAttr = F.getFnAttribute("target-cpu"); 14110e730a2SDan Gohman Attribute FSAttr = F.getFnAttribute("target-features"); 14210e730a2SDan Gohman 14310e730a2SDan Gohman std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 14410e730a2SDan Gohman ? CPUAttr.getValueAsString().str() 14510e730a2SDan Gohman : TargetCPU; 14610e730a2SDan Gohman std::string FS = !FSAttr.hasAttribute(Attribute::None) 14710e730a2SDan Gohman ? FSAttr.getValueAsString().str() 14810e730a2SDan Gohman : TargetFS; 14910e730a2SDan Gohman 15010e730a2SDan Gohman // This needs to be done before we create a new subtarget since any 15110e730a2SDan Gohman // creation will depend on the TM and the code generation flags on the 15210e730a2SDan Gohman // function that reside in TargetOptions. 15310e730a2SDan Gohman resetTargetOptions(F); 154f3b4f990SThomas Lively 155f3b4f990SThomas Lively return getSubtargetImpl(CPU, FS); 15610e730a2SDan Gohman } 15710e730a2SDan Gohman 15810e730a2SDan Gohman namespace { 159*3f34e1b8SThomas Lively 160*3f34e1b8SThomas Lively class CoalesceFeaturesAndStripAtomics final : public ModulePass { 161*3f34e1b8SThomas Lively // Take the union of all features used in the module and use it for each 162*3f34e1b8SThomas Lively // function individually, since having multiple feature sets in one module 163*3f34e1b8SThomas Lively // currently does not make sense for WebAssembly. If atomics are not enabled, 164*3f34e1b8SThomas Lively // also strip atomic operations and thread local storage. 16539b5367cSDerek Schuff static char ID; 166*3f34e1b8SThomas Lively WebAssemblyTargetMachine *WasmTM; 16739b5367cSDerek Schuff 16839b5367cSDerek Schuff public: 169*3f34e1b8SThomas Lively CoalesceFeaturesAndStripAtomics(WebAssemblyTargetMachine *WasmTM) 170*3f34e1b8SThomas Lively : ModulePass(ID), WasmTM(WasmTM) {} 171*3f34e1b8SThomas Lively 17239b5367cSDerek Schuff bool runOnModule(Module &M) override { 173*3f34e1b8SThomas Lively FeatureBitset Features = coalesceFeatures(M); 174*3f34e1b8SThomas Lively 175*3f34e1b8SThomas Lively std::string FeatureStr = getFeatureString(Features); 176*3f34e1b8SThomas Lively for (auto &F : M) 177*3f34e1b8SThomas Lively replaceFeatures(F, FeatureStr); 178*3f34e1b8SThomas Lively 179*3f34e1b8SThomas Lively bool Stripped = false; 180*3f34e1b8SThomas Lively if (!Features[WebAssembly::FeatureAtomics]) { 181*3f34e1b8SThomas Lively Stripped |= stripAtomics(M); 182*3f34e1b8SThomas Lively Stripped |= stripThreadLocals(M); 183*3f34e1b8SThomas Lively } 184*3f34e1b8SThomas Lively 185*3f34e1b8SThomas Lively recordFeatures(M, Features, Stripped); 186*3f34e1b8SThomas Lively 187*3f34e1b8SThomas Lively // Conservatively assume we have made some change 18839b5367cSDerek Schuff return true; 18939b5367cSDerek Schuff } 190*3f34e1b8SThomas Lively 191*3f34e1b8SThomas Lively private: 192*3f34e1b8SThomas Lively FeatureBitset coalesceFeatures(const Module &M) { 193*3f34e1b8SThomas Lively FeatureBitset Features = 194*3f34e1b8SThomas Lively WasmTM 195*3f34e1b8SThomas Lively ->getSubtargetImpl(WasmTM->getTargetCPU(), 196*3f34e1b8SThomas Lively WasmTM->getTargetFeatureString()) 197*3f34e1b8SThomas Lively ->getFeatureBits(); 198*3f34e1b8SThomas Lively for (auto &F : M) 199*3f34e1b8SThomas Lively Features |= WasmTM->getSubtargetImpl(F)->getFeatureBits(); 200*3f34e1b8SThomas Lively return Features; 201*3f34e1b8SThomas Lively } 202*3f34e1b8SThomas Lively 203*3f34e1b8SThomas Lively std::string getFeatureString(const FeatureBitset &Features) { 204*3f34e1b8SThomas Lively std::string Ret; 205*3f34e1b8SThomas Lively for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 206*3f34e1b8SThomas Lively if (Features[KV.Value]) 207*3f34e1b8SThomas Lively Ret += (StringRef("+") + KV.Key + ",").str(); 208*3f34e1b8SThomas Lively } 209*3f34e1b8SThomas Lively return Ret; 210*3f34e1b8SThomas Lively } 211*3f34e1b8SThomas Lively 212*3f34e1b8SThomas Lively void replaceFeatures(Function &F, const std::string &Features) { 213*3f34e1b8SThomas Lively F.removeFnAttr("target-features"); 214*3f34e1b8SThomas Lively F.removeFnAttr("target-cpu"); 215*3f34e1b8SThomas Lively F.addFnAttr("target-features", Features); 216*3f34e1b8SThomas Lively } 217*3f34e1b8SThomas Lively 218*3f34e1b8SThomas Lively bool stripAtomics(Module &M) { 219*3f34e1b8SThomas Lively // Detect whether any atomics will be lowered, since there is no way to tell 220*3f34e1b8SThomas Lively // whether the LowerAtomic pass lowers e.g. stores. 221*3f34e1b8SThomas Lively bool Stripped = false; 222*3f34e1b8SThomas Lively for (auto &F : M) { 223*3f34e1b8SThomas Lively for (auto &B : F) { 224*3f34e1b8SThomas Lively for (auto &I : B) { 225*3f34e1b8SThomas Lively if (I.isAtomic()) { 226*3f34e1b8SThomas Lively Stripped = true; 227*3f34e1b8SThomas Lively goto done; 228*3f34e1b8SThomas Lively } 229*3f34e1b8SThomas Lively } 230*3f34e1b8SThomas Lively } 231*3f34e1b8SThomas Lively } 232*3f34e1b8SThomas Lively 233*3f34e1b8SThomas Lively done: 234*3f34e1b8SThomas Lively if (!Stripped) 235*3f34e1b8SThomas Lively return false; 236*3f34e1b8SThomas Lively 237*3f34e1b8SThomas Lively LowerAtomicPass Lowerer; 238*3f34e1b8SThomas Lively FunctionAnalysisManager FAM; 239*3f34e1b8SThomas Lively for (auto &F : M) 240*3f34e1b8SThomas Lively Lowerer.run(F, FAM); 241*3f34e1b8SThomas Lively 242*3f34e1b8SThomas Lively return true; 243*3f34e1b8SThomas Lively } 244*3f34e1b8SThomas Lively 245*3f34e1b8SThomas Lively bool stripThreadLocals(Module &M) { 246*3f34e1b8SThomas Lively bool Stripped = false; 247*3f34e1b8SThomas Lively for (auto &GV : M.globals()) { 248*3f34e1b8SThomas Lively if (GV.getThreadLocalMode() != 249*3f34e1b8SThomas Lively GlobalValue::ThreadLocalMode::NotThreadLocal) { 250*3f34e1b8SThomas Lively Stripped = true; 251*3f34e1b8SThomas Lively GV.setThreadLocalMode(GlobalValue::ThreadLocalMode::NotThreadLocal); 252*3f34e1b8SThomas Lively } 253*3f34e1b8SThomas Lively } 254*3f34e1b8SThomas Lively return Stripped; 255*3f34e1b8SThomas Lively } 256*3f34e1b8SThomas Lively 257*3f34e1b8SThomas Lively void recordFeatures(Module &M, const FeatureBitset &Features, bool Stripped) { 258*3f34e1b8SThomas Lively for (const SubtargetFeatureKV &KV : WebAssemblyFeatureKV) { 259*3f34e1b8SThomas Lively std::string MDKey = (StringRef("wasm-feature-") + KV.Key).str(); 260*3f34e1b8SThomas Lively if (KV.Value == WebAssembly::FeatureAtomics && Stripped) { 261*3f34e1b8SThomas Lively // "atomics" is special: code compiled without atomics may have had its 262*3f34e1b8SThomas Lively // atomics lowered to nonatomic operations. In that case, atomics is 263*3f34e1b8SThomas Lively // disallowed to prevent unsafe linking with atomics-enabled objects. 264*3f34e1b8SThomas Lively assert(!Features[WebAssembly::FeatureAtomics]); 265*3f34e1b8SThomas Lively M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey, 266*3f34e1b8SThomas Lively wasm::WASM_FEATURE_PREFIX_DISALLOWED); 267*3f34e1b8SThomas Lively } else if (Features[KV.Value]) { 268*3f34e1b8SThomas Lively // Otherwise features are marked Used or not mentioned 269*3f34e1b8SThomas Lively M.addModuleFlag(Module::ModFlagBehavior::Error, MDKey, 270*3f34e1b8SThomas Lively wasm::WASM_FEATURE_PREFIX_USED); 271*3f34e1b8SThomas Lively } 272*3f34e1b8SThomas Lively } 273*3f34e1b8SThomas Lively } 27439b5367cSDerek Schuff }; 275*3f34e1b8SThomas Lively char CoalesceFeaturesAndStripAtomics::ID = 0; 27639b5367cSDerek Schuff 27710e730a2SDan Gohman /// WebAssembly Code Generator Pass Configuration Options. 27810e730a2SDan Gohman class WebAssemblyPassConfig final : public TargetPassConfig { 27910e730a2SDan Gohman public: 2805e394c3dSMatthias Braun WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM) 28110e730a2SDan Gohman : TargetPassConfig(TM, PM) {} 28210e730a2SDan Gohman 28310e730a2SDan Gohman WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const { 28410e730a2SDan Gohman return getTM<WebAssemblyTargetMachine>(); 28510e730a2SDan Gohman } 28610e730a2SDan Gohman 28710e730a2SDan Gohman FunctionPass *createTargetRegisterAllocator(bool) override; 28810e730a2SDan Gohman 28910e730a2SDan Gohman void addIRPasses() override; 29010e730a2SDan Gohman bool addInstSelector() override; 29110e730a2SDan Gohman void addPostRegAlloc() override; 292ad154c83SDerek Schuff bool addGCPasses() override { return false; } 29310e730a2SDan Gohman void addPreEmitPass() override; 294cf55a657SMatt Arsenault 295cf55a657SMatt Arsenault // No reg alloc 296cf55a657SMatt Arsenault bool addRegAssignmentFast() override { return false; } 297cf55a657SMatt Arsenault 298cf55a657SMatt Arsenault // No reg alloc 299cf55a657SMatt Arsenault bool addRegAssignmentOptimized() override { return false; } 30010e730a2SDan Gohman }; 30110e730a2SDan Gohman } // end anonymous namespace 30210e730a2SDan Gohman 30326d11ca4SSanjoy Das TargetTransformInfo 30426d11ca4SSanjoy Das WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) { 30510e730a2SDan Gohman return TargetTransformInfo(WebAssemblyTTIImpl(this, F)); 30610e730a2SDan Gohman } 30710e730a2SDan Gohman 30810e730a2SDan Gohman TargetPassConfig * 30910e730a2SDan Gohman WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) { 3105e394c3dSMatthias Braun return new WebAssemblyPassConfig(*this, PM); 31110e730a2SDan Gohman } 31210e730a2SDan Gohman 31310e730a2SDan Gohman FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) { 31410e730a2SDan Gohman return nullptr; // No reg alloc 31510e730a2SDan Gohman } 31610e730a2SDan Gohman 31710e730a2SDan Gohman //===----------------------------------------------------------------------===// 31810e730a2SDan Gohman // The following functions are called from lib/CodeGen/Passes.cpp to modify 31910e730a2SDan Gohman // the CodeGen pass sequence. 32010e730a2SDan Gohman //===----------------------------------------------------------------------===// 32110e730a2SDan Gohman 32210e730a2SDan Gohman void WebAssemblyPassConfig::addIRPasses() { 323*3f34e1b8SThomas Lively // Runs LowerAtomicPass if necessary 324*3f34e1b8SThomas Lively addPass(new CoalesceFeaturesAndStripAtomics(&getWebAssemblyTargetMachine())); 325*3f34e1b8SThomas Lively 326*3f34e1b8SThomas Lively // This is a no-op if atomics are not used in the module 3278b61764cSFrancis Visoiu Mistrih addPass(createAtomicExpandPass()); 32810e730a2SDan Gohman 32992617559SSam Clegg // Add signatures to prototype-less function declarations 33092617559SSam Clegg addPass(createWebAssemblyAddMissingPrototypes()); 33192617559SSam Clegg 332bafe6902SSam Clegg // Lower .llvm.global_dtors into .llvm_global_ctors with __cxa_atexit calls. 333bafe6902SSam Clegg addPass(createWebAssemblyLowerGlobalDtors()); 334bafe6902SSam Clegg 3351b637458SDan Gohman // Fix function bitcasts, as WebAssembly requires caller and callee signatures 3361b637458SDan Gohman // to match. 3371b637458SDan Gohman addPass(createWebAssemblyFixFunctionBitcasts()); 3381b637458SDan Gohman 33981719f85SDan Gohman // Optimize "returned" function attributes. 340b13c91f1SDan Gohman if (getOptLevel() != CodeGenOpt::None) 34181719f85SDan Gohman addPass(createWebAssemblyOptimizeReturned()); 34281719f85SDan Gohman 343c0f18172SHeejin Ahn // If exception handling is not enabled and setjmp/longjmp handling is 344c0f18172SHeejin Ahn // enabled, we lower invokes into calls and delete unreachable landingpad 345c0f18172SHeejin Ahn // blocks. Lowering invokes when there is no EH support is done in 346c0f18172SHeejin Ahn // TargetPassConfig::addPassesToHandleExceptions, but this runs after this 347c0f18172SHeejin Ahn // function and SjLj handling expects all invokes to be lowered before. 3489386bde1SHeejin Ahn if (!EnableEmException && 3499386bde1SHeejin Ahn TM->Options.ExceptionModel == ExceptionHandling::None) { 350c0f18172SHeejin Ahn addPass(createLowerInvokePass()); 351c0f18172SHeejin Ahn // The lower invoke pass may create unreachable code. Remove it in order not 352c0f18172SHeejin Ahn // to process dead blocks in setjmp/longjmp handling. 353c0f18172SHeejin Ahn addPass(createUnreachableBlockEliminationPass()); 354c0f18172SHeejin Ahn } 355c0f18172SHeejin Ahn 356c0f18172SHeejin Ahn // Handle exceptions and setjmp/longjmp if enabled. 357ccdceda1SDerek Schuff if (EnableEmException || EnableEmSjLj) 358ccdceda1SDerek Schuff addPass(createWebAssemblyLowerEmscriptenEHSjLj(EnableEmException, 359ccdceda1SDerek Schuff EnableEmSjLj)); 360f41f67d3SDerek Schuff 36110e730a2SDan Gohman TargetPassConfig::addIRPasses(); 36210e730a2SDan Gohman } 36310e730a2SDan Gohman 36410e730a2SDan Gohman bool WebAssemblyPassConfig::addInstSelector() { 365b0921ca9SDan Gohman (void)TargetPassConfig::addInstSelector(); 36610e730a2SDan Gohman addPass( 36710e730a2SDan Gohman createWebAssemblyISelDag(getWebAssemblyTargetMachine(), getOptLevel())); 3681cf96c0cSDan Gohman // Run the argument-move pass immediately after the ScheduleDAG scheduler 3691cf96c0cSDan Gohman // so that we can fix up the ARGUMENT instructions before anything else 3701cf96c0cSDan Gohman // sees them in the wrong place. 3711cf96c0cSDan Gohman addPass(createWebAssemblyArgumentMove()); 372bb372243SDan Gohman // Set the p2align operands. This information is present during ISel, however 373bb372243SDan Gohman // it's inconvenient to collect. Collect it now, and update the immediate 374bb372243SDan Gohman // operands. 375bb372243SDan Gohman addPass(createWebAssemblySetP2AlignOperands()); 37610e730a2SDan Gohman return false; 37710e730a2SDan Gohman } 37810e730a2SDan Gohman 379600aee98SJF Bastien void WebAssemblyPassConfig::addPostRegAlloc() { 3809c54d3b4SDan Gohman // TODO: The following CodeGen passes don't currently support code containing 3819c54d3b4SDan Gohman // virtual registers. Consider removing their restrictions and re-enabling 3829c54d3b4SDan Gohman // them. 383ad154c83SDerek Schuff 3841eb47368SMatthias Braun // These functions all require the NoVRegs property. 385600aee98SJF Bastien disablePass(&MachineCopyPropagationID); 3867ab1b32bSJun Bum Lim disablePass(&PostRAMachineSinkingID); 387ecabac62SDerek Schuff disablePass(&PostRASchedulerID); 388ecabac62SDerek Schuff disablePass(&FuncletLayoutID); 389ecabac62SDerek Schuff disablePass(&StackMapLivenessID); 390ecabac62SDerek Schuff disablePass(&LiveDebugValuesID); 391fe71ec77SSanjoy Das disablePass(&PatchableFunctionID); 3927ab1b32bSJun Bum Lim disablePass(&ShrinkWrapID); 393950a13cfSDan Gohman 394ef9d6aeaSHeejin Ahn // This pass hurts code size for wasm because it can generate irreducible 395ef9d6aeaSHeejin Ahn // control flow. 396ef9d6aeaSHeejin Ahn disablePass(&MachineBlockPlacementID); 397ef9d6aeaSHeejin Ahn 398b0921ca9SDan Gohman TargetPassConfig::addPostRegAlloc(); 399600aee98SJF Bastien } 40010e730a2SDan Gohman 401950a13cfSDan Gohman void WebAssemblyPassConfig::addPreEmitPass() { 402b0921ca9SDan Gohman TargetPassConfig::addPreEmitPass(); 403b0921ca9SDan Gohman 4046f69783fSDerek Schuff // Rewrite pseudo call_indirect instructions as real instructions. 4056f69783fSDerek Schuff // This needs to run before register stackification, because we change the 4066f69783fSDerek Schuff // order of the arguments. 4076f69783fSDerek Schuff addPass(createWebAssemblyCallIndirectFixup()); 4086f69783fSDerek Schuff 409e95056d6SHeejin Ahn // Eliminate multiple-entry loops. 410e95056d6SHeejin Ahn addPass(createWebAssemblyFixIrreducibleControlFlow()); 411e95056d6SHeejin Ahn 412e95056d6SHeejin Ahn // Do various transformations for exception handling. 413d6f48786SHeejin Ahn // Every CFG-changing optimizations should come before this. 414e95056d6SHeejin Ahn addPass(createWebAssemblyLateEHPrepare()); 415e95056d6SHeejin Ahn 4160bb98650SHeejin Ahn // Now that we have a prologue and epilogue and all frame indices are 4170bb98650SHeejin Ahn // rewritten, eliminate SP and FP. This allows them to be stackified, 4180bb98650SHeejin Ahn // colored, and numbered with the rest of the registers. 4190bb98650SHeejin Ahn addPass(createWebAssemblyReplacePhysRegs()); 4200bb98650SHeejin Ahn 421d6f48786SHeejin Ahn // Preparations and optimizations related to register stackification. 4220cfb5f85SDan Gohman if (getOptLevel() != CodeGenOpt::None) { 4230cfb5f85SDan Gohman // LiveIntervals isn't commonly run this late. Re-establish preconditions. 4240cfb5f85SDan Gohman addPass(createWebAssemblyPrepareForLiveIntervals()); 4250cfb5f85SDan Gohman 4260cfb5f85SDan Gohman // Depend on LiveIntervals and perform some optimizations on it. 4270cfb5f85SDan Gohman addPass(createWebAssemblyOptimizeLiveIntervals()); 4280cfb5f85SDan Gohman 429321d5220SHeejin Ahn // Prepare memory intrinsic calls for register stackifying. 430321d5220SHeejin Ahn addPass(createWebAssemblyMemIntrinsicResults()); 4310cfb5f85SDan Gohman 432e040533eSDan Gohman // Mark registers as representing wasm's value stack. This is a key 4330cfb5f85SDan Gohman // code-compression technique in WebAssembly. We run this pass (and 434321d5220SHeejin Ahn // MemIntrinsicResults above) very late, so that it sees as much code as 435321d5220SHeejin Ahn // possible, including code emitted by PEI and expanded by late tail 436321d5220SHeejin Ahn // duplication. 4370cfb5f85SDan Gohman addPass(createWebAssemblyRegStackify()); 4380cfb5f85SDan Gohman 4390cfb5f85SDan Gohman // Run the register coloring pass to reduce the total number of registers. 4400cfb5f85SDan Gohman // This runs after stackification so that it doesn't consider registers 4410cfb5f85SDan Gohman // that become stackified. 4420cfb5f85SDan Gohman addPass(createWebAssemblyRegColoring()); 4430cfb5f85SDan Gohman } 4440cfb5f85SDan Gohman 4456a87ddacSThomas Lively // Insert explicit local.get and local.set operators. 446a7be3755SWouter van Oortmerssen addPass(createWebAssemblyExplicitLocals()); 447a7be3755SWouter van Oortmerssen 448f52ee17aSDan Gohman // Sort the blocks of the CFG into topological order, a prerequisite for 449f52ee17aSDan Gohman // BLOCK and LOOP markers. 450f52ee17aSDan Gohman addPass(createWebAssemblyCFGSort()); 451f52ee17aSDan Gohman 452f52ee17aSDan Gohman // Insert BLOCK and LOOP markers. 453950a13cfSDan Gohman addPass(createWebAssemblyCFGStackify()); 4545941bde0SDan Gohman 455f0b165a7SDan Gohman // Lower br_unless into br_if. 456f0b165a7SDan Gohman addPass(createWebAssemblyLowerBrUnless()); 457f0b165a7SDan Gohman 4585941bde0SDan Gohman // Perform the very last peephole optimizations on the code. 459b13c91f1SDan Gohman if (getOptLevel() != CodeGenOpt::None) 46081719f85SDan Gohman addPass(createWebAssemblyPeephole()); 461b7c2400fSDan Gohman 462b7c2400fSDan Gohman // Create a mapping from LLVM CodeGen virtual registers to wasm registers. 463b7c2400fSDan Gohman addPass(createWebAssemblyRegNumbering()); 464950a13cfSDan Gohman } 46552221d56SHeejin Ahn 46652221d56SHeejin Ahn yaml::MachineFunctionInfo * 46752221d56SHeejin Ahn WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const { 46852221d56SHeejin Ahn return new yaml::WebAssemblyFunctionInfo(); 46952221d56SHeejin Ahn } 47052221d56SHeejin Ahn 47152221d56SHeejin Ahn yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML( 47252221d56SHeejin Ahn const MachineFunction &MF) const { 47352221d56SHeejin Ahn const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>(); 47452221d56SHeejin Ahn return new yaml::WebAssemblyFunctionInfo(*MFI); 47552221d56SHeejin Ahn } 47652221d56SHeejin Ahn 47752221d56SHeejin Ahn bool WebAssemblyTargetMachine::parseMachineFunctionInfo( 47852221d56SHeejin Ahn const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS, 47952221d56SHeejin Ahn SMDiagnostic &Error, SMRange &SourceRange) const { 48052221d56SHeejin Ahn const auto &YamlMFI = 48152221d56SHeejin Ahn reinterpret_cast<const yaml::WebAssemblyFunctionInfo &>(MFI); 48252221d56SHeejin Ahn MachineFunction &MF = PFS.MF; 48352221d56SHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(YamlMFI); 48452221d56SHeejin Ahn return false; 48552221d56SHeejin Ahn } 486