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"
109#include "llvm/Support/CodeGen.h"
110#include "llvm/Support/Debug.h"
111#include "llvm/Support/Error.h"
125#include <cassert>
126#include <utility>
127
128using namespace llvm;
129
130namespace llvm {
131#define DUMMY_MACHINE_FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
132 AnalysisKey PASS_NAME::Key;
133#include "llvm/Passes/MachinePassRegistry.def"
134} // namespace llvm
135
137 const CGPassBuilderOption &Opts,
139 : TM(TM), Opt(Opts), PIC(PIC) {
140 // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
141 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
142
143 // Target should override TM.Options.EnableIPRA in their target-specific
144 // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
145 if (Opt.EnableIPRA) {
146 TM.Options.EnableIPRA = *Opt.EnableIPRA;
147 } else {
148 // If not explicitly specified, use target default.
149 TM.Options.EnableIPRA |= TM.useIPRA();
150 }
151
152 if (Opt.EnableGlobalISelAbort)
153 TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
154
155 if (Opt.EnableRegAllocFastTied != cl::boolOrDefault::BOU_UNSET)
156 TM.setEnableTiedFastRegAlloc(Opt.EnableRegAllocFastTied ==
158
159 // An explicit RegAlloc choice implies its pipeline: only the fast
160 // allocator uses the unoptimized one.
161 if (Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_UNSET) {
162 bool Optimized = Opt.RegAlloc > RegAllocType::Default
163 ? Opt.RegAlloc != RegAllocType::Fast
164 : getOptLevel() != CodeGenOptLevel::None;
165 Opt.OptimizeRegAlloc =
166 Optimized ? cl::boolOrDefault::BOU_TRUE : cl::boolOrDefault::BOU_FALSE;
167 }
168}
169
170// Out-of-line to anchor the vtable in this translation unit.
172
174 return make_error<StringError>("addInstSelector is not overridden",
176}
177
179 return make_error<StringError>("addIRTranslator is not overridden",
181}
182
184 return make_error<StringError>("addLegalizeMachineIR is not overridden",
186}
187
189 return make_error<StringError>("addRegBankSelect is not overridden",
191}
192
194 return make_error<StringError>("addGlobalInstructionSelect is not overridden",
196}
197
199 llvm_unreachable("addAsmPrinterBegin is not overriden");
200}
201
203 llvm_unreachable("addAsmPrinter is not overridden");
204}
205
207 llvm_unreachable("addAsmPrinterEnd is not overriden");
208}
209
211 bool FreeMachineFunctions) {
212 if (PMW.FPM.isEmpty() && PMW.MFPM.isEmpty())
213 return;
214 if (!PMW.MFPM.isEmpty()) {
215 PMW.FPM.addPass(
216 createFunctionToMachineFunctionPassAdaptor(std::move(PMW.MFPM)));
217 PMW.MFPM = MachineFunctionPassManager();
218 }
219 if (FreeMachineFunctions)
221 if (AddInCGSCCOrder) {
223 createCGSCCToFunctionPassAdaptor(std::move(PMW.FPM))));
224 } else {
225 PMW.MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PMW.FPM)));
226 }
227 PMW.FPM = FunctionPassManager();
228}
229
232 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) {
233 auto StartStopInfo = TargetPassConfig::getStartStopInfo(TM, *PIC);
234 if (!StartStopInfo)
235 return StartStopInfo.takeError();
236 setStartStopPasses(*StartStopInfo);
237
238 CompletesPipeline = StartStopInfo->StopPass.empty();
239 bool PrintAsm = CompletesPipeline;
240 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
241
242 PassManagerWrapper PMW(MPM);
243
245 /*Force=*/true);
247 /*Force=*/true);
249 /*Force=*/true);
251 /*Force=*/true);
253 PMW,
254 /*Force=*/true);
255 addISelPasses(PMW);
256 flushFPMsToMPM(PMW);
257
258 if (PrintAsm) {
259 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
260 TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
261 if (!MCStreamerOrErr)
262 return MCStreamerOrErr.takeError();
263 std::unique_ptr<AsmPrinter> Printer(
264 TM.getTarget().createAsmPrinter(TM, std::move(*MCStreamerOrErr)));
265 if (!Printer)
266 return createStringError("failed to create AsmPrinter");
267 MAM.registerPass([&] { return AsmPrinterAnalysis(std::move(Printer)); });
269 }
270
271 if (PrintMIR)
272 addModulePass(PrintMIRPreparePass(Out), PMW, /*Force=*/true);
273
274 if (auto Err = addCoreISelPasses(PMW))
275 return Err;
276
277 if (auto Err = addMachinePasses(PMW))
278 return Err;
279
280 if (PrintAsm ? !Opt.DisableVerify && TM.Options.EnableDefaultMachineVerifier
281 : Opt.VerifyMachineCode == MachineVerifierMode::End)
282 addMachineFunctionPass(MachineVerifierPass(), PMW, /*Force=*/!PrintAsm);
283
284 // We add AsmPrinter regardless if we are emitting MIR or Assembly as the
285 // final output so that -stop-before=<target>-asm-printer works. When printing
286 // MIR as the final output, we never end up running AsmPrinter.
287 addAsmPrinter(PMW);
288
289 if (PrintAsm) {
290 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/true);
291 addAsmPrinterEnd(PMW);
292 } else {
293 if (PrintMIR)
294 addMachineFunctionPass(PrintMIRPass(Out), PMW, /*Force=*/true);
295 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/true);
296 }
297
298 return verifyStartStop(*StartStopInfo);
299}
300
301void CodeGenPassBuilder::setStartStopPasses(
303 if (!Info.StartPass.empty()) {
304 Started = false;
305 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
306 Count = 0u](StringRef ClassName) mutable {
307 if (Count == Info.StartInstanceNum) {
308 if (AfterFlag) {
309 AfterFlag = false;
310 Started = true;
311 }
312 return Started;
313 }
314
315 auto PassName = PIC->getPassNameForClassName(ClassName);
316 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
317 Started = !Info.StartAfter;
318
319 return Started;
320 });
321 }
322
323 if (!Info.StopPass.empty()) {
324 Stopped = false;
325 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
326 Count = 0u](StringRef ClassName) mutable {
327 if (Count == Info.StopInstanceNum) {
328 if (AfterFlag) {
329 AfterFlag = false;
330 Stopped = true;
331 }
332 return !Stopped;
333 }
334
335 auto PassName = PIC->getPassNameForClassName(ClassName);
336 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
337 Stopped = !Info.StopAfter;
338 return !Stopped;
339 });
340 }
341}
342
343Error CodeGenPassBuilder::verifyStartStop(
344 const TargetPassConfig::StartStopInfo &Info) const {
345 if (Started && Stopped)
346 return Error::success();
347
348 if (!Started)
350 "Can't find start pass \"" + Info.StartPass + "\".",
351 std::make_error_code(std::errc::invalid_argument));
352 if (!Stopped)
354 "Can't find stop pass \"" + Info.StopPass + "\".",
355 std::make_error_code(std::errc::invalid_argument));
356 return Error::success();
357}
358
361 if (TM.useEmulatedTLS())
363
364 // ObjCARCContract operates on ObjC intrinsics and must run before
365 // PreISelIntrinsicLowering.
368 flushFPMsToMPM(PMW);
369 }
372
373 addIRPasses(PMW);
376 addISelPrepare(PMW);
377}
378
379/// Add common target configurable passes that perform LLVM IR to IR transforms
380/// following machine independent optimization.
382 // Before running any passes, run the verifier to determine if the input
383 // coming from the front-end and/or optimizer is valid.
384 if (!Opt.DisableVerify)
385 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
386
387 // Run loop strength reduction before anything else.
388 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
389 // These passes do not use MSSA.
390 LoopPassManager LPM;
391 LPM.addPass(CanonicalizeFreezeInLoopsPass());
392 LPM.addPass(LoopStrengthReducePass());
393 if (Opt.EnableLoopTermFold)
394 LPM.addPass(LoopTermFoldPass());
396 /*UseMemorySSA=*/false),
397 PMW);
398 }
399
400 // Run GC lowering passes for builtin collectors
401 // TODO: add a pass insertion point here
403 // Explicitly check to see if we should add ShadowStackGCLowering to avoid
404 // splitting the function pipeline if we do not have to.
405 if (runBeforeAdding(ShadowStackGCLoweringPass::name())) {
406 flushFPMsToMPM(PMW);
408 }
409
410 // Make sure that no unreachable blocks are instruction selected.
412
413 // Prepare expensive constants for SelectionDAG.
414 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
416
417 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
418 // operands with calls to the corresponding functions in a vector library.
421
423 !Opt.DisablePartialLibcallInlining)
425
426 // Instrument function entry and exit, e.g. with calls to mcount().
427 addFunctionPass(EntryExitInstrumenterPass(/*PostInlining=*/true), PMW);
428
429 // Add scalarization of target's unsupported masked memory intrinsics pass.
430 // the unsupported intrinsic will be replaced with a chain of basic blocks,
431 // that stores/loads element one-by-one if the appropriate mask bit is set.
433
434 // Expand reduction intrinsics into shuffle sequences if the target wants to.
435 if (!Opt.DisableExpandReductions)
437
438 // Convert conditional moves to conditional jumps when profitable.
439 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
441
442 if (Opt.EnableGlobalMergeFunc) {
443 flushFPMsToMPM(PMW);
445 }
446}
447
448/// Turn exception handling constructs into something the code generators can
449/// handle.
451 // The module's exception model is not known when the pipeline is built, so
452 // schedule the preparation pass for every model the target supports. Each
453 // pass does nothing for other models.
454 bool HasEHPrep = false;
455
456 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
457 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
458 // catch info can get misplaced when a selector ends up more than one block
459 // removed from the parent invoke(s). This could happen when a landing
460 // pad is shared by multiple invokes and is also a target of a normal
461 // edge from elsewhere.
462 if (TM.supportsExceptionModel(ExceptionHandling::SjLj)) {
464 HasEHPrep = true;
465 }
466 // We support using both GCC-style and MSVC-style exceptions on Windows, so
467 // WinEHPrepare runs in addition to DwarfEHPrepare below. Each pass will only
468 // actually run if it recognizes the personality function.
469 //
470 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
471 // on catchpads and cleanuppads because it does not outline them into
472 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
473 // should remove PHIs there.
474 if (TM.supportsExceptionModel(ExceptionHandling::WinEH) ||
475 TM.supportsExceptionModel(ExceptionHandling::Wasm)) {
477 HasEHPrep = true;
478 }
479 if (TM.supportsExceptionModel(ExceptionHandling::Wasm))
481 if (TM.supportsExceptionModel(ExceptionHandling::DwarfCFI)) {
483 HasEHPrep = true;
484 }
485
486 // If the target supports no exception model, nothing else lowers invokes.
487 if (!HasEHPrep) {
489
490 // The lower invoke pass may create unreachable code. Remove it.
492 }
493}
494
495/// Add pass to prepare the LLVM IR for code generation. This should be done
496/// before exception handling preparation passes.
498 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
500 // TODO: Default ctor'd RewriteSymbolPass is no-op.
501 // addPass(RewriteSymbolPass());
502}
503
504/// Add common passes that perform LLVM IR to IR transforms in preparation for
505/// instruction selection.
507 addPreISel(PMW);
508
509 if (Opt.RequiresCodeGenSCCOrder && !AddInCGSCCOrder)
511
513 // Add both the safe stack and the stack protection passes: each of them will
514 // only protect functions that have corresponding attributes.
517
518 if (Opt.PrintISelInput)
520 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"),
521 PMW);
522
523 // All passes which modify the LLVM IR are now complete; run the verifier
524 // to ensure that the IR is valid.
525 if (!Opt.DisableVerify)
526 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
527}
528
530 // Enable FastISel with -fast-isel, but allow that to be overridden.
531 TM.setO0WantsFastISel(Opt.EnableFastISelOption !=
533
534 // Determine an instruction selector.
535 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
536 SelectorType Selector;
537
538 if (Opt.EnableFastISelOption == cl::boolOrDefault::BOU_TRUE)
539 Selector = SelectorType::FastISel;
540 else if (Opt.EnableGlobalISelOption == cl::boolOrDefault::BOU_TRUE ||
541 (TM.Options.EnableGlobalISel &&
542 Opt.EnableGlobalISelOption != cl::boolOrDefault::BOU_FALSE))
543 Selector = SelectorType::GlobalISel;
544 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
545 Selector = SelectorType::FastISel;
546 else
547 Selector = SelectorType::SelectionDAG;
548
549 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
550 if (Selector == SelectorType::FastISel) {
551 TM.setFastISel(true);
552 TM.setGlobalISel(false);
553 } else if (Selector == SelectorType::GlobalISel) {
554 TM.setFastISel(false);
555 TM.setGlobalISel(true);
556 }
557
558 // Add instruction selector passes.
559 if (Selector == SelectorType::GlobalISel) {
560 if (auto Err = addIRTranslator(PMW))
561 return Err;
562
564
565 if (auto Err = addLegalizeMachineIR(PMW))
566 return Err;
567
568 // Before running the register bank selector, ask the target if it
569 // wants to run some passes.
571
572 if (auto Err = addRegBankSelect(PMW))
573 return Err;
574
576
577 if (auto Err = addGlobalInstructionSelect(PMW))
578 return Err;
579
580 // Pass to reset the MachineFunction if the ISel failed.
584 PMW);
585
586 // Provide a fallback path when we do not want to abort on
587 // not-yet-supported input.
589 if (auto Err = addInstSelector(PMW))
590 return Err;
591
592 } else if (auto Err = addInstSelector(PMW))
593 return Err;
594
595 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
596 // FinalizeISel.
598
599 // // Print the instruction selected machine code...
600 // printAndVerify("After Instruction Selection");
601
602 return Error::success();
603}
604
605/// Add the complete set of target-independent postISel code generator passes.
606///
607/// This can be read as the standard order of major LLVM CodeGen stages. Stages
608/// with nontrivial configuration or multiple passes are broken out below in
609/// add%Stage routines.
610///
611/// Any CodeGenPassBuilder::addXX routine may be overriden by the Target. The
612/// addPre/Post methods with empty header implementations allow injecting
613/// target-specific fixups just before or after major stages. Additionally,
614/// targets have the flexibility to change pass order within a stage by
615/// overriding default implementation of add%Stage routines below. Each
616/// technique has maintainability tradeoffs because alternate pass orders are
617/// not well supported. addPre/Post works better if the target pass is easily
618/// tied to a common pass. But if it has subtle dependencies on multiple passes,
619/// the target should override the stage instead.
621 // Add passes that optimize machine instructions in SSA form.
624 } else {
625 // If the target requests it, assign local variables to stack slots relative
626 // to one another and simplify frame index references where possible.
628 }
629
630 if (TM.Options.EnableIPRA) {
631 flushFPMsToMPM(PMW);
633 PMW, /*Force=*/true);
635 }
636
638 (Opt.EnableMachinePipeliner == cl::boolOrDefault::BOU_UNSET
640 : Opt.EnableMachinePipeliner == cl::boolOrDefault::BOU_TRUE))
642
643 // Run pre-ra passes.
644 addPreRegAlloc(PMW);
645
646 // Run register allocation and passes that are tightly coupled with it,
647 // including phi elimination and scheduling.
648 if (auto Err = Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_TRUE
650 : addFastRegAlloc(PMW))
651 return Err;
652
653 // Run post-ra passes.
654 addPostRegAlloc(PMW);
655
658
659 // Insert prolog/epilog code. Eliminate abstract frame index references...
663 }
664
666
667 /// Add passes that optimize machine instructions after register allocation.
670
671 // Expand pseudo instructions before second scheduling pass.
673
674 // Run pre-sched2 passes.
675 addPreSched2(PMW);
676
677 if (Opt.EnableImplicitNullChecks)
679
680 // Second pass scheduler.
681 // Let Target optionally insert this pass by itself at some other
682 // point.
684 !TM.targetSchedulesPostRAScheduling()) {
685 if (Opt.MISchedPostRA)
687 else
689 }
690
691 // GC
692 addGCPasses(PMW);
693
694 // Basic block placement.
697
698 // Insert before XRay Instrumentation.
700
703
704 addPreEmitPass(PMW);
705
706 if (TM.Options.EnableIPRA) {
707 // Collect register usage information and produce a register mask of
708 // clobbered registers, to be used to optimize call sites.
710 // If -print-regusage is specified, print the collected register usage info.
711 if (Opt.PrintRegUsage) {
712 flushFPMsToMPM(PMW);
714 }
715 }
716
718
720 addMachineFunctionPass(StackMapLivenessPass(), PMW);
721 addMachineFunctionPass(LiveDebugValuesPass(TM.shouldEmitDebugEntryValues()),
722 PMW);
724
725 if (TM.Options.EnableMachineOutliner &&
727 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
728 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
729 TM.supportsDefaultOutlining()) {
730 flushFPMsToMPM(PMW);
731 addModulePass(MachineOutlinerPass(Opt.EnableMachineOutliner), PMW);
732 }
733 }
734
735 if (Opt.EnableGCEmptyBlocks)
737
739
741
742 // Add passes that directly emit MI after all other MI passes.
743 addPreEmitPass2(PMW);
744
745 return Error::success();
746}
747
748/// Add passes that optimize machine instructions in SSA form.
750 // Pre-ra tail duplication.
752
753 // Optimize PHIs before DCE: removing dead PHI cycles may make more
754 // instructions dead.
756
757 // This pass merges large allocas. StackSlotColoring is a different pass
758 // which merges spill slots.
760
761 // If the target requests it, assign local variables to stack slots relative
762 // to one another and simplify frame index references where possible.
764
765 // With optimization, dead code should already be eliminated. However
766 // there is one known exception: lowered code for arguments that are only
767 // used by tail calls, where the tail calls reuse the incoming stack
768 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
770
771 // Allow targets to insert passes that improve instruction level parallelism,
772 // like if-conversion. Such passes will typically need dominator trees and
773 // loop info, just like LICM and CSE below.
774 addILPOpts(PMW);
775
778
779 addMachineFunctionPass(MachineSinkingPass(Opt.EnableSinkAndFold), PMW);
780
782 // Clean-up the dead code that may have been generated by peephole
783 // rewriting.
785}
786
787//===---------------------------------------------------------------------===//
788/// Register Allocation Pass Configuration
789//===---------------------------------------------------------------------===//
790
791/// Instantiate the default register allocator pass for this target for either
792/// the optimized or unoptimized allocation path. This will be added to the pass
793/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
794/// in the optimized case.
795///
796/// A target that uses the standard regalloc pass order for fast or optimized
797/// allocation may still override this for per-target regalloc
798/// selection. But -regalloc-npm=... always takes precedence.
799/// If a target does not want to allow users to set -regalloc-npm=... at all,
800/// check if Opt.RegAlloc == RegAllocType::Unset.
802 bool Optimized) {
803 if (Optimized)
805 else
807}
808
809/// Find and instantiate the register allocation pass requested by this target
810/// at the current optimization level. Different register allocators are
811/// defined as separate passes because they may require different analysis.
812///
813/// This helper ensures that the -regalloc-npm= option is always available,
814/// even for targets that override the default allocator.
816 bool Optimized) {
817 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
818 if (Opt.RegAlloc > RegAllocType::Default) {
819 switch (Opt.RegAlloc) {
822 break;
825 break;
826 default:
827 reportFatalUsageError("register allocator not supported yet");
828 }
829 return;
830 }
831 // -regalloc=default or unspecified, so pick based on the optimization level
832 // or ask the target for the regalloc pass.
833 addTargetRegisterAllocator(PMW, Optimized);
834}
835
837 // TODO: Ensure allocator is default or fast.
838 addRegAllocPass(PMW, false);
839 return Error::success();
840}
841
844 // Add the selected register allocation pass.
845 addRegAllocPass(PMW, true);
846
847 // Allow targets to change the register assignments before rewriting.
848 addPreRewrite(PMW);
849
850 // Finally rewrite virtual registers.
852
853 return true;
854}
855
856/// Add the minimum set of target-independent passes that are required for
857/// register allocation. No coalescing or scheduling.
864
865/// Add standard target-independent passes that are tightly coupled with
866/// optimized register allocation, including coalescing, machine instruction
867/// scheduling, and register allocation itself.
870
872
874
875 // LiveIntervals requires pure SSA form and no unreachable blocks.
876 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
877 // after it with -stop-before/-stop-after.
879
880 // If enabled, run the SSA machine scheduler just before PHI elimination.
881 if (Opt.EnableSSAMachineScheduler) {
885 }
886
887 // LiveIntervals is computed unconditionally before TwoAddressInstruction so
888 // that pass can rely on it instead of LiveVariables. This is a step toward
889 // removing LiveVariables entirely.
892
893 // Edge splitting is smarter with machine loop info.
897
900
901 // The machine scheduler may accidentally create disconnected components
902 // when moving subregister definitions around, avoid this by splitting them to
903 // separate vregs before. Splitting can also improve reg. allocation quality.
905
906 // PreRA instruction scheduling.
908
910 if (!AddedPasses)
911 return AddedPasses.takeError();
912 if (!AddedPasses.get())
913 return Error::success();
914
916
917 // Allow targets to expand pseudo instructions depending on the choice of
918 // registers before MachineCopyPropagation.
919 addPostRewrite(PMW);
920
921 // Copy propagate to forward register uses and try to eliminate COPYs that
922 // were not coalesced.
924
925 // Run post-ra machine LICM to hoist reloads / remats.
926 //
927 // FIXME: can this move into MachineLateOptimization?
929
930 return Error::success();
931}
932
933//===---------------------------------------------------------------------===//
934/// Post RegAlloc Pass Configuration
935//===---------------------------------------------------------------------===//
936
937/// Add passes that optimize machine instructions after register allocation.
939 // Cleanup of redundant (identical) address/immediate loads.
941
942 // Branch folding must be run after regalloc and prolog/epilog insertion.
943 addMachineFunctionPass(BranchFolderPass(Opt.EnableTailMerge), PMW);
944
945 // Tail duplication.
946 // Note that duplicating tail just increases code size and degrades
947 // performance for targets that require Structured Control Flow.
948 // In addition it can also make CFG irreducible. Thus we disable it.
949 if (!TM.requiresStructuredCFG())
951
952 // Copy propagation.
954}
955
956/// Add standard basic block placement passes.
959 // Run a separate pass to collect block placement statistics.
960 if (Opt.EnableBlockPlacementStats)
962}
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 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 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.
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
@ 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.