LLVM 24.0.0git
PassBuilderPipelines.cpp
Go to the documentation of this file.
1//===- Construction of pass pipelines -------------------------------------===//
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/// \file
9///
10/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
14///
15//===----------------------------------------------------------------------===//
16
17#include "PassesOptions.h"
18#include "llvm/ADT/Statistic.h"
30#include "llvm/IR/PassManager.h"
31#include "llvm/IR/Verifier.h"
32#include "llvm/Pass.h"
162
163using namespace llvm;
164
165namespace llvm {
167
169
171} // namespace llvm
172
174 const cl::LibraryOptionsContext &LibraryOptions) const {
175 const PassesOptions &Opts = LibraryOptions.get<PassesOptions>();
176 PipelineTuningOptions R = *this;
177 R.LoopInterchange = LoopInterchange.value_or(Opts.enable_loopinterchange);
178 R.ForgetAllSCEVInLoopUnroll = ForgetAllSCEVInLoopUnroll.value_or(
179 getForgetSCEVInLoopUnroll(LibraryOptions));
180 R.LicmMssaOptCap = LicmMssaOptCap.value_or(getLicmMssaOptCap(LibraryOptions));
181 R.LicmMssaNoAccForPromotionCap = LicmMssaNoAccForPromotionCap.value_or(
182 getLicmMssaNoAccForPromotionCap(LibraryOptions));
183 R.MergeFunctions = MergeFunctions.value_or(Opts.enable_merge_functions);
184 R.MaxDevirtIterations =
185 MaxDevirtIterations.value_or(getMaxDevirtIterations(LibraryOptions));
186 R.EagerlyInvalidateAnalyses =
187 EagerlyInvalidateAnalyses.value_or(Opts.eagerly_invalidate_analyses);
188 R.DevirtualizeSpeculatively = DevirtualizeSpeculatively.value_or(
189 Opts.enable_devirtualize_speculatively);
190 return R;
191}
192
194 OptimizationLevel Level) {
195 for (auto &C : PeepholeEPCallbacks)
196 C(FPM, Level);
197}
200 for (auto &C : LateLoopOptimizationsEPCallbacks)
201 C(LPM, Level);
202}
204 OptimizationLevel Level) {
205 for (auto &C : LoopOptimizerEndEPCallbacks)
206 C(LPM, Level);
207}
210 for (auto &C : ScalarOptimizerLateEPCallbacks)
211 C(FPM, Level);
212}
214 OptimizationLevel Level) {
215 for (auto &C : CGSCCOptimizerLateEPCallbacks)
216 C(CGPM, Level);
217}
219 OptimizationLevel Level) {
220 for (auto &C : VectorizerStartEPCallbacks)
221 C(FPM, Level);
222}
224 OptimizationLevel Level) {
225 for (auto &C : VectorizerEndEPCallbacks)
226 C(FPM, Level);
227}
229 OptimizationLevel Level,
231 for (auto &C : OptimizerEarlyEPCallbacks)
232 C(MPM, Level, Phase);
233}
235 OptimizationLevel Level,
237 for (auto &C : OptimizerLastEPCallbacks)
238 C(MPM, Level, Phase);
239}
242 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
243 C(MPM, Level);
244}
247 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
248 C(MPM, Level);
249}
252 for (auto &C : ThinLinkTimeOptimizationEarlyEPCallbacks)
253 C(MPM, Level);
254}
257 for (auto &C : ThinLinkTimeOptimizationLastEPCallbacks)
258 C(MPM, Level);
259}
261 OptimizationLevel Level) {
262 for (auto &C : PipelineStartEPCallbacks)
263 C(MPM, Level);
264}
267 for (auto &C : PipelineEarlySimplificationEPCallbacks)
268 C(MPM, Level, Phase);
269}
270
271// Get IR stats with InstCount before/after the optimization pipeline
273 bool IsPreOptimization) {
274 if (AreStatisticsEnabled()) {
275 MPM.addPass(
278 FunctionPropertiesStatisticsPass(IsPreOptimization)));
279 }
280}
281
282// Add passes to run at the start of the pipeline. This includes things like
283// statistics passes.
285 const PassesOptions &Opts) {
286 instructionCountersPass(MPM, /*IsPreOptimization=*/true);
289}
290
291// Add passes to run at the end of the pipeline. This includes things like
292// statistics passes.
294 const PassesOptions &Opts) {
295 instructionCountersPass(MPM, /*IsPreOptimization=*/false);
298}
299
300// Helper to add AnnotationRemarksPass.
304
305// Helper to check if the current compilation phase is preparing for LTO
310
311// Helper to check if the current compilation phase is preparing for FullLTO
312[[maybe_unused]] static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase) {
314}
315
316// Helper to check if the current compilation phase is preparing for ThinLTO
320
321// Helper to check if the current compilation phase is LTO backend
326
327// Helper to check if the current compilation phase is FullLTO backend
331
332// Helper to check if the current compilation phase is ThinLTO backend
336
337// Helper to wrap conditionally Coro passes.
339 // TODO: Skip passes according to Phase.
340 ModulePassManager CoroPM;
341 CoroPM.addPass(CoroEarlyPass());
342 CGSCCPassManager CGPM;
343 CGPM.addPass(CoroSplitPass());
344 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
345 CoroPM.addPass(CoroCleanupPass());
346 CoroPM.addPass(GlobalDCEPass());
347 return CoroConditionalWrapper(std::move(CoroPM));
348}
349
351 OptimizationLevel Level) {
352 return getInlineParamsFromOptLevel(Context, static_cast<unsigned>(Level));
353}
354
356 const LLVMContext &Context,
357 OptimizationLevel Level,
359 const PassesOptions &Opts = getPassesOptions(Context);
360 InlineParams IP = ::getInlineParamsFromOptLevel(Context, Level);
361 if (Opts.enable_module_inliner)
362 MPM.addPass(ModuleInlinerPass(IP, Opts.enable_ml_inliner, Phase));
363 else
365 IP,
366 /* MandatoryFirst */ true,
368}
369
370// TODO: Investigate the cost/benefit of tail call elimination on debugging.
372PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
374
376
378 FPM.addPass(CountVisitsPass());
379
380 // Form SSA out of local memory accesses after breaking apart aggregates into
381 // scalars.
382 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
383
384 // Catch trivial redundancies
385 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
386
387 // Hoisting of scalars and load expressions.
388 FPM.addPass(
389 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
390 FPM.addPass(InstCombinePass());
391
392 FPM.addPass(LibCallsShrinkWrapPass());
393
394 invokePeepholeEPCallbacks(FPM, Level);
395
396 FPM.addPass(
397 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
398
399 // Form canonically associated expression trees, and simplify the trees using
400 // basic mathematical properties. For example, this will form (nearly)
401 // minimal multiplication trees.
402 FPM.addPass(ReassociatePass());
403
404 // Add the primary loop simplification pipeline.
405 // FIXME: Currently this is split into two loop pass pipelines because we run
406 // some function passes in between them. These can and should be removed
407 // and/or replaced by scheduling the loop pass equivalents in the correct
408 // positions. But those equivalent passes aren't powerful enough yet.
409 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
410 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
411 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
412 // `LoopInstSimplify`.
413 LoopPassManager LPM1, LPM2;
414
415 // Simplify the loop body. We do this initially to clean up after other loop
416 // passes run, either when iterating on a loop or on inner loops with
417 // implications on the outer loop.
418 LPM1.addPass(LoopInstSimplifyPass());
419 LPM1.addPass(LoopSimplifyCFGPass());
420
421 // Try to remove as much code from the loop header as possible,
422 // to reduce amount of IR that will have to be duplicated. However,
423 // do not perform speculative hoisting the first time as LICM
424 // will destroy metadata that may not need to be destroyed if run
425 // after loop rotation.
426 // TODO: Investigate promotion cap for O1.
427 LPM1.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
428 /*AllowSpeculation=*/false));
429
430 LPM1.addPass(
431 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
432 // TODO: Investigate promotion cap for O1.
433 LPM1.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
434 /*AllowSpeculation=*/true));
435 LPM1.addPass(SimpleLoopUnswitchPass());
436 if (Opts.enable_loop_flatten)
437 LPM1.addPass(LoopFlattenPass());
438
439 LPM2.addPass(LoopIdiomRecognizePass());
440 LPM2.addPass(IndVarSimplifyPass());
441
443
444 LPM2.addPass(LoopDeletionPass());
445
446 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
447 // because it changes IR to makes profile annotation in back compile
448 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
449 // attributes so we need to make sure and allow the full unroll pass to pay
450 // attention to it.
451 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
452 PGOOpt->Action != PGOOptions::SampleUse)
453 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
454 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
455 *PTO.ForgetAllSCEVInLoopUnroll));
456
458
459 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
460 /*UseMemorySSA=*/true));
461 FPM.addPass(
462 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
463 FPM.addPass(InstCombinePass());
464 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
465 // *All* loop passes must preserve it, in order to be able to use it.
466 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
467 /*UseMemorySSA=*/false));
468
469 // Delete small array after loop unroll.
470 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
471
472 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
473 FPM.addPass(MemCpyOptPass());
474
475 // Sparse conditional constant propagation.
476 // FIXME: It isn't clear why we do this *after* loop passes rather than
477 // before...
478 FPM.addPass(SCCPPass());
479
480 // Delete dead bit computations (instcombine runs after to fold away the dead
481 // computations, and then ADCE will run later to exploit any new DCE
482 // opportunities that creates).
483 FPM.addPass(BDCEPass());
484
485 // Run instcombine after redundancy and dead bit elimination to exploit
486 // opportunities opened up by them.
487 FPM.addPass(InstCombinePass());
488 invokePeepholeEPCallbacks(FPM, Level);
489
490 FPM.addPass(CoroElidePass());
491
493
494 // Finally, do an expensive DCE pass to catch all the dead code exposed by
495 // the simplifications and basic cleanup after all the simplifications.
496 // TODO: Investigate if this is too expensive.
497 FPM.addPass(ADCEPass());
498 FPM.addPass(
499 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
500 FPM.addPass(InstCombinePass());
501 invokePeepholeEPCallbacks(FPM, Level);
502
503 return FPM;
504}
505
509 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
510
511 // The O1 pipeline has a separate pipeline creation function to simplify
512 // construction readability.
513 if (Level == OptimizationLevel::O1)
514 return buildO1FunctionSimplificationPipeline(Level, Phase);
515
517
520
521 // Form SSA out of local memory accesses after breaking apart aggregates into
522 // scalars.
524
525 // Catch trivial redundancies
526 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
529
530 // Hoisting of scalars and load expressions.
531 if (Opts.enable_gvn_hoist)
532 FPM.addPass(GVNHoistPass());
533
534 // Global value numbering based sinking.
535 if (Opts.enable_gvn_sink) {
536 FPM.addPass(GVNSinkPass());
537 FPM.addPass(
538 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
539 }
540
541 // Speculative execution if the target has divergent branches; otherwise nop.
542 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
543
544 // Optimize based on known information about branches, and cleanup afterward.
547
548 // Jump table to switch conversion.
549 if (Opts.enable_jump_table_to_switch)
551
552 FPM.addPass(
553 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
557
558 invokePeepholeEPCallbacks(FPM, Level);
559
560 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
561 // using the size value profile. Don't perform this when optimizing for size.
562 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse)
564
565 FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
566 isInstrumentedPGOUse()));
567 FPM.addPass(
568 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
569
570 // Form canonically associated expression trees, and simplify the trees using
571 // basic mathematical properties. For example, this will form (nearly)
572 // minimal multiplication trees.
574
575 if (Opts.enable_constraint_elimination)
577
578 // Add the primary loop simplification pipeline.
579 // FIXME: Currently this is split into two loop pass pipelines because we run
580 // some function passes in between them. These can and should be removed
581 // and/or replaced by scheduling the loop pass equivalents in the correct
582 // positions. But those equivalent passes aren't powerful enough yet.
583 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
584 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
585 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
586 // `LoopInstSimplify`.
587 LoopPassManager LPM1, LPM2;
588
589 // Simplify the loop body. We do this initially to clean up after other loop
590 // passes run, either when iterating on a loop or on inner loops with
591 // implications on the outer loop.
592 LPM1.addPass(LoopInstSimplifyPass());
593 LPM1.addPass(LoopSimplifyCFGPass());
594
595 // Try to remove as much code from the loop header as possible,
596 // to reduce amount of IR that will have to be duplicated. However,
597 // do not perform speculative hoisting the first time as LICM
598 // will destroy metadata that may not need to be destroyed if run
599 // after loop rotation.
600 // TODO: Investigate promotion cap for O1.
601 LPM1.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
602 /*AllowSpeculation=*/false));
603
604 LPM1.addPass(
605 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
606 // TODO: Investigate promotion cap for O1.
607 LPM1.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
608 /*AllowSpeculation=*/true));
609 LPM1.addPass(
610 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
611 if (Opts.enable_loop_flatten)
612 LPM1.addPass(LoopFlattenPass());
613
614 LPM2.addPass(LoopIdiomRecognizePass());
615 LPM2.addPass(IndVarSimplifyPass());
616
617 {
619 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
621 LPM2.addPass(std::move(ExtraPasses));
622 }
623
625
626 LPM2.addPass(LoopDeletionPass());
627
628 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
629 // because it changes IR to makes profile annotation in back compile
630 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
631 // attributes so we need to make sure and allow the full unroll pass to pay
632 // attention to it.
633 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
634 PGOOpt->Action != PGOOptions::SampleUse)
635 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
636 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
637 *PTO.ForgetAllSCEVInLoopUnroll));
638
640
641 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
642 /*UseMemorySSA=*/true));
643 FPM.addPass(
644 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
646 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
647 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
648 // *All* loop passes must preserve it, in order to be able to use it.
649 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
650 /*UseMemorySSA=*/false));
651
652 // Delete small array after loop unroll.
654
655 // Try vectorization/scalarization transforms that are both improvements
656 // themselves and can allow further folds with GVN and InstCombine.
657 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
658
659 // Eliminate redundancies.
661 if (Opts.enable_newgvn)
662 FPM.addPass(NewGVNPass());
663 else
664 FPM.addPass(GVNPass());
665
666 // Sparse conditional constant propagation.
667 // FIXME: It isn't clear why we do this *after* loop passes rather than
668 // before...
669 FPM.addPass(SCCPPass());
670
671 // Delete dead bit computations (instcombine runs after to fold away the dead
672 // computations, and then ADCE will run later to exploit any new DCE
673 // opportunities that creates).
674 FPM.addPass(BDCEPass());
675
676 // Run instcombine after redundancy and dead bit elimination to exploit
677 // opportunities opened up by them.
679 invokePeepholeEPCallbacks(FPM, Level);
680
681 // Re-consider control flow based optimizations after redundancy elimination,
682 // redo DCE, etc.
683 if (Opts.enable_dfa_jump_thread)
685
688
689 // Finally, do an expensive DCE pass to catch all the dead code exposed by
690 // the simplifications and basic cleanup after all the simplifications.
691 // TODO: Investigate if this is too expensive.
692 FPM.addPass(ADCEPass());
693
694 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
695 FPM.addPass(MemCpyOptPass());
696
697 FPM.addPass(DSEPass());
699
701 LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
702 /*AllowSpeculation=*/true),
703 /*UseMemorySSA=*/true));
704
705 FPM.addPass(CoroElidePass());
706
708
710 .convertSwitchRangeToICmp(true)
711 .convertSwitchToArithmetic(true)
712 .hoistCommonInsts(true)
713 .sinkCommonInsts(true)));
715 invokePeepholeEPCallbacks(FPM, Level);
716
717 return FPM;
718}
719
720void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
723 MPM.addPass(AssignGUIDPass());
724}
725
726void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
727 OptimizationLevel Level,
728 ThinOrFullLTOPhase LTOPhase,
729 bool IgnoreProfile) {
730 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
731 if (Opts.disable_preinline)
732 return;
733 InlineParams IP;
734
735 IP.DefaultThreshold = Opts.preinline_threshold;
736 IP.IgnoreProfile = IgnoreProfile;
737
738 // FIXME: The hint threshold has the same value used by the regular inliner
739 // when not optimzing for size. This should probably be lowered after
740 // performance testing.
741 // FIXME: this comment is cargo culted from the old pass manager, revisit).
742 IP.HintThreshold = 325;
743 IP.OptSizeHintThreshold = Opts.preinline_threshold;
745 IP, /* MandatoryFirst */ true,
747 CGSCCPassManager &CGPipeline = MIWP.getPM();
748
750 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
751 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
752 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
753 true))); // Merge & remove basic blocks.
754 FPM.addPass(InstCombinePass()); // Combine silly sequences.
755 invokePeepholeEPCallbacks(FPM, Level);
756
757 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
758 std::move(FPM), *PTO.EagerlyInvalidateAnalyses));
759
760 MPM.addPass(std::move(MIWP));
761
762 // Delete anything that is now dead to make sure that we don't instrument
763 // dead code. Instrumentation can end up keeping dead code around and
764 // dramatically increase code size.
765 MPM.addPass(GlobalDCEPass());
766}
767
768void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
769 OptimizationLevel Level) {
770 if (Opts.enable_post_pgo_loop_rotation) {
771 // Disable header duplication in loop rotation at -Oz.
773 createFunctionToLoopPassAdaptor(LoopRotatePass(),
774 /*UseMemorySSA=*/false),
775 *PTO.EagerlyInvalidateAnalyses));
776 }
777}
778
779void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
780 OptimizationLevel Level, bool RunProfileGen,
781 bool IsCS, bool AtomicCounterUpdate,
782 std::string ProfileFile,
783 std::string ProfileRemappingFile) {
784 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
785
786 if (!RunProfileGen) {
787 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
788 MPM.addPass(
789 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
790 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
791 // RequireAnalysisPass for PSI before subsequent non-module passes.
792 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
793 return;
794 }
795
796 // Perform PGO instrumentation.
797 MPM.addPass(PGOInstrumentationGen(IsCS ? PGOInstrumentationType::CSFDO
799
800 addPostPGOLoopRotation(MPM, Level);
801 // Add the profile lowering pass.
802 InstrProfOptions Options;
803 if (!ProfileFile.empty())
804 Options.InstrProfileOutput = ProfileFile;
805 // Do counter promotion at Level greater than O0.
806 Options.DoCounterPromotion = true;
807 Options.UseBFIInPromotion = IsCS;
808 if (Opts.enable_sampled_instrumentation) {
809 Options.Sampling = true;
810 // With sampling, there is little beneifit to enable counter promotion.
811 // But note that sampling does work with counter promotion.
812 Options.DoCounterPromotion = false;
813 }
814 Options.Atomic = AtomicCounterUpdate;
815 MPM.addPass(InstrProfilingLoweringPass(Options, IsCS));
816}
817
819 bool RunProfileGen, bool IsCS,
820 bool AtomicCounterUpdate,
821 std::string ProfileFile,
822 std::string ProfileRemappingFile) {
823 if (!RunProfileGen) {
824 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
825 MPM.addPass(
826 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
827 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
828 // RequireAnalysisPass for PSI before subsequent non-module passes.
830 return;
831 }
832
833 // Perform PGO instrumentation.
836 // Add the profile lowering pass.
838 if (!ProfileFile.empty())
839 Options.InstrProfileOutput = ProfileFile;
840 // Do not do counter promotion at O0.
841 Options.DoCounterPromotion = false;
842 Options.UseBFIInPromotion = IsCS;
843 Options.Atomic = AtomicCounterUpdate;
845}
846
850 InlineParams IP;
851 if (PTO.InlinerThreshold == -1)
852 IP = ::getInlineParamsFromOptLevel(Context, Level);
853 else
854 IP = getInlineParams(Context, PTO.InlinerThreshold);
855 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
856 // set hot-caller threshold to 0 to disable hot
857 // callsite inline (as much as possible [1]) because it makes
858 // profile annotation in the backend inaccurate.
859 //
860 // [1] Note the cost of a function could be below zero due to erased
861 // prologue / epilogue.
862 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
864
865 if (PGOOpt)
866 IP.EnableDeferral = Opts.enable_npm_pgo_inline_deferral;
867
868 ModuleInlinerWrapperPass MIWP(IP, Opts.mandatory_inlining_first,
869 InlineContext{Phase, InlinePass::CGSCCInliner},
870 Opts.enable_ml_inliner,
871 *PTO.MaxDevirtIterations);
872
873 // Require the GlobalsAA analysis for the module so we can query it within
874 // the CGSCC pipeline.
875 if (Opts.enable_global_analyses) {
877 // Invalidate AAManager so it can be recreated and pick up the newly
878 // available GlobalsAA.
879 MIWP.addModulePass(
881 }
882
883 // Require the ProfileSummaryAnalysis for the module so we can query it within
884 // the inliner pass.
886
887 // Now begin the main postorder CGSCC pipeline.
888 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
889 // manager and trying to emulate its precise behavior. Much of this doesn't
890 // make a lot of sense and we should revisit the core CGSCC structure.
891 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
892
893 // Note: historically, the PruneEH pass was run first to deduce nounwind and
894 // generally clean up exception handling overhead. It isn't clear this is
895 // valuable as the inliner doesn't currently care whether it is inlining an
896 // invoke or a call.
897
898 if (Opts.attributor_enable & AttributorRunOption::CGSCC)
899 MainCGPipeline.addPass(AttributorCGSCCPass());
900
901 // Deduce function attributes. We do another run of this after the function
902 // simplification pipeline, so this only needs to run when it could affect the
903 // function simplification pipeline, which is only the case with recursive
904 // functions.
905 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT) {
906 MainCGPipeline.addPass(AttributorLightCGSCCPass());
907 } else {
908 MainCGPipeline.addPass(
909 PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
910 }
911
912 // When at O3 add argument promotion to the pass pipeline.
913 // FIXME: It isn't at all clear why this should be limited to O3.
914 if (Level == OptimizationLevel::O3)
915 MainCGPipeline.addPass(ArgumentPromotionPass());
916
917 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
918 // there are no OpenMP runtime calls present in the module.
919 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
920 MainCGPipeline.addPass(OpenMPOptCGSCCPass(Phase));
921
922 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
923
924 // Add the core function simplification pipeline nested inside the
925 // CGSCC walk.
928 *PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
929
930 // Finally, deduce any function attributes based on the fully simplified
931 // function.
932 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT)
933 MainCGPipeline.addPass(AttributorLightCGSCCPass());
934 else
935 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
936
937 // Mark that the function is fully simplified and that it shouldn't be
938 // simplified again if we somehow revisit it due to CGSCC mutations unless
939 // it's been modified since.
942
943 if (!isThinLTOPreLink(Phase)) {
944 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
945 MainCGPipeline.addPass(CoroAnnotationElidePass());
946 }
947
948 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
951
952 return MIWP;
953}
954
959
960 InlineParams IP = ::getInlineParamsFromOptLevel(Context, Level);
961 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
962 // set hot-caller threshold to 0 to disable hot
963 // callsite inline (as much as possible [1]) because it makes
964 // profile annotation in the backend inaccurate.
965 //
966 // [1] Note the cost of a function could be below zero due to erased
967 // prologue / epilogue.
968 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
970
971 if (PGOOpt)
972 IP.EnableDeferral = Opts.enable_npm_pgo_inline_deferral;
973
974 // The inline deferral logic is used to avoid losing some
975 // inlining chance in future. It is helpful in SCC inliner, in which
976 // inlining is processed in bottom-up order.
977 // While in module inliner, the inlining order is a priority-based order
978 // by default. The inline deferral is unnecessary there. So we disable the
979 // inline deferral logic in module inliner.
980 IP.EnableDeferral = false;
981
982 MPM.addPass(ModuleInlinerPass(IP, Opts.enable_ml_inliner, Phase));
984 MPM.addPass(GlobalOptPass());
985 MPM.addPass(GlobalDCEPass());
986 MPM.addPass(AssignGUIDPass());
987 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
988 }
989
992 *PTO.EagerlyInvalidateAnalyses));
993
994 if (!isThinLTOPreLink(Phase)) {
997 MPM.addPass(
999 }
1000
1001 return MPM;
1002}
1003
1007 assert(Level != OptimizationLevel::O0 &&
1008 "Should not be used for O0 pipeline");
1009
1011 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
1012
1014
1015 // Place pseudo probe instrumentation as the first pass of the pipeline to
1016 // minimize the impact of optimization changes.
1017 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && !isThinLTOPostLink(Phase))
1019
1020 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1021
1022 // In ThinLTO mode, when flattened profile is used, all the available
1023 // profile information will be annotated in PreLink phase so there is
1024 // no need to load the profile again in PostLink.
1025 bool LoadSampleProfile = HasSampleProfile && !(Opts.flattened_profile_used &&
1027
1028 // During the ThinLTO backend phase we perform early indirect call promotion
1029 // here, before globalopt. Otherwise imported available_externally functions
1030 // look unreferenced and are removed. If we are going to load the sample
1031 // profile then defer until later.
1032 // TODO: See if we can move later and consolidate with the location where
1033 // we perform ICP when we are loading a sample profile.
1034 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1035 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1036 // determine whether the new direct calls are annotated with prof metadata.
1037 // Ideally this should be determined from whether the IR is annotated with
1038 // sample profile, and not whether the a sample profile was provided on the
1039 // command line. E.g. for flattened profiles where we will not be reloading
1040 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1041 // provide the sample profile file.
1042 if (isThinLTOPostLink(Phase) && !LoadSampleProfile)
1043 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1044
1045 // Create an early function pass manager to cleanup the output of the
1046 // frontend. Not necessary with LTO post link pipelines since the pre link
1047 // pipeline already cleaned up the frontend output.
1048 if (!isThinLTOPostLink(Phase)) {
1049 // Do basic inference of function attributes from known properties of system
1050 // libraries and other oracles.
1052 MPM.addPass(CoroEarlyPass());
1053
1054 FunctionPassManager EarlyFPM;
1055 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1056 // Lower llvm.expect to metadata before attempting transforms.
1057 // Compare/branch metadata may alter the behavior of passes like
1058 // SimplifyCFG.
1060 EarlyFPM.addPass(SimplifyCFGPass());
1062 EarlyFPM.addPass(EarlyCSEPass());
1063 if (Level == OptimizationLevel::O3)
1064 EarlyFPM.addPass(CallSiteSplittingPass());
1066 std::move(EarlyFPM), *PTO.EagerlyInvalidateAnalyses));
1067 }
1068
1069 if (LoadSampleProfile) {
1070 // Annotate sample profile right after early FPM to ensure freshness of
1071 // the debug info.
1073 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS));
1074 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1075 // RequireAnalysisPass for PSI before subsequent non-module passes.
1077 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1078 // for the profile annotation to be accurate in the LTO backend.
1079 if (!isLTOPreLink(Phase))
1080 // We perform early indirect call promotion here, before globalopt.
1081 // This is important for the ThinLTO backend phase because otherwise
1082 // imported available_externally functions look unreferenced and are
1083 // removed.
1084 MPM.addPass(
1085 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1086 }
1087
1088 // Try to perform OpenMP specific optimizations on the module. This is a
1089 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1091
1092 if (Opts.attributor_enable & AttributorRunOption::MODULE)
1093 MPM.addPass(AttributorPass());
1094 else if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1096
1097 // Lower type metadata and the type.test intrinsic in the ThinLTO
1098 // post link pipeline after ICP. This is to enable usage of the type
1099 // tests in ICP sequences.
1102
1104
1105 // Interprocedural constant propagation now that basic cleanup has occurred
1106 // and prior to optimizing globals.
1107 // FIXME: This position in the pipeline hasn't been carefully considered in
1108 // years, it should be re-analyzed.
1109 MPM.addPass(
1110 IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/!isLTOPreLink(Phase))));
1111
1112 // Attach metadata to indirect call sites indicating the set of functions
1113 // they may target at run-time. This should follow IPSCCP.
1115
1116 // Optimize globals to try and fold them into constants.
1117 MPM.addPass(GlobalOptPass());
1118
1119 // Create a small function pass pipeline to cleanup after all the global
1120 // optimizations.
1121 FunctionPassManager GlobalCleanupPM;
1122 // FIXME: Should this instead by a run of SROA?
1123 GlobalCleanupPM.addPass(PromotePass());
1124 GlobalCleanupPM.addPass(InstCombinePass());
1125 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1126 GlobalCleanupPM.addPass(
1127 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1129 std::move(GlobalCleanupPM), *PTO.EagerlyInvalidateAnalyses));
1130
1131 // We already asserted this happens in non-FullLTOPostLink earlier.
1132 const bool IsPreLink = !isThinLTOPostLink(Phase);
1133 // Enable contextual profiling instrumentation.
1134 const bool IsCtxProfGen =
1136 Context.getLibraryOptions());
1137 const bool IsPGOPreLink = !IsCtxProfGen && PGOOpt && IsPreLink;
1138 const bool IsPGOInstrGen =
1139 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1140 const bool IsPGOInstrUse =
1141 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1142 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1143 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1144 // enable ctx profiling from the frontend.
1146 Context.getLibraryOptions())) &&
1147 "Enabling both instrumented PGO and contextual instrumentation is not "
1148 "supported.");
1149 const bool IsCtxProfUse = !UseCtxProfile.empty() && isThinLTOPreLink(Phase);
1150
1151 assert((Opts.instrument_cold_function_only_path.empty() ||
1152 isPGOInstrumentColdFunctionOnly(Context.getLibraryOptions())) &&
1153 "--instrument-cold-function-only-path is provided but "
1154 "--pgo-instrument-cold-function-only is not enabled");
1155 const bool IsColdFuncOnlyInstrGen =
1156 isPGOInstrumentColdFunctionOnly(Context.getLibraryOptions()) &&
1157 IsPGOPreLink && !Opts.instrument_cold_function_only_path.empty();
1158
1159 // When a memory profile is used together with a sample profile, the
1160 // pre-inliner runs after the sample profile has been loaded. By default make
1161 // it ignore the sample profile, so that the inlining seen by MemProfUsePass
1162 // doesn't depend on the sample profile. Otherwise, a different sample profile
1163 // than the one used to build the memory-profiled binary can cause additional
1164 // inlining (e.g. of newly hot callees) that leads to memprof matching
1165 // failures. This matches the IR PGO pipeline, where the pre-inliner runs
1166 // before the profile is annotated.
1167 const bool PreInlinerIgnoreProfile =
1168 IsMemprofUse && HasSampleProfile && Opts.memprof_preinline_ignore_profile;
1169 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1170 IsCtxProfUse || IsColdFuncOnlyInstrGen)
1171 addPreInlinerPasses(MPM, Level, Phase, PreInlinerIgnoreProfile);
1172
1173 // Add all the requested passes for instrumentation PGO, if requested.
1174 if (IsPGOInstrGen || IsPGOInstrUse) {
1175 addPGOInstrPasses(MPM, Level,
1176 /*RunProfileGen=*/IsPGOInstrGen,
1177 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1178 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1179 } else if (IsCtxProfGen || IsCtxProfUse) {
1181 // In pre-link, we just want the instrumented IR. We use the contextual
1182 // profile in the post-thinlink phase.
1183 // The instrumentation will be removed in post-thinlink after IPO.
1184 if (IsCtxProfUse) {
1185 MPM.addPass(AssignGUIDPass());
1186 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
1187 return MPM;
1188 }
1189 // Block further inlining in the instrumented ctxprof case. This avoids
1190 // confusingly collecting profiles for the same GUID corresponding to
1191 // different variants of the function. We could do like PGO and identify
1192 // functions by a (GUID, Hash) tuple, but since the ctxprof "use" waits for
1193 // thinlto to happen before performing any further optimizations, it's
1194 // unnecessary to collect profiles for non-prevailing copies.
1196 addPostPGOLoopRotation(MPM, Level);
1197 MPM.addPass(AssignGUIDPass());
1199 } else if (IsColdFuncOnlyInstrGen) {
1200 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
1201 /* AtomicCounterUpdate */ false,
1202 Opts.instrument_cold_function_only_path.str(),
1203 /* ProfileRemappingFile */ "");
1204 }
1205
1206 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1207 MPM.addPass(PGOIndirectCallPromotion(false, false));
1208
1209 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1211 PGOOpt->CSProfileGenFile, Opts.enable_sampled_instrumentation));
1212
1213 if (IsMemprofUse)
1214 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS));
1215
1216 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse ||
1217 PGOOpt->Action == PGOOptions::SampleUse))
1218 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1219
1220 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1221
1222 if (Opts.enable_module_inliner)
1224 else
1225 MPM.addPass(buildInlinerPipeline(Level, Phase));
1226
1227 // Remove any dead arguments exposed by cleanups, constant folding globals,
1228 // and argument promotion.
1230
1233
1234 if (!isThinLTOPreLink(Phase))
1235 MPM.addPass(CoroCleanupPass());
1236
1237 // Optimize globals now that functions are fully simplified.
1238 MPM.addPass(GlobalOptPass());
1239 MPM.addPass(GlobalDCEPass());
1240
1241 return MPM;
1242}
1243
1244/// TODO: Should LTO cause any differences to this set of passes?
1245void PassBuilder::addVectorPasses(OptimizationLevel Level,
1247 ThinOrFullLTOPhase LTOPhase) {
1250
1251 // Drop dereferenceable assumes after vectorization, as they are no longer
1252 // needed and can inhibit further optimization.
1253 if (!isLTOPreLink(LTOPhase))
1254 FPM.addPass(DropUnnecessaryAssumesPass(/*DropDereferenceable=*/true));
1255
1257 if (isFullLTOPostLink(LTOPhase)) {
1258 // The vectorizer may have significantly shortened a loop body; unroll
1259 // again. Unroll small loops to hide loop backedge latency and saturate any
1260 // parallel execution resources of an out-of-order processor. We also then
1261 // need to clean up redundancies and loop invariant code.
1262 // FIXME: It would be really good to use a loop-integrated instruction
1263 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1264 // across the loop nests.
1265 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1266 if (Opts.enable_unroll_and_jam && PTO.LoopUnrolling)
1268 LoopUnrollAndJamPass(static_cast<int>(Level))));
1270 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1273 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1274 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1275 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1276 // NOTE: we are very late in the pipeline, and we don't have any LICM
1277 // or SimplifyCFG passes scheduled after us, that would cleanup
1278 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1279
1280 // We also turn on struct to vector canonicalization here, which allows
1281 // converting allocas of homogeneous structs into vector allocas when the
1282 // allocas' users are all memory intrinsics. This allows promotion in some
1283 // cases because structs cannot promote to SSA values, but vectors can. We
1284 // only turn this on after memcpyopt runs because this might hinder
1285 // memcpyopt's optimizations if done before. Look at the documentation for
1286 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1288 /*AggregateToVector=*/true)));
1289 }
1290
1291 if (!isFullLTOPostLink(LTOPhase)) {
1292 // Eliminate loads by forwarding stores from the previous iteration to loads
1293 // of the current iteration.
1295 }
1296 // Cleanup after the loop optimization passes.
1297 FPM.addPass(InstCombinePass());
1298
1299 if (Level > OptimizationLevel::O1 && Opts.extra_vectorizer_passes) {
1300 ExtraFunctionPassManager<ShouldRunExtraVectorPasses> ExtraPasses;
1301 // At higher optimization levels, try to clean up any runtime overlap and
1302 // alignment checks inserted by the vectorizer. We want to track correlated
1303 // runtime checks for two inner loops in the same outer loop, fold any
1304 // common computations, hoist loop-invariant aspects out of any outer loop,
1305 // and unswitch the runtime checks if possible. Once hoisted, we may have
1306 // dead (or speculatable) control flows or more combining opportunities.
1307 ExtraPasses.addPass(EarlyCSEPass());
1308 ExtraPasses.addPass(CorrelatedValuePropagationPass());
1309 ExtraPasses.addPass(InstCombinePass());
1310 LoopPassManager LPM;
1311 LPM.addPass(LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
1312 /*AllowSpeculation=*/true));
1313 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1315 ExtraPasses.addPass(
1316 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true));
1317 ExtraPasses.addPass(
1318 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1319 ExtraPasses.addPass(InstCombinePass());
1320 FPM.addPass(std::move(ExtraPasses));
1321 }
1322
1323 // Now that we've formed fast to execute loop structures, we do further
1324 // optimizations. These are run afterward as they might block doing complex
1325 // analyses and transforms such as what are needed for loop vectorization.
1326
1327 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1328 // GVN, loop transforms, and others have already run, so it's now better to
1329 // convert to more optimized IR using more aggressive simplify CFG options.
1330 // The extra sinking transform can create larger basic blocks, so do this
1331 // before SLP vectorization.
1332 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1333 .forwardSwitchCondToPhi(true)
1334 .convertSwitchRangeToICmp(true)
1335 .convertSwitchToArithmetic(true)
1336 .convertSwitchToLookupTable(true)
1337 .needCanonicalLoops(false)
1338 .hoistCommonInsts(true)
1339 .sinkCommonInsts(true)));
1340
1341 if (isFullLTOPostLink(LTOPhase)) {
1342 FPM.addPass(SCCPPass());
1343 FPM.addPass(InstCombinePass());
1344 FPM.addPass(BDCEPass());
1345 }
1346
1347 // Optimize parallel scalar instruction chains into SIMD instructions.
1348 if (PTO.SLPVectorization) {
1349 FPM.addPass(SLPVectorizerPass());
1350 if (Level >= OptimizationLevel::O2 && Opts.extra_vectorizer_passes) {
1351 FPM.addPass(EarlyCSEPass());
1352 }
1353 }
1354 // Enhance/cleanup vector code.
1355 FPM.addPass(VectorCombinePass());
1356
1357 if (!isFullLTOPostLink(LTOPhase)) {
1358 FPM.addPass(InstCombinePass());
1359 // Unroll small loops to hide loop backedge latency and saturate any
1360 // parallel execution resources of an out-of-order processor. We also then
1361 // need to clean up redundancies and loop invariant code.
1362 // FIXME: It would be really good to use a loop-integrated instruction
1363 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1364 // across the loop nests.
1365 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1366 if (Opts.enable_unroll_and_jam && PTO.LoopUnrolling) {
1368 LoopUnrollAndJamPass(static_cast<int>(Level))));
1369 }
1370 FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1371 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1372 *PTO.ForgetAllSCEVInLoopUnroll)));
1373 FPM.addPass(WarnMissedTransformationsPass());
1374 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1375 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1376 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1377 // NOTE: we are very late in the pipeline, and we don't have any LICM
1378 // or SimplifyCFG passes scheduled after us, that would cleanup
1379 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1380
1381 // We also turn on struct to vector canonicalization here, which allows
1382 // converting allocas of homogeneous structs into vector allocas when the
1383 // allocas' users are all memory intrinsics. This allows promotion in some
1384 // cases because structs cannot promote to SSA values, but vectors can. We
1385 // only turn this on after memcpyopt runs because this might hinder
1386 // memcpyopt's optimizations if done before. Look at the documentation for
1387 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1388 FPM.addPass(SROAPass(SROAOptions(SROAOptions::PreserveCFG,
1389 /*AggregateToVector=*/true)));
1390 }
1391
1392 FPM.addPass(InferAlignmentPass());
1393 FPM.addPass(InstCombinePass());
1394
1395 // This is needed for two reasons:
1396 // 1. It works around problems that instcombine introduces, such as sinking
1397 // expensive FP divides into loops containing multiplications using the
1398 // divide result.
1399 // 2. It helps to clean up some loop-invariant code created by the loop
1400 // unroll pass when IsFullLTO=false.
1402 LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
1403 /*AllowSpeculation=*/true),
1404 /*UseMemorySSA=*/true));
1405
1406 // Now that we've vectorized and unrolled loops, we may have more refined
1407 // alignment information, try to re-derive it here.
1408 FPM.addPass(AlignmentFromAssumptionsPass());
1409}
1410
1413 ThinOrFullLTOPhase LTOPhase) {
1415
1416 // Run partial inlining pass to partially inline functions that have
1417 // large bodies.
1418 if (Opts.enable_partial_inlining)
1420
1421 // Remove avail extern fns and globals definitions since we aren't compiling
1422 // an object file for later LTO. For LTO we want to preserve these so they
1423 // are eligible for inlining at link-time. Note if they are unreferenced they
1424 // will be removed by GlobalDCE later, so this only impacts referenced
1425 // available externally globals. Eventually they will be suppressed during
1426 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1427 // may make globals referenced by available external functions dead and saves
1428 // running remaining passes on the eliminated functions. These should be
1429 // preserved during prelinking for link-time inlining decisions.
1430 if (!isLTOPreLink(LTOPhase))
1432
1433 // Do RPO function attribute inference across the module to forward-propagate
1434 // attributes where applicable.
1435 // FIXME: Is this really an optimization rather than a canonicalization?
1436 if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1438 else
1440
1441 // Do a post inline PGO instrumentation and use pass. This is a context
1442 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1443 // cross-module inline has not been done yet. The context sensitive
1444 // instrumentation is after all the inlines are done.
1445 if (!isLTOPreLink(LTOPhase) && PGOOpt) {
1446 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1447 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1448 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1449 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
1450 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1451 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1452 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1453 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1454 }
1455
1456 // Re-compute GlobalsAA here prior to function passes. This is particularly
1457 // useful as the above will have inlined, DCE'ed, and function-attr
1458 // propagated everything. We should at this point have a reasonably minimal
1459 // and richly annotated call graph. By computing aliasing and mod/ref
1460 // information for all local globals here, the late loop passes and notably
1461 // the vectorizer will be able to use them to help recognize vectorizable
1462 // memory operations.
1463 if (Opts.enable_global_analyses)
1465
1466 invokeOptimizerEarlyEPCallbacks(MPM, Level, LTOPhase);
1467
1468 FunctionPassManager OptimizePM;
1469
1470 // Only drop unnecessary assumes post-inline and post-link, as otherwise
1471 // additional uses of the affected value may be introduced through inlining
1472 // and CSE.
1473 if (!isLTOPreLink(LTOPhase))
1474 OptimizePM.addPass(DropUnnecessaryAssumesPass());
1475
1476 // Scheduling LoopVersioningLICM when inlining is over, because after that
1477 // we may see more accurate aliasing. Reason to run this late is that too
1478 // early versioning may prevent further inlining due to increase of code
1479 // size. Other optimizations which runs later might get benefit of no-alias
1480 // assumption in clone loop.
1481 if (Opts.enable_loop_versioning_licm) {
1482 OptimizePM.addPass(
1484 // LoopVersioningLICM pass might increase new LICM opportunities.
1486 LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
1487 /*AllowSpeculation=*/true),
1488 /*USeMemorySSA=*/true));
1489 }
1490
1491 OptimizePM.addPass(Float2IntPass());
1492 // Defer until LTO post-link where some constants may become known.
1493 if (!isLTOPreLink(LTOPhase))
1495
1496 if (Opts.enable_matrix) {
1497 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1498 OptimizePM.addPass(EarlyCSEPass());
1499 }
1500
1501 // CHR pass should only be applied with the profile information.
1502 // The check is to check the profile summary information in CHR.
1503 if (Opts.enable_chr && Level == OptimizationLevel::O3)
1504 OptimizePM.addPass(ControlHeightReductionPass());
1505
1506 // FIXME: We need to run some loop optimizations to re-rotate loops after
1507 // simplifycfg and others undo their rotation.
1508
1509 // Optimize the loop execution. These passes operate on entire loop nests
1510 // rather than on each loop in an inside-out manner, and so they are actually
1511 // function passes.
1512
1513 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1514
1515 LoopPassManager LPM;
1516 // First rotate loops that may have been un-rotated by prior passes.
1517 // Disable header duplication at -Oz.
1518 LPM.addPass(LoopRotatePass(/*EnableLoopHeaderDuplication=*/true,
1519 isLTOPreLink(LTOPhase),
1520 /*CheckExitCount=*/true));
1521 // Some loops may have become dead by now. Try to delete them.
1522 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1523 // this may need to be revisited once we run GVN before loop deletion
1524 // in the simplification pipeline.
1525 LPM.addPass(LoopDeletionPass());
1526
1527 if (*PTO.LoopInterchange)
1528 LPM.addPass(LoopInterchangePass());
1529
1530 OptimizePM.addPass(
1531 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
1532
1533 // FIXME: This may not be the right place in the pipeline.
1534 // We need to have the data to support the right place.
1535 if (PTO.LoopFusion)
1536 OptimizePM.addPass(LoopFusePass());
1537
1538 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1539 // into separate loop that would otherwise inhibit vectorization. This is
1540 // currently only performed for loops marked with the metadata
1541 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1542 OptimizePM.addPass(LoopDistributePass());
1543
1544 // Populates the VFABI attribute with the scalar-to-vector mappings
1545 // from the TargetLibraryInfo.
1546 OptimizePM.addPass(InjectTLIMappings());
1547
1548 addVectorPasses(Level, OptimizePM, LTOPhase);
1549
1550 invokeVectorizerEndEPCallbacks(OptimizePM, Level);
1551
1552 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1553 // canonicalization pass that enables other optimizations. As a result,
1554 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1555 // result too early.
1556 OptimizePM.addPass(LoopSinkPass());
1557
1558 // And finally clean up LCSSA form before generating code.
1559 OptimizePM.addPass(InstSimplifyPass());
1560
1561 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1562 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1563 // flattening of blocks.
1564 OptimizePM.addPass(DivRemPairsPass());
1565
1566 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
1567 // TODO: move this further up so that it can be optimized by GVN, etc.
1568 if (Opts.enable_mergeicmps)
1569 OptimizePM.addPass(MergeICmpsPass());
1570 OptimizePM.addPass(ExpandMemCmpPass());
1571
1572 // Try to annotate calls that were created during optimization.
1573 OptimizePM.addPass(
1574 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
1575
1576 // LoopSink (and other loop passes since the last simplifyCFG) might have
1577 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1578 OptimizePM.addPass(
1580 .convertSwitchRangeToICmp(true)
1581 .convertSwitchToArithmetic(true)
1582 .speculateUnpredictables(true)
1583 .hoistLoadsStoresWithCondFaulting(true)));
1584
1585 // Add the core optimizing pipeline.
1587 std::move(OptimizePM), *PTO.EagerlyInvalidateAnalyses));
1588
1589 // AllocToken transforms heap allocation calls; this needs to run late after
1590 // other allocation call transformations (such as those in InstCombine).
1591 if (!isLTOPreLink(LTOPhase))
1592 MPM.addPass(AllocTokenPass());
1593
1594 invokeOptimizerLastEPCallbacks(MPM, Level, LTOPhase);
1595
1596 // Run the Instrumentor pass late.
1597 if (Opts.enable_instrumentor)
1598 MPM.addPass(InstrumentorPass(FS));
1599
1600 // Split out cold code. Splitting is done late to avoid hiding context from
1601 // other optimizations and inadvertently regressing performance. The tradeoff
1602 // is that this has a higher code size cost than splitting early.
1603 if (Opts.hot_cold_split && !isLTOPreLink(LTOPhase))
1605
1606 // Now we need to do some global optimization transforms.
1607 // FIXME: It would seem like these should come first in the optimization
1608 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1609 // ordering here.
1610 MPM.addPass(GlobalDCEPass());
1612
1613 // Merge functions if requested. It has a better chance to merge functions
1614 // after ConstantMerge folded jump tables.
1615 if (*PTO.MergeFunctions)
1617
1618 if (PTO.CallGraphProfile && !isLTOPreLink(LTOPhase))
1619 MPM.addPass(CGProfilePass(isLTOPostLink(LTOPhase)));
1620
1621 // RelLookupTableConverterPass runs later in LTO post-link pipeline.
1622 if (!isLTOPreLink(LTOPhase))
1624
1625 // Add devirtualization pass only when LTO is not enabled, as otherwise
1626 // the pass is already enabled in the LTO pipeline.
1627 if (*PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
1628 // TODO: explore a better pipeline configuration that can improve
1629 // compilation time overhead.
1630 // FIXME: move this earlier (lots of pass ordering tests will need fixing)
1631 MPM.addPass(AssignGUIDPass());
1633 /*ExportSummary*/ nullptr,
1634 /*ImportSummary*/ nullptr,
1635 /*DevirtSpeculatively*/ *PTO.DevirtualizeSpeculatively));
1637 // Given that the devirtualization creates more opportunities for inlining,
1638 // we run the Inliner again here to maximize the optimization gain we
1639 // get from devirtualization.
1640 // Also, we can't run devirtualization before inlining because the
1641 // devirtualization depends on the passes optimizing/eliminating vtable GVs
1642 // and those passes are only effective after inlining.
1643 addModuleInlinerPass(MPM, Context, Level, ThinOrFullLTOPhase::None);
1644 }
1645
1646 // Attach !implicit.ref metadata from all functions to copyright strings.
1648
1649 return MPM;
1650}
1651
1655 if (Level == OptimizationLevel::O0)
1656 return buildO0DefaultPipeline(Level, Phase);
1657
1659 addPipelineStartPasses(MPM, Opts);
1660 // Currently this pipeline is only invoked in an LTO pre link pass or when we
1661 // are not running LTO. If that changes the below checks may need updating.
1663
1664 // If we are invoking this in non-LTO mode, remove any MemProf related
1665 // attributes and metadata, as we don't know whether we are linking with
1666 // a library containing the necessary interfaces.
1669
1670 // Convert @llvm.global.annotations to !annotation metadata.
1672
1673 // Force any function attributes we want the rest of the pipeline to observe.
1675
1676 if (Opts.opt_pipeline_trigger_crash)
1678
1679 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1681
1682 // Apply module pipeline start EP callback.
1684
1685 // Add the core simplification pipeline.
1687
1688 // Now add the optimization pipeline.
1690
1691 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1692 PGOOpt->Action == PGOOptions::SampleUse)
1694
1695 // Emit annotation remarks.
1697
1698 if (isLTOPreLink(Phase))
1699 addRequiredLTOPreLinkPasses(MPM);
1700
1701 addPipelineEndPasses(MPM, Opts);
1702 return MPM;
1703}
1704
1707 bool EmitSummary, bool Verify) {
1709
1710 addPipelineStartPasses(MPM, Opts);
1711
1712 if (ThinLTO)
1714 else
1716 // AssignGUIDPass attaches !guid metadata (MD_unique_id) to global objects,
1717 // triggering the bitcode writer to emit a METADATA_KIND_BLOCK. Standard LTO
1718 // bitcode emission runs VerifierPass by default, which registers metadata
1719 // kind IDs in LLVMContext. Running VerifierPass here before EmbedBitcodePass
1720 // to get the same behavior.
1721 if (Verify)
1722 MPM.addPass(VerifierPass());
1723 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1724
1725 // Perform any cleanups to the IR that aren't suitable for per TU compilation,
1726 // like removing CFI/WPD related instructions. Note, we reuse
1727 // DropTypeTestsPass to clean up type tests rather than duplicate that logic
1728 // in FatLtoCleanup; checked-load cleanup is shared the other way, with
1729 // FatLtoCleanup calling lowertypetests::cleanUpTypeCheckedLoad.
1730 MPM.addPass(FatLtoCleanup());
1731
1732 // If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
1733 // object code, only in the bitcode section, so drop it before we run
1734 // module optimization and generate machine code. If llvm.type.test() isn't in
1735 // the IR, this won't do anything.
1737
1738 // Use the ThinLTO post-link pipeline with sample profiling
1739 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1740 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1741 else {
1742 // ModuleSimplification does not run the coroutine passes for
1743 // ThinLTOPreLink, so we need the coroutine passes to run for ThinLTO
1744 // builds, otherwise they will miscompile.
1745 if (ThinLTO) {
1746 // TODO: replace w/ buildCoroWrapper() when it takes phase and level into
1747 // consideration.
1748 CGSCCPassManager CGPM;
1752 MPM.addPass(CoroCleanupPass());
1753 }
1754
1755 // otherwise, just use module optimization
1756 MPM.addPass(
1758 // Emit annotation remarks.
1760 }
1761
1762 addPipelineEndPasses(MPM, Opts);
1763
1764 return MPM;
1765}
1766
1769 if (Level == OptimizationLevel::O0)
1771
1773
1774 addPipelineStartPasses(MPM, Opts);
1775
1776 // Convert @llvm.global.annotations to !annotation metadata.
1778
1779 // Force any function attributes we want the rest of the pipeline to observe.
1781
1782 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1784
1785 // Apply module pipeline start EP callback.
1787
1788 // If we are planning to perform ThinLTO later, we don't bloat the code with
1789 // unrolling/vectorization/... now. Just simplify the module as much as we
1790 // can.
1793 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1794 // thinlto use the contextual info to perform imports; then use the contextual
1795 // profile in the post-thinlink phase.
1796 if (!UseCtxProfile.empty()) {
1797 addRequiredLTOPreLinkPasses(MPM);
1798 return MPM;
1799 }
1800
1801 // Run partial inlining pass to partially inline functions that have
1802 // large bodies.
1803 // FIXME: It isn't clear whether this is really the right place to run this
1804 // in ThinLTO. Because there is another canonicalization and simplification
1805 // phase that will run after the thin link, running this here ends up with
1806 // less information than will be available later and it may grow functions in
1807 // ways that aren't beneficial.
1808 if (Opts.enable_partial_inlining)
1810
1811 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1812 PGOOpt->Action == PGOOptions::SampleUse)
1814
1815 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1816 // optimization is going to be done in PostLink stage, but clang can't add
1817 // callbacks there in case of in-process ThinLTO called by linker.
1822
1823 // Emit annotation remarks.
1825
1826 // Attach !implicit.ref metadata from all functions to copyright strings.
1828
1829 addRequiredLTOPreLinkPasses(MPM);
1830
1831 addPipelineEndPasses(MPM, Opts);
1832
1833 return MPM;
1834}
1835
1837 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1839
1840 addPipelineStartPasses(MPM, Opts);
1841
1843
1844 // If we are invoking this without a summary index noting that we are linking
1845 // with a library containing the necessary APIs, remove any MemProf related
1846 // attributes and metadata.
1847 if (!ImportSummary || !ImportSummary->withSupportsHotColdNew())
1849
1850 if (ImportSummary) {
1851 // For ThinLTO we must apply the context disambiguation decisions early, to
1852 // ensure we can correctly match the callsites to summary data.
1855 ImportSummary, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1856
1857 // These passes import type identifier resolutions for whole-program
1858 // devirtualization and CFI. They must run early because other passes may
1859 // disturb the specific instruction patterns that these passes look for,
1860 // creating dependencies on resolutions that may not appear in the summary.
1861 //
1862 // For example, GVN may transform the pattern assume(type.test) appearing in
1863 // two basic blocks into assume(phi(type.test, type.test)), which would
1864 // transform a dependency on a WPD resolution into a dependency on a type
1865 // identifier resolution for CFI.
1866 //
1867 // Also, WPD has access to more precise information than ICP and can
1868 // devirtualize more effectively, so it should operate on the IR first.
1869 //
1870 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1871 // metadata and intrinsics.
1872 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1873 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1874 }
1875
1876 if (Level == OptimizationLevel::O0) {
1877 // Run a second time to clean up any type tests left behind by WPD for use
1878 // in ICP.
1881
1882 // AllocToken transforms heap allocation calls; this needs to run late after
1883 // other allocation call transformations (such as those in InstCombine).
1884 MPM.addPass(AllocTokenPass());
1885
1886 // Drop available_externally and unreferenced globals. This is necessary
1887 // with ThinLTO in order to avoid leaving undefined references to dead
1888 // globals in the object file.
1890 MPM.addPass(GlobalDCEPass());
1891
1893
1894 return MPM;
1895 }
1896 if (!UseCtxProfile.empty()) {
1897 MPM.addPass(
1899 } else {
1900 // Add the core simplification pipeline.
1903 }
1904 // Now add the optimization pipeline.
1907
1909
1910 // Emit annotation remarks.
1912
1913 addPipelineEndPasses(MPM, Opts);
1914
1915 return MPM;
1916}
1917
1920 // FIXME: We should use a customized pre-link pipeline!
1921 return buildPerModuleDefaultPipeline(Level,
1923}
1924
1927 ModuleSummaryIndex *ExportSummary) {
1929
1930 addPipelineStartPasses(MPM, Opts);
1931
1933
1934 // If we are invoking this without a summary index noting that we are linking
1935 // with a library containing the necessary APIs, remove any MemProf related
1936 // attributes and metadata.
1937 if (!ExportSummary || !ExportSummary->withSupportsHotColdNew())
1939
1940 // Create a function that performs CFI checks for cross-DSO calls with targets
1941 // in the current module.
1942 MPM.addPass(CrossDSOCFIPass());
1943
1944 if (Level == OptimizationLevel::O0) {
1945 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1946 // metadata and intrinsics.
1947 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1948 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1949 // Run a second time to clean up any type tests left behind by WPD for use
1950 // in ICP.
1952
1954
1955 // AllocToken transforms heap allocation calls; this needs to run late after
1956 // other allocation call transformations (such as those in InstCombine).
1957 MPM.addPass(AllocTokenPass());
1958
1960
1961 // Emit annotation remarks.
1963
1964 return MPM;
1965 }
1966
1967 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1968 // Load sample profile before running the LTO optimization pipeline.
1969 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1970 PGOOpt->ProfileRemappingFile,
1972 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1973 // RequireAnalysisPass for PSI before subsequent non-module passes.
1975 }
1976
1977 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
1979
1980 // Remove unused virtual tables to improve the quality of code generated by
1981 // whole-program devirtualization and bitset lowering.
1982 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
1983
1984 // Do basic inference of function attributes from known properties of system
1985 // libraries and other oracles.
1987
1988 if (Level >= OptimizationLevel::O2) {
1990 CallSiteSplittingPass(), *PTO.EagerlyInvalidateAnalyses));
1991
1992 // Indirect call promotion. This should promote all the targets that are
1993 // left by the earlier promotion pass that promotes intra-module targets.
1994 // This two-step promotion is to save the compile time. For LTO, it should
1995 // produce the same result as if we only do promotion here.
1997 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1998
1999 // Promoting by-reference arguments to by-value exposes more constants to
2000 // IPSCCP.
2001 CGSCCPassManager CGPM;
2002 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT)
2004 else
2007 CGPM.addPass(
2010
2011 // Propagate constants at call sites into the functions they call. This
2012 // opens opportunities for globalopt (and inlining) by substituting function
2013 // pointers passed as arguments to direct uses of functions.
2014 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/true)));
2015
2016 // Attach metadata to indirect call sites indicating the set of functions
2017 // they may target at run-time. This should follow IPSCCP.
2019 }
2020
2021 // Do RPO function attribute inference across the module to forward-propagate
2022 // attributes where applicable.
2023 // FIXME: Is this really an optimization rather than a canonicalization?
2024 if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
2026 else
2028
2029 // Use in-range annotations on GEP indices to split globals where beneficial.
2030 MPM.addPass(GlobalSplitPass());
2031
2032 // Run whole program optimization of virtual call when the list of callees
2033 // is fixed.
2034 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2035
2037 // Stop here at -O1.
2038 if (Level == OptimizationLevel::O1) {
2040 LowerConstantIntrinsicsPass(), *PTO.EagerlyInvalidateAnalyses));
2041
2042 // The LowerTypeTestsPass needs to run to lower type metadata and the
2043 // type.test intrinsics. The pass does nothing if CFI is disabled.
2044 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2045 // Run a second time to clean up any type tests left behind by WPD for use
2046 // in ICP (which is performed earlier than this in the regular LTO
2047 // pipeline).
2049
2051
2052 // AllocToken transforms heap allocation calls; this needs to run late after
2053 // other allocation call transformations (such as those in InstCombine).
2054 MPM.addPass(AllocTokenPass());
2055
2057
2058 // Emit annotation remarks.
2060
2061 addPipelineEndPasses(MPM, Opts);
2062
2063 return MPM;
2064 }
2065
2066 // TODO: Skip to match buildCoroWrapper.
2067 MPM.addPass(CoroEarlyPass());
2068
2069 // Optimize globals to try and fold them into constants.
2070 MPM.addPass(GlobalOptPass());
2071
2072 // Promote any localized globals to SSA registers.
2074
2075 // Linking modules together can lead to duplicate global constant, only
2076 // keep one copy of each constant.
2078
2079 // Remove unused arguments from functions.
2081
2082 // Reduce the code after globalopt and ipsccp. Both can open up significant
2083 // simplification opportunities, and both can propagate functions through
2084 // function pointers. When this happens, we often have to resolve varargs
2085 // calls, etc, so let instcombine do this.
2086 FunctionPassManager PeepholeFPM;
2087 PeepholeFPM.addPass(InstCombinePass());
2088 if (Level >= OptimizationLevel::O2)
2089 PeepholeFPM.addPass(AggressiveInstCombinePass());
2090 invokePeepholeEPCallbacks(PeepholeFPM, Level);
2091
2093 std::move(PeepholeFPM), *PTO.EagerlyInvalidateAnalyses));
2094
2095 // Lower variadic functions for supported targets prior to inlining.
2097
2098 // Note: historically, the PruneEH pass was run first to deduce nounwind and
2099 // generally clean up exception handling overhead. It isn't clear this is
2100 // valuable as the inliner doesn't currently care whether it is inlining an
2101 // invoke or a call.
2102 // Run the inliner now.
2103 addModuleInlinerPass(MPM, Context, Level,
2105
2106 // Perform context disambiguation after inlining, since that would reduce the
2107 // amount of additional cloning required to distinguish the allocation
2108 // contexts.
2111 /*Summary=*/nullptr,
2112 PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2113
2114 // Optimize globals again after we ran the inliner.
2115 MPM.addPass(GlobalOptPass());
2116
2117 // Run the OpenMPOpt pass again after global optimizations.
2119
2120 // Garbage collect dead functions.
2121 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2122
2123 // If we didn't decide to inline a function, check to see if we can
2124 // transform it to pass arguments by value instead of by reference.
2125 CGSCCPassManager CGPM;
2131
2133 // The IPO Passes may leave cruft around. Clean up after them.
2134 FPM.addPass(InstCombinePass());
2135 invokePeepholeEPCallbacks(FPM, Level);
2136
2137 if (Opts.enable_constraint_elimination)
2139
2141
2142 // Do a post inline PGO instrumentation and use pass. This is a context
2143 // sensitive PGO pass.
2144 if (PGOOpt) {
2145 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
2146 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
2147 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2148 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
2149 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
2150 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
2151 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2152 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
2153 }
2154
2155 // Break up allocas
2157
2158 // LTO provides additional opportunities for tailcall elimination due to
2159 // link-time inlining, and visibility of nocapture attribute.
2160 FPM.addPass(
2161 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
2162
2163 // Run a few AA driver optimizations here and now to cleanup the code.
2165 std::move(FPM), *PTO.EagerlyInvalidateAnalyses));
2166
2167 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT) {
2168 MPM.addPass(
2170 } else {
2171 MPM.addPass(
2173 }
2174
2175 // Require the GlobalsAA analysis for the module so we can query it within
2176 // MainFPM.
2177 if (Opts.enable_global_analyses) {
2179 // Invalidate AAManager so it can be recreated and pick up the newly
2180 // available GlobalsAA.
2181 MPM.addPass(
2183 }
2184
2185 FunctionPassManager MainFPM;
2187 LICMPass(*PTO.LicmMssaOptCap, *PTO.LicmMssaNoAccForPromotionCap,
2188 /*AllowSpeculation=*/true),
2189 /*USeMemorySSA=*/true));
2190
2191 if (Opts.enable_newgvn)
2192 MainFPM.addPass(NewGVNPass());
2193 else
2194 MainFPM.addPass(GVNPass());
2195
2196 // Remove dead memcpy()'s.
2197 MainFPM.addPass(MemCpyOptPass());
2198
2199 // Nuke dead stores.
2200 MainFPM.addPass(DSEPass());
2201 MainFPM.addPass(MoveAutoInitPass());
2203
2205
2206 invokeVectorizerStartEPCallbacks(MainFPM, Level);
2207
2208 LoopPassManager LPM;
2209 if (Opts.enable_loop_flatten && Level >= OptimizationLevel::O2)
2210 LPM.addPass(LoopFlattenPass());
2211 LPM.addPass(IndVarSimplifyPass());
2212 LPM.addPass(LoopDeletionPass());
2213 // FIXME: Add loop interchange.
2214
2215 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2216 // *All* loop passes must preserve it, in order to be able to use it.
2217 // TODO: Explore enabling MemorySSA for loop passes after we remove the
2218 // LoopFullUnrollPass.
2219 MainFPM.addPass(
2220 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
2221
2222 MainFPM.addPass(LoopDistributePass());
2223
2224 addVectorPasses(Level, MainFPM, ThinOrFullLTOPhase::FullLTOPostLink);
2225
2226 invokeVectorizerEndEPCallbacks(MainFPM, Level);
2227
2228 // Run the OpenMPOpt CGSCC pass again late.
2231
2232 invokePeepholeEPCallbacks(MainFPM, Level);
2233 MainFPM.addPass(JumpThreadingPass());
2235 std::move(MainFPM), *PTO.EagerlyInvalidateAnalyses));
2236
2237 // Lower type metadata and the type.test intrinsic. This pass supports
2238 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2239 // to be run at link time if CFI is enabled. This pass does nothing if
2240 // CFI is disabled.
2241 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2242 // Run a second time to clean up any type tests left behind by WPD for use
2243 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2245
2246 // Enable splitting late in the FullLTO post-link pipeline.
2247 if (Opts.hot_cold_split)
2249
2250 // Add late LTO optimization passes.
2251 FunctionPassManager LateFPM;
2252
2253 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2254 // canonicalization pass that enables other optimizations. As a result,
2255 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2256 // result too early.
2257 LateFPM.addPass(LoopSinkPass());
2258
2259 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2260 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2261 // flattening of blocks.
2262 LateFPM.addPass(DivRemPairsPass());
2263
2264 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
2265 // TODO: move this further up so that it can be optimized by GVN, etc.
2266 if (Opts.enable_mergeicmps)
2267 LateFPM.addPass(MergeICmpsPass());
2268 LateFPM.addPass(ExpandMemCmpPass());
2269
2270 // Delete basic blocks, which optimization passes may have killed.
2272 .convertSwitchRangeToICmp(true)
2273 .convertSwitchToArithmetic(true)
2274 .hoistCommonInsts(true)
2275 .speculateUnpredictables(true)));
2276 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2277
2278 // Drop bodies of available eternally objects to improve GlobalDCE.
2280
2281 // Now that we have optimized the program, discard unreachable functions.
2282 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2283
2284 if (*PTO.MergeFunctions)
2286
2288
2289 if (PTO.CallGraphProfile)
2290 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2291
2292 MPM.addPass(CoroCleanupPass());
2293
2294 // AllocToken transforms heap allocation calls; this needs to run late after
2295 // other allocation call transformations (such as those in InstCombine).
2296 MPM.addPass(AllocTokenPass());
2297
2299
2300 // Emit annotation remarks.
2302
2303 addPipelineEndPasses(MPM, Opts);
2304
2305 return MPM;
2306}
2307
2311 assert(Level == OptimizationLevel::O0 &&
2312 "buildO0DefaultPipeline should only be used with O0");
2313
2315
2316 addPipelineStartPasses(MPM, Opts);
2317
2318 // Perform pseudo probe instrumentation in O0 mode. This is for the
2319 // consistency between different build modes. For example, a LTO build can be
2320 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2321 // the postlink will require pseudo probe instrumentation in the prelink.
2322 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2324
2325 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2326 PGOOpt->Action == PGOOptions::IRUse))
2328 MPM,
2329 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2330 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2331 PGOOpt->ProfileRemappingFile);
2332
2333 // Instrument function entry and exit before all inlining.
2335 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2336
2338
2339 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2341
2342 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2343 // Explicitly disable sample loader inlining and use flattened profile in O0
2344 // pipeline.
2345 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2346 PGOOpt->ProfileRemappingFile,
2348 /*DisableSampleProfileInlining=*/true,
2349 /*UseFlattenedProfile=*/true));
2350 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2351 // RequireAnalysisPass for PSI before subsequent non-module passes.
2353 }
2354
2356
2357 // Build a minimal pipeline based on the semantics required by LLVM,
2358 // which is just that always inlining occurs. Further, disable generating
2359 // lifetime intrinsics to avoid enabling further optimizations during
2360 // code generation.
2362 /*InsertLifetimeIntrinsics=*/false));
2363
2364 if (*PTO.MergeFunctions)
2366
2367 if (Opts.enable_matrix)
2368 MPM.addPass(
2370
2371 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2372 CGSCCPassManager CGPM;
2374 if (!CGPM.isEmpty())
2376 }
2377 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2378 LoopPassManager LPM;
2380 if (!LPM.isEmpty()) {
2382 createFunctionToLoopPassAdaptor(std::move(LPM))));
2383 }
2384 }
2385 if (!LoopOptimizerEndEPCallbacks.empty()) {
2386 LoopPassManager LPM;
2388 if (!LPM.isEmpty()) {
2390 createFunctionToLoopPassAdaptor(std::move(LPM))));
2391 }
2392 }
2393 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2396 if (!FPM.isEmpty())
2397 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2398 }
2399
2401
2402 if (!VectorizerStartEPCallbacks.empty()) {
2405 if (!FPM.isEmpty())
2406 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2407 }
2408
2409 if (!VectorizerEndEPCallbacks.empty()) {
2412 if (!FPM.isEmpty())
2413 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2414 }
2415
2417
2418 // AllocToken transforms heap allocation calls; this needs to run late after
2419 // other allocation call transformations (such as those in InstCombine).
2420 if (!isLTOPreLink(Phase))
2421 MPM.addPass(AllocTokenPass());
2422
2424
2425 if (Opts.enable_instrumentor)
2426 MPM.addPass(InstrumentorPass(FS));
2427
2428 // Attach !implicit.ref metadata from all functions to copyright strings.
2430
2431 if (isLTOPreLink(Phase))
2432 addRequiredLTOPreLinkPasses(MPM);
2433
2434 // Emit annotation remarks.
2436
2437 addPipelineEndPasses(MPM, Opts);
2438
2439 return MPM;
2440}
2441
2443 AAManager AA;
2444
2445 // The order in which these are registered determines their priority when
2446 // being queried.
2447
2448 // Add any target-specific alias analyses that should be run early.
2449 if (TM)
2450 TM->registerEarlyDefaultAliasAnalyses(AA);
2451
2452 // First we register the basic alias analysis that provides the majority of
2453 // per-function local AA logic. This is a stateless, on-demand local set of
2454 // AA techniques.
2455 AA.registerFunctionAnalysis<BasicAA>();
2456
2457 // Next we query fast, specialized alias analyses that wrap IR-embedded
2458 // information about aliasing.
2459 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2460 AA.registerFunctionAnalysis<TypeBasedAA>();
2461
2462 // Add support for querying global aliasing information when available.
2463 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2464 // analysis, all that the `AAManager` can do is query for any *cached*
2465 // results from `GlobalsAA` through a readonly proxy.
2466 if (Opts.enable_global_analyses)
2467 AA.registerModuleAnalysis<GlobalsAA>();
2468
2469 // Add target-specific alias analyses.
2470 if (TM)
2471 TM->registerDefaultAliasAnalyses(AA);
2472
2473 return AA;
2474}
2475
2476bool PassBuilder::isInstrumentedPGOUse() const {
2477 return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2478 !UseCtxProfile.empty();
2479}
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AggressiveInstCombiner - Combine expression patterns to form expressions with fewer,...
Provides passes to inlining "always_inline" functions.
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file provides the interface for LLVM's Call Graph Profile pass.
This header provides classes for managing passes over SCCs of the call graph.
This file provides the interface for a simple, fast CSE pass.
This file provides a pass which clones the current module and runs the provided pass pipeline on the ...
This file provides a pass manager that only runs its passes if the provided marker analysis has been ...
Super simple passes to force specific function attrs from the commandline into the IR for debugging p...
Provides passes for computing function attributes based on interprocedural analyses.
This file provides the interface for the GVNHoist pass.
This file provides the interface for the GVNSink pass.
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
This is the interface for a simple mod/ref and alias analysis over globals.
AcceleratorCodeSelection - Identify all functions reachable from a kernel, removing those that are un...
This header defines various interfaces for pass management in LLVM.
Interfaces for passes which infer implicit function attributes from the name and signature of functio...
This file provides the primary interface to the instcombine pass.
Defines passes for running instruction simplification across chunks of IR.
This file provides the interface for LLVM's PGO Instrumentation lowering pass.
See the comments on JumpThreadingPass.
static LVOptions Options
Definition LVOptions.cpp:25
This file implements the Loop Fusion pass.
This header defines the LoopLoadEliminationPass object.
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
The header file for the LowerConstantIntrinsics pass as used by the new pass manager.
The header file for the LowerExpectIntrinsic pass as used by the new pass manager.
This pass performs merges of loads and stores on both sides of a.
This file provides the interface for LLVM's Global Value Numbering pass.
This header enumerates the LLVM-provided high-level optimization levels.
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
Define option tunables for PGO.
ppc ctr loops PowerPC CTR Loops Verify
static void addPipelineEndPasses(ModulePassManager &MPM, const PassesOptions &Opts)
static void addPipelineStartPasses(ModulePassManager &MPM, const PassesOptions &Opts)
static bool isThinLTOPostLink(ThinOrFullLTOPhase Phase)
static void addModuleInlinerPass(ModulePassManager &MPM, const LLVMContext &Context, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
static void addAnnotationRemarksPass(ModulePassManager &MPM)
static CoroConditionalWrapper buildCoroWrapper(ThinOrFullLTOPhase Phase)
static bool isFullLTOPostLink(ThinOrFullLTOPhase Phase)
static bool isThinLTOPreLink(ThinOrFullLTOPhase Phase)
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
static void instructionCountersPass(ModulePassManager &MPM, bool IsPreOptimization)
static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase)
static bool isLTOPostLink(ThinOrFullLTOPhase Phase)
This file implements relative lookup table converter that converts lookup tables to relative lookup t...
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
This file provides the interface for the pseudo probe implementation for AutoFDO.
This file provides the interface for the sampled PGO loader pass.
This is the interface for a metadata-based scoped no-alias analysis.
This file provides the interface for the pass responsible for both simplifying and canonicalizing the...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
This is the interface for a metadata-based TBAA.
A manager for alias analyses.
A module pass that rewrites heap allocations to use token-enabled allocation functions based on vario...
Definition AllocToken.h:36
Inlines functions marked as "always_inline".
Argument promotion pass.
Analysis pass providing a never-invalidated alias analysis result.
Simple pass that canonicalizes aliases.
A pass that merges duplicate global constants into a single constant.
Eliminate dead arguments (and return values) from functions.
A pass that transforms external global definitions into declarations.
Pass embeds a copy of the module optimized with the provided pass pipeline into a global variable.
A pass manager to run a set of extra loop passes if the MarkerTy analysis is present.
Statistics pass for the FunctionPropertiesAnalysis results.
Pass to remove unused function declarations.
Definition GlobalDCE.h:38
Optimize globals that never have their address taken.
Definition GlobalOpt.h:25
Pass to perform split of global variables.
Definition GlobalSplit.h:26
Analysis pass providing a never-invalidated alias analysis result.
Pass to outline cold regions.
Pass to perform interprocedural constant propagation.
Definition SCCP.h:48
Run instruction simplification across each instruction in the function.
Instrumentation based profiling lowering pass.
The Instrumentor pass.
This pass performs 'jump threading', which looks at blocks that have multiple predecessors and multip...
Performs Loop Invariant Code Motion Pass.
Definition LICM.h:71
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Loop unroll pass that only does full loop unrolling and peeling.
Performs Loop Idiom Recognize Pass.
Performs Loop Inst Simplify Pass.
A simple loop rotation transformation.
Performs basic CFG simplifications to assist other loop passes.
A pass that does profile-guided sinking of instructions into loops.
Definition LoopSink.h:33
A simple loop rotation transformation.
Loop unroll pass that will support both full and partial unrolling.
Strips MemProf attributes and metadata.
Merge identical functions.
The module inliner pass for the new pass manager.
Module pass, wrapping the inliner pass.
Definition Inliner.h:65
void addModulePass(T Pass)
Add a module pass that runs before the CGSCC passes.
Definition Inliner.h:80
CGSCCPassManager & getPM()
Allow adding more CGSCC passes, besides inlining.
Definition Inliner.h:77
void addLateModulePass(T Pass)
Add a module pass that runs after the CGSCC passes.
Definition Inliner.h:85
Class to hold module path string table and global value map, and encapsulate methods for operating on...
Simple pass that provides a name to every anonymous globals.
Additional 'norecurse' attribute deduction during postlink LTO phase.
OpenMP optimizations pass.
Definition OpenMPOpt.h:42
static LLVM_ABI bool isCtxIRPGOInstrEnabled(const cl::LibraryOptionsContext &LibraryOptions)
The indirect function call promotion pass.
The instrumentation (profile-instr-gen) pass for IR based PGO.
The instrumentation (profile-instr-gen) pass for IR based PGO.
The profile annotation (profile-instr-use) pass for IR based PGO.
The profile size based optimization pass for memory intrinsics.
Pass to remove unused function declarations.
LLVM_ABI void invokeFullLinkTimeOptimizationLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModuleInlinerWrapperPass buildInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining as well as the inlining-driven cleanups.
LLVM_ABI void invokeOptimizerEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI ModulePassManager buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO, bool EmitSummary, bool Verify=true)
Build a fat object default optimization pipeline.
LLVM_ABI void invokeVectorizerStartEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI AAManager buildDefaultAAPipeline()
Build the default AAManager with the default alias analysis pipeline registered.
LLVM_ABI void invokeCGSCCOptimizerLateEPCallbacks(CGSCCPassManager &CGPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, ThinLTO-targeting default optimization pipeline to a pass manager.
LLVM_ABI void addPGOInstrPassesForO0(ModulePassManager &MPM, bool RunProfileGen, bool IsCS, bool AtomicCounterUpdate, std::string ProfileFile, std::string ProfileRemappingFile)
Add PGOInstrumenation passes for O0 only.
LLVM_ABI void invokeScalarOptimizerLateEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildPerModuleDefaultPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase=ThinOrFullLTOPhase::None)
Build a per-module default optimization pipeline.
LLVM_ABI void invokePipelineStartEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI void invokeVectorizerEndEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI void invokeThinLinkTimeOptimizationLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildO0DefaultPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase=ThinOrFullLTOPhase::None)
Build an O0 pipeline with the minimal semantically required passes.
LLVM_ABI FunctionPassManager buildFunctionSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the core LLVM function canonicalization and simplification pipeline.
LLVM_ABI void invokePeepholeEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI void invokePipelineEarlySimplificationEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI void invokeLoopOptimizerEndEPCallbacks(LoopPassManager &LPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
LLVM_ABI ModulePassManager buildModuleInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining with module inliner pass.
LLVM_ABI ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary)
Build a ThinLTO default optimization pipeline to a pass manager.
LLVM_ABI void invokeLateLoopOptimizationsEPCallbacks(LoopPassManager &LPM, OptimizationLevel Level)
LLVM_ABI void invokeFullLinkTimeOptimizationEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildModuleSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the core LLVM module canonicalization and simplification pipeline.
LLVM_ABI ModulePassManager buildModuleOptimizationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase LTOPhase)
Construct the core LLVM module optimization pipeline.
LLVM_ABI void invokeThinLinkTimeOptimizationEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI void invokeOptimizerLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI ModulePassManager buildLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, LTO-targeting default optimization pipeline to a pass manager.
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.
Tunable parameters for passes in the default pipelines.
Definition PassBuilder.h:48
std::optional< bool > EagerlyInvalidateAnalyses
std::optional< bool > ForgetAllSCEVInLoopUnroll
Tuning option to forget all SCEV loops in LoopUnroll.
Definition PassBuilder.h:75
std::optional< unsigned > MaxDevirtIterations
Tuning option to cap how many times the inliner pipeline reruns on an SCC after devirtualizing a call...
Definition PassBuilder.h:99
std::optional< unsigned > LicmMssaNoAccForPromotionCap
Tuning option to disable promotion to scalars in LICM with MemorySSA, if the number of access is too ...
Definition PassBuilder.h:83
std::optional< bool > DevirtualizeSpeculatively
std::optional< unsigned > LicmMssaOptCap
Tuning option to cap the number of calls to retrive clobbering accesses in MemorySSA,...
Definition PassBuilder.h:79
LLVM_ABI PipelineTuningOptions resolve(const cl::LibraryOptionsContext &LibraryOptions) const
Return a copy whose unset members are set from LibraryOptions.
std::optional< bool > LoopInterchange
Tuning option to enable/disable loop interchange.
Definition PassBuilder.h:69
bool LoopInterleaving
Tuning option to set loop interleaving on/off, set based on opt level.
Definition PassBuilder.h:55
std::optional< bool > MergeFunctions
Tuning option to enable/disable function merging.
Definition PassBuilder.h:92
bool LoopUnrolling
Tuning option to enable/disable loop unrolling.
Definition PassBuilder.h:66
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:59
Inject MD_prof metadata where it's missing.
Checks that MD_prof is present on every instruction that supports it.
Reassociate commutative expressions.
Definition Reassociate.h:75
A pass to do RPO deduction and propagation of function attributes.
This pass performs function-level constant propagation and merging.
Definition SCCP.h:30
The sample profiler data loader pass.
Analysis pass providing a never-invalidated alias analysis result.
This pass transforms loops that contain branches or switches on loop- invariant conditions to have mu...
A pass to simplify and canonicalize the CFG of a function.
Definition SimplifyCFG.h:30
Analysis pass providing a never-invalidated alias analysis result.
Optimize scalar/vector interactions in IR using target cost models.
Create a verifier pass.
Definition Verifier.h:134
Interfaces for registering analysis passes, producing common pass manager configurations,...
Abstract Attribute helper functions.
Definition Attributor.h:165
@ All
Drop only llvm.assumes using type test value.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > EnableKnowledgeRetention
LLVM_ABI InlineParams getInlineParams(const LLVMContext &C)
Generate the parameters to tune the inline cost analysis based only on the commandline options.
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 unsigned getLicmMssaOptCap(const cl::LibraryOptionsContext &LibraryOptions)
Return -licm-mssa-optimization-cap.
Definition LICM.cpp:120
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
@ O1
Optimize quickly without destroying debuggability.
@ O0
Disable as many optimizations as possible.
@ O3
Optimize for fast execution as much as possible.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
PassManager< LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, CGSCCUpdateResult & > CGSCCPassManager
The CGSCC pass manager.
@ CGSCC_LIGHT
@ MODULE_LIGHT
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:75
@ FullLTOPreLink
Full LTO prelink phase.
Definition Pass.h:83
@ ThinLTOPostLink
ThinLTO postlink (backend compile) phase.
Definition Pass.h:81
@ None
No LTO/ThinLTO behavior needed.
Definition Pass.h:77
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:85
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
Definition Pass.h:79
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.
LLVM_ABI InlineParams getInlineParamsFromOptLevel(const LLVMContext &C, unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
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.
LLVM_ABI bool getForgetSCEVInLoopUnroll(const cl::LibraryOptionsContext &LibraryOptions)
Return -forget-scev-loop-unroll.
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
PassManager< Function > FunctionPassManager
Convenience typedef for a pass manager over functions.
LLVM_ABI unsigned getLicmMssaNoAccForPromotionCap(const cl::LibraryOptionsContext &LibraryOptions)
Return -licm-mssa-max-acc-promotion.
Definition LICM.cpp:124
LLVM_ABI unsigned getMaxDevirtIterations(const cl::LibraryOptionsContext &)
const PassesOptions & getPassesOptions(const LLVMContext &C)
LLVM_ABI bool isPGOInstrumentColdFunctionOnly(const cl::LibraryOptionsContext &LibraryOptions)
Return the value of -pgo-instrument-cold-function-only in LibraryOptions.
A DCE pass that assumes instructions are dead until proven otherwise.
Definition ADCE.h:31
Pass to convert @llvm.global.annotations to !annotation metadata.
This pass attempts to minimize the number of assume without loosing any information.
A more lightweight version of the Attributor which only runs attribute inference but no simplificatio...
A more lightweight version of the Attributor which only runs attribute inference but no simplificatio...
Hoist/decompose integer division and remainder instructions to enable CFG improvements and better cod...
Definition DivRemPairs.h:23
A simple and fast domtree-based CSE pass.
Definition EarlyCSE.h:31
Pass which forces specific function attributes into the IR, primarily as a debugging tool.
A simple and fast domtree-based GVN pass to hoist common expressions from sibling branches.
Definition GVNHoist.h:23
Uses an "inverted" value numbering to decide the similarity of expressions and sinks similar expressi...
Definition GVNSink.h:23
A set of parameters to control various transforms performed by IPSCCP pass.
Definition SCCP.h:35
A pass which infers function attributes from the names and signatures of function declarations in a m...
Provides context on when an inline advisor is constructed in the pipeline (e.g., link phase,...
Thresholds to tune inline cost analysis.
Definition InlineCost.h:210
std::optional< int > OptSizeHintThreshold
Threshold to use for callees with inline hint, when the caller is optimized for size.
Definition InlineCost.h:219
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition InlineCost.h:231
std::optional< bool > IgnoreProfile
Indicate whether to ignore profile information.
Definition InlineCost.h:252
int DefaultThreshold
The default threshold to start with for a callee.
Definition InlineCost.h:212
std::optional< bool > EnableDeferral
Indicate whether we should allow inline deferral.
Definition InlineCost.h:244
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition InlineCost.h:215
Options for the frontend instrumentation based profiling pass.
A no-op pass template which simply forces a specific analysis result to be invalidated.
Pass to forward loads in a loop around the backedge to subsequent iterations.
A set of parameters used to control various transforms performed by the LoopUnroll pass.
The LoopVectorize Pass.
Computes function attributes in post-order over the call graph.
A utility pass template to force an analysis result to be available.