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"
23#include "llvm/MC/MCStreamer.h"
27#include "llvm/Support/Error.h"
30
31using namespace llvm;
32
33namespace {
34
35class WebAssemblyCodeGenPassBuilder : public CodeGenPassBuilder {
36 using Base = CodeGenPassBuilder;
37
38 WebAssemblyTargetMachine &getTM() const {
39 return static_cast<WebAssemblyTargetMachine &>(TM);
40 }
41
42public:
43 explicit WebAssemblyCodeGenPassBuilder(WebAssemblyTargetMachine &TM,
44 const CGPassBuilderOption &Opts,
45 PassInstrumentationCallbacks *PIC)
46 : CodeGenPassBuilder(TM, Opts, PIC) {
47 disablePass<MachineBlockPlacementPass>();
48
49 // Currently RegisterCoalesce degrades wasm debug info quality by a
50 // significant margin. As a quick fix, disable this for -O1, which is often
51 // used for debugging large applications. Disabling this increases code size
52 // of Emscripten core benchmarks by ~5%, which is acceptable for -O1, which
53 // is usually not used for production builds.
54 // TODO Investigate why RegisterCoalesce degrades debug info quality and fix
55 // it properly
56 if (getOptLevel() == CodeGenOptLevel::Less)
57 disablePass<RegisterCoalescerPass>();
58 }
59
60protected:
61 void addIRPasses(PassManagerWrapper &PMW) override;
62 void addISelPrepare(PassManagerWrapper &PMW) override;
63
64 Error addInstSelector(PassManagerWrapper &PMW) override;
65
66 Error addIRTranslator(PassManagerWrapper &PMW) override;
67 void addPreLegalizeMachineIR(PassManagerWrapper &PMW) override;
68 Error addLegalizeMachineIR(PassManagerWrapper &PMW) override;
69 void addPreRegBankSelect(PassManagerWrapper &PMW) override;
70 Error addRegBankSelect(PassManagerWrapper &PMW) override;
71 Error addGlobalInstructionSelect(PassManagerWrapper &PMW) override;
72
73 void addPreEmitPass(PassManagerWrapper &PMW) override;
74 void addAsmPrinterBegin(PassManagerWrapper &PMW) override;
75 void addAsmPrinter(PassManagerWrapper &PMW) override;
76 void addAsmPrinterEnd(PassManagerWrapper &PMW) override;
77};
78
79} // namespace
80
81void WebAssemblyCodeGenPassBuilder::addIRPasses(PassManagerWrapper &PMW) {
82 // Add signatures to prototype-less function declarations
83 flushFPMsToMPM(PMW);
84 addModulePass(WebAssemblyAddMissingPrototypesPass(), PMW);
85
86 // Lower .llvm.global_dtors into .llvm.global_ctors with __cxa_atexit calls.
87 addModulePass(LowerGlobalDtorsPass(), PMW);
88
89 // Fix function bitcasts, as WebAssembly requires caller and callee signatures
90 // to match.
91 addModulePass(WebAssemblyFixFunctionBitcastsPass(), PMW);
92
93 // Optimize "returned" function attributes.
94 if (getOptLevel() != CodeGenOptLevel::None)
95 addFunctionPass(WebAssemblyOptimizeReturnedPass(), PMW);
96
97 // Wasm SjLj shares Emscripten SjLj's transformation, so it is handled here.
98 // Without Wasm or Emscripten EH, this also lowers invokes.
99 flushFPMsToMPM(PMW);
100 addModulePass(WebAssemblyLowerEmscriptenEHSjLjPass(), PMW);
101
102 // Expand indirectbr instructions to switches.
103 addFunctionPass(IndirectBrExpandPass(TM), PMW);
104
105 // Try to expand `vecreduce_{and, or}` into `{any, all}_true`.
106 addFunctionPass(WebAssemblyReduceToAnyAllTruePass(getTM()), PMW);
107
108 Base::addIRPasses(PMW);
109}
110
111void WebAssemblyCodeGenPassBuilder::addISelPrepare(PassManagerWrapper &PMW) {
112 // We need to move reference type allocas to WASM_ADDRESS_SPACE_VAR so that
113 // loads and stores are promoted to local.gets/local.sets.
114 addFunctionPass(WebAssemblyRefTypeMem2LocalPass(), PMW);
115 // Lower atomics and TLS if necessary
116 flushFPMsToMPM(PMW);
117 addModulePass(WebAssemblyCoalesceFeaturesAndStripAtomicsPass(getTM()), PMW);
118
119 // This is a no-op if atomics are not used in the module
120 addFunctionPass(AtomicExpandPass(TM), PMW);
121
122 Base::addISelPrepare(PMW);
123}
124
125Error WebAssemblyCodeGenPassBuilder::addInstSelector(PassManagerWrapper &PMW) {
126 addMachineFunctionPass(WebAssemblyISelDAGToDAGPass(getTM(), getOptLevel()),
127 PMW);
128
129 // Run the argument-move pass immediately after the ScheduleDAG scheduler
130 // so that we can fix up the ARGUMENT instructions before anything else
131 // sees them in the wrong place.
132 addMachineFunctionPass(WebAssemblyArgumentMovePass(), PMW);
133
134 // Set the p2align operands. This information is present during ISel, however
135 // it's inconvenient to collect. Collect it now, and update the immediate
136 // operands.
137 addMachineFunctionPass(WebAssemblySetP2AlignOperandsPass(), PMW);
138
139 // Eliminate range checks and add default targets to br_table instructions.
140 addMachineFunctionPass(WebAssemblyFixBrTableDefaultsPass(), PMW);
141
142 // unreachable is terminator, non-terminator instruction after it is not
143 // allowed.
144 addMachineFunctionPass(WebAssemblyCleanCodeAfterTrapPass(), PMW);
145
146 return Error::success();
147}
148
149Error WebAssemblyCodeGenPassBuilder::addIRTranslator(PassManagerWrapper &PMW) {
150 addMachineFunctionPass(IRTranslatorPass(getOptLevel()), PMW);
151 return Error::success();
152}
153
154void WebAssemblyCodeGenPassBuilder::addPreLegalizeMachineIR(
155 PassManagerWrapper &PMW) {
156 if (getOptLevel() != CodeGenOptLevel::None)
157 addMachineFunctionPass(WebAssemblyPreLegalizerCombinerPass(), PMW);
158}
159
160Error WebAssemblyCodeGenPassBuilder::addLegalizeMachineIR(
161 PassManagerWrapper &PMW) {
162 addMachineFunctionPass(LegalizerPass(), PMW);
163 return Error::success();
164}
165
166void WebAssemblyCodeGenPassBuilder::addPreRegBankSelect(
167 PassManagerWrapper &PMW) {
168 if (getOptLevel() != CodeGenOptLevel::None)
169 addMachineFunctionPass(WebAssemblyPostLegalizerCombinerPass(), PMW);
170}
171
172Error WebAssemblyCodeGenPassBuilder::addRegBankSelect(PassManagerWrapper &PMW) {
173 addMachineFunctionPass(RegBankSelectPass(), PMW);
174 return Error::success();
175}
176
177Error WebAssemblyCodeGenPassBuilder::addGlobalInstructionSelect(
178 PassManagerWrapper &PMW) {
179 addMachineFunctionPass(InstructionSelectPass(getOptLevel()), PMW);
180
181 if (isGlobalISelAbortEnabled()) {
182 addMachineFunctionPass(WebAssemblyArgumentMovePass(), PMW);
183 addMachineFunctionPass(WebAssemblySetP2AlignOperandsPass(), PMW);
184 addMachineFunctionPass(WebAssemblyFixBrTableDefaultsPass(), PMW);
185 addMachineFunctionPass(WebAssemblyCleanCodeAfterTrapPass(), PMW);
186 }
187
188 return Error::success();
189}
190
191void WebAssemblyCodeGenPassBuilder::addPreEmitPass(PassManagerWrapper &PMW) {
192 Base::addPreEmitPass(PMW);
193
194 // Nullify DBG_VALUE_LISTs that we cannot handle.
195 addMachineFunctionPass(WebAssemblyNullifyDebugValueListsPass(), PMW);
196
197 // Remove any unreachable blocks that may be left floating around.
198 // Rare, but possible. Needed for WebAssemblyFixIrreducibleControlFlow.
199 addMachineFunctionPass(UnreachableMachineBlockElimPass(), PMW);
200
201 // Eliminate multiple-entry loops.
202 addMachineFunctionPass(WebAssemblyFixIrreducibleControlFlowPass(), PMW);
203
204 // Do various transformations for exception handling.
205 // Every CFG-changing optimizations should come before this.
206 addMachineFunctionPass(WebAssemblyLateEHPreparePass(), PMW);
207
208 // Now that we have a prologue and epilogue and all frame indices are
209 // rewritten, eliminate SP and FP. This allows them to be stackified,
210 // colored, and numbered with the rest of the registers.
211 addMachineFunctionPass(WebAssemblyReplacePhysRegsPass(), PMW);
212
213 // Preparations and optimizations related to register stackification.
214 if (getOptLevel() != CodeGenOptLevel::None) {
215 // Depend on LiveIntervals and perform some optimizations on it.
216 addMachineFunctionPass(WebAssemblyOptimizeLiveIntervalsPass(), PMW);
217
218 // Prepare memory intrinsic calls for register stackifying.
219 addMachineFunctionPass(WebAssemblyMemIntrinsicResultsPass(), PMW);
220 }
221
222 // Mark registers as representing wasm's value stack. This is a key
223 // code-compression technique in WebAssembly. We run this pass (and
224 // MemIntrinsicResults above) very late, so that it sees as much code as
225 // possible, including code emitted by PEI and expanded by late tail
226 // duplication.
227 addMachineFunctionPass(WebAssemblyRegStackifyPass(getOptLevel()), PMW);
228
229 if (getOptLevel() != CodeGenOptLevel::None) {
230 // Run the register coloring pass to reduce the total number of registers.
231 // This runs after stackification so that it doesn't consider registers
232 // that become stackified.
233 addMachineFunctionPass(WebAssemblyRegColoringPass(), PMW);
234 }
235
236 // Sort the blocks of the CFG into topological order, a prerequisite for
237 // BLOCK and LOOP markers.
238 addMachineFunctionPass(WebAssemblyCFGSortPass(), PMW);
239
240 // Insert BLOCK and LOOP markers.
241 addMachineFunctionPass(WebAssemblyCFGStackifyPass(), PMW);
242
243 // Insert explicit local.get and local.set operators.
244 if (getTM().getCLOpts().emit_explicit_locals)
245 addMachineFunctionPass(WebAssemblyExplicitLocalsPass(), PMW);
246
247 // Lower br_unless into br_if.
248 addMachineFunctionPass(WebAssemblyLowerBrUnlessPass(), PMW);
249
250 // Perform the very last peephole optimizations on the code.
251 if (getOptLevel() != CodeGenOptLevel::None)
252 addMachineFunctionPass(WebAssemblyPeepholePass(), PMW);
253
254 // Create a mapping from LLVM CodeGen virtual registers to wasm registers.
255 addMachineFunctionPass(WebAssemblyRegNumberingPass(), PMW);
256
257 // Fix debug_values whose defs have been stackified.
258 if (getTM().getCLOpts().emit_explicit_locals)
259 addMachineFunctionPass(WebAssemblyDebugFixupPass(), PMW);
260
261 // Collect information to prepare for MC lowering / asm printing.
262 flushFPMsToMPM(PMW);
263 addModulePass(WebAssemblyMCLowerPrePass(), PMW);
264}
265
266void WebAssemblyCodeGenPassBuilder::addAsmPrinterBegin(
267 PassManagerWrapper &PMW) {
268 addModulePass(WebAssemblyAsmPrinterBeginPass(), PMW, /*Force=*/true);
269}
270
271void WebAssemblyCodeGenPassBuilder::addAsmPrinter(PassManagerWrapper &PMW) {
272 addMachineFunctionPass(WebAssemblyAsmPrinterPass(), PMW);
273}
274
275void WebAssemblyCodeGenPassBuilder::addAsmPrinterEnd(PassManagerWrapper &PMW) {
276 addModulePass(WebAssemblyAsmPrinterEndPass(), PMW);
277}
278
280#define GET_PASS_REGISTRY "WebAssemblyPassRegistry.def"
282}
283
286 raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
287 const CGPassBuilderOption &Opt, MCContext &Ctx,
289 auto CGPB = WebAssemblyCodeGenPassBuilder(*this, Opt, PIC);
290 return CGPB.buildPipeline(MPM, MAM, Out, DwoOut, FileType, Ctx);
291}
Interfaces for producing common pass manager configurations.
This file declares the IRTranslator pass.
ModuleAnalysisManager MAM
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
PassInstrumentationCallbacks 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)
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:84
This class provides access to building LLVM's passes.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
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,...
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
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:309
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