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