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