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
172// Out-of-line to anchor the vtable in this translation unit.
174
176 return make_error<StringError>("addInstSelector is not overridden",
178}
179
181 return make_error<StringError>("addIRTranslator is not overridden",
183}
184
186 return make_error<StringError>("addLegalizeMachineIR is not overridden",
188}
189
191 return make_error<StringError>("addRegBankSelect is not overridden",
193}
194
196 return make_error<StringError>("addGlobalInstructionSelect is not overridden",
198}
199
201 llvm_unreachable("addAsmPrinterBegin is not overriden");
202}
203
205 llvm_unreachable("addAsmPrinter is not overridden");
206}
207
209 llvm_unreachable("addAsmPrinterEnd is not overriden");
210}
211
213 bool FreeMachineFunctions) {
214 if (PMW.FPM.isEmpty() && PMW.MFPM.isEmpty())
215 return;
216 if (!PMW.MFPM.isEmpty()) {
217 PMW.FPM.addPass(
218 createFunctionToMachineFunctionPassAdaptor(std::move(PMW.MFPM)));
219 PMW.MFPM = MachineFunctionPassManager();
220 }
221 if (FreeMachineFunctions)
223 if (AddInCGSCCOrder) {
225 createCGSCCToFunctionPassAdaptor(std::move(PMW.FPM))));
226 } else {
227 PMW.MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PMW.FPM)));
228 }
229 PMW.FPM = FunctionPassManager();
230}
231
234 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) {
235 auto StartStopInfo = TargetPassConfig::getStartStopInfo(TM, *PIC);
236 if (!StartStopInfo)
237 return StartStopInfo.takeError();
238 setStartStopPasses(*StartStopInfo);
239
240 CompletesPipeline = StartStopInfo->StopPass.empty();
241 bool PrintAsm = CompletesPipeline;
242 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
243
244 PassManagerWrapper PMW(MPM);
245
247 /*Force=*/true);
249 /*Force=*/true);
251 /*Force=*/true);
253 /*Force=*/true);
255 PMW,
256 /*Force=*/true);
257 addISelPasses(PMW);
258 flushFPMsToMPM(PMW);
259
260 if (PrintAsm) {
261 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
262 TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
263 if (!MCStreamerOrErr)
264 return MCStreamerOrErr.takeError();
265 std::unique_ptr<AsmPrinter> Printer(
266 TM.getTarget().createAsmPrinter(TM, std::move(*MCStreamerOrErr)));
267 if (!Printer)
268 return createStringError("failed to create AsmPrinter");
269 MAM.registerPass([&] { return AsmPrinterAnalysis(std::move(Printer)); });
271 }
272
273 if (auto Err = addCoreISelPasses(PMW))
274 return Err;
275
276 if (auto Err = addMachinePasses(PMW))
277 return Err;
278
279 if (PrintAsm ? !Opt.DisableVerify && TM.Options.EnableDefaultMachineVerifier
280 : Opt.VerifyMachineCode == MachineVerifierMode::End)
281 addMachineFunctionPass(MachineVerifierPass(), PMW, /*Force=*/!PrintAsm);
282
283 // We add AsmPrinter regardless if we are emitting MIR or Assembly as the
284 // final output so that -stop-before=<target>-asm-printer works. When printing
285 // MIR as the final output, we never end up running AsmPrinter.
286 addAsmPrinter(PMW);
287
288 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/!PrintMIR);
289 if (PrintAsm)
290 addAsmPrinterEnd(PMW);
291 else if (PrintMIR)
292 addModulePass(PrintMIRPass(Out), PMW, /*Force=*/true);
293
294 return verifyStartStop(*StartStopInfo);
295}
296
297void CodeGenPassBuilder::setStartStopPasses(
299 if (!Info.StartPass.empty()) {
300 Started = false;
301 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
302 Count = 0u](StringRef ClassName) mutable {
303 if (Count == Info.StartInstanceNum) {
304 if (AfterFlag) {
305 AfterFlag = false;
306 Started = true;
307 }
308 return Started;
309 }
310
311 auto PassName = PIC->getPassNameForClassName(ClassName);
312 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
313 Started = !Info.StartAfter;
314
315 return Started;
316 });
317 }
318
319 if (!Info.StopPass.empty()) {
320 Stopped = false;
321 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
322 Count = 0u](StringRef ClassName) mutable {
323 if (Count == Info.StopInstanceNum) {
324 if (AfterFlag) {
325 AfterFlag = false;
326 Stopped = true;
327 }
328 return !Stopped;
329 }
330
331 auto PassName = PIC->getPassNameForClassName(ClassName);
332 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
333 Stopped = !Info.StopAfter;
334 return !Stopped;
335 });
336 }
337}
338
339Error CodeGenPassBuilder::verifyStartStop(
340 const TargetPassConfig::StartStopInfo &Info) const {
341 if (Started && Stopped)
342 return Error::success();
343
344 if (!Started)
346 "Can't find start pass \"" + Info.StartPass + "\".",
347 std::make_error_code(std::errc::invalid_argument));
348 if (!Stopped)
350 "Can't find stop pass \"" + Info.StopPass + "\".",
351 std::make_error_code(std::errc::invalid_argument));
352 return Error::success();
353}
354
358 flushFPMsToMPM(PMW);
359 }
360
362 if (TM.useEmulatedTLS())
364
365 // ObjCARCContract operates on ObjC intrinsics and must run before
366 // PreISelIntrinsicLowering.
369 flushFPMsToMPM(PMW);
370 }
373
374 addIRPasses(PMW);
377 addISelPrepare(PMW);
378}
379
380/// Add common target configurable passes that perform LLVM IR to IR transforms
381/// following machine independent optimization.
383 // Before running any passes, run the verifier to determine if the input
384 // coming from the front-end and/or optimizer is valid.
385 if (!Opt.DisableVerify)
386 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
387
388 // Run loop strength reduction before anything else.
389 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
390 // These passes do not use MSSA.
391 LoopPassManager LPM;
392 LPM.addPass(CanonicalizeFreezeInLoopsPass());
393 LPM.addPass(LoopStrengthReducePass());
394 if (Opt.EnableLoopTermFold)
395 LPM.addPass(LoopTermFoldPass());
397 /*UseMemorySSA=*/false),
398 PMW);
399 }
400
401 // Run GC lowering passes for builtin collectors
402 // TODO: add a pass insertion point here
404 // Explicitly check to see if we should add ShadowStackGCLowering to avoid
405 // splitting the function pipeline if we do not have to.
406 if (runBeforeAdding(ShadowStackGCLoweringPass::name())) {
407 flushFPMsToMPM(PMW);
409 }
410
411 // Make sure that no unreachable blocks are instruction selected.
413
414 // Prepare expensive constants for SelectionDAG.
415 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
417
418 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
419 // operands with calls to the corresponding functions in a vector library.
422
424 !Opt.DisablePartialLibcallInlining)
426
427 // Instrument function entry and exit, e.g. with calls to mcount().
428 addFunctionPass(EntryExitInstrumenterPass(/*PostInlining=*/true), PMW);
429
430 // Add scalarization of target's unsupported masked memory intrinsics pass.
431 // the unsupported intrinsic will be replaced with a chain of basic blocks,
432 // that stores/loads element one-by-one if the appropriate mask bit is set.
434
435 // Expand reduction intrinsics into shuffle sequences if the target wants to.
436 if (!Opt.DisableExpandReductions)
438
439 // Convert conditional moves to conditional jumps when profitable.
440 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
442
443 if (Opt.EnableGlobalMergeFunc) {
444 flushFPMsToMPM(PMW);
446 }
447}
448
449/// Turn exception handling constructs into something the code generators can
450/// handle.
452 // The module's exception model is not known when the pipeline is built, so
453 // schedule the preparation pass for every model the target supports. Each
454 // pass does nothing for other models.
455 bool HasEHPrep = false;
456
457 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
458 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
459 // catch info can get misplaced when a selector ends up more than one block
460 // removed from the parent invoke(s). This could happen when a landing
461 // pad is shared by multiple invokes and is also a target of a normal
462 // edge from elsewhere.
463 if (TM.supportsExceptionModel(ExceptionHandling::SjLj)) {
465 HasEHPrep = true;
466 }
467 // We support using both GCC-style and MSVC-style exceptions on Windows, so
468 // WinEHPrepare runs in addition to DwarfEHPrepare below. Each pass will only
469 // actually run if it recognizes the personality function.
470 //
471 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
472 // on catchpads and cleanuppads because it does not outline them into
473 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
474 // should remove PHIs there.
475 if (TM.supportsExceptionModel(ExceptionHandling::WinEH) ||
476 TM.supportsExceptionModel(ExceptionHandling::Wasm)) {
478 HasEHPrep = true;
479 }
480 if (TM.supportsExceptionModel(ExceptionHandling::Wasm))
482 if (TM.supportsExceptionModel(ExceptionHandling::DwarfCFI)) {
484 HasEHPrep = true;
485 }
486
487 // If the target supports no exception model, nothing else lowers invokes.
488 if (!HasEHPrep) {
490
491 // The lower invoke pass may create unreachable code. Remove it.
493 }
494}
495
496/// Add pass to prepare the LLVM IR for code generation. This should be done
497/// before exception handling preparation passes.
499 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
501 // TODO: Default ctor'd RewriteSymbolPass is no-op.
502 // addPass(RewriteSymbolPass());
503}
504
505/// Add common passes that perform LLVM IR to IR transforms in preparation for
506/// instruction selection.
508 addPreISel(PMW);
509
510 if (Opt.RequiresCodeGenSCCOrder && !AddInCGSCCOrder)
512
514 // Add both the safe stack and the stack protection passes: each of them will
515 // only protect functions that have corresponding attributes.
518
519 if (Opt.PrintISelInput)
521 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"),
522 PMW);
523
525 flushFPMsToMPM(PMW);
527 }
528
529 // All passes which modify the LLVM IR are now complete; run the verifier
530 // to ensure that the IR is valid.
531 if (!Opt.DisableVerify)
532 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
533}
534
536 // Enable FastISel with -fast-isel, but allow that to be overridden.
537 TM.setO0WantsFastISel(Opt.EnableFastISelOption !=
539
540 // Determine an instruction selector.
541 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
542 SelectorType Selector;
543
544 if (Opt.EnableFastISelOption == cl::boolOrDefault::BOU_TRUE)
545 Selector = SelectorType::FastISel;
546 else if (Opt.EnableGlobalISelOption == cl::boolOrDefault::BOU_TRUE ||
547 (TM.Options.EnableGlobalISel &&
548 Opt.EnableGlobalISelOption != cl::boolOrDefault::BOU_FALSE))
549 Selector = SelectorType::GlobalISel;
550 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
551 Selector = SelectorType::FastISel;
552 else
553 Selector = SelectorType::SelectionDAG;
554
555 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
556 if (Selector == SelectorType::FastISel) {
557 TM.setFastISel(true);
558 TM.setGlobalISel(false);
559 } else if (Selector == SelectorType::GlobalISel) {
560 TM.setFastISel(false);
561 TM.setGlobalISel(true);
562 }
563
564 // Add instruction selector passes.
565 if (Selector == SelectorType::GlobalISel) {
566 if (auto Err = addIRTranslator(PMW))
567 return Err;
568
570
571 if (auto Err = addLegalizeMachineIR(PMW))
572 return Err;
573
574 // Before running the register bank selector, ask the target if it
575 // wants to run some passes.
577
578 if (auto Err = addRegBankSelect(PMW))
579 return Err;
580
582
583 if (auto Err = addGlobalInstructionSelect(PMW))
584 return Err;
585
586 // Pass to reset the MachineFunction if the ISel failed.
590 PMW);
591
592 // Provide a fallback path when we do not want to abort on
593 // not-yet-supported input.
595 if (auto Err = addInstSelector(PMW))
596 return Err;
597
598 } else if (auto Err = addInstSelector(PMW))
599 return Err;
600
601 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
602 // FinalizeISel.
604
605 // // Print the instruction selected machine code...
606 // printAndVerify("After Instruction Selection");
607
608 return Error::success();
609}
610
611/// Add the complete set of target-independent postISel code generator passes.
612///
613/// This can be read as the standard order of major LLVM CodeGen stages. Stages
614/// with nontrivial configuration or multiple passes are broken out below in
615/// add%Stage routines.
616///
617/// Any CodeGenPassBuilder::addXX routine may be overriden by the Target. The
618/// addPre/Post methods with empty header implementations allow injecting
619/// target-specific fixups just before or after major stages. Additionally,
620/// targets have the flexibility to change pass order within a stage by
621/// overriding default implementation of add%Stage routines below. Each
622/// technique has maintainability tradeoffs because alternate pass orders are
623/// not well supported. addPre/Post works better if the target pass is easily
624/// tied to a common pass. But if it has subtle dependencies on multiple passes,
625/// the target should override the stage instead.
627 // Add passes that optimize machine instructions in SSA form.
630 } else {
631 // If the target requests it, assign local variables to stack slots relative
632 // to one another and simplify frame index references where possible.
634 }
635
636 if (TM.Options.EnableIPRA) {
637 flushFPMsToMPM(PMW);
639 PMW, /*Force=*/true);
641 }
642
644 (Opt.EnableMachinePipeliner == cl::boolOrDefault::BOU_UNSET
646 : Opt.EnableMachinePipeliner == cl::boolOrDefault::BOU_TRUE))
648
649 // Run pre-ra passes.
650 addPreRegAlloc(PMW);
651
652 // Run register allocation and passes that are tightly coupled with it,
653 // including phi elimination and scheduling.
654 if (auto Err = Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_TRUE
656 : addFastRegAlloc(PMW))
657 return Err;
658
659 // Run post-ra passes.
660 addPostRegAlloc(PMW);
661
664
665 // Insert prolog/epilog code. Eliminate abstract frame index references...
669 }
670
672
673 /// Add passes that optimize machine instructions after register allocation.
676
677 // Expand pseudo instructions before second scheduling pass.
679
680 // Run pre-sched2 passes.
681 addPreSched2(PMW);
682
683 if (Opt.EnableImplicitNullChecks)
685
686 // Second pass scheduler.
687 // Let Target optionally insert this pass by itself at some other
688 // point.
690 !TM.targetSchedulesPostRAScheduling()) {
691 if (Opt.MISchedPostRA)
693 else
695 }
696
697 // GC
698 addGCPasses(PMW);
699
700 // Basic block placement.
703
704 // Insert before XRay Instrumentation.
706
709
710 addPreEmitPass(PMW);
711
712 if (TM.Options.EnableIPRA) {
713 // Collect register usage information and produce a register mask of
714 // clobbered registers, to be used to optimize call sites.
716 // If -print-regusage is specified, print the collected register usage info.
717 if (Opt.PrintRegUsage) {
718 flushFPMsToMPM(PMW);
720 }
721 }
722
724
726 addMachineFunctionPass(StackMapLivenessPass(), PMW);
727 addMachineFunctionPass(LiveDebugValuesPass(TM.shouldEmitDebugEntryValues()),
728 PMW);
730
731 if (TM.Options.EnableMachineOutliner &&
733 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
734 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
735 TM.supportsDefaultOutlining()) {
736 flushFPMsToMPM(PMW);
737 addModulePass(MachineOutlinerPass(Opt.EnableMachineOutliner), PMW);
738 }
739 }
740
741 if (Opt.EnableGCEmptyBlocks)
743
745
746 if (!Opt.DisableCFIFixup && TM.Options.EnableCFIFixup)
748
750
751 // Add passes that directly emit MI after all other MI passes.
752 addPreEmitPass2(PMW);
753
754 return Error::success();
755}
756
757/// Add passes that optimize machine instructions in SSA form.
759 // Pre-ra tail duplication.
761
762 // Optimize PHIs before DCE: removing dead PHI cycles may make more
763 // instructions dead.
765
766 // This pass merges large allocas. StackSlotColoring is a different pass
767 // which merges spill slots.
769
770 // If the target requests it, assign local variables to stack slots relative
771 // to one another and simplify frame index references where possible.
773
774 // With optimization, dead code should already be eliminated. However
775 // there is one known exception: lowered code for arguments that are only
776 // used by tail calls, where the tail calls reuse the incoming stack
777 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
779
780 // Allow targets to insert passes that improve instruction level parallelism,
781 // like if-conversion. Such passes will typically need dominator trees and
782 // loop info, just like LICM and CSE below.
783 addILPOpts(PMW);
784
787
788 addMachineFunctionPass(MachineSinkingPass(Opt.EnableSinkAndFold), PMW);
789
791 // Clean-up the dead code that may have been generated by peephole
792 // rewriting.
794}
795
796//===---------------------------------------------------------------------===//
797/// Register Allocation Pass Configuration
798//===---------------------------------------------------------------------===//
799
800/// Instantiate the default register allocator pass for this target for either
801/// the optimized or unoptimized allocation path. This will be added to the pass
802/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
803/// in the optimized case.
804///
805/// A target that uses the standard regalloc pass order for fast or optimized
806/// allocation may still override this for per-target regalloc
807/// selection. But -regalloc-npm=... always takes precedence.
808/// If a target does not want to allow users to set -regalloc-npm=... at all,
809/// check if Opt.RegAlloc == RegAllocType::Unset.
811 bool Optimized) {
812 if (Optimized)
814 else
816}
817
818/// Find and instantiate the register allocation pass requested by this target
819/// at the current optimization level. Different register allocators are
820/// defined as separate passes because they may require different analysis.
821///
822/// This helper ensures that the -regalloc-npm= option is always available,
823/// even for targets that override the default allocator.
825 bool Optimized) {
826 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
827 if (Opt.RegAlloc > RegAllocType::Default) {
828 switch (Opt.RegAlloc) {
831 break;
834 break;
835 default:
836 reportFatalUsageError("register allocator not supported yet");
837 }
838 return;
839 }
840 // -regalloc=default or unspecified, so pick based on the optimization level
841 // or ask the target for the regalloc pass.
842 addTargetRegisterAllocator(PMW, Optimized);
843}
844
846 // TODO: Ensure allocator is default or fast.
847 addRegAllocPass(PMW, false);
848 return Error::success();
849}
850
853 // Add the selected register allocation pass.
854 addRegAllocPass(PMW, true);
855
856 // Allow targets to change the register assignments before rewriting.
857 addPreRewrite(PMW);
858
859 // Finally rewrite virtual registers.
861
862 return true;
863}
864
865/// Add the minimum set of target-independent passes that are required for
866/// register allocation. No coalescing or scheduling.
873
874/// Add standard target-independent passes that are tightly coupled with
875/// optimized register allocation, including coalescing, machine instruction
876/// scheduling, and register allocation itself.
879
881
883
884 // LiveIntervals requires pure SSA form and no unreachable blocks.
885 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
886 // after it with -stop-before/-stop-after.
888
889 // If enabled, run the SSA machine scheduler just before PHI elimination.
890 if (Opt.EnableSSAMachineScheduler) {
894 }
895
898
899 // Edge splitting is smarter with machine loop info.
903
906
907 // The machine scheduler may accidentally create disconnected components
908 // when moving subregister definitions around, avoid this by splitting them to
909 // separate vregs before. Splitting can also improve reg. allocation quality.
911
912 // PreRA instruction scheduling.
914
916 if (!AddedPasses)
917 return AddedPasses.takeError();
918 if (!AddedPasses.get())
919 return Error::success();
920
922
923 // Allow targets to expand pseudo instructions depending on the choice of
924 // registers before MachineCopyPropagation.
925 addPostRewrite(PMW);
926
927 // Copy propagate to forward register uses and try to eliminate COPYs that
928 // were not coalesced.
930
931 // Run post-ra machine LICM to hoist reloads / remats.
932 //
933 // FIXME: can this move into MachineLateOptimization?
935
936 return Error::success();
937}
938
939//===---------------------------------------------------------------------===//
940/// Post RegAlloc Pass Configuration
941//===---------------------------------------------------------------------===//
942
943/// Add passes that optimize machine instructions after register allocation.
945 // Cleanup of redundant (identical) address/immediate loads.
947
948 // Branch folding must be run after regalloc and prolog/epilog insertion.
949 addMachineFunctionPass(BranchFolderPass(Opt.EnableTailMerge), PMW);
950
951 // Tail duplication.
952 // Note that duplicating tail just increases code size and degrades
953 // performance for targets that require Structured Control Flow.
954 // In addition it can also make CFG irreducible. Thus we disable it.
955 if (!TM.requiresStructuredCFG())
957
958 // Copy propagation.
960}
961
962/// Add standard basic block placement passes.
965 // Run a separate pass to collect block placement statistics.
966 if (Opt.EnableBlockPlacementStats)
968}
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...
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.
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.