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