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"
63#include "llvm/CodeGen/PEI.h"
101#include "llvm/IR/PassManager.h"
102#include "llvm/IR/Verifier.h"
104#include "llvm/MC/MCAsmInfo.h"
105#include "llvm/MC/MCStreamer.h"
108#include "llvm/Support/CodeGen.h"
109#include "llvm/Support/Debug.h"
110#include "llvm/Support/Error.h"
125#include <cassert>
126#include <utility>
127
128using namespace llvm;
129
130namespace llvm {
132
133#define DUMMY_MACHINE_FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
134 AnalysisKey PASS_NAME::Key;
135#include "llvm/Passes/MachinePassRegistry.def"
136} // namespace llvm
137
139 const CGPassBuilderOption &Opts,
141 : TM(TM), Opt(Opts), PIC(PIC) {
142 // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
143 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
144
145 // Target should override TM.Options.EnableIPRA in their target-specific
146 // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
147 if (Opt.EnableIPRA) {
148 TM.Options.EnableIPRA = *Opt.EnableIPRA;
149 } else {
150 // If not explicitly specified, use target default.
151 TM.Options.EnableIPRA |= TM.useIPRA();
152 }
153
154 if (Opt.EnableGlobalISelAbort)
155 TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
156
157 if (Opt.EnableRegAllocFastTied != cl::boolOrDefault::BOU_UNSET)
158 TM.setEnableTiedFastRegAlloc(Opt.EnableRegAllocFastTied ==
160
161 // An explicit RegAlloc choice implies its pipeline: only the fast
162 // allocator uses the unoptimized one.
163 if (Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_UNSET) {
164 bool Optimized = Opt.RegAlloc > RegAllocType::Default
165 ? Opt.RegAlloc != RegAllocType::Fast
166 : getOptLevel() != CodeGenOptLevel::None;
167 Opt.OptimizeRegAlloc =
168 Optimized ? cl::boolOrDefault::BOU_TRUE : cl::boolOrDefault::BOU_FALSE;
169 }
170
171 // These passes require NoVRegs, which a target keeping virtual registers
172 // never reaches.
173 if (!TM.usesPhysRegsForValues())
178 ShrinkWrapPass, StackMapLivenessPass>();
179}
180
181// Out-of-line to anchor the vtable in this translation unit.
183
185 return make_error<StringError>("addInstSelector is not overridden",
187}
188
190 return make_error<StringError>("addIRTranslator is not overridden",
192}
193
195 return make_error<StringError>("addLegalizeMachineIR is not overridden",
197}
198
200 return make_error<StringError>("addRegBankSelect is not overridden",
202}
203
205 return make_error<StringError>("addGlobalInstructionSelect is not overridden",
207}
208
210 llvm_unreachable("addAsmPrinterBegin is not overriden");
211}
212
214 llvm_unreachable("addAsmPrinter is not overridden");
215}
216
218 llvm_unreachable("addAsmPrinterEnd is not overriden");
219}
220
222 bool FreeMachineFunctions) {
223 if (PMW.FPM.isEmpty() && PMW.MFPM.isEmpty())
224 return;
225 if (!PMW.MFPM.isEmpty()) {
226 PMW.FPM.addPass(
227 createFunctionToMachineFunctionPassAdaptor(std::move(PMW.MFPM)));
228 PMW.MFPM = MachineFunctionPassManager();
229 }
230 if (FreeMachineFunctions)
232 if (AddInCGSCCOrder) {
234 createCGSCCToFunctionPassAdaptor(std::move(PMW.FPM))));
235 } else {
236 PMW.MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PMW.FPM)));
237 }
238 PMW.FPM = FunctionPassManager();
239}
240
243 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) {
244 auto StartStopInfo = TargetPassConfig::getStartStopInfo(TM, *PIC);
245 if (!StartStopInfo)
246 return StartStopInfo.takeError();
247 setStartStopPasses(*StartStopInfo);
248
249 CompletesPipeline = StartStopInfo->StopPass.empty();
250 bool PrintAsm = CompletesPipeline;
251 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
252
253 PassManagerWrapper PMW(MPM);
254
256 /*Force=*/true);
258 /*Force=*/true);
260 /*Force=*/true);
262 /*Force=*/true);
264 PMW,
265 /*Force=*/true);
266 addISelPasses(PMW);
267 flushFPMsToMPM(PMW);
268
269 if (PrintAsm) {
270 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
271 TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
272 if (!MCStreamerOrErr)
273 return MCStreamerOrErr.takeError();
274 std::unique_ptr<AsmPrinter> Printer(
275 TM.getTarget().createAsmPrinter(TM, std::move(*MCStreamerOrErr)));
276 if (!Printer)
277 return createStringError("failed to create AsmPrinter");
278 MAM.registerPass([&] { return AsmPrinterAnalysis(std::move(Printer)); });
280 }
281
282 if (auto Err = addCoreISelPasses(PMW))
283 return Err;
284
285 if (auto Err = addMachinePasses(PMW))
286 return Err;
287
288 if (PrintAsm ? !Opt.DisableVerify && TM.Options.EnableDefaultMachineVerifier
289 : Opt.VerifyMachineCode == MachineVerifierMode::End)
290 addMachineFunctionPass(MachineVerifierPass(), PMW, /*Force=*/!PrintAsm);
291
292 // We add AsmPrinter regardless if we are emitting MIR or Assembly as the
293 // final output so that -stop-before=<target>-asm-printer works. When printing
294 // MIR as the final output, we never end up running AsmPrinter.
295 addAsmPrinter(PMW);
296
297 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/!PrintMIR);
298 if (PrintAsm)
299 addAsmPrinterEnd(PMW);
300 else if (PrintMIR)
301 addModulePass(PrintMIRPass(Out), PMW, /*Force=*/true);
302
303 return verifyStartStop(*StartStopInfo);
304}
305
306void CodeGenPassBuilder::setStartStopPasses(
308 if (!Info.StartPass.empty()) {
309 Started = false;
310 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
311 Count = 0u](StringRef ClassName) mutable {
312 if (Count == Info.StartInstanceNum) {
313 if (AfterFlag) {
314 AfterFlag = false;
315 Started = true;
316 }
317 return Started;
318 }
319
320 auto PassName = PIC->getPassNameForClassName(ClassName);
321 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
322 Started = !Info.StartAfter;
323
324 return Started;
325 });
326 }
327
328 if (!Info.StopPass.empty()) {
329 Stopped = false;
330 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
331 Count = 0u](StringRef ClassName) mutable {
332 if (Count == Info.StopInstanceNum) {
333 if (AfterFlag) {
334 AfterFlag = false;
335 Stopped = true;
336 }
337 return !Stopped;
338 }
339
340 auto PassName = PIC->getPassNameForClassName(ClassName);
341 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
342 Stopped = !Info.StopAfter;
343 return !Stopped;
344 });
345 }
346}
347
348Error CodeGenPassBuilder::verifyStartStop(
349 const TargetPassConfig::StartStopInfo &Info) const {
350 if (Started && Stopped)
351 return Error::success();
352
353 if (!Started)
355 "Can't find start pass \"" + Info.StartPass + "\".",
356 std::make_error_code(std::errc::invalid_argument));
357 if (!Stopped)
359 "Can't find stop pass \"" + Info.StopPass + "\".",
360 std::make_error_code(std::errc::invalid_argument));
361 return Error::success();
362}
363
367 flushFPMsToMPM(PMW);
368 }
369
371 if (TM.useEmulatedTLS())
373
374 // ObjCARCContract operates on ObjC intrinsics and must run before
375 // PreISelIntrinsicLowering.
378 flushFPMsToMPM(PMW);
379 }
382
383 addIRPasses(PMW);
386 addISelPrepare(PMW);
387}
388
389/// Add common target configurable passes that perform LLVM IR to IR transforms
390/// following machine independent optimization.
392 // Before running any passes, run the verifier to determine if the input
393 // coming from the front-end and/or optimizer is valid.
394 if (!Opt.DisableVerify)
395 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
396
397 // Run loop strength reduction before anything else.
398 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
399 // These passes do not use MSSA.
400 LoopPassManager LPM;
401 LPM.addPass(CanonicalizeFreezeInLoopsPass());
402 LPM.addPass(LoopStrengthReducePass());
403 if (Opt.EnableLoopTermFold)
404 LPM.addPass(LoopTermFoldPass());
406 /*UseMemorySSA=*/false),
407 PMW);
408 }
409
410 // Run GC lowering passes for builtin collectors
411 // TODO: add a pass insertion point here
413 // Explicitly check to see if we should add ShadowStackGCLowering to avoid
414 // splitting the function pipeline if we do not have to.
415 if (runBeforeAdding(ShadowStackGCLoweringPass::name())) {
416 flushFPMsToMPM(PMW);
418 }
419
420 // Make sure that no unreachable blocks are instruction selected.
422
423 // Prepare expensive constants for SelectionDAG.
424 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
426
427 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
428 // operands with calls to the corresponding functions in a vector library.
431
433 !Opt.DisablePartialLibcallInlining)
435
436 // Instrument function entry and exit, e.g. with calls to mcount().
437 addFunctionPass(EntryExitInstrumenterPass(/*PostInlining=*/true), PMW);
438
439 // Add scalarization of target's unsupported masked memory intrinsics pass.
440 // the unsupported intrinsic will be replaced with a chain of basic blocks,
441 // that stores/loads element one-by-one if the appropriate mask bit is set.
443
444 // Expand reduction intrinsics into shuffle sequences if the target wants to.
445 if (!Opt.DisableExpandReductions)
447
448 // Convert conditional moves to conditional jumps when profitable.
449 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
451
452 if (Opt.EnableGlobalMergeFunc) {
453 flushFPMsToMPM(PMW);
455 }
456}
457
458/// Turn exception handling constructs into something the code generators can
459/// handle.
461 // The module's exception model is not known when the pipeline is built, so
462 // schedule the preparation pass for every model the target supports. Each
463 // pass does nothing for other models.
464 bool HasEHPrep = false;
465
466 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
467 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
468 // catch info can get misplaced when a selector ends up more than one block
469 // removed from the parent invoke(s). This could happen when a landing
470 // pad is shared by multiple invokes and is also a target of a normal
471 // edge from elsewhere.
472 if (TM.supportsExceptionModel(ExceptionHandling::SjLj)) {
474 HasEHPrep = true;
475 }
476 // We support using both GCC-style and MSVC-style exceptions on Windows, so
477 // WinEHPrepare runs in addition to DwarfEHPrepare below. Each pass will only
478 // actually run if it recognizes the personality function.
479 //
480 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
481 // on catchpads and cleanuppads because it does not outline them into
482 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
483 // should remove PHIs there.
484 if (TM.supportsExceptionModel(ExceptionHandling::WinEH) ||
485 TM.supportsExceptionModel(ExceptionHandling::Wasm)) {
487 HasEHPrep = true;
488 }
489 if (TM.supportsExceptionModel(ExceptionHandling::Wasm))
491 if (TM.supportsExceptionModel(ExceptionHandling::DwarfCFI)) {
493 HasEHPrep = true;
494 }
495
496 // If the target supports no exception model, nothing else lowers invokes.
497 if (!HasEHPrep) {
499
500 // The lower invoke pass may create unreachable code. Remove it.
502 }
503}
504
505/// Add pass to prepare the LLVM IR for code generation. This should be done
506/// before exception handling preparation passes.
508 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
510 // TODO: Default ctor'd RewriteSymbolPass is no-op.
511 // addPass(RewriteSymbolPass());
512}
513
514/// Add common passes that perform LLVM IR to IR transforms in preparation for
515/// instruction selection.
517 addPreISel(PMW);
518
519 if (Opt.RequiresCodeGenSCCOrder && !AddInCGSCCOrder)
521
523 // Add both the safe stack and the stack protection passes: each of them will
524 // only protect functions that have corresponding attributes.
527
528 if (Opt.PrintISelInput)
530 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"),
531 PMW);
532
534 flushFPMsToMPM(PMW);
536 }
537
538 // All passes which modify the LLVM IR are now complete; run the verifier
539 // to ensure that the IR is valid.
540 if (!Opt.DisableVerify)
541 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
542}
543
545 // Enable FastISel with -fast-isel, but allow that to be overridden.
546 TM.setO0WantsFastISel(Opt.EnableFastISelOption !=
548
549 // Determine an instruction selector.
550 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
551 SelectorType Selector;
552
553 if (Opt.EnableFastISelOption == cl::boolOrDefault::BOU_TRUE)
554 Selector = SelectorType::FastISel;
555 else if (Opt.EnableGlobalISelOption == cl::boolOrDefault::BOU_TRUE ||
556 (TM.Options.EnableGlobalISel &&
557 Opt.EnableGlobalISelOption != cl::boolOrDefault::BOU_FALSE))
558 Selector = SelectorType::GlobalISel;
559 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
560 Selector = SelectorType::FastISel;
561 else
562 Selector = SelectorType::SelectionDAG;
563
564 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
565 if (Selector == SelectorType::FastISel) {
566 TM.setFastISel(true);
567 TM.setGlobalISel(false);
568 } else if (Selector == SelectorType::GlobalISel) {
569 TM.setFastISel(false);
570 TM.setGlobalISel(true);
571 }
572
573 // Add instruction selector passes.
574 if (Selector == SelectorType::GlobalISel) {
575 if (auto Err = addIRTranslator(PMW))
576 return Err;
577
579
580 if (auto Err = addLegalizeMachineIR(PMW))
581 return Err;
582
583 // Before running the register bank selector, ask the target if it
584 // wants to run some passes.
586
587 if (auto Err = addRegBankSelect(PMW))
588 return Err;
589
591
592 if (auto Err = addGlobalInstructionSelect(PMW))
593 return Err;
594
595 // Pass to reset the MachineFunction if the ISel failed.
599 PMW);
600
601 // Provide a fallback path when we do not want to abort on
602 // not-yet-supported input.
604 if (auto Err = addInstSelector(PMW))
605 return Err;
606
607 } else if (auto Err = addInstSelector(PMW))
608 return Err;
609
610 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
611 // FinalizeISel.
613
614 // // Print the instruction selected machine code...
615 // printAndVerify("After Instruction Selection");
616
617 return Error::success();
618}
619
620/// Add the complete set of target-independent postISel code generator passes.
621///
622/// This can be read as the standard order of major LLVM CodeGen stages. Stages
623/// with nontrivial configuration or multiple passes are broken out below in
624/// add%Stage routines.
625///
626/// Any CodeGenPassBuilder::addXX routine may be overriden by the Target. The
627/// addPre/Post methods with empty header implementations allow injecting
628/// target-specific fixups just before or after major stages. Additionally,
629/// targets have the flexibility to change pass order within a stage by
630/// overriding default implementation of add%Stage routines below. Each
631/// technique has maintainability tradeoffs because alternate pass orders are
632/// not well supported. addPre/Post works better if the target pass is easily
633/// tied to a common pass. But if it has subtle dependencies on multiple passes,
634/// the target should override the stage instead.
636 // Add passes that optimize machine instructions in SSA form.
639 } else {
640 // If the target requests it, assign local variables to stack slots relative
641 // to one another and simplify frame index references where possible.
643 }
644
645 if (TM.Options.EnableIPRA) {
646 flushFPMsToMPM(PMW);
648 PMW, /*Force=*/true);
650 }
651
653 (Opt.EnableMachinePipeliner == cl::boolOrDefault::BOU_UNSET
655 : Opt.EnableMachinePipeliner == cl::boolOrDefault::BOU_TRUE))
657
658 // Run pre-ra passes.
659 addPreRegAlloc(PMW);
660
661 // Run register allocation and passes that are tightly coupled with it,
662 // including phi elimination and scheduling.
663 if (auto Err = Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_TRUE
665 : addFastRegAlloc(PMW))
666 return Err;
667
668 // Run post-ra passes.
669 addPostRegAlloc(PMW);
670
673
674 // Insert prolog/epilog code. Eliminate abstract frame index references...
678 }
679
681
682 /// Add passes that optimize machine instructions after register allocation.
685
686 // Expand pseudo instructions before second scheduling pass.
688
689 // Run pre-sched2 passes.
690 addPreSched2(PMW);
691
692 if (Opt.EnableImplicitNullChecks)
694
695 // Second pass scheduler.
696 // Let Target optionally insert this pass by itself at some other
697 // point.
699 !TM.targetSchedulesPostRAScheduling()) {
700 if (Opt.MISchedPostRA)
702 else
704 }
705
706 // GC
707 addGCPasses(PMW);
708
709 // Basic block placement.
712
713 // Insert before XRay Instrumentation.
715
718
719 addPreEmitPass(PMW);
720
721 if (TM.Options.EnableIPRA) {
722 // Collect register usage information and produce a register mask of
723 // clobbered registers, to be used to optimize call sites.
725 // If -print-regusage is specified, print the collected register usage info.
726 if (Opt.PrintRegUsage) {
727 flushFPMsToMPM(PMW);
729 }
730 }
731
733
735 addMachineFunctionPass(StackMapLivenessPass(), PMW);
738
739 if (TM.Options.EnableMachineOutliner &&
741 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
742 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
743 TM.supportsDefaultOutlining()) {
744 flushFPMsToMPM(PMW);
745 addModulePass(MachineOutlinerPass(Opt.EnableMachineOutliner), PMW);
746 }
747 }
748
749 if (Opt.EnableGCEmptyBlocks)
751
753
754 if (!Opt.DisableCFIFixup && TM.Options.EnableCFIFixup)
756
758
759 // Add passes that directly emit MI after all other MI passes.
760 addPreEmitPass2(PMW);
761
762 return Error::success();
763}
764
765/// Add passes that optimize machine instructions in SSA form.
767 // Pre-ra tail duplication.
769
770 // Optimize PHIs before DCE: removing dead PHI cycles may make more
771 // instructions dead.
773
774 // This pass merges large allocas. StackSlotColoring is a different pass
775 // which merges spill slots.
777
778 // If the target requests it, assign local variables to stack slots relative
779 // to one another and simplify frame index references where possible.
781
782 // With optimization, dead code should already be eliminated. However
783 // there is one known exception: lowered code for arguments that are only
784 // used by tail calls, where the tail calls reuse the incoming stack
785 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
787
788 // Allow targets to insert passes that improve instruction level parallelism,
789 // like if-conversion. Such passes will typically need dominator trees and
790 // loop info, just like LICM and CSE below.
791 addILPOpts(PMW);
792
795
796 addMachineFunctionPass(MachineSinkingPass(Opt.EnableSinkAndFold), PMW);
797
799 // Clean-up the dead code that may have been generated by peephole
800 // rewriting.
802}
803
804//===---------------------------------------------------------------------===//
805/// Register Allocation Pass Configuration
806//===---------------------------------------------------------------------===//
807
808/// Instantiate the default register allocator pass for this target for either
809/// the optimized or unoptimized allocation path. This will be added to the pass
810/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
811/// in the optimized case.
812///
813/// A target that uses the standard regalloc pass order for fast or optimized
814/// allocation may still override this for per-target regalloc
815/// selection. But -regalloc-npm=... always takes precedence.
816/// If a target does not want to allow users to set -regalloc-npm=... at all,
817/// check if Opt.RegAlloc == RegAllocType::Unset.
819 bool Optimized) {
820 if (Optimized)
822 else
824}
825
826/// Find and instantiate the register allocation pass requested by this target
827/// at the current optimization level. Different register allocators are
828/// defined as separate passes because they may require different analysis.
829///
830/// This helper ensures that the -regalloc-npm= option is always available,
831/// even for targets that override the default allocator.
833 bool Optimized) {
834 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
835 if (Opt.RegAlloc > RegAllocType::Default) {
836 switch (Opt.RegAlloc) {
839 break;
842 break;
843 default:
844 reportFatalUsageError("register allocator not supported yet");
845 }
846 return;
847 }
848 // -regalloc=default or unspecified, so pick based on the optimization level
849 // or ask the target for the regalloc pass.
850 addTargetRegisterAllocator(PMW, Optimized);
851}
852
854 // TODO: Ensure allocator is default or fast.
855 addRegAllocPass(PMW, false);
856 return Error::success();
857}
858
860 PassManagerWrapper &PMW) {
861 // Add the selected register allocation pass.
862 addRegAllocPass(PMW, true);
863
864 // Allow targets to change the register assignments before rewriting.
865 addPreRewrite(PMW);
866
867 // Finally rewrite virtual registers.
869
870 return Error::success();
871}
872
873/// Add the minimum set of target-independent passes that are required for
874/// register allocation. No coalescing or scheduling.
877 // RegAllocFast rewrites tied operands itself, but only when it runs.
878 bool RunRegAlloc = TM.usesPhysRegsForValues();
879 if (!RunRegAlloc || !TM.enableTiedFastRegAlloc())
881 if (!RunRegAlloc)
882 return Error::success();
883 return addRegAssignAndRewriteFast(PMW);
884}
885
886/// Add standard target-independent passes that are tightly coupled with
887/// optimized register allocation, including coalescing, machine instruction
888/// scheduling, and register allocation itself.
891
893
895
896 // LiveIntervals requires pure SSA form and no unreachable blocks.
897 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
898 // after it with -stop-before/-stop-after.
900
901 // If enabled, run the SSA machine scheduler just before PHI elimination.
902 if (Opt.EnableSSAMachineScheduler) {
906 }
907
910
911 // Edge splitting is smarter with machine loop info.
915
918
919 // The machine scheduler may accidentally create disconnected components
920 // when moving subregister definitions around, avoid this by splitting them to
921 // separate vregs before. Splitting can also improve reg. allocation quality.
923
924 // PreRA instruction scheduling.
926
927 if (!TM.usesPhysRegsForValues())
928 return Error::success();
930 return Err;
931
933
934 // Allow targets to expand pseudo instructions depending on the choice of
935 // registers before MachineCopyPropagation.
936 addPostRewrite(PMW);
937
938 // Copy propagate to forward register uses and try to eliminate COPYs that
939 // were not coalesced.
941
942 // Run post-ra machine LICM to hoist reloads / remats.
943 //
944 // FIXME: can this move into MachineLateOptimization?
946
947 return Error::success();
948}
949
950//===---------------------------------------------------------------------===//
951/// Post RegAlloc Pass Configuration
952//===---------------------------------------------------------------------===//
953
954/// Add passes that optimize machine instructions after register allocation.
956 // Cleanup of redundant (identical) address/immediate loads.
958
959 // Branch folding must be run after regalloc and prolog/epilog insertion.
960 addMachineFunctionPass(BranchFolderPass(Opt.EnableTailMerge), PMW);
961
962 // Tail duplication.
963 // Note that duplicating tail just increases code size and degrades
964 // performance for targets that require Structured Control Flow.
965 // In addition it can also make CFG irreducible. Thus we disable it.
966 if (!TM.requiresStructuredCFG())
968
969 // Copy propagation.
971}
972
973/// Add standard basic block placement passes.
976 // Run a separate pass to collect block placement statistics.
977 if (Opt.EnableBlockPlacementStats)
979}
amdgpu next use AMDGPU Next Use Analysis Printer
Contains definition of the base CFIFixup pass.
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...
void disablePass()
Allow the target to disable a specific pass by default.
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 bool isMachinePipelinerEnabled() const
Return true if the MachinePipeliner should run before addPreRegAlloc by default.
virtual void addGlobalMergePass(PassManagerWrapper &PMW)
Target can override this to add GlobalMergePass before all IR passes.
CodeGenOptLevel getOptLevel() const
virtual Error addRegAssignAndRewriteOptimized(PassManagerWrapper &PMW)
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 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
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.
Context object for machine code objects.
Definition MCContext.h:84
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.
Inject MD_prof metadata where it's missing.
Checks that MD_prof is present on every instruction that supports it.
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.
cl::opt< bool > EnableProfcheckInPipeline("enable-profcheck-in-pipeline", cl::init(false), cl::desc("Adds profile verification to the pipeline, erroring if profile " "information is dropped."))
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:309
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
@ 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:320
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.