LLVM 24.0.0git
WebAssemblyCodeGenPassBuilder.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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#include "WebAssembly.h"
31#include "llvm/MC/MCStreamer.h"
35#include "llvm/Support/Error.h"
39
40using namespace llvm;
41
49
55
56namespace {
57
58class WebAssemblyCodeGenPassBuilder : public CodeGenPassBuilder {
60
62 return static_cast<WebAssemblyTargetMachine &>(TM);
63 }
64
65public:
66 explicit WebAssemblyCodeGenPassBuilder(WebAssemblyTargetMachine &TM,
67 const CGPassBuilderOption &Opts,
68 PassInstrumentationCallbacks *PIC)
69 : CodeGenPassBuilder(TM, Opts, PIC) {
70 disablePass<MachineLateInstrsCleanupPass, MachineCopyPropagationPass,
71 PostRAMachineSinkingPass, PostRASchedulerPass,
72 FuncletLayoutPass, StackMapLivenessPass, PatchableFunctionPass,
73 ShrinkWrapPass, RemoveLoadsIntoFakeUsesPass,
74 MachineBlockPlacementPass>();
75
76 // Currently RegisterCoalesce degrades wasm debug info quality by a
77 // significant margin. As a quick fix, disable this for -O1, which is often
78 // used for debugging large applications. Disabling this increases code size
79 // of Emscripten core benchmarks by ~5%, which is acceptable for -O1, which
80 // is usually not used for production builds.
81 // TODO Investigate why RegisterCoalesce degrades debug info quality and fix
82 // it properly
83 if (getOptLevel() == CodeGenOptLevel::Less)
84 disablePass<RegisterCoalescerPass>();
85 }
86
87 void addIRPasses(PassManagerWrapper &PMW) override;
88 void addISelPrepare(PassManagerWrapper &PMW) override;
89
90 Error addInstSelector(PassManagerWrapper &PMW) override;
91
92 Error addIRTranslator(PassManagerWrapper &PMW) override;
93 void addPreLegalizeMachineIR(PassManagerWrapper &PMW) override;
94 Error addLegalizeMachineIR(PassManagerWrapper &PMW) override;
95 void addPreRegBankSelect(PassManagerWrapper &PMW) override;
96 Error addRegBankSelect(PassManagerWrapper &PMW) override;
97 Error addGlobalInstructionSelect(PassManagerWrapper &PMW) override;
98
99 Error addRegAssignAndRewriteFast(PassManagerWrapper &PMW) override;
100 Expected<bool>
101 addRegAssignAndRewriteOptimized(PassManagerWrapper &PMW) override;
102 void addPreEmitPass(PassManagerWrapper &PMW) override;
103 void addAsmPrinterBegin(PassManagerWrapper &PMW) override;
104 void addAsmPrinter(PassManagerWrapper &PMW) override;
105 void addAsmPrinterEnd(PassManagerWrapper &PMW) override;
106};
107
108void WebAssemblyCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) {
109 // Add signatures to prototype-less function declarations
110 flushFPMsToMPM(PMW);
111 addModulePass(WebAssemblyAddMissingPrototypesPass(), PMW);
112
113 // Lower .llvm.global_dtors into .llvm.global_ctors with __cxa_atexit calls.
114 addModulePass(LowerGlobalDtorsPass(), PMW);
115
116 // Fix function bitcasts, as WebAssembly requires caller and callee signatures
117 // to match.
118 addModulePass(WebAssemblyFixFunctionBitcastsPass(), PMW);
119
120 // Optimize "returned" function attributes.
121 if (getOptLevel() != CodeGenOptLevel::None)
122 addFunctionPass(WebAssemblyOptimizeReturnedPass(), PMW);
123
124 // If exception handling is not enabled and setjmp/longjmp handling is
125 // enabled, we lower invokes into calls and delete unreachable landingpad
126 // blocks. Lowering invokes when there is no EH support is done in
127 // TargetPassConfig::addPassesToHandleExceptions, but that runs after these IR
128 // passes and Emscripten SjLj handling expects all invokes to be lowered
129 // before.
130 if (!WasmEnableEmEH && !WasmEnableEH) {
131 addFunctionPass(LowerInvokePass(), PMW);
132 // The lower invoke pass may create unreachable code. Remove it in order not
133 // to process dead blocks in setjmp/longjmp handling.
134 addFunctionPass(UnreachableBlockElimPass(), PMW);
135 }
136
137 // Handle exceptions and setjmp/longjmp if enabled. Unlike Wasm EH preparation
138 // done in WasmEHPrepare pass, Wasm SjLj preparation shares libraries and
139 // transformation algorithms with Emscripten SjLj, so we run
140 // LowerEmscriptenEHSjLj pass also when Wasm SjLj is enabled.
142 flushFPMsToMPM(PMW);
143 addModulePass(WebAssemblyLowerEmscriptenEHSjLjPass(), PMW);
144 }
145
146 // Expand indirectbr instructions to switches.
147 addFunctionPass(IndirectBrExpandPass(TM), PMW);
148
149 // Try to expand `vecreduce_{and, or}` into `{any, all}_true`.
150 addFunctionPass(WebAssemblyReduceToAnyAllTruePass(getTM()), PMW);
151
152 Base::addIRPasses(PMW);
153}
154
155void WebAssemblyCodeGenPassBuilder::addISelPrepare(PassManagerWrapper &PMW) {
156 // We need to move reference type allocas to WASM_ADDRESS_SPACE_VAR so that
157 // loads and stores are promoted to local.gets/local.sets.
158 addFunctionPass(WebAssemblyRefTypeMem2LocalPass(), PMW);
159 // Lower atomics and TLS if necessary
160 flushFPMsToMPM(PMW);
161 addModulePass(WebAssemblyCoalesceFeaturesAndStripAtomicsPass(getTM()), PMW);
162
163 // This is a no-op if atomics are not used in the module
164 addFunctionPass(AtomicExpandPass(TM), PMW);
165
166 Base::addISelPrepare(PMW);
167}
168
169Error WebAssemblyCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) {
170 addMachineFunctionPass(WebAssemblyISelDAGToDAGPass(getTM(), getOptLevel()),
171 PMW);
172
173 // Run the argument-move pass immediately after the ScheduleDAG scheduler
174 // so that we can fix up the ARGUMENT instructions before anything else
175 // sees them in the wrong place.
176 addMachineFunctionPass(WebAssemblyArgumentMovePass(), PMW);
177
178 // Set the p2align operands. This information is present during ISel, however
179 // it's inconvenient to collect. Collect it now, and update the immediate
180 // operands.
181 addMachineFunctionPass(WebAssemblySetP2AlignOperandsPass(), PMW);
182
183 // Eliminate range checks and add default targets to br_table instructions.
184 addMachineFunctionPass(WebAssemblyFixBrTableDefaultsPass(), PMW);
185
186 // unreachable is terminator, non-terminator instruction after it is not
187 // allowed.
188 addMachineFunctionPass(WebAssemblyCleanCodeAfterTrapPass(), PMW);
189
190 return Error::success();
191}
192
193Error WebAssemblyCodeGenPassBuilder::addIRTranslator(PassManagerWrapper &PMW) {
194 addMachineFunctionPass(IRTranslatorPass(getOptLevel()), PMW);
195 return Error::success();
196}
197
198void WebAssemblyCodeGenPassBuilder::addPreLegalizeMachineIR(
199 PassManagerWrapper &PMW) {
200 if (getOptLevel() != CodeGenOptLevel::None) {
201 // TODO(boomanaiden154): Add WebAssemblyPreLegalizerCombiner when it has
202 // been ported.
203 }
204}
205
206Error WebAssemblyCodeGenPassBuilder::addLegalizeMachineIR(
207 PassManagerWrapper &PMW) {
208 addMachineFunctionPass(LegalizerPass(), PMW);
209 return Error::success();
210}
211
212void WebAssemblyCodeGenPassBuilder::addPreRegBankSelect(
213 PassManagerWrapper &PMW) {
214 if (getOptLevel() != CodeGenOptLevel::None) {
215 // TODO(boomanaiden154): Add WebAssemblyPostLegalizerCombiner when it has
216 // been ported.
217 }
218}
219
220Error WebAssemblyCodeGenPassBuilder::addRegBankSelect(PassManagerWrapper &PMW) {
221 addMachineFunctionPass(RegBankSelectPass(), PMW);
222 return Error::success();
223}
224
225Error WebAssemblyCodeGenPassBuilder::addGlobalInstructionSelect(
226 PassManagerWrapper &PMW) {
227 addMachineFunctionPass(InstructionSelectPass(getOptLevel()), PMW);
228
229 if (isGlobalISelAbortEnabled()) {
230 addMachineFunctionPass(WebAssemblyArgumentMovePass(), PMW);
231 addMachineFunctionPass(WebAssemblySetP2AlignOperandsPass(), PMW);
232 addMachineFunctionPass(WebAssemblyFixBrTableDefaultsPass(), PMW);
233 addMachineFunctionPass(WebAssemblyCleanCodeAfterTrapPass(), PMW);
234 }
235
236 return Error::success();
237}
238
239Error WebAssemblyCodeGenPassBuilder::addRegAssignAndRewriteFast(
240 PassManagerWrapper &PMW) {
241 return Error::success();
242}
243
244Expected<bool> WebAssemblyCodeGenPassBuilder::addRegAssignAndRewriteOptimized(
245 PassManagerWrapper &PMW) {
246 return false;
247}
248
249void WebAssemblyCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) {
250 Base::addPreEmitPass(PMW);
251
252 // Nullify DBG_VALUE_LISTs that we cannot handle.
253 addMachineFunctionPass(WebAssemblyNullifyDebugValueListsPass(), PMW);
254
255 // Remove any unreachable blocks that may be left floating around.
256 // Rare, but possible. Needed for WebAssemblyFixIrreducibleControlFlow.
257 addMachineFunctionPass(UnreachableMachineBlockElimPass(), PMW);
258
259 // Eliminate multiple-entry loops.
260 addMachineFunctionPass(WebAssemblyFixIrreducibleControlFlowPass(), PMW);
261
262 // Do various transformations for exception handling.
263 // Every CFG-changing optimizations should come before this.
264 if (TM.Options.ExceptionModel == ExceptionHandling::Wasm)
265 addMachineFunctionPass(WebAssemblyLateEHPreparePass(), PMW);
266
267 // Now that we have a prologue and epilogue and all frame indices are
268 // rewritten, eliminate SP and FP. This allows them to be stackified,
269 // colored, and numbered with the rest of the registers.
270 addMachineFunctionPass(WebAssemblyReplacePhysRegsPass(), PMW);
271
272 // Preparations and optimizations related to register stackification.
273 if (getOptLevel() != CodeGenOptLevel::None) {
274 // Depend on LiveIntervals and perform some optimizations on it.
275 addMachineFunctionPass(WebAssemblyOptimizeLiveIntervalsPass(), PMW);
276
277 // Prepare memory intrinsic calls for register stackifying.
278 addMachineFunctionPass(WebAssemblyMemIntrinsicResultsPass(), PMW);
279 }
280
281 // Mark registers as representing wasm's value stack. This is a key
282 // code-compression technique in WebAssembly. We run this pass (and
283 // MemIntrinsicResults above) very late, so that it sees as much code as
284 // possible, including code emitted by PEI and expanded by late tail
285 // duplication.
286 addMachineFunctionPass(WebAssemblyRegStackifyPass(getOptLevel()), PMW);
287
288 if (getOptLevel() != CodeGenOptLevel::None) {
289 // Run the register coloring pass to reduce the total number of registers.
290 // This runs after stackification so that it doesn't consider registers
291 // that become stackified.
292 addMachineFunctionPass(WebAssemblyRegColoringPass(), PMW);
293 }
294
295 // Sort the blocks of the CFG into topological order, a prerequisite for
296 // BLOCK and LOOP markers.
297 addMachineFunctionPass(WebAssemblyCFGSortPass(), PMW);
298
299 // Insert BLOCK and LOOP markers.
300 addMachineFunctionPass(WebAssemblyCFGStackifyPass(), PMW);
301
302 // Insert explicit local.get and local.set operators.
304 addMachineFunctionPass(WebAssemblyExplicitLocalsPass(), PMW);
305
306 // Lower br_unless into br_if.
307 addMachineFunctionPass(WebAssemblyLowerBrUnlessPass(), PMW);
308
309 // Perform the very last peephole optimizations on the code.
310 if (getOptLevel() != CodeGenOptLevel::None)
311 addMachineFunctionPass(WebAssemblyPeepholePass(), PMW);
312
313 // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
314 addMachineFunctionPass(WebAssemblyRegNumberingPass(), PMW);
315
316 // Fix debug_values whose defs have been stackified.
318 addMachineFunctionPass(WebAssemblyDebugFixupPass(), PMW);
319
320 // Collect information to prepare for MC lowering / asm printing.
321 flushFPMsToMPM(PMW);
322 addModulePass(WebAssemblyMCLowerPrePass(), PMW);
323}
324
325void WebAssemblyCodeGenPassBuilder::addAsmPrinterBegin(
326 PassManagerWrapper &PMW) {
327 addModulePass(WebAssemblyAsmPrinterBeginPass(), PMW, /*Force=*/true);
328}
329
330void WebAssemblyCodeGenPassBuilder::addAsmPrinter(PassManagerWrapper &PMW) {
331 addMachineFunctionPass(WebAssemblyAsmPrinterPass(), PMW);
332}
333
334void WebAssemblyCodeGenPassBuilder::addAsmPrinterEnd(PassManagerWrapper &PMW) {
335 addModulePass(WebAssemblyAsmPrinterEndPass(), PMW);
336}
337
338} // namespace
339
341#define GET_PASS_REGISTRY "WebAssemblyPassRegistry.def"
343}
344
347 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
348 const CGPassBuilderOption &Opt, MCContext &Ctx,
350 auto CGPB = WebAssemblyCodeGenPassBuilder(*this, Opt, PIC);
351 return CGPB.buildPipeline(MPM, MAM, Out, DwoOut, FileType, Ctx);
352}
Interfaces for producing common pass manager configurations.
This file declares the IRTranslator pass.
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
This file describes the interface of the MachineFunctionPass responsible for assigning the generic vi...
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
cl::opt< bool > WasmEnableEH
cl::opt< bool > WasmEnableSjLj
cl::opt< bool > WasmEnableEmEH
cl::opt< bool > WasmEnableEmSjLj
cl::opt< bool > WasmDisableExplicitLocals
This file implements WebAssemblyException information analysis.
This file declares the WebAssembly-specific subclass of TargetMachine.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
This class provides access to building LLVM's passes.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Context object for machine code objects.
Definition MCContext.h:83
This class provides access to building LLVM's passes.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
TargetOptions Options
ExceptionHandling ExceptionModel
What exception model to use.
void registerPassBuilderCallbacks(PassBuilder &PbB) override
Allow the target to modify the pass pipeline.
Error buildCodeGenPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, const CGPassBuilderOption &Opt, MCContext &Ctx, PassInstrumentationCallbacks *PIC) override
An abstract base class for streams implementations that also support a pwrite operation.
Interfaces for registering analysis passes, producing common pass manager configurations,...
cl::opt< bool > WasmEnableEmEH
cl::opt< bool > WasmEnableEH
cl::opt< bool > WasmEnableSjLj
cl::opt< bool > WasmEnableEmSjLj
cl::opt< bool > WasmDisableExplicitLocals
cl::opt< bool > WasmEnableEH
cl::opt< bool > WasmEnableSjLj
cl::opt< bool > WasmEnableEmEH
cl::opt< bool > WasmEnableEmSjLj
cl::opt< bool > WasmDisableExplicitLocals
This is an optimization pass for GlobalISel generic memory operations.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:178
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39