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,
244 CodeGenFileType FileType,
245 MCContext &Ctx) {
246 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
247 TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
248 if (!MCStreamerOrErr)
249 return MCStreamerOrErr.takeError();
250 std::unique_ptr<AsmPrinter> Printer(
251 TM.getTarget().createAsmPrinter(TM, std::move(*MCStreamerOrErr)));
252 if (!Printer)
253 return createStringError("failed to create AsmPrinter");
254 MAM.registerPass([&] { return AsmPrinterAnalysis(std::move(Printer)); });
255 return Error::success();
256}
257
260 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) {
261 auto StartStopInfo = TargetPassConfig::getStartStopInfo(TM, *PIC);
262 if (!StartStopInfo)
263 return StartStopInfo.takeError();
264 setStartStopPasses(*StartStopInfo);
265
266 CompletesPipeline = StartStopInfo->StopPass.empty();
267
268 PassManagerWrapper PMW(MPM);
269 if (auto Err = buildPipelineImpl(PMW, MAM, Out, DwoOut, FileType, Ctx))
270 return Err;
271
272 return verifyStartStop(*StartStopInfo);
273}
274
277 raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx) {
278 bool PrintAsm = CompletesPipeline;
279 bool PrintMIR = !PrintAsm && FileType != CodeGenFileType::Null;
280
282 /*Force=*/true);
284 /*Force=*/true);
286 /*Force=*/true);
288 /*Force=*/true);
290 PMW,
291 /*Force=*/true);
292 addISelPasses(PMW);
293 flushFPMsToMPM(PMW);
294
295 if (PrintAsm) {
296 if (auto Err = registerAsmPrinter(MAM, Out, DwoOut, FileType, Ctx))
297 return Err;
299 }
300
301 if (auto Err = addCoreISelPasses(PMW))
302 return Err;
303
304 if (auto Err = addMachinePasses(PMW))
305 return Err;
306
307 if (PrintAsm ? !Opt.DisableVerify && TM.Options.EnableDefaultMachineVerifier
308 : Opt.VerifyMachineCode == MachineVerifierMode::End)
309 addMachineFunctionPass(MachineVerifierPass(), PMW, /*Force=*/!PrintAsm);
310
311 // We add AsmPrinter regardless if we are emitting MIR or Assembly as the
312 // final output so that -stop-before=<target>-asm-printer works. When printing
313 // MIR as the final output, we never end up running AsmPrinter.
314 addAsmPrinter(PMW);
315
316 flushFPMsToMPM(PMW, /*FreeMachineFunctions=*/!PrintMIR);
317 if (PrintAsm)
318 addAsmPrinterEnd(PMW);
319 else if (PrintMIR)
320 addModulePass(PrintMIRPass(Out), PMW, /*Force=*/true);
321
322 return Error::success();
323}
324
325void CodeGenPassBuilder::setStartStopPasses(
327 if (!Info.StartPass.empty()) {
328 Started = false;
329 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StartAfter,
330 Count = 0u](StringRef ClassName) mutable {
331 if (Count == Info.StartInstanceNum) {
332 if (AfterFlag) {
333 AfterFlag = false;
334 Started = true;
335 }
336 return Started;
337 }
338
339 auto PassName = PIC->getPassNameForClassName(ClassName);
340 if (Info.StartPass == PassName && ++Count == Info.StartInstanceNum)
341 Started = !Info.StartAfter;
342
343 return Started;
344 });
345 }
346
347 if (!Info.StopPass.empty()) {
348 Stopped = false;
349 BeforeCallbacks.emplace_back([this, &Info, AfterFlag = Info.StopAfter,
350 Count = 0u](StringRef ClassName) mutable {
351 if (Count == Info.StopInstanceNum) {
352 if (AfterFlag) {
353 AfterFlag = false;
354 Stopped = true;
355 }
356 return !Stopped;
357 }
358
359 auto PassName = PIC->getPassNameForClassName(ClassName);
360 if (Info.StopPass == PassName && ++Count == Info.StopInstanceNum)
361 Stopped = !Info.StopAfter;
362 return !Stopped;
363 });
364 }
365}
366
367Error CodeGenPassBuilder::verifyStartStop(
368 const TargetPassConfig::StartStopInfo &Info) const {
369 if (Started && Stopped)
370 return Error::success();
371
372 if (!Started)
374 "Can't find start pass \"" + Info.StartPass + "\".",
375 std::make_error_code(std::errc::invalid_argument));
376 if (!Stopped)
378 "Can't find stop pass \"" + Info.StopPass + "\".",
379 std::make_error_code(std::errc::invalid_argument));
380 return Error::success();
381}
382
386 flushFPMsToMPM(PMW);
387 }
388
390 if (TM.useEmulatedTLS())
392
393 // ObjCARCContract operates on ObjC intrinsics and must run before
394 // PreISelIntrinsicLowering.
397 flushFPMsToMPM(PMW);
398 }
401
402 addIRPasses(PMW);
405 addISelPrepare(PMW);
406}
407
408/// Add common target configurable passes that perform LLVM IR to IR transforms
409/// following machine independent optimization.
411 // Before running any passes, run the verifier to determine if the input
412 // coming from the front-end and/or optimizer is valid.
413 if (!Opt.DisableVerify)
414 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
415
416 // Run loop strength reduction before anything else.
417 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableLSR) {
418 // These passes do not use MSSA.
419 LoopPassManager LPM;
420 LPM.addPass(CanonicalizeFreezeInLoopsPass());
421 LPM.addPass(LoopStrengthReducePass());
422 if (Opt.EnableLoopTermFold)
423 LPM.addPass(LoopTermFoldPass());
425 /*UseMemorySSA=*/false),
426 PMW);
427 }
428
429 // Run GC lowering passes for builtin collectors
430 // TODO: add a pass insertion point here
432 // Explicitly check to see if we should add ShadowStackGCLowering to avoid
433 // splitting the function pipeline if we do not have to.
434 if (runBeforeAdding(ShadowStackGCLoweringPass::name())) {
435 flushFPMsToMPM(PMW);
437 }
438
439 // Make sure that no unreachable blocks are instruction selected.
441
442 // Prepare expensive constants for SelectionDAG.
443 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableConstantHoisting)
445
446 // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
447 // operands with calls to the corresponding functions in a vector library.
450
452 !Opt.DisablePartialLibcallInlining)
454
455 // Instrument function entry and exit, e.g. with calls to mcount().
456 addFunctionPass(EntryExitInstrumenterPass(/*PostInlining=*/true), PMW);
457
458 // Add scalarization of target's unsupported masked memory intrinsics pass.
459 // the unsupported intrinsic will be replaced with a chain of basic blocks,
460 // that stores/loads element one-by-one if the appropriate mask bit is set.
462
463 // Expand reduction intrinsics into shuffle sequences if the target wants to.
464 if (!Opt.DisableExpandReductions)
466
467 // Convert conditional moves to conditional jumps when profitable.
468 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableSelectOptimize)
470
471 if (Opt.EnableGlobalMergeFunc) {
472 flushFPMsToMPM(PMW);
474 }
475}
476
477/// Turn exception handling constructs into something the code generators can
478/// handle.
480 // The module's exception model is not known when the pipeline is built, so
481 // schedule the preparation pass for every model the target supports. Each
482 // pass does nothing for other models.
483 bool HasEHPrep = false;
484
485 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
486 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
487 // catch info can get misplaced when a selector ends up more than one block
488 // removed from the parent invoke(s). This could happen when a landing
489 // pad is shared by multiple invokes and is also a target of a normal
490 // edge from elsewhere.
491 if (TM.supportsExceptionModel(ExceptionHandling::SjLj)) {
493 HasEHPrep = true;
494 }
495 // We support using both GCC-style and MSVC-style exceptions on Windows, so
496 // WinEHPrepare runs in addition to DwarfEHPrepare below. Each pass will only
497 // actually run if it recognizes the personality function.
498 //
499 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
500 // on catchpads and cleanuppads because it does not outline them into
501 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
502 // should remove PHIs there.
503 if (TM.supportsExceptionModel(ExceptionHandling::WinEH) ||
504 TM.supportsExceptionModel(ExceptionHandling::Wasm)) {
506 HasEHPrep = true;
507 }
508 if (TM.supportsExceptionModel(ExceptionHandling::Wasm))
510 if (TM.supportsExceptionModel(ExceptionHandling::DwarfCFI)) {
512 HasEHPrep = true;
513 }
514
515 // If the target supports no exception model, nothing else lowers invokes.
516 if (!HasEHPrep) {
518
519 // The lower invoke pass may create unreachable code. Remove it.
521 }
522}
523
524/// Add pass to prepare the LLVM IR for code generation. This should be done
525/// before exception handling preparation passes.
527 if (getOptLevel() != CodeGenOptLevel::None && !Opt.DisableCGP)
529 // TODO: Default ctor'd RewriteSymbolPass is no-op.
530 // addPass(RewriteSymbolPass());
531}
532
533/// Add common passes that perform LLVM IR to IR transforms in preparation for
534/// instruction selection.
536 addPreISel(PMW);
537
538 if (Opt.RequiresCodeGenSCCOrder && !AddInCGSCCOrder)
540
542 // Add both the safe stack and the stack protection passes: each of them will
543 // only protect functions that have corresponding attributes.
546
547 if (Opt.PrintISelInput)
549 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"),
550 PMW);
551
553 flushFPMsToMPM(PMW);
555 }
556
557 // All passes which modify the LLVM IR are now complete; run the verifier
558 // to ensure that the IR is valid.
559 if (!Opt.DisableVerify)
560 addFunctionPass(VerifierPass(), PMW, /*Force=*/true);
561}
562
564 // Enable FastISel with -fast-isel, but allow that to be overridden.
565 TM.setO0WantsFastISel(Opt.EnableFastISelOption !=
567
568 // Determine an instruction selector.
569 enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
570 SelectorType Selector;
571
572 if (Opt.EnableFastISelOption == cl::boolOrDefault::BOU_TRUE)
573 Selector = SelectorType::FastISel;
574 else if (Opt.EnableGlobalISelOption == cl::boolOrDefault::BOU_TRUE ||
575 (TM.Options.EnableGlobalISel &&
576 Opt.EnableGlobalISelOption != cl::boolOrDefault::BOU_FALSE))
577 Selector = SelectorType::GlobalISel;
578 else if (TM.getOptLevel() == CodeGenOptLevel::None && TM.getO0WantsFastISel())
579 Selector = SelectorType::FastISel;
580 else
581 Selector = SelectorType::SelectionDAG;
582
583 // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
584 if (Selector == SelectorType::FastISel) {
585 TM.setFastISel(true);
586 TM.setGlobalISel(false);
587 } else if (Selector == SelectorType::GlobalISel) {
588 TM.setFastISel(false);
589 TM.setGlobalISel(true);
590 }
591
592 // Add instruction selector passes.
593 if (Selector == SelectorType::GlobalISel) {
594 if (auto Err = addIRTranslator(PMW))
595 return Err;
596
598
599 if (auto Err = addLegalizeMachineIR(PMW))
600 return Err;
601
602 // Before running the register bank selector, ask the target if it
603 // wants to run some passes.
605
606 if (auto Err = addRegBankSelect(PMW))
607 return Err;
608
610
611 if (auto Err = addGlobalInstructionSelect(PMW))
612 return Err;
613
614 // Pass to reset the MachineFunction if the ISel failed.
618 PMW);
619
620 // Provide a fallback path when we do not want to abort on
621 // not-yet-supported input.
623 if (auto Err = addInstSelector(PMW))
624 return Err;
625
626 } else if (auto Err = addInstSelector(PMW))
627 return Err;
628
629 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
630 // FinalizeISel.
632
633 // // Print the instruction selected machine code...
634 // printAndVerify("After Instruction Selection");
635
636 return Error::success();
637}
638
639/// Add the complete set of target-independent postISel code generator passes.
640///
641/// This can be read as the standard order of major LLVM CodeGen stages. Stages
642/// with nontrivial configuration or multiple passes are broken out below in
643/// add%Stage routines.
644///
645/// Any CodeGenPassBuilder::addXX routine may be overriden by the Target. The
646/// addPre/Post methods with empty header implementations allow injecting
647/// target-specific fixups just before or after major stages. Additionally,
648/// targets have the flexibility to change pass order within a stage by
649/// overriding default implementation of add%Stage routines below. Each
650/// technique has maintainability tradeoffs because alternate pass orders are
651/// not well supported. addPre/Post works better if the target pass is easily
652/// tied to a common pass. But if it has subtle dependencies on multiple passes,
653/// the target should override the stage instead.
655 // Add passes that optimize machine instructions in SSA form.
658 } else {
659 // If the target requests it, assign local variables to stack slots relative
660 // to one another and simplify frame index references where possible.
662 }
663
664 if (TM.Options.EnableIPRA) {
665 flushFPMsToMPM(PMW);
667 PMW, /*Force=*/true);
669 }
670
672 (Opt.EnableMachinePipeliner == cl::boolOrDefault::BOU_UNSET
674 : Opt.EnableMachinePipeliner == cl::boolOrDefault::BOU_TRUE))
676
677 // Run pre-ra passes.
678 addPreRegAlloc(PMW);
679
680 // Run register allocation and passes that are tightly coupled with it,
681 // including phi elimination and scheduling.
682 if (auto Err = Opt.OptimizeRegAlloc == cl::boolOrDefault::BOU_TRUE
684 : addFastRegAlloc(PMW))
685 return Err;
686
687 // Run post-ra passes.
688 addPostRegAlloc(PMW);
689
692
693 // Insert prolog/epilog code. Eliminate abstract frame index references...
697 }
698
700
701 /// Add passes that optimize machine instructions after register allocation.
704
705 // Expand pseudo instructions before second scheduling pass.
707
708 // Run pre-sched2 passes.
709 addPreSched2(PMW);
710
711 if (Opt.EnableImplicitNullChecks)
713
714 // Second pass scheduler.
715 // Let Target optionally insert this pass by itself at some other
716 // point.
718 !TM.targetSchedulesPostRAScheduling()) {
719 if (Opt.MISchedPostRA)
721 else
723 }
724
725 // GC
726 addGCPasses(PMW);
727
728 // Basic block placement.
731
732 // Insert before XRay Instrumentation.
734
737
738 addPreEmitPass(PMW);
739
740 if (TM.Options.EnableIPRA) {
741 // Collect register usage information and produce a register mask of
742 // clobbered registers, to be used to optimize call sites.
744 // If -print-regusage is specified, print the collected register usage info.
745 if (Opt.PrintRegUsage) {
746 flushFPMsToMPM(PMW);
748 }
749 }
750
752
754 addMachineFunctionPass(StackMapLivenessPass(), PMW);
757
758 if (TM.Options.EnableMachineOutliner &&
760 Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
761 if (Opt.EnableMachineOutliner != RunOutliner::TargetDefault ||
762 TM.supportsDefaultOutlining()) {
763 flushFPMsToMPM(PMW);
764 addModulePass(MachineOutlinerPass(Opt.EnableMachineOutliner), PMW);
765 }
766 }
767
768 if (Opt.EnableGCEmptyBlocks)
770
772
773 if (!Opt.DisableCFIFixup && TM.Options.EnableCFIFixup)
775
777
778 // Add passes that directly emit MI after all other MI passes.
779 addPreEmitPass2(PMW);
780
781 return Error::success();
782}
783
784/// Add passes that optimize machine instructions in SSA form.
786 // Pre-ra tail duplication.
788
789 // Optimize PHIs before DCE: removing dead PHI cycles may make more
790 // instructions dead.
792
793 // This pass merges large allocas. StackSlotColoring is a different pass
794 // which merges spill slots.
796
797 // If the target requests it, assign local variables to stack slots relative
798 // to one another and simplify frame index references where possible.
800
801 // With optimization, dead code should already be eliminated. However
802 // there is one known exception: lowered code for arguments that are only
803 // used by tail calls, where the tail calls reuse the incoming stack
804 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
806
807 // Allow targets to insert passes that improve instruction level parallelism,
808 // like if-conversion. Such passes will typically need dominator trees and
809 // loop info, just like LICM and CSE below.
810 addILPOpts(PMW);
811
814
815 addMachineFunctionPass(MachineSinkingPass(Opt.EnableSinkAndFold), PMW);
816
818 // Clean-up the dead code that may have been generated by peephole
819 // rewriting.
821}
822
823//===---------------------------------------------------------------------===//
824/// Register Allocation Pass Configuration
825//===---------------------------------------------------------------------===//
826
827/// Instantiate the default register allocator pass for this target for either
828/// the optimized or unoptimized allocation path. This will be added to the pass
829/// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
830/// in the optimized case.
831///
832/// A target that uses the standard regalloc pass order for fast or optimized
833/// allocation may still override this for per-target regalloc
834/// selection. But -regalloc-npm=... always takes precedence.
835/// If a target does not want to allow users to set -regalloc-npm=... at all,
836/// check if Opt.RegAlloc == RegAllocType::Unset.
838 bool Optimized) {
839 if (Optimized)
841 else
843}
844
845/// Find and instantiate the register allocation pass requested by this target
846/// at the current optimization level. Different register allocators are
847/// defined as separate passes because they may require different analysis.
848///
849/// This helper ensures that the -regalloc-npm= option is always available,
850/// even for targets that override the default allocator.
852 bool Optimized) {
853 // Use the specified -regalloc-npm={basic|greedy|fast|pbqp}
854 if (Opt.RegAlloc > RegAllocType::Default) {
855 switch (Opt.RegAlloc) {
858 break;
861 break;
862 default:
863 reportFatalUsageError("register allocator not supported yet");
864 }
865 return;
866 }
867 // -regalloc=default or unspecified, so pick based on the optimization level
868 // or ask the target for the regalloc pass.
869 addTargetRegisterAllocator(PMW, Optimized);
870}
871
873 // TODO: Ensure allocator is default or fast.
874 addRegAllocPass(PMW, false);
875 return Error::success();
876}
877
879 PassManagerWrapper &PMW) {
880 // Add the selected register allocation pass.
881 addRegAllocPass(PMW, true);
882
883 // Allow targets to change the register assignments before rewriting.
884 addPreRewrite(PMW);
885
886 // Finally rewrite virtual registers.
888
889 return Error::success();
890}
891
892/// Add the minimum set of target-independent passes that are required for
893/// register allocation. No coalescing or scheduling.
896 // RegAllocFast rewrites tied operands itself, but only when it runs.
897 bool RunRegAlloc = TM.usesPhysRegsForValues();
898 if (!RunRegAlloc || !TM.enableTiedFastRegAlloc())
900 if (!RunRegAlloc)
901 return Error::success();
902 return addRegAssignAndRewriteFast(PMW);
903}
904
905/// Add standard target-independent passes that are tightly coupled with
906/// optimized register allocation, including coalescing, machine instruction
907/// scheduling, and register allocation itself.
910
912
914
915 // LiveIntervals requires pure SSA form and no unreachable blocks.
916 // Explicit addition of UnreachableMachineBlockElim allows stopping before or
917 // after it with -stop-before/-stop-after.
919
920 // If enabled, run the SSA machine scheduler just before PHI elimination.
921 if (Opt.EnableSSAMachineScheduler) {
925 }
926
929
930 // Edge splitting is smarter with machine loop info.
934
937
938 // The machine scheduler may accidentally create disconnected components
939 // when moving subregister definitions around, avoid this by splitting them to
940 // separate vregs before. Splitting can also improve reg. allocation quality.
942
943 // PreRA instruction scheduling.
945
946 if (!TM.usesPhysRegsForValues())
947 return Error::success();
949 return Err;
950
952
953 // Allow targets to expand pseudo instructions depending on the choice of
954 // registers before MachineCopyPropagation.
955 addPostRewrite(PMW);
956
957 // Copy propagate to forward register uses and try to eliminate COPYs that
958 // were not coalesced.
960
961 // Run post-ra machine LICM to hoist reloads / remats.
962 //
963 // FIXME: can this move into MachineLateOptimization?
965
966 return Error::success();
967}
968
969//===---------------------------------------------------------------------===//
970/// Post RegAlloc Pass Configuration
971//===---------------------------------------------------------------------===//
972
973/// Add passes that optimize machine instructions after register allocation.
975 // Cleanup of redundant (identical) address/immediate loads.
977
978 // Branch folding must be run after regalloc and prolog/epilog insertion.
979 addMachineFunctionPass(BranchFolderPass(Opt.EnableTailMerge), PMW);
980
981 // Tail duplication.
982 // Note that duplicating tail just increases code size and degrades
983 // performance for targets that require Structured Control Flow.
984 // In addition it can also make CFG irreducible. Thus we disable it.
985 if (!TM.requiresStructuredCFG())
987
988 // Copy propagation.
990}
991
992/// Add standard basic block placement passes.
995 // Run a separate pass to collect block placement statistics.
996 if (Opt.EnableBlockPlacementStats)
998}
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...
if(!TBB||Cond.size()< 1) return false
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 Error buildPipelineImpl(PassManagerWrapper &PMW, ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
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
Error registerAsmPrinter(ModuleAnalysisManager &MAM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
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.