LLVM 24.0.0git
CodeGenPassBuilder.cpp
Go to the documentation of this file.
1//===--- CodeGenPassBuilder.cpp --------------------------------------- ---===//
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// This file defines interfaces to access the target independent code
10// generation passes provided by the LLVM backend.
11//
12//===----------------------------------------------------------------------===//
13
16#include "llvm/ADT/StringRef.h"
62#include "llvm/CodeGen/PEI.h"
99#include "llvm/IR/PassManager.h"
100#include "llvm/IR/Verifier.h"
102#include "llvm/MC/MCAsmInfo.h"
103#include "llvm/MC/MCStreamer.h"
107#include "llvm/Support/CodeGen.h"
108#include "llvm/Support/Debug.h"
109#include "llvm/Support/Error.h"
123#include <cassert>
124#include <utility>
125
126using namespace llvm;
127
128namespace llvm {
129#define DUMMY_MACHINE_FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
130 AnalysisKey PASS_NAME::Key;
131#include "llvm/Passes/MachinePassRegistry.def"
132} // namespace llvm
133
135 const CGPassBuilderOption &Opts,
137 : TM(TM), Opt(Opts), PIC(PIC) {
138 // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
139 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
140
141 // Target should override TM.Options.EnableIPRA in their target-specific
142 // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
143 if (Opt.EnableIPRA) {
144 TM.Options.EnableIPRA = *Opt.EnableIPRA;
145 } else {
146 // If not explicitly specified, use target default.
147 TM.Options.EnableIPRA |= TM.useIPRA();
148 }
149
150 if (Opt.EnableGlobalISelAbort)
151 TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
152
153 if (Opt.EnableRegAllocFastTied != cl::boolOrDefault::BOU_UNSET)
154 TM.setEnableTiedFastRegAlloc(Opt.EnableRegAllocFastTied ==
156
157 // An explicit RegAlloc choice implies its pipeline: only the fast
158 // allocator uses the unoptimized one.
159 if (Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_UNSET) {
160 bool Optimized = Opt.RegAlloc > RegAllocType::Default
161 ? Opt.RegAlloc != RegAllocType::Fast
162 : getOptLevel() != CodeGenOptLevel::None;
163 Opt.OptimizeRegAlloc =
164 Optimized ? cl::boolOrDefault::BOU_TRUE : cl::boolOrDefault::BOU_FALSE;
165 }
166}
167
168// Out-of-line to anchor the vtable in this translation unit.
170
172 return make_error<StringError>("addInstSelector is not overridden",
174}
175
177 return make_error<StringError>("addIRTranslator is not overridden",
179}
180
182 return make_error<StringError>("addLegalizeMachineIR is not overridden",
184}
185
187 return make_error<StringError>("addRegBankSelect is not overridden",
189}
190
192 return make_error<StringError>("addGlobalInstructionSelect is not overridden",
194}
195
197 llvm_unreachable("addAsmPrinterBegin is not overriden");
198}
199
201 llvm_unreachable("addAsmPrinter is not overridden");
202}
203
205 llvm_unreachable("addAsmPrinterEnd is not overriden");
206}
207
209 bool FreeMachineFunctions) {
210 if (PMW.FPM.isEmpty() && PMW.MFPM.isEmpty())
211 return;
212 if (!PMW.MFPM.isEmpty()) {
213 PMW.FPM.addPass(
214 createFunctionToMachineFunctionPassAdaptor(std::move(PMW.MFPM)));
215 PMW.MFPM = MachineFunctionPassManager();
216 }
217 if (FreeMachineFunctions)
219 if (AddInCGSCCOrder) {
221 createCGSCCToFunctionPassAdaptor(std::move(PMW.FPM))));
222 } else {
223 PMW.MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PMW.FPM)));
224 }
225 PMW.FPM = FunctionPassManager();
226}
227
230 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) {
231 auto StartStopInfo = TargetPassConfig::getStartStopInfo(TM, *PIC);
232 if (!StartStopInfo)
233 return StartStopInfo.takeError();
234 setStartStopPasses(*StartStopInfo);
235
236 CompletesPipeline = StartStopInfo->StopPass.empty();
237 bool PrintAsm = CompletesPipeline;
238 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
239
240 PassManagerWrapper PMW(MPM);
241
243 /*Force=*/true);
245 /*Force=*/true);
247 /*Force=*/true);
249 /*Force=*/true);
251 PMW,
252 /*Force=*/true);
253 addISelPasses(PMW);
254 flushFPMsToMPM(PMW);
255
256 if (PrintAsm) {
257 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
258 TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
259 if (!MCStreamerOrErr)
260 return MCStreamerOrErr.takeError();
261 std::unique_ptr<AsmPrinter> Printer(
262 TM.getTarget().createAsmPrinter(TM, std::move(*MCStreamerOrErr)));
263 if (!Printer)
264 return createStringError("failed to create AsmPrinter");
265 MAM.registerPass([&] { return AsmPrinterAnalysis(std::move(Printer)); });
267 }
268
269 if (PrintMIR)
270 addModulePass(PrintMIRPreparePass(Out), PMW, /*Force=*/true);
271
272 if (auto Err = addCoreISelPasses(PMW))
273 return Err;
274
275 if (auto Err = addMachinePasses(PMW))
276 return Err;
277
278 if (PrintAsm ? !Opt.DisableVerify && TM.Options.EnableDefaultMachineVerifier
279 : Opt.VerifyMachineCode == MachineVerifierMode::End)
280 addMachineFunctionPass(MachineVerifierPass(), PMW, /*Force=*/!PrintAsm);
281
282 // We add AsmPrinter regardless if we are emitting MIR or Assembly as the
283 // final output so that -stop-before=<target>-asm-printer works. When printing
284 // MIR as the final output, we never end up running AsmPrinter.
285 addAsmPrinter(PMW);
286
287 if (PrintAsm) {
288 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/true);
289 addAsmPrinterEnd(PMW);
290 } else {
291 if (PrintMIR)
292 addMachineFunctionPass(PrintMIRPass(Out), PMW, /*Force=*/true);
293 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/true);
294 }
295
296 return verifyStartStop(*StartStopInfo);
297}
298
299void CodeGenPassBuilder::setStartStopPasses(
301 if (!Info.StartPass.empty()) {
302 Started = false;
303 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
304 Count = 0u](StringRef ClassName) mutable {
305 if (Count == Info.StartInstanceNum) {
306 if (AfterFlag) {
307 AfterFlag = false;
308 Started = true;
309 }
310 return Started;
311 }
312
313 auto PassName = PIC->getPassNameForClassName(ClassName);
314 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
315 Started = !Info.StartAfter;
316
317 return Started;
318 });
319 }
320
321 if (!Info.StopPass.empty()) {
322 Stopped = false;
323 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
324 Count = 0u](StringRef ClassName) mutable {
325 if (Count == Info.StopInstanceNum) {
326 if (AfterFlag) {
327 AfterFlag = false;
328 Stopped = true;
329 }
330 return !Stopped;
331 }
332
333 auto PassName = PIC->getPassNameForClassName(ClassName);
334 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
335 Stopped = !Info.StopAfter;
336 return !Stopped;
337 });
338 }
339}
340
341Error CodeGenPassBuilder::verifyStartStop(
342 const TargetPassConfig::StartStopInfo &Info) const {
343 if (Started && Stopped)
344 return Error::success();
345
346 if (!Started)
348 "Can't find start pass \"" + Info.StartPass + "\".",
349 std::make_error_code(std::errc::invalid_argument));
350 if (!Stopped)
352 "Can't find stop pass \"" + Info.StopPass + "\".",
353 std::make_error_code(std::errc::invalid_argument));
354 return Error::success();
355}
356
359 if (TM.useEmulatedTLS())
361
362 // ObjCARCContract operates on ObjC intrinsics and must run before
363 // PreISelIntrinsicLowering.
366 flushFPMsToMPM(PMW);
367 }
370
371 addIRPasses(PMW);
374 addISelPrepare(PMW);
375}
376
377/// Add common target configurable passes that perform LLVM IR to IR transforms
378/// following machine independent optimization.
380 // Before running any passes, run the verifier to determine if the input
381 // coming from the front-end and/or optimizer is valid.
382 if (!Opt.DisableVerify)
383 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
384
385 // Run loop strength reduction before anything else.
386 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
387 // These passes do not use MSSA.
388 LoopPassManager LPM;
389 LPM.addPass(CanonicalizeFreezeInLoopsPass());
390 LPM.addPass(LoopStrengthReducePass());
391 if (Opt.EnableLoopTermFold)
392 LPM.addPass(LoopTermFoldPass());
394 /*UseMemorySSA=*/false),
395 PMW);
396 }
397
398 // Run GC lowering passes for builtin collectors
399 // TODO: add a pass insertion point here
401 // Explicitly check to see if we should add ShadowStackGCLowering to avoid
402 // splitting the function pipeline if we do not have to.
403 if (runBeforeAdding(ShadowStackGCLoweringPass::name())) {
404 flushFPMsToMPM(PMW);
406 }
407
408 // Make sure that no unreachable blocks are instruction selected.
410
411 // Prepare expensive constants for SelectionDAG.
412 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
414
415 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
416 // operands with calls to the corresponding functions in a vector library.
419
421 !Opt.DisablePartialLibcallInlining)
423
424 // Instrument function entry and exit, e.g. with calls to mcount().
425 addFunctionPass(EntryExitInstrumenterPass(/*PostInlining=*/true), PMW);
426
427 // Add scalarization of target's unsupported masked memory intrinsics pass.
428 // the unsupported intrinsic will be replaced with a chain of basic blocks,
429 // that stores/loads element one-by-one if the appropriate mask bit is set.
431
432 // Expand reduction intrinsics into shuffle sequences if the target wants to.
433 if (!Opt.DisableExpandReductions)
435
436 // Convert conditional moves to conditional jumps when profitable.
437 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
439
440 if (Opt.EnableGlobalMergeFunc) {
441 flushFPMsToMPM(PMW);
443 }
444}
445
446/// Turn exception handling constructs into something the code generators can
447/// handle.
449 const MCAsmInfo &MCAI = TM.getMCAsmInfo();
450 switch (MCAI.getExceptionHandlingType()) {
452 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
453 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
454 // catch info can get misplaced when a selector ends up more than one block
455 // removed from the parent invoke(s). This could happen when a landing
456 // pad is shared by multiple invokes and is also a target of a normal
457 // edge from elsewhere.
459 [[fallthrough]];
465 break;
467 // We support using both GCC-style and MSVC-style exceptions on Windows, so
468 // add both preparation passes. Each pass will only actually run if it
469 // recognizes the personality function.
472 break;
474 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
475 // on catchpads and cleanuppads because it does not outline them into
476 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
477 // should remove PHIs there.
479 break;
483 // Emscripten EH is lowered earlier by WebAssemblyLowerEmscriptenEHSjLj, so
484 // by this point it needs no generic EH preparation, like the None case.
486
487 // The lower invoke pass may create unreachable code. Remove it.
489 break;
490 }
491}
492
493/// Add pass to prepare the LLVM IR for code generation. This should be done
494/// before exception handling preparation passes.
496 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
498 // TODO: Default ctor'd RewriteSymbolPass is no-op.
499 // addPass(RewriteSymbolPass());
500}
501
502/// Add common passes that perform LLVM IR to IR transforms in preparation for
503/// instruction selection.
505 addPreISel(PMW);
506
507 if (Opt.RequiresCodeGenSCCOrder && !AddInCGSCCOrder)
509
511 // Add both the safe stack and the stack protection passes: each of them will
512 // only protect functions that have corresponding attributes.
515
516 if (Opt.PrintISelInput)
518 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"),
519 PMW);
520
521 // All passes which modify the LLVM IR are now complete; run the verifier
522 // to ensure that the IR is valid.
523 if (!Opt.DisableVerify)
524 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
525}
526
528 // Enable FastISel with -fast-isel, but allow that to be overridden.
529 TM.setO0WantsFastISel(Opt.EnableFastISelOption !=
531
532 // Determine an instruction selector.
533 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
534 SelectorType Selector;
535
536 if (Opt.EnableFastISelOption == cl::boolOrDefault::BOU_TRUE)
537 Selector = SelectorType::FastISel;
538 else if (Opt.EnableGlobalISelOption == cl::boolOrDefault::BOU_TRUE ||
539 (TM.Options.EnableGlobalISel &&
540 Opt.EnableGlobalISelOption != cl::boolOrDefault::BOU_FALSE))
541 Selector = SelectorType::GlobalISel;
542 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
543 Selector = SelectorType::FastISel;
544 else
545 Selector = SelectorType::SelectionDAG;
546
547 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
548 if (Selector == SelectorType::FastISel) {
549 TM.setFastISel(true);
550 TM.setGlobalISel(false);
551 } else if (Selector == SelectorType::GlobalISel) {
552 TM.setFastISel(false);
553 TM.setGlobalISel(true);
554 }
555
556 // Add instruction selector passes.
557 if (Selector == SelectorType::GlobalISel) {
558 if (auto Err = addIRTranslator(PMW))
559 return Err;
560
562
563 if (auto Err = addLegalizeMachineIR(PMW))
564 return Err;
565
566 // Before running the register bank selector, ask the target if it
567 // wants to run some passes.
569
570 if (auto Err = addRegBankSelect(PMW))
571 return Err;
572
574
575 if (auto Err = addGlobalInstructionSelect(PMW))
576 return Err;
577
578 // Pass to reset the MachineFunction if the ISel failed.
582 PMW);
583
584 // Provide a fallback path when we do not want to abort on
585 // not-yet-supported input.
587 if (auto Err = addInstSelector(PMW))
588 return Err;
589
590 } else if (auto Err = addInstSelector(PMW))
591 return Err;
592
593 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
594 // FinalizeISel.
596
597 // // Print the instruction selected machine code...
598 // printAndVerify("After Instruction Selection");
599
600 return Error::success();
601}
602
603/// Add the complete set of target-independent postISel code generator passes.
604///
605/// This can be read as the standard order of major LLVM CodeGen stages. Stages
606/// with nontrivial configuration or multiple passes are broken out below in
607/// add%Stage routines.
608///
609/// Any CodeGenPassBuilder::addXX routine may be overriden by the Target. The
610/// addPre/Post methods with empty header implementations allow injecting
611/// target-specific fixups just before or after major stages. Additionally,
612/// targets have the flexibility to change pass order within a stage by
613/// overriding default implementation of add%Stage routines below. Each
614/// technique has maintainability tradeoffs because alternate pass orders are
615/// not well supported. addPre/Post works better if the target pass is easily
616/// tied to a common pass. But if it has subtle dependencies on multiple passes,
617/// the target should override the stage instead.
619 // Add passes that optimize machine instructions in SSA form.
622 } else {
623 // If the target requests it, assign local variables to stack slots relative
624 // to one another and simplify frame index references where possible.
626 }
627
628 if (TM.Options.EnableIPRA) {
629 flushFPMsToMPM(PMW);
631 PMW, /*Force=*/true);
633 }
634 // Run pre-ra passes.
635 addPreRegAlloc(PMW);
636
637 // Run register allocation and passes that are tightly coupled with it,
638 // including phi elimination and scheduling.
639 if (auto Err = Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_TRUE
641 : addFastRegAlloc(PMW))
642 return Err;
643
644 // Run post-ra passes.
645 addPostRegAlloc(PMW);
646
649
650 // Insert prolog/epilog code. Eliminate abstract frame index references...
654 }
655
657
658 /// Add passes that optimize machine instructions after register allocation.
661
662 // Expand pseudo instructions before second scheduling pass.
664
665 // Run pre-sched2 passes.
666 addPreSched2(PMW);
667
668 if (Opt.EnableImplicitNullChecks)
670
671 // Second pass scheduler.
672 // Let Target optionally insert this pass by itself at some other
673 // point.
675 !TM.targetSchedulesPostRAScheduling()) {
676 if (Opt.MISchedPostRA)
678 else
680 }
681
682 // GC
683 addGCPasses(PMW);
684
685 // Basic block placement.
688
689 // Insert before XRay Instrumentation.
691
694
695 addPreEmitPass(PMW);
696
697 if (TM.Options.EnableIPRA) {
698 // Collect register usage information and produce a register mask of
699 // clobbered registers, to be used to optimize call sites.
701 // If -print-regusage is specified, print the collected register usage info.
702 if (Opt.PrintRegUsage) {
703 flushFPMsToMPM(PMW);
705 }
706 }
707
709
711 addMachineFunctionPass(StackMapLivenessPass(), PMW);
712 addMachineFunctionPass(LiveDebugValuesPass(TM.shouldEmitDebugEntryValues()),
713 PMW);
715
716 if (TM.Options.EnableMachineOutliner &&
718 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
719 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
720 TM.supportsDefaultOutlining()) {
721 flushFPMsToMPM(PMW);
722 addModulePass(MachineOutlinerPass(Opt.EnableMachineOutliner), PMW);
723 }
724 }
725
726 if (Opt.EnableGCEmptyBlocks)
728
730
732
733 // Add passes that directly emit MI after all other MI passes.
734 addPreEmitPass2(PMW);
735
736 return Error::success();
737}
738
739/// Add passes that optimize machine instructions in SSA form.
741 // Pre-ra tail duplication.
743
744 // Optimize PHIs before DCE: removing dead PHI cycles may make more
745 // instructions dead.
747
748 // This pass merges large allocas. StackSlotColoring is a different pass
749 // which merges spill slots.
751
752 // If the target requests it, assign local variables to stack slots relative
753 // to one another and simplify frame index references where possible.
755
756 // With optimization, dead code should already be eliminated. However
757 // there is one known exception: lowered code for arguments that are only
758 // used by tail calls, where the tail calls reuse the incoming stack
759 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
761
762 // Allow targets to insert passes that improve instruction level parallelism,
763 // like if-conversion. Such passes will typically need dominator trees and
764 // loop info, just like LICM and CSE below.
765 addILPOpts(PMW);
766
769
770 addMachineFunctionPass(MachineSinkingPass(Opt.EnableSinkAndFold), PMW);
771
773 // Clean-up the dead code that may have been generated by peephole
774 // rewriting.
776}
777
778//===---------------------------------------------------------------------===//
779/// Register Allocation Pass Configuration
780//===---------------------------------------------------------------------===//
781
782/// Instantiate the default register allocator pass for this target for either
783/// the optimized or unoptimized allocation path. This will be added to the pass
784/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
785/// in the optimized case.
786///
787/// A target that uses the standard regalloc pass order for fast or optimized
788/// allocation may still override this for per-target regalloc
789/// selection. But -regalloc-npm=... always takes precedence.
790/// If a target does not want to allow users to set -regalloc-npm=... at all,
791/// check if Opt.RegAlloc == RegAllocType::Unset.
793 bool Optimized) {
794 if (Optimized)
796 else
798}
799
800/// Find and instantiate the register allocation pass requested by this target
801/// at the current optimization level. Different register allocators are
802/// defined as separate passes because they may require different analysis.
803///
804/// This helper ensures that the -regalloc-npm= option is always available,
805/// even for targets that override the default allocator.
807 bool Optimized) {
808 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
809 if (Opt.RegAlloc > RegAllocType::Default) {
810 switch (Opt.RegAlloc) {
813 break;
816 break;
817 default:
818 reportFatalUsageError("register allocator not supported yet");
819 }
820 return;
821 }
822 // -regalloc=default or unspecified, so pick based on the optimization level
823 // or ask the target for the regalloc pass.
824 addTargetRegisterAllocator(PMW, Optimized);
825}
826
828 // TODO: Ensure allocator is default or fast.
829 addRegAllocPass(PMW, false);
830 return Error::success();
831}
832
835 // Add the selected register allocation pass.
836 addRegAllocPass(PMW, true);
837
838 // Allow targets to change the register assignments before rewriting.
839 addPreRewrite(PMW);
840
841 // Finally rewrite virtual registers.
843
844 return true;
845}
846
847/// Add the minimum set of target-independent passes that are required for
848/// register allocation. No coalescing or scheduling.
855
856/// Add standard target-independent passes that are tightly coupled with
857/// optimized register allocation, including coalescing, machine instruction
858/// scheduling, and register allocation itself.
861
863
865
866 // LiveIntervals requires pure SSA form and no unreachable blocks.
867 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
868 // after it with -stop-before/-stop-after.
870
871 // If enabled, run the SSA machine scheduler just before PHI elimination.
872 if (Opt.EnableSSAMachineScheduler) {
876 }
877
878 // LiveIntervals is computed unconditionally before TwoAddressInstruction so
879 // that pass can rely on it instead of LiveVariables. This is a step toward
880 // removing LiveVariables entirely.
883
884 // Edge splitting is smarter with machine loop info.
888
891
892 // The machine scheduler may accidentally create disconnected components
893 // when moving subregister definitions around, avoid this by splitting them to
894 // separate vregs before. Splitting can also improve reg. allocation quality.
896
897 // PreRA instruction scheduling.
899
901 if (!AddedPasses)
902 return AddedPasses.takeError();
903 if (!AddedPasses.get())
904 return Error::success();
905
907
908 // Allow targets to expand pseudo instructions depending on the choice of
909 // registers before MachineCopyPropagation.
910 addPostRewrite(PMW);
911
912 // Copy propagate to forward register uses and try to eliminate COPYs that
913 // were not coalesced.
915
916 // Run post-ra machine LICM to hoist reloads / remats.
917 //
918 // FIXME: can this move into MachineLateOptimization?
920
921 return Error::success();
922}
923
924//===---------------------------------------------------------------------===//
925/// Post RegAlloc Pass Configuration
926//===---------------------------------------------------------------------===//
927
928/// Add passes that optimize machine instructions after register allocation.
930 // Cleanup of redundant (identical) address/immediate loads.
932
933 // Branch folding must be run after regalloc and prolog/epilog insertion.
934 addMachineFunctionPass(BranchFolderPass(Opt.EnableTailMerge), PMW);
935
936 // Tail duplication.
937 // Note that duplicating tail just increases code size and degrades
938 // performance for targets that require Structured Control Flow.
939 // In addition it can also make CFG irreducible. Thus we disable it.
940 if (!TM.requiresStructuredCFG())
942
943 // Copy propagation.
945}
946
947/// Add standard basic block placement passes.
950 // Run a separate pass to collect block placement statistics.
951 if (Opt.EnableBlockPlacementStats)
953}
amdgpu next use AMDGPU Next Use Analysis Printer
This header provides classes for managing passes over SCCs of the call graph.
Interfaces for producing common pass manager configurations.
Defines an IR pass for CodeGen Prepare.
Analysis that tracks defined/used subregister lanes across COPY instructions and instructions that ge...
This file defines passes to print out IR in various granularities.
This header defines various interfaces for pass management in LLVM.
This file contains the declaration of the InterleavedAccessPass class, its corresponding pass name is...
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
ModuleAnalysisManager MAM
if(PassOpts->AAPipeline)
PassInstrumentationCallbacks PIC
This pass is required to take advantage of the interprocedural register allocation infrastructure.
This file contains the declaration of the ResetMachineFunctionPass class.
This file contains the declaration of the SelectOptimizePass class, its corresponding pass name is se...
This file defines the SmallVector class.
Target-Independent Code Generator Pass Configuration Options pass.
static const char PassName[]
A pass that canonicalizes freeze instructions in a loop.
virtual void addPreEmitPass(PassManagerWrapper &PMW)
This pass may be implemented by targets that want to run passes immediately before machine code is em...
virtual void addMachineSSAOptimization(PassManagerWrapper &PMW)
Methods with trivial inline returns are convenient points in the common codegen pass pipeline where t...
void addRegAllocPass(PassManagerWrapper &PMW, bool Optimized)
addMachinePasses helper to create the target-selected or overriden regalloc pass.
void addMachineFunctionPass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
CodeGenPassBuilder(TargetMachine &TM, const CGPassBuilderOption &Opts, PassInstrumentationCallbacks *PIC)
virtual Error addLegalizeMachineIR(PassManagerWrapper &PMW)
This method should install a legalize pass, which converts the instruction sequence into one that can...
virtual void addPreRewrite(PassManagerWrapper &PMW)
addPreRewrite - Add passes to the optimized register allocation pipeline after register allocation is...
virtual Error addMachinePasses(PassManagerWrapper &PMW)
Add the complete, standard set of LLVM CodeGen passes.
void flushFPMsToMPM(PassManagerWrapper &PMW, bool FreeMachineFunctions=false)
virtual void addAsmPrinter(PassManagerWrapper &PMW)
virtual Error addRegAssignAndRewriteFast(PassManagerWrapper &PMW)
Add core register allocator passes which do the actual register assignment and rewriting.
void addFunctionPass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
virtual void addIRPasses(PassManagerWrapper &PMW)
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
virtual void addMachineLateOptimization(PassManagerWrapper &PMW)
Add passes that optimize machine instructions after register allocation.
Error buildPipeline(ModulePassManager &MPM, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
virtual void addPreRegAlloc(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before register allocat...
virtual void addPostRegAlloc(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes after register allocation pass pipe...
bool isGlobalISelAbortEnabled() const
Check whether or not GlobalISel should abort on error.
virtual void addPreSched2(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes after prolog-epilog insertion and b...
void addISelPasses(PassManagerWrapper &PMW)
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
virtual void addCodeGenPrepare(PassManagerWrapper &PMW)
Add pass to prepare the LLVM IR for code generation.
Error addCoreISelPasses(PassManagerWrapper &PMW)
Add the actual instruction selection passes.
virtual void addPreEmitPass2(PassManagerWrapper &PMW)
Targets may add passes immediately before machine code is emitted in this callback.
virtual void addPreRegBankSelect(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before the register ban...
virtual void addGlobalMergePass(PassManagerWrapper &PMW)
Target can override this to add GlobalMergePass before all IR passes.
CodeGenOptLevel getOptLevel() const
virtual void addTargetRegisterAllocator(PassManagerWrapper &PMW, bool Optimized)
Utilities for targets to add passes to the pass manager.
virtual Error addGlobalInstructionSelect(PassManagerWrapper &PMW)
This method should install a (global) instruction selector pass, which converts possibly generic inst...
virtual void addAsmPrinterBegin(PassManagerWrapper &PMW)
virtual Error addIRTranslator(PassManagerWrapper &PMW)
This method should install an IR translator pass, which converts from LLVM code to machine instructio...
virtual void addPreLegalizeMachineIR(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before legalization.
virtual Expected< bool > addRegAssignAndRewriteOptimized(PassManagerWrapper &PMW)
virtual void addISelPrepare(PassManagerWrapper &PMW)
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection.
virtual void addPreISel(PassManagerWrapper &PMW)
{{@ For GlobalISel
virtual Error addOptimizedRegAlloc(PassManagerWrapper &PMW)
addOptimizedRegAlloc - Add passes related to register allocation.
virtual void addPostBBSections(PassManagerWrapper &PMW)
void addModulePass(PassT &&Pass, PassManagerWrapper &PMW, bool Force=false, StringRef Name=PassT::name())
virtual Error addFastRegAlloc(PassManagerWrapper &PMW)
addFastRegAlloc - Add the minimum set of target-independent passes that are required for fast registe...
virtual void addPreGlobalInstructionSelect(PassManagerWrapper &PMW)
This method may be implemented by targets that want to run passes immediately before the (global) ins...
virtual void addPassesToHandleExceptions(PassManagerWrapper &PMW)
Add passes to lower exception handling for the code generator.
virtual void addILPOpts(PassManagerWrapper &PMW)
Add passes that optimize instruction level parallelism for out-of-order targets.
PassInstrumentationCallbacks * PIC
virtual void addAsmPrinterEnd(PassManagerWrapper &PMW)
virtual Error addInstSelector(PassManagerWrapper &PMW)
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
virtual void addBlockPlacement(PassManagerWrapper &PMW)
Add standard basic block placement passes.
virtual void addPostRewrite(PassManagerWrapper &PMW)
Add passes to be run immediately after virtual registers are rewritten to physical registers.
bool reportDiagnosticWhenGlobalISelFallback() const
Check whether or not a diagnostic should be emitted when GlobalISel uses the fallback path.
virtual void addGCPasses(PassManagerWrapper &PMW)
addGCPasses - Add late codegen passes that analyze code for garbage collection.
void requireCGSCCOrder(PassManagerWrapper &PMW)
bool CompletesPipeline
Whether no -stop-before/-stop-after option ends the pipeline early.
virtual Error addRegBankSelect(PassManagerWrapper &PMW)
This method should install a register bank selector pass, which assigns register banks to virtual reg...
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
LowerIntrinsics - This pass rewrites calls to the llvm.gcread or llvm.gcwrite intrinsics,...
Definition GCMetadata.h:229
Performs Loop Strength Reduce Pass.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:67
ExceptionHandling getExceptionHandlingType() const
Definition MCAsmInfo.h:656
Context object for machine code objects.
Definition MCContext.h:83
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ABI StringRef getPassNameForClassName(StringRef ClassName)
Get the pass name for a given pass class name. Empty if no match found.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
bool isEmpty() const
Returns if the pass manager contains any passes.
Pass (for the new pass manager) for printing a Function as LLVM's text IR assembly.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Primary interface to the complete machine description for the target machine.
static Expected< StartStopInfo > getStartStopInfo(const TargetMachine &TM, PassInstrumentationCallbacks &PIC)
Returns pass name in -stop-before or -stop-after NOTE: New pass manager migration only.
Create a verifier pass.
Definition Verifier.h:134
An abstract base class for streams implementations that also support a pwrite operation.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
ModuleToPostOrderCGSCCPassAdaptor createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition CodeGen.h:256
FunctionToMachineFunctionPassAdaptor createFunctionToMachineFunctionPassAdaptor(MachineFunctionPassT &&Pass)
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
@ SjLj
setjmp/longjmp based exceptions
Definition CodeGen.h:58
@ ZOS
z/OS MVS Exception Handling.
Definition CodeGen.h:64
@ Emscripten
Emscripten JavaScript-based exception handling.
Definition CodeGen.h:62
@ None
No exception support.
Definition CodeGen.h:56
@ Default
Not specified; resolve to the target's default model.
Definition CodeGen.h:55
@ AIX
AIX Exception Handling.
Definition CodeGen.h:63
@ DwarfCFI
DWARF-like instruction based exceptions.
Definition CodeGen.h:57
@ WinEH
Windows Exception Handling.
Definition CodeGen.h:60
@ Wasm
WebAssembly Exception Handling.
Definition CodeGen.h:61
PassManager< MachineFunction > MachineFunctionPassManager
Convenience typedef for a pass manager over functions.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Global function merging pass for new pass manager.
A utility pass template to force an analysis result to be available.