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 "WebAssemblyISelLowering.h"
19#include "WebAssemblyMachineFunctionInfo.h"
20#include "WebAssemblyTargetObjectFile.h"
21#include "WebAssemblyTargetTransformInfo.h"
22#include "WebAssemblyUtilities.h"
23#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
24#include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
25#include "llvm/CodeGen/GlobalISel/Legalizer.h"
26#include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
27#include "llvm/CodeGen/MIRParser/MIParser.h"
28#include "llvm/CodeGen/Passes.h"
29#include "llvm/CodeGen/RegAllocRegistry.h"
30#include "llvm/CodeGen/TargetPassConfig.h"
31#include "llvm/IR/Function.h"
32#include "llvm/InitializePasses.h"
33#include "llvm/MC/TargetRegistry.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Target/TargetOptions.h"
36#include "llvm/Transforms/Scalar.h"
37#include "llvm/Transforms/Scalar/LowerAtomicPass.h"
38#include "llvm/Transforms/Utils.h"
39#include <optional>
40using namespace llvm;
41
42#define DEBUG_TYPE "wasm"
43
44// A command-line option to keep implicit locals
45// for the purpose of testing with lit/llc ONLY.
46// This produces output which is not valid WebAssembly, and is not supported
47// by assemblers/disassemblers and other MC based tools.
48cl::opt<bool> WebAssembly::WasmDisableExplicitLocals(
49 "wasm-disable-explicit-locals", cl::Hidden,
50 cl::desc("WebAssembly: output implicit locals in"
51 " instruction output for test purposes only."),
52 cl::init(Val: false));
53
54// Exception handling & setjmp-longjmp handling related options.
55
56// Emscripten's asm.js-style exception handling
57cl::opt<bool> WebAssembly::WasmEnableEmEH(
58 "enable-emscripten-cxx-exceptions",
59 cl::desc("WebAssembly Emscripten-style exception handling"),
60 cl::init(Val: false));
61// Emscripten's asm.js-style setjmp/longjmp handling
62cl::opt<bool> WebAssembly::WasmEnableEmSjLj(
63 "enable-emscripten-sjlj",
64 cl::desc("WebAssembly Emscripten-style setjmp/longjmp handling"),
65 cl::init(Val: false));
66// Exception handling using wasm EH instructions
67cl::opt<bool>
68 WebAssembly::WasmEnableEH("wasm-enable-eh",
69 cl::desc("WebAssembly exception handling"));
70// setjmp/longjmp handling using wasm EH instrutions
71cl::opt<bool> WebAssembly::WasmEnableSjLj(
72 "wasm-enable-sjlj", cl::desc("WebAssembly setjmp/longjmp handling"));
73// If true, use the legacy Wasm EH proposal:
74// https://github.com/WebAssembly/exception-handling/blob/main/proposals/exception-handling/legacy/Exceptions.md
75// And if false, use the standardized Wasm EH proposal:
76// https://github.com/WebAssembly/exception-handling/blob/main/proposals/exception-handling/Exceptions.md
77// Currently set to true by default because not all major web browsers turn on
78// the new standard proposal by default, but will later change to false.
79cl::opt<bool> WebAssembly::WasmUseLegacyEH(
80 "wasm-use-legacy-eh", cl::desc("WebAssembly exception handling (legacy)"),
81 cl::init(Val: true));
82
83extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
84LLVMInitializeWebAssemblyTarget() {
85 // Register the target.
86 RegisterTargetMachine<WebAssemblyTargetMachine> X(
87 getTheWebAssemblyTarget32());
88 RegisterTargetMachine<WebAssemblyTargetMachine> Y(
89 getTheWebAssemblyTarget64());
90
91 // Register backend passes
92 auto &PR = *PassRegistry::getPassRegistry();
93 initializeGlobalISel(PR);
94 initializeWebAssemblyPreLegalizerCombinerPass(PR);
95 initializeWebAssemblyPostLegalizerCombinerPass(PR);
96 initializeWebAssemblyAddMissingPrototypesLegacyPass(PR);
97 initializeWebAssemblyLowerEmscriptenEHSjLjLegacyPass(PR);
98 initializeLowerGlobalDtorsLegacyPassPass(PR);
99 initializeWebAssemblyFixFunctionBitcastsLegacyPass(PR);
100 initializeWebAssemblyOptimizeReturnedLegacyPass(PR);
101 initializeWebAssemblyRefTypeMem2LocalLegacyPass(PR);
102 initializeWebAssemblyArgumentMoveLegacyPass(PR);
103 initializeWebAssemblyAsmPrinterPass(PR);
104 initializeWebAssemblySetP2AlignOperandsLegacyPass(PR);
105 initializeWebAssemblyReplacePhysRegsLegacyPass(PR);
106 initializeWebAssemblyOptimizeLiveIntervalsPass(PR);
107 initializeWebAssemblyMemIntrinsicResultsPass(PR);
108 initializeWebAssemblyRegStackifyPass(PR);
109 initializeWebAssemblyRegColoringPass(PR);
110 initializeWebAssemblyNullifyDebugValueListsLegacyPass(PR);
111 initializeWebAssemblyFixIrreducibleControlFlowLegacyPass(PR);
112 initializeWebAssemblyLateEHPrepareLegacyPass(PR);
113 initializeWebAssemblyExceptionInfoPass(PR);
114 initializeWebAssemblyCFGSortPass(PR);
115 initializeWebAssemblyCFGStackifyPass(PR);
116 initializeWebAssemblyExplicitLocalsPass(PR);
117 initializeWebAssemblyLowerBrUnlessPass(PR);
118 initializeWebAssemblyRegNumberingPass(PR);
119 initializeWebAssemblyDebugFixupPass(PR);
120 initializeWebAssemblyPeepholePass(PR);
121 initializeWebAssemblyMCLowerPrePassPass(PR);
122 initializeWebAssemblyFixBrTableDefaultsLegacyPass(PR);
123 initializeWebAssemblyDAGToDAGISelLegacyPass(PR);
124}
125
126//===----------------------------------------------------------------------===//
127// WebAssembly Lowering public interface.
128//===----------------------------------------------------------------------===//
129
130static Reloc::Model getEffectiveRelocModel(std::optional<Reloc::Model> RM) {
131 // Default to static relocation model. This should always be more optimial
132 // than PIC since the static linker can determine all global addresses and
133 // assume direct function calls.
134 return RM.value_or(u: Reloc::Static);
135}
136
137using WebAssembly::WasmDisableExplicitLocals;
138using WebAssembly::WasmEnableEH;
139using WebAssembly::WasmEnableEmEH;
140using WebAssembly::WasmEnableEmSjLj;
141using WebAssembly::WasmEnableSjLj;
142
143static void basicCheckForEHAndSjLj(TargetMachine *TM) {
144
145 // You can't enable two modes of EH at the same time
146 if (WasmEnableEmEH && WasmEnableEH)
147 report_fatal_error(
148 reason: "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-eh");
149 // You can't enable two modes of SjLj at the same time
150 if (WasmEnableEmSjLj && WasmEnableSjLj)
151 report_fatal_error(
152 reason: "-enable-emscripten-sjlj not allowed with -wasm-enable-sjlj");
153 // You can't mix Emscripten EH with Wasm SjLj.
154 if (WasmEnableEmEH && WasmEnableSjLj)
155 report_fatal_error(
156 reason: "-enable-emscripten-cxx-exceptions not allowed with -wasm-enable-sjlj");
157
158 if (TM->Options.ExceptionModel == ExceptionHandling::None) {
159 // FIXME: These flags should be removed in favor of directly using the
160 // generically configured ExceptionsType
161 if (WebAssembly::WasmEnableEH || WebAssembly::WasmEnableSjLj)
162 TM->Options.ExceptionModel = ExceptionHandling::Wasm;
163 }
164
165 // Basic Correctness checking related to -exception-model
166 if (TM->Options.ExceptionModel != ExceptionHandling::None &&
167 TM->Options.ExceptionModel != ExceptionHandling::Wasm)
168 report_fatal_error(reason: "-exception-model should be either 'none' or 'wasm'");
169 if (WasmEnableEmEH && TM->Options.ExceptionModel == ExceptionHandling::Wasm)
170 report_fatal_error(reason: "-exception-model=wasm not allowed with "
171 "-enable-emscripten-cxx-exceptions");
172 if (WasmEnableEH && TM->Options.ExceptionModel != ExceptionHandling::Wasm)
173 report_fatal_error(
174 reason: "-wasm-enable-eh only allowed with -exception-model=wasm");
175 if (WasmEnableSjLj && TM->Options.ExceptionModel != ExceptionHandling::Wasm)
176 report_fatal_error(
177 reason: "-wasm-enable-sjlj only allowed with -exception-model=wasm");
178 if ((!WasmEnableEH && !WasmEnableSjLj) &&
179 TM->Options.ExceptionModel == ExceptionHandling::Wasm)
180 report_fatal_error(
181 reason: "-exception-model=wasm only allowed with at least one of "
182 "-wasm-enable-eh or -wasm-enable-sjlj");
183
184 // Currently it is allowed to mix Wasm EH with Emscripten SjLj as an interim
185 // measure, but some code will error out at compile time in this combination.
186 // See WebAssemblyLowerEmscriptenEHSjLj pass for details.
187}
188
189/// Create an WebAssembly architecture model.
190///
191WebAssemblyTargetMachine::WebAssemblyTargetMachine(
192 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
193 const TargetOptions &Options, std::optional<Reloc::Model> RM,
194 std::optional<CodeModel::Model> CM, CodeGenOptLevel OL, bool JIT)
195 : CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT, CPU, FS, Options,
196 getEffectiveRelocModel(RM),
197 getEffectiveCodeModel(CM, Default: CodeModel::Large), OL),
198 TLOF(new WebAssemblyTargetObjectFile()),
199 UsesMultivalueABI(Options.MCOptions.getABIName() == "experimental-mv") {
200 // WebAssembly type-checks instructions, but a noreturn function with a return
201 // type that doesn't match the context will cause a check failure. So we lower
202 // LLVM 'unreachable' to ISD::TRAP and then lower that to WebAssembly's
203 // 'unreachable' instructions which is meant for that case. Formerly, we also
204 // needed to add checks to SP failure emission in the instruction selection
205 // backends, but this has since been tied to TrapUnreachable and is no longer
206 // necessary.
207 this->Options.TrapUnreachable = true;
208 this->Options.NoTrapAfterNoreturn = false;
209
210 // WebAssembly treats each function as an independent unit. Force
211 // -ffunction-sections, effectively, so that we can emit them independently.
212 this->Options.FunctionSections = true;
213 this->Options.DataSections = true;
214 this->Options.UniqueSectionNames = true;
215
216 basicCheckForEHAndSjLj(TM: this);
217 initAsmInfo();
218
219 LLT::setUseExtended(true);
220
221 // Note that we don't use setRequiresStructuredCFG(true). It disables
222 // optimizations than we're ok with, and want, such as critical edge
223 // splitting and tail merging.
224}
225
226WebAssemblyTargetMachine::~WebAssemblyTargetMachine() = default; // anchor.
227
228const WebAssemblySubtarget *WebAssemblyTargetMachine::getSubtargetImpl() const {
229 return getSubtargetImpl(CPU: std::string(getTargetCPU()),
230 FS: std::string(getTargetFeatureString()));
231}
232
233const WebAssemblySubtarget *
234WebAssemblyTargetMachine::getSubtargetImpl(std::string CPU,
235 std::string FS) const {
236 auto &I = SubtargetMap[CPU + FS];
237 if (!I) {
238 I = std::make_unique<WebAssemblySubtarget>(args: TargetTriple, args&: CPU, args&: FS, args: *this);
239 }
240 return I.get();
241}
242
243const WebAssemblySubtarget *
244WebAssemblyTargetMachine::getSubtargetImpl(const Function &F) const {
245 Attribute CPUAttr = F.getFnAttribute(Kind: "target-cpu");
246 Attribute FSAttr = F.getFnAttribute(Kind: "target-features");
247
248 std::string CPU =
249 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
250 std::string FS =
251 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
252
253 return getSubtargetImpl(CPU, FS);
254}
255
256namespace {
257
258/// WebAssembly Code Generator Pass Configuration Options.
259class WebAssemblyPassConfig final : public TargetPassConfig {
260public:
261 WebAssemblyPassConfig(WebAssemblyTargetMachine &TM, PassManagerBase &PM)
262 : TargetPassConfig(TM, PM) {}
263
264 WebAssemblyTargetMachine &getWebAssemblyTargetMachine() const {
265 return getTM<WebAssemblyTargetMachine>();
266 }
267
268 FunctionPass *createTargetRegisterAllocator(bool) override;
269
270 void addIRPasses() override;
271 void addISelPrepare() override;
272 bool addInstSelector() override;
273 void addOptimizedRegAlloc() override;
274 void addPostRegAlloc() override;
275 bool addGCPasses() override { return false; }
276 void addPreEmitPass() override;
277 bool addPreISel() override;
278
279 // No reg alloc
280 bool addRegAssignAndRewriteFast() override { return false; }
281
282 // No reg alloc
283 bool addRegAssignAndRewriteOptimized() override { return false; }
284
285 bool addIRTranslator() override;
286 void addPreLegalizeMachineIR() override;
287 bool addLegalizeMachineIR() override;
288 void addPreRegBankSelect() override;
289 bool addRegBankSelect() override;
290 bool addGlobalInstructionSelect() override;
291};
292} // end anonymous namespace
293
294MachineFunctionInfo *WebAssemblyTargetMachine::createMachineFunctionInfo(
295 BumpPtrAllocator &Allocator, const Function &F,
296 const TargetSubtargetInfo *STI) const {
297 return WebAssemblyFunctionInfo::create<WebAssemblyFunctionInfo>(Allocator, F,
298 STI);
299}
300
301TargetTransformInfo
302WebAssemblyTargetMachine::getTargetTransformInfo(const Function &F) const {
303 return TargetTransformInfo(std::make_unique<WebAssemblyTTIImpl>(args: this, args: F));
304}
305
306TargetPassConfig *
307WebAssemblyTargetMachine::createPassConfig(PassManagerBase &PM) {
308 return new WebAssemblyPassConfig(*this, PM);
309}
310
311FunctionPass *WebAssemblyPassConfig::createTargetRegisterAllocator(bool) {
312 return nullptr; // No reg alloc
313}
314
315//===----------------------------------------------------------------------===//
316// The following functions are called from lib/CodeGen/Passes.cpp to modify
317// the CodeGen pass sequence.
318//===----------------------------------------------------------------------===//
319
320void WebAssemblyPassConfig::addIRPasses() {
321 // Add signatures to prototype-less function declarations
322 addPass(P: createWebAssemblyAddMissingPrototypesLegacyPass());
323
324 // Lower .llvm.global_dtors into .llvm.global_ctors with __cxa_atexit calls.
325 addPass(P: createLowerGlobalDtorsLegacyPass());
326
327 // Fix function bitcasts, as WebAssembly requires caller and callee signatures
328 // to match.
329 addPass(P: createWebAssemblyFixFunctionBitcastsLegacyPass());
330
331 // Optimize "returned" function attributes.
332 if (getOptLevel() != CodeGenOptLevel::None)
333 addPass(P: createWebAssemblyOptimizeReturnedLegacyPass());
334
335 // If exception handling is not enabled and setjmp/longjmp handling is
336 // enabled, we lower invokes into calls and delete unreachable landingpad
337 // blocks. Lowering invokes when there is no EH support is done in
338 // TargetPassConfig::addPassesToHandleExceptions, but that runs after these IR
339 // passes and Emscripten SjLj handling expects all invokes to be lowered
340 // before.
341 if (!WasmEnableEmEH && !WasmEnableEH) {
342 addPass(P: createLowerInvokePass());
343 // The lower invoke pass may create unreachable code. Remove it in order not
344 // to process dead blocks in setjmp/longjmp handling.
345 addPass(P: createUnreachableBlockEliminationPass());
346 }
347
348 // Handle exceptions and setjmp/longjmp if enabled. Unlike Wasm EH preparation
349 // done in WasmEHPrepare pass, Wasm SjLj preparation shares libraries and
350 // transformation algorithms with Emscripten SjLj, so we run
351 // LowerEmscriptenEHSjLj pass also when Wasm SjLj is enabled.
352 if (WasmEnableEmEH || WasmEnableEmSjLj || WasmEnableSjLj)
353 addPass(P: createWebAssemblyLowerEmscriptenEHSjLjLegacyPass());
354
355 // Expand indirectbr instructions to switches.
356 addPass(P: createIndirectBrExpandPass());
357
358 // Try to expand `vecreduce_{and, or}` into `{any, all}_true`.
359 addPass(P: createWebAssemblyReduceToAnyAllTrueLegacyPass(
360 TM&: getWebAssemblyTargetMachine()));
361
362 TargetPassConfig::addIRPasses();
363}
364
365void WebAssemblyPassConfig::addISelPrepare() {
366 // We need to move reference type allocas to WASM_ADDRESS_SPACE_VAR so that
367 // loads and stores are promoted to local.gets/local.sets.
368 addPass(P: createWebAssemblyRefTypeMem2LocalLegacyPass());
369 // Lower atomics and TLS if necessary
370 addPass(P: createWebAssemblyCoalesceFeaturesAndStripAtomicsLegacyPass(
371 TM&: getWebAssemblyTargetMachine()));
372
373 // This is a no-op if atomics are not used in the module
374 addPass(P: createAtomicExpandLegacyPass());
375
376 TargetPassConfig::addISelPrepare();
377}
378
379bool WebAssemblyPassConfig::addInstSelector() {
380 (void)TargetPassConfig::addInstSelector();
381 addPass(P: createWebAssemblyISelDagLegacyPass(TM&: getWebAssemblyTargetMachine(),
382 OptLevel: getOptLevel()));
383 // Run the argument-move pass immediately after the ScheduleDAG scheduler
384 // so that we can fix up the ARGUMENT instructions before anything else
385 // sees them in the wrong place.
386 addPass(P: createWebAssemblyArgumentMoveLegacyPass());
387 // Set the p2align operands. This information is present during ISel, however
388 // it's inconvenient to collect. Collect it now, and update the immediate
389 // operands.
390 addPass(P: createWebAssemblySetP2AlignOperandsLegacyPass());
391
392 // Eliminate range checks and add default targets to br_table instructions.
393 addPass(P: createWebAssemblyFixBrTableDefaultsLegacyPass());
394
395 // unreachable is terminator, non-terminator instruction after it is not
396 // allowed.
397 addPass(P: createWebAssemblyCleanCodeAfterTrapLegacyPass());
398
399 return false;
400}
401
402void WebAssemblyPassConfig::addOptimizedRegAlloc() {
403 // Currently RegisterCoalesce degrades wasm debug info quality by a
404 // significant margin. As a quick fix, disable this for -O1, which is often
405 // used for debugging large applications. Disabling this increases code size
406 // of Emscripten core benchmarks by ~5%, which is acceptable for -O1, which is
407 // usually not used for production builds.
408 // TODO Investigate why RegisterCoalesce degrades debug info quality and fix
409 // it properly
410 if (getOptLevel() == CodeGenOptLevel::Less)
411 disablePass(PassID: &RegisterCoalescerID);
412 TargetPassConfig::addOptimizedRegAlloc();
413}
414
415void WebAssemblyPassConfig::addPostRegAlloc() {
416 // TODO: The following CodeGen passes don't currently support code containing
417 // virtual registers. Consider removing their restrictions and re-enabling
418 // them.
419
420 // These functions all require the NoVRegs property.
421 disablePass(PassID: &MachineLateInstrsCleanupID);
422 disablePass(PassID: &MachineCopyPropagationID);
423 disablePass(PassID: &PostRAMachineSinkingID);
424 disablePass(PassID: &PostRASchedulerID);
425 disablePass(PassID: &FuncletLayoutID);
426 disablePass(PassID: &StackMapLivenessID);
427 disablePass(PassID: &PatchableFunctionID);
428 disablePass(PassID: &ShrinkWrapID);
429 disablePass(PassID: &RemoveLoadsIntoFakeUsesID);
430
431 // This pass hurts code size for wasm because it can generate irreducible
432 // control flow.
433 disablePass(PassID: &MachineBlockPlacementID);
434
435 TargetPassConfig::addPostRegAlloc();
436}
437
438void WebAssemblyPassConfig::addPreEmitPass() {
439 TargetPassConfig::addPreEmitPass();
440
441 // Nullify DBG_VALUE_LISTs that we cannot handle.
442 addPass(P: createWebAssemblyNullifyDebugValueListsLegacyPass());
443
444 // Remove any unreachable blocks that may be left floating around.
445 // Rare, but possible. Needed for WebAssemblyFixIrreducibleControlFlow.
446 addPass(PassID: &UnreachableMachineBlockElimID);
447
448 // Eliminate multiple-entry loops.
449 addPass(P: createWebAssemblyFixIrreducibleControlFlowLegacyPass());
450
451 // Do various transformations for exception handling.
452 // Every CFG-changing optimizations should come before this.
453 if (TM->Options.ExceptionModel == ExceptionHandling::Wasm)
454 addPass(P: createWebAssemblyLateEHPrepareLegacyPass());
455
456 // Now that we have a prologue and epilogue and all frame indices are
457 // rewritten, eliminate SP and FP. This allows them to be stackified,
458 // colored, and numbered with the rest of the registers.
459 addPass(P: createWebAssemblyReplacePhysRegsLegacyPass());
460
461 // Preparations and optimizations related to register stackification.
462 if (getOptLevel() != CodeGenOptLevel::None) {
463 // Depend on LiveIntervals and perform some optimizations on it.
464 addPass(P: createWebAssemblyOptimizeLiveIntervals());
465
466 // Prepare memory intrinsic calls for register stackifying.
467 addPass(P: createWebAssemblyMemIntrinsicResults());
468 }
469
470 // Mark registers as representing wasm's value stack. This is a key
471 // code-compression technique in WebAssembly. We run this pass (and
472 // MemIntrinsicResults above) very late, so that it sees as much code as
473 // possible, including code emitted by PEI and expanded by late tail
474 // duplication.
475 addPass(P: createWebAssemblyRegStackify(OptLevel: getOptLevel()));
476
477 if (getOptLevel() != CodeGenOptLevel::None) {
478 // Run the register coloring pass to reduce the total number of registers.
479 // This runs after stackification so that it doesn't consider registers
480 // that become stackified.
481 addPass(P: createWebAssemblyRegColoring());
482 }
483
484 // Sort the blocks of the CFG into topological order, a prerequisite for
485 // BLOCK and LOOP markers.
486 addPass(P: createWebAssemblyCFGSort());
487
488 // Insert BLOCK and LOOP markers.
489 addPass(P: createWebAssemblyCFGStackify());
490
491 // Insert explicit local.get and local.set operators.
492 if (!WasmDisableExplicitLocals)
493 addPass(P: createWebAssemblyExplicitLocals());
494
495 // Lower br_unless into br_if.
496 addPass(P: createWebAssemblyLowerBrUnless());
497
498 // Perform the very last peephole optimizations on the code.
499 if (getOptLevel() != CodeGenOptLevel::None)
500 addPass(P: createWebAssemblyPeephole());
501
502 // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
503 addPass(P: createWebAssemblyRegNumbering());
504
505 // Fix debug_values whose defs have been stackified.
506 if (!WasmDisableExplicitLocals)
507 addPass(P: createWebAssemblyDebugFixup());
508
509 // Collect information to prepare for MC lowering / asm printing.
510 addPass(P: createWebAssemblyMCLowerPrePass());
511}
512
513bool WebAssemblyPassConfig::addPreISel() {
514 TargetPassConfig::addPreISel();
515 return false;
516}
517
518bool WebAssemblyPassConfig::addIRTranslator() {
519 addPass(P: new IRTranslator());
520 return false;
521}
522
523void WebAssemblyPassConfig::addPreLegalizeMachineIR() {
524 if (getOptLevel() != CodeGenOptLevel::None) {
525 addPass(P: createWebAssemblyPreLegalizerCombiner());
526 }
527}
528bool WebAssemblyPassConfig::addLegalizeMachineIR() {
529 addPass(P: new Legalizer());
530 return false;
531}
532
533void WebAssemblyPassConfig::addPreRegBankSelect() {
534 if (getOptLevel() != CodeGenOptLevel::None) {
535 addPass(P: createWebAssemblyPostLegalizerCombiner());
536 }
537}
538
539bool WebAssemblyPassConfig::addRegBankSelect() {
540 addPass(P: new RegBankSelect());
541 return false;
542}
543
544bool WebAssemblyPassConfig::addGlobalInstructionSelect() {
545 addPass(P: new InstructionSelect(getOptLevel()));
546
547 // We insert only if ISelDAG won't insert these at a later point.
548 if (isGlobalISelAbortEnabled()) {
549 addPass(P: createWebAssemblyArgumentMoveLegacyPass());
550 addPass(P: createWebAssemblySetP2AlignOperandsLegacyPass());
551 addPass(P: createWebAssemblyFixBrTableDefaultsLegacyPass());
552 addPass(P: createWebAssemblyCleanCodeAfterTrapLegacyPass());
553 }
554
555 return false;
556}
557
558yaml::MachineFunctionInfo *
559WebAssemblyTargetMachine::createDefaultFuncInfoYAML() const {
560 return new yaml::WebAssemblyFunctionInfo();
561}
562
563yaml::MachineFunctionInfo *WebAssemblyTargetMachine::convertFuncInfoToYAML(
564 const MachineFunction &MF) const {
565 const auto *MFI = MF.getInfo<WebAssemblyFunctionInfo>();
566 return new yaml::WebAssemblyFunctionInfo(MF, *MFI);
567}
568
569bool WebAssemblyTargetMachine::parseMachineFunctionInfo(
570 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
571 SMDiagnostic &Error, SMRange &SourceRange) const {
572 const auto &YamlMFI = static_cast<const yaml::WebAssemblyFunctionInfo &>(MFI);
573 MachineFunction &MF = PFS.MF;
574 MF.getInfo<WebAssemblyFunctionInfo>()->initializeBaseYamlFields(MF, YamlMFI);
575 return false;
576}
577