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"
29#include "llvm/IR/PassManager.h"
30#include "llvm/IR/Verifier.h"
31#include "llvm/Pass.h"
161
162using namespace llvm;
163
164namespace llvm {
166
168
170} // namespace llvm
171
173 const cl::LibraryOptionsContext *LibraryOptions) {
174 const PassesOptions &Opts =
176 LoopInterleaving = true;
177 LoopVectorization = true;
178 SLPVectorization = false;
179 LoopUnrolling = true;
180 LoopInterchange = Opts.enable_loopinterchange;
181 LoopFusion = false;
183 LicmMssaOptCap = getLicmMssaOptCap(LibraryOptions);
185 getLicmMssaNoAccForPromotionCap(LibraryOptions);
186 CallGraphProfile = true;
187 UnifiedLTO = false;
188 MergeFunctions = Opts.enable_merge_functions;
189 InlinerThreshold = -1;
190 EagerlyInvalidateAnalyses = Opts.eagerly_invalidate_analyses;
191 DevirtualizeSpeculatively = Opts.enable_devirtualize_speculatively;
192}
193
194namespace llvm {
196} // namespace llvm
197
199 OptimizationLevel Level) {
200 for (auto &C : PeepholeEPCallbacks)
201 C(FPM, Level);
202}
205 for (auto &C : LateLoopOptimizationsEPCallbacks)
206 C(LPM, Level);
207}
209 OptimizationLevel Level) {
210 for (auto &C : LoopOptimizerEndEPCallbacks)
211 C(LPM, Level);
212}
215 for (auto &C : ScalarOptimizerLateEPCallbacks)
216 C(FPM, Level);
217}
219 OptimizationLevel Level) {
220 for (auto &C : CGSCCOptimizerLateEPCallbacks)
221 C(CGPM, Level);
222}
224 OptimizationLevel Level) {
225 for (auto &C : VectorizerStartEPCallbacks)
226 C(FPM, Level);
227}
229 OptimizationLevel Level) {
230 for (auto &C : VectorizerEndEPCallbacks)
231 C(FPM, Level);
232}
234 OptimizationLevel Level,
236 for (auto &C : OptimizerEarlyEPCallbacks)
237 C(MPM, Level, Phase);
238}
240 OptimizationLevel Level,
242 for (auto &C : OptimizerLastEPCallbacks)
243 C(MPM, Level, Phase);
244}
247 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
248 C(MPM, Level);
249}
252 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
253 C(MPM, Level);
254}
257 for (auto &C : ThinLinkTimeOptimizationEarlyEPCallbacks)
258 C(MPM, Level);
259}
262 for (auto &C : ThinLinkTimeOptimizationLastEPCallbacks)
263 C(MPM, Level);
264}
266 OptimizationLevel Level) {
267 for (auto &C : PipelineStartEPCallbacks)
268 C(MPM, Level);
269}
272 for (auto &C : PipelineEarlySimplificationEPCallbacks)
273 C(MPM, Level, Phase);
274}
275
276// Get IR stats with InstCount before/after the optimization pipeline
278 bool IsPreOptimization) {
279 if (AreStatisticsEnabled()) {
280 MPM.addPass(
283 FunctionPropertiesStatisticsPass(IsPreOptimization)));
284 }
285}
286
287// Add passes to run at the start of the pipeline. This includes things like
288// statistics passes.
290 const PassesOptions &Opts) {
291 instructionCountersPass(MPM, /*IsPreOptimization=*/true);
294}
295
296// Add passes to run at the end of the pipeline. This includes things like
297// statistics passes.
299 const PassesOptions &Opts) {
300 instructionCountersPass(MPM, /*IsPreOptimization=*/false);
303}
304
305// Helper to add AnnotationRemarksPass.
309
310// Helper to check if the current compilation phase is preparing for LTO
315
316// Helper to check if the current compilation phase is preparing for FullLTO
317[[maybe_unused]] static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase) {
319}
320
321// Helper to check if the current compilation phase is preparing for ThinLTO
325
326// Helper to check if the current compilation phase is LTO backend
331
332// Helper to check if the current compilation phase is FullLTO backend
336
337// Helper to check if the current compilation phase is ThinLTO backend
341
342// Helper to wrap conditionally Coro passes.
344 // TODO: Skip passes according to Phase.
345 ModulePassManager CoroPM;
346 CoroPM.addPass(CoroEarlyPass());
347 CGSCCPassManager CGPM;
348 CGPM.addPass(CoroSplitPass());
349 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
350 CoroPM.addPass(CoroCleanupPass());
351 CoroPM.addPass(GlobalDCEPass());
352 return CoroConditionalWrapper(std::move(CoroPM));
353}
354
356 return getInlineParamsFromOptLevel(static_cast<unsigned>(Level));
357}
358
360 const PassesOptions &Opts,
361 OptimizationLevel Level,
364 if (Opts.enable_module_inliner)
365 MPM.addPass(ModuleInlinerPass(IP, Opts.enable_ml_inliner, Phase));
366 else
368 IP,
369 /* MandatoryFirst */ true,
371}
372
373// TODO: Investigate the cost/benefit of tail call elimination on debugging.
375PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
377
379
381 FPM.addPass(CountVisitsPass());
382
383 // Form SSA out of local memory accesses after breaking apart aggregates into
384 // scalars.
385 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
386
387 // Catch trivial redundancies
388 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
389
390 // Hoisting of scalars and load expressions.
391 FPM.addPass(
392 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
393 FPM.addPass(InstCombinePass());
394
395 FPM.addPass(LibCallsShrinkWrapPass());
396
397 invokePeepholeEPCallbacks(FPM, Level);
398
399 FPM.addPass(
400 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
401
402 // Form canonically associated expression trees, and simplify the trees using
403 // basic mathematical properties. For example, this will form (nearly)
404 // minimal multiplication trees.
405 FPM.addPass(ReassociatePass());
406
407 // Add the primary loop simplification pipeline.
408 // FIXME: Currently this is split into two loop pass pipelines because we run
409 // some function passes in between them. These can and should be removed
410 // and/or replaced by scheduling the loop pass equivalents in the correct
411 // positions. But those equivalent passes aren't powerful enough yet.
412 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
413 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
414 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
415 // `LoopInstSimplify`.
416 LoopPassManager LPM1, LPM2;
417
418 // Simplify the loop body. We do this initially to clean up after other loop
419 // passes run, either when iterating on a loop or on inner loops with
420 // implications on the outer loop.
421 LPM1.addPass(LoopInstSimplifyPass());
422 LPM1.addPass(LoopSimplifyCFGPass());
423
424 // Try to remove as much code from the loop header as possible,
425 // to reduce amount of IR that will have to be duplicated. However,
426 // do not perform speculative hoisting the first time as LICM
427 // will destroy metadata that may not need to be destroyed if run
428 // after loop rotation.
429 // TODO: Investigate promotion cap for O1.
430 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
431 /*AllowSpeculation=*/false));
432
433 LPM1.addPass(
434 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
435 // TODO: Investigate promotion cap for O1.
436 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
437 /*AllowSpeculation=*/true));
438 LPM1.addPass(SimpleLoopUnswitchPass());
439 if (Opts.enable_loop_flatten)
440 LPM1.addPass(LoopFlattenPass());
441
442 LPM2.addPass(LoopIdiomRecognizePass());
443 LPM2.addPass(IndVarSimplifyPass());
444
446
447 LPM2.addPass(LoopDeletionPass());
448
449 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
450 // because it changes IR to makes profile annotation in back compile
451 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
452 // attributes so we need to make sure and allow the full unroll pass to pay
453 // attention to it.
454 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
455 PGOOpt->Action != PGOOptions::SampleUse)
456 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
457 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
458 PTO.ForgetAllSCEVInLoopUnroll));
459
461
462 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
463 /*UseMemorySSA=*/true));
464 FPM.addPass(
465 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
466 FPM.addPass(InstCombinePass());
467 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
468 // *All* loop passes must preserve it, in order to be able to use it.
469 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
470 /*UseMemorySSA=*/false));
471
472 // Delete small array after loop unroll.
473 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
474
475 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
476 FPM.addPass(MemCpyOptPass());
477
478 // Sparse conditional constant propagation.
479 // FIXME: It isn't clear why we do this *after* loop passes rather than
480 // before...
481 FPM.addPass(SCCPPass());
482
483 // Delete dead bit computations (instcombine runs after to fold away the dead
484 // computations, and then ADCE will run later to exploit any new DCE
485 // opportunities that creates).
486 FPM.addPass(BDCEPass());
487
488 // Run instcombine after redundancy and dead bit elimination to exploit
489 // opportunities opened up by them.
490 FPM.addPass(InstCombinePass());
491 invokePeepholeEPCallbacks(FPM, Level);
492
493 FPM.addPass(CoroElidePass());
494
496
497 // Finally, do an expensive DCE pass to catch all the dead code exposed by
498 // the simplifications and basic cleanup after all the simplifications.
499 // TODO: Investigate if this is too expensive.
500 FPM.addPass(ADCEPass());
501 FPM.addPass(
502 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
503 FPM.addPass(InstCombinePass());
504 invokePeepholeEPCallbacks(FPM, Level);
505
506 return FPM;
507}
508
512 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
513
514 // The O1 pipeline has a separate pipeline creation function to simplify
515 // construction readability.
516 if (Level == OptimizationLevel::O1)
517 return buildO1FunctionSimplificationPipeline(Level, Phase);
518
520
523
524 // Form SSA out of local memory accesses after breaking apart aggregates into
525 // scalars.
527
528 // Catch trivial redundancies
529 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
532
533 // Hoisting of scalars and load expressions.
534 if (Opts.enable_gvn_hoist)
535 FPM.addPass(GVNHoistPass());
536
537 // Global value numbering based sinking.
538 if (Opts.enable_gvn_sink) {
539 FPM.addPass(GVNSinkPass());
540 FPM.addPass(
541 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
542 }
543
544 // Speculative execution if the target has divergent branches; otherwise nop.
545 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
546
547 // Optimize based on known information about branches, and cleanup afterward.
550
551 // Jump table to switch conversion.
552 if (Opts.enable_jump_table_to_switch)
554
555 FPM.addPass(
556 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
560
561 invokePeepholeEPCallbacks(FPM, Level);
562
563 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
564 // using the size value profile. Don't perform this when optimizing for size.
565 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse)
567
568 FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
569 isInstrumentedPGOUse()));
570 FPM.addPass(
571 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
572
573 // Form canonically associated expression trees, and simplify the trees using
574 // basic mathematical properties. For example, this will form (nearly)
575 // minimal multiplication trees.
577
578 if (Opts.enable_constraint_elimination)
580
581 // Add the primary loop simplification pipeline.
582 // FIXME: Currently this is split into two loop pass pipelines because we run
583 // some function passes in between them. These can and should be removed
584 // and/or replaced by scheduling the loop pass equivalents in the correct
585 // positions. But those equivalent passes aren't powerful enough yet.
586 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
587 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
588 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
589 // `LoopInstSimplify`.
590 LoopPassManager LPM1, LPM2;
591
592 // Simplify the loop body. We do this initially to clean up after other loop
593 // passes run, either when iterating on a loop or on inner loops with
594 // implications on the outer loop.
595 LPM1.addPass(LoopInstSimplifyPass());
596 LPM1.addPass(LoopSimplifyCFGPass());
597
598 // Try to remove as much code from the loop header as possible,
599 // to reduce amount of IR that will have to be duplicated. However,
600 // do not perform speculative hoisting the first time as LICM
601 // will destroy metadata that may not need to be destroyed if run
602 // after loop rotation.
603 // TODO: Investigate promotion cap for O1.
604 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
605 /*AllowSpeculation=*/false));
606
607 LPM1.addPass(
608 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
609 // TODO: Investigate promotion cap for O1.
610 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
611 /*AllowSpeculation=*/true));
612 LPM1.addPass(
613 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
614 if (Opts.enable_loop_flatten)
615 LPM1.addPass(LoopFlattenPass());
616
617 LPM2.addPass(LoopIdiomRecognizePass());
618 LPM2.addPass(IndVarSimplifyPass());
619
620 {
622 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
624 LPM2.addPass(std::move(ExtraPasses));
625 }
626
628
629 LPM2.addPass(LoopDeletionPass());
630
631 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
632 // because it changes IR to makes profile annotation in back compile
633 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
634 // attributes so we need to make sure and allow the full unroll pass to pay
635 // attention to it.
636 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
637 PGOOpt->Action != PGOOptions::SampleUse)
638 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
639 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
640 PTO.ForgetAllSCEVInLoopUnroll));
641
643
644 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
645 /*UseMemorySSA=*/true));
646 FPM.addPass(
647 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
649 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
650 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
651 // *All* loop passes must preserve it, in order to be able to use it.
652 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
653 /*UseMemorySSA=*/false));
654
655 // Delete small array after loop unroll.
657
658 // Try vectorization/scalarization transforms that are both improvements
659 // themselves and can allow further folds with GVN and InstCombine.
660 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
661
662 // Eliminate redundancies.
664 if (Opts.enable_newgvn)
665 FPM.addPass(NewGVNPass());
666 else
667 FPM.addPass(GVNPass());
668
669 // Sparse conditional constant propagation.
670 // FIXME: It isn't clear why we do this *after* loop passes rather than
671 // before...
672 FPM.addPass(SCCPPass());
673
674 // Delete dead bit computations (instcombine runs after to fold away the dead
675 // computations, and then ADCE will run later to exploit any new DCE
676 // opportunities that creates).
677 FPM.addPass(BDCEPass());
678
679 // Run instcombine after redundancy and dead bit elimination to exploit
680 // opportunities opened up by them.
682 invokePeepholeEPCallbacks(FPM, Level);
683
684 // Re-consider control flow based optimizations after redundancy elimination,
685 // redo DCE, etc.
686 if (Opts.enable_dfa_jump_thread)
688
691
692 // Finally, do an expensive DCE pass to catch all the dead code exposed by
693 // the simplifications and basic cleanup after all the simplifications.
694 // TODO: Investigate if this is too expensive.
695 FPM.addPass(ADCEPass());
696
697 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
698 FPM.addPass(MemCpyOptPass());
699
700 FPM.addPass(DSEPass());
702
704 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
705 /*AllowSpeculation=*/true),
706 /*UseMemorySSA=*/true));
707
708 FPM.addPass(CoroElidePass());
709
711
713 .convertSwitchRangeToICmp(true)
714 .convertSwitchToArithmetic(true)
715 .hoistCommonInsts(true)
716 .sinkCommonInsts(true)));
718 invokePeepholeEPCallbacks(FPM, Level);
719
720 return FPM;
721}
722
723void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
726 MPM.addPass(AssignGUIDPass());
727}
728
729void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
730 OptimizationLevel Level,
731 ThinOrFullLTOPhase LTOPhase,
732 bool IgnoreProfile) {
733 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
734 if (Opts.disable_preinline)
735 return;
736 InlineParams IP;
737
738 IP.DefaultThreshold = Opts.preinline_threshold;
739 IP.IgnoreProfile = IgnoreProfile;
740
741 // FIXME: The hint threshold has the same value used by the regular inliner
742 // when not optimzing for size. This should probably be lowered after
743 // performance testing.
744 // FIXME: this comment is cargo culted from the old pass manager, revisit).
745 IP.HintThreshold = 325;
746 IP.OptSizeHintThreshold = Opts.preinline_threshold;
748 IP, /* MandatoryFirst */ true,
750 CGSCCPassManager &CGPipeline = MIWP.getPM();
751
753 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
754 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
755 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
756 true))); // Merge & remove basic blocks.
757 FPM.addPass(InstCombinePass()); // Combine silly sequences.
758 invokePeepholeEPCallbacks(FPM, Level);
759
760 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
761 std::move(FPM), PTO.EagerlyInvalidateAnalyses));
762
763 MPM.addPass(std::move(MIWP));
764
765 // Delete anything that is now dead to make sure that we don't instrument
766 // dead code. Instrumentation can end up keeping dead code around and
767 // dramatically increase code size.
768 MPM.addPass(GlobalDCEPass());
769}
770
771void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
772 OptimizationLevel Level) {
773 if (Opts.enable_post_pgo_loop_rotation) {
774 // Disable header duplication in loop rotation at -Oz.
776 createFunctionToLoopPassAdaptor(LoopRotatePass(),
777 /*UseMemorySSA=*/false),
778 PTO.EagerlyInvalidateAnalyses));
779 }
780}
781
782void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
783 OptimizationLevel Level, bool RunProfileGen,
784 bool IsCS, bool AtomicCounterUpdate,
785 std::string ProfileFile,
786 std::string ProfileRemappingFile) {
787 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
788
789 if (!RunProfileGen) {
790 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
791 MPM.addPass(
792 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
793 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
794 // RequireAnalysisPass for PSI before subsequent non-module passes.
795 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
796 return;
797 }
798
799 // Perform PGO instrumentation.
800 MPM.addPass(PGOInstrumentationGen(IsCS ? PGOInstrumentationType::CSFDO
802
803 addPostPGOLoopRotation(MPM, Level);
804 // Add the profile lowering pass.
805 InstrProfOptions Options;
806 if (!ProfileFile.empty())
807 Options.InstrProfileOutput = ProfileFile;
808 // Do counter promotion at Level greater than O0.
809 Options.DoCounterPromotion = true;
810 Options.UseBFIInPromotion = IsCS;
811 if (Opts.enable_sampled_instrumentation) {
812 Options.Sampling = true;
813 // With sampling, there is little beneifit to enable counter promotion.
814 // But note that sampling does work with counter promotion.
815 Options.DoCounterPromotion = false;
816 }
817 Options.Atomic = AtomicCounterUpdate;
818 MPM.addPass(InstrProfilingLoweringPass(Options, IsCS));
819}
820
822 bool RunProfileGen, bool IsCS,
823 bool AtomicCounterUpdate,
824 std::string ProfileFile,
825 std::string ProfileRemappingFile) {
826 if (!RunProfileGen) {
827 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
828 MPM.addPass(
829 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
830 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
831 // RequireAnalysisPass for PSI before subsequent non-module passes.
833 return;
834 }
835
836 // Perform PGO instrumentation.
839 // Add the profile lowering pass.
841 if (!ProfileFile.empty())
842 Options.InstrProfileOutput = ProfileFile;
843 // Do not do counter promotion at O0.
844 Options.DoCounterPromotion = false;
845 Options.UseBFIInPromotion = IsCS;
846 Options.Atomic = AtomicCounterUpdate;
848}
849
853 InlineParams IP;
854 if (PTO.InlinerThreshold == -1)
856 else
857 IP = getInlineParams(PTO.InlinerThreshold);
858 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
859 // set hot-caller threshold to 0 to disable hot
860 // callsite inline (as much as possible [1]) because it makes
861 // profile annotation in the backend inaccurate.
862 //
863 // [1] Note the cost of a function could be below zero due to erased
864 // prologue / epilogue.
865 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
867
868 if (PGOOpt)
869 IP.EnableDeferral = Opts.enable_npm_pgo_inline_deferral;
870
871 ModuleInlinerWrapperPass MIWP(IP, Opts.mandatory_inlining_first,
872 InlineContext{Phase, InlinePass::CGSCCInliner},
873 Opts.enable_ml_inliner, MaxDevirtIterations);
874
875 // Require the GlobalsAA analysis for the module so we can query it within
876 // the CGSCC pipeline.
877 if (Opts.enable_global_analyses) {
879 // Invalidate AAManager so it can be recreated and pick up the newly
880 // available GlobalsAA.
881 MIWP.addModulePass(
883 }
884
885 // Require the ProfileSummaryAnalysis for the module so we can query it within
886 // the inliner pass.
888
889 // Now begin the main postorder CGSCC pipeline.
890 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
891 // manager and trying to emulate its precise behavior. Much of this doesn't
892 // make a lot of sense and we should revisit the core CGSCC structure.
893 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
894
895 // Note: historically, the PruneEH pass was run first to deduce nounwind and
896 // generally clean up exception handling overhead. It isn't clear this is
897 // valuable as the inliner doesn't currently care whether it is inlining an
898 // invoke or a call.
899
900 if (Opts.attributor_enable & AttributorRunOption::CGSCC)
901 MainCGPipeline.addPass(AttributorCGSCCPass());
902
903 // Deduce function attributes. We do another run of this after the function
904 // simplification pipeline, so this only needs to run when it could affect the
905 // function simplification pipeline, which is only the case with recursive
906 // functions.
907 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT) {
908 MainCGPipeline.addPass(AttributorLightCGSCCPass());
909 } else {
910 MainCGPipeline.addPass(
911 PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
912 }
913
914 // When at O3 add argument promotion to the pass pipeline.
915 // FIXME: It isn't at all clear why this should be limited to O3.
916 if (Level == OptimizationLevel::O3)
917 MainCGPipeline.addPass(ArgumentPromotionPass());
918
919 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
920 // there are no OpenMP runtime calls present in the module.
921 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
922 MainCGPipeline.addPass(OpenMPOptCGSCCPass(Phase));
923
924 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
925
926 // Add the core function simplification pipeline nested inside the
927 // CGSCC walk.
930 PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
931
932 // Finally, deduce any function attributes based on the fully simplified
933 // function.
934 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT)
935 MainCGPipeline.addPass(AttributorLightCGSCCPass());
936 else
937 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
938
939 // Mark that the function is fully simplified and that it shouldn't be
940 // simplified again if we somehow revisit it due to CGSCC mutations unless
941 // it's been modified since.
944
945 if (!isThinLTOPreLink(Phase)) {
946 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
947 MainCGPipeline.addPass(CoroAnnotationElidePass());
948 }
949
950 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
953
954 return MIWP;
955}
956
961
963 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
964 // set hot-caller threshold to 0 to disable hot
965 // callsite inline (as much as possible [1]) because it makes
966 // profile annotation in the backend inaccurate.
967 //
968 // [1] Note the cost of a function could be below zero due to erased
969 // prologue / epilogue.
970 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
972
973 if (PGOOpt)
974 IP.EnableDeferral = Opts.enable_npm_pgo_inline_deferral;
975
976 // The inline deferral logic is used to avoid losing some
977 // inlining chance in future. It is helpful in SCC inliner, in which
978 // inlining is processed in bottom-up order.
979 // While in module inliner, the inlining order is a priority-based order
980 // by default. The inline deferral is unnecessary there. So we disable the
981 // inline deferral logic in module inliner.
982 IP.EnableDeferral = false;
983
984 MPM.addPass(ModuleInlinerPass(IP, Opts.enable_ml_inliner, Phase));
986 MPM.addPass(GlobalOptPass());
987 MPM.addPass(GlobalDCEPass());
988 MPM.addPass(AssignGUIDPass());
989 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
990 }
991
994 PTO.EagerlyInvalidateAnalyses));
995
996 if (!isThinLTOPreLink(Phase)) {
999 MPM.addPass(
1001 }
1002
1003 return MPM;
1004}
1005
1009 assert(Level != OptimizationLevel::O0 &&
1010 "Should not be used for O0 pipeline");
1011
1013 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
1014
1016
1017 // Place pseudo probe instrumentation as the first pass of the pipeline to
1018 // minimize the impact of optimization changes.
1019 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && !isThinLTOPostLink(Phase))
1021
1022 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1023
1024 // In ThinLTO mode, when flattened profile is used, all the available
1025 // profile information will be annotated in PreLink phase so there is
1026 // no need to load the profile again in PostLink.
1027 bool LoadSampleProfile = HasSampleProfile && !(Opts.flattened_profile_used &&
1029
1030 // During the ThinLTO backend phase we perform early indirect call promotion
1031 // here, before globalopt. Otherwise imported available_externally functions
1032 // look unreferenced and are removed. If we are going to load the sample
1033 // profile then defer until later.
1034 // TODO: See if we can move later and consolidate with the location where
1035 // we perform ICP when we are loading a sample profile.
1036 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1037 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1038 // determine whether the new direct calls are annotated with prof metadata.
1039 // Ideally this should be determined from whether the IR is annotated with
1040 // sample profile, and not whether the a sample profile was provided on the
1041 // command line. E.g. for flattened profiles where we will not be reloading
1042 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1043 // provide the sample profile file.
1044 if (isThinLTOPostLink(Phase) && !LoadSampleProfile)
1045 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1046
1047 // Create an early function pass manager to cleanup the output of the
1048 // frontend. Not necessary with LTO post link pipelines since the pre link
1049 // pipeline already cleaned up the frontend output.
1050 if (!isThinLTOPostLink(Phase)) {
1051 // Do basic inference of function attributes from known properties of system
1052 // libraries and other oracles.
1054 MPM.addPass(CoroEarlyPass());
1055
1056 FunctionPassManager EarlyFPM;
1057 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1058 // Lower llvm.expect to metadata before attempting transforms.
1059 // Compare/branch metadata may alter the behavior of passes like
1060 // SimplifyCFG.
1062 EarlyFPM.addPass(SimplifyCFGPass());
1064 EarlyFPM.addPass(EarlyCSEPass());
1065 if (Level == OptimizationLevel::O3)
1066 EarlyFPM.addPass(CallSiteSplittingPass());
1068 std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
1069 }
1070
1071 if (LoadSampleProfile) {
1072 // Annotate sample profile right after early FPM to ensure freshness of
1073 // the debug info.
1075 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS));
1076 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1077 // RequireAnalysisPass for PSI before subsequent non-module passes.
1079 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1080 // for the profile annotation to be accurate in the LTO backend.
1081 if (!isLTOPreLink(Phase))
1082 // We perform early indirect call promotion here, before globalopt.
1083 // This is important for the ThinLTO backend phase because otherwise
1084 // imported available_externally functions look unreferenced and are
1085 // removed.
1086 MPM.addPass(
1087 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1088 }
1089
1090 // Try to perform OpenMP specific optimizations on the module. This is a
1091 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1093
1094 if (Opts.attributor_enable & AttributorRunOption::MODULE)
1095 MPM.addPass(AttributorPass());
1096 else if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1098
1099 // Lower type metadata and the type.test intrinsic in the ThinLTO
1100 // post link pipeline after ICP. This is to enable usage of the type
1101 // tests in ICP sequences.
1104
1106
1107 // Interprocedural constant propagation now that basic cleanup has occurred
1108 // and prior to optimizing globals.
1109 // FIXME: This position in the pipeline hasn't been carefully considered in
1110 // years, it should be re-analyzed.
1111 MPM.addPass(
1112 IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/!isLTOPreLink(Phase))));
1113
1114 // Attach metadata to indirect call sites indicating the set of functions
1115 // they may target at run-time. This should follow IPSCCP.
1117
1118 // Optimize globals to try and fold them into constants.
1119 MPM.addPass(GlobalOptPass());
1120
1121 // Create a small function pass pipeline to cleanup after all the global
1122 // optimizations.
1123 FunctionPassManager GlobalCleanupPM;
1124 // FIXME: Should this instead by a run of SROA?
1125 GlobalCleanupPM.addPass(PromotePass());
1126 GlobalCleanupPM.addPass(InstCombinePass());
1127 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1128 GlobalCleanupPM.addPass(
1129 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1130 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
1131 PTO.EagerlyInvalidateAnalyses));
1132
1133 // We already asserted this happens in non-FullLTOPostLink earlier.
1134 const bool IsPreLink = !isThinLTOPostLink(Phase);
1135 // Enable contextual profiling instrumentation.
1136 const bool IsCtxProfGen =
1138 Context.getLibraryOptions());
1139 const bool IsPGOPreLink = !IsCtxProfGen && PGOOpt && IsPreLink;
1140 const bool IsPGOInstrGen =
1141 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1142 const bool IsPGOInstrUse =
1143 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1144 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1145 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1146 // enable ctx profiling from the frontend.
1148 Context.getLibraryOptions())) &&
1149 "Enabling both instrumented PGO and contextual instrumentation is not "
1150 "supported.");
1151 const bool IsCtxProfUse = !UseCtxProfile.empty() && isThinLTOPreLink(Phase);
1152
1153 assert((Opts.instrument_cold_function_only_path.empty() ||
1154 isPGOInstrumentColdFunctionOnly(Context.getLibraryOptions())) &&
1155 "--instrument-cold-function-only-path is provided but "
1156 "--pgo-instrument-cold-function-only is not enabled");
1157 const bool IsColdFuncOnlyInstrGen =
1158 isPGOInstrumentColdFunctionOnly(Context.getLibraryOptions()) &&
1159 IsPGOPreLink && !Opts.instrument_cold_function_only_path.empty();
1160
1161 // When a memory profile is used together with a sample profile, the
1162 // pre-inliner runs after the sample profile has been loaded. By default make
1163 // it ignore the sample profile, so that the inlining seen by MemProfUsePass
1164 // doesn't depend on the sample profile. Otherwise, a different sample profile
1165 // than the one used to build the memory-profiled binary can cause additional
1166 // inlining (e.g. of newly hot callees) that leads to memprof matching
1167 // failures. This matches the IR PGO pipeline, where the pre-inliner runs
1168 // before the profile is annotated.
1169 const bool PreInlinerIgnoreProfile =
1170 IsMemprofUse && HasSampleProfile && Opts.memprof_preinline_ignore_profile;
1171 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1172 IsCtxProfUse || IsColdFuncOnlyInstrGen)
1173 addPreInlinerPasses(MPM, Level, Phase, PreInlinerIgnoreProfile);
1174
1175 // Add all the requested passes for instrumentation PGO, if requested.
1176 if (IsPGOInstrGen || IsPGOInstrUse) {
1177 addPGOInstrPasses(MPM, Level,
1178 /*RunProfileGen=*/IsPGOInstrGen,
1179 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1180 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1181 } else if (IsCtxProfGen || IsCtxProfUse) {
1183 // In pre-link, we just want the instrumented IR. We use the contextual
1184 // profile in the post-thinlink phase.
1185 // The instrumentation will be removed in post-thinlink after IPO.
1186 if (IsCtxProfUse) {
1187 MPM.addPass(AssignGUIDPass());
1188 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
1189 return MPM;
1190 }
1191 // Block further inlining in the instrumented ctxprof case. This avoids
1192 // confusingly collecting profiles for the same GUID corresponding to
1193 // different variants of the function. We could do like PGO and identify
1194 // functions by a (GUID, Hash) tuple, but since the ctxprof "use" waits for
1195 // thinlto to happen before performing any further optimizations, it's
1196 // unnecessary to collect profiles for non-prevailing copies.
1198 addPostPGOLoopRotation(MPM, Level);
1199 MPM.addPass(AssignGUIDPass());
1201 } else if (IsColdFuncOnlyInstrGen) {
1202 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
1203 /* AtomicCounterUpdate */ false,
1204 Opts.instrument_cold_function_only_path.str(),
1205 /* ProfileRemappingFile */ "");
1206 }
1207
1208 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1209 MPM.addPass(PGOIndirectCallPromotion(false, false));
1210
1211 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1213 PGOOpt->CSProfileGenFile, Opts.enable_sampled_instrumentation));
1214
1215 if (IsMemprofUse)
1216 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS));
1217
1218 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse ||
1219 PGOOpt->Action == PGOOptions::SampleUse))
1220 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1221
1222 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1223
1224 if (Opts.enable_module_inliner)
1226 else
1227 MPM.addPass(buildInlinerPipeline(Level, Phase));
1228
1229 // Remove any dead arguments exposed by cleanups, constant folding globals,
1230 // and argument promotion.
1232
1235
1236 if (!isThinLTOPreLink(Phase))
1237 MPM.addPass(CoroCleanupPass());
1238
1239 // Optimize globals now that functions are fully simplified.
1240 MPM.addPass(GlobalOptPass());
1241 MPM.addPass(GlobalDCEPass());
1242
1243 return MPM;
1244}
1245
1246/// TODO: Should LTO cause any differences to this set of passes?
1247void PassBuilder::addVectorPasses(OptimizationLevel Level,
1249 ThinOrFullLTOPhase LTOPhase) {
1252
1253 // Drop dereferenceable assumes after vectorization, as they are no longer
1254 // needed and can inhibit further optimization.
1255 if (!isLTOPreLink(LTOPhase))
1256 FPM.addPass(DropUnnecessaryAssumesPass(/*DropDereferenceable=*/true));
1257
1259 if (isFullLTOPostLink(LTOPhase)) {
1260 // The vectorizer may have significantly shortened a loop body; unroll
1261 // again. Unroll small loops to hide loop backedge latency and saturate any
1262 // parallel execution resources of an out-of-order processor. We also then
1263 // need to clean up redundancies and loop invariant code.
1264 // FIXME: It would be really good to use a loop-integrated instruction
1265 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1266 // across the loop nests.
1267 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1268 if (Opts.enable_unroll_and_jam && PTO.LoopUnrolling)
1270 LoopUnrollAndJamPass(static_cast<int>(Level))));
1272 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1275 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1276 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1277 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1278 // NOTE: we are very late in the pipeline, and we don't have any LICM
1279 // or SimplifyCFG passes scheduled after us, that would cleanup
1280 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1281
1282 // We also turn on struct to vector canonicalization here, which allows
1283 // converting allocas of homogeneous structs into vector allocas when the
1284 // allocas' users are all memory intrinsics. This allows promotion in some
1285 // cases because structs cannot promote to SSA values, but vectors can. We
1286 // only turn this on after memcpyopt runs because this might hinder
1287 // memcpyopt's optimizations if done before. Look at the documentation for
1288 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1290 /*AggregateToVector=*/true)));
1291 }
1292
1293 if (!isFullLTOPostLink(LTOPhase)) {
1294 // Eliminate loads by forwarding stores from the previous iteration to loads
1295 // of the current iteration.
1297 }
1298 // Cleanup after the loop optimization passes.
1299 FPM.addPass(InstCombinePass());
1300
1301 if (Level > OptimizationLevel::O1 && Opts.extra_vectorizer_passes) {
1302 ExtraFunctionPassManager<ShouldRunExtraVectorPasses> ExtraPasses;
1303 // At higher optimization levels, try to clean up any runtime overlap and
1304 // alignment checks inserted by the vectorizer. We want to track correlated
1305 // runtime checks for two inner loops in the same outer loop, fold any
1306 // common computations, hoist loop-invariant aspects out of any outer loop,
1307 // and unswitch the runtime checks if possible. Once hoisted, we may have
1308 // dead (or speculatable) control flows or more combining opportunities.
1309 ExtraPasses.addPass(EarlyCSEPass());
1310 ExtraPasses.addPass(CorrelatedValuePropagationPass());
1311 ExtraPasses.addPass(InstCombinePass());
1312 LoopPassManager LPM;
1313 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1314 /*AllowSpeculation=*/true));
1315 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1317 ExtraPasses.addPass(
1318 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true));
1319 ExtraPasses.addPass(
1320 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1321 ExtraPasses.addPass(InstCombinePass());
1322 FPM.addPass(std::move(ExtraPasses));
1323 }
1324
1325 // Now that we've formed fast to execute loop structures, we do further
1326 // optimizations. These are run afterward as they might block doing complex
1327 // analyses and transforms such as what are needed for loop vectorization.
1328
1329 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1330 // GVN, loop transforms, and others have already run, so it's now better to
1331 // convert to more optimized IR using more aggressive simplify CFG options.
1332 // The extra sinking transform can create larger basic blocks, so do this
1333 // before SLP vectorization.
1334 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1335 .forwardSwitchCondToPhi(true)
1336 .convertSwitchRangeToICmp(true)
1337 .convertSwitchToArithmetic(true)
1338 .convertSwitchToLookupTable(true)
1339 .needCanonicalLoops(false)
1340 .hoistCommonInsts(true)
1341 .sinkCommonInsts(true)));
1342
1343 if (isFullLTOPostLink(LTOPhase)) {
1344 FPM.addPass(SCCPPass());
1345 FPM.addPass(InstCombinePass());
1346 FPM.addPass(BDCEPass());
1347 }
1348
1349 // Optimize parallel scalar instruction chains into SIMD instructions.
1350 if (PTO.SLPVectorization) {
1351 FPM.addPass(SLPVectorizerPass());
1352 if (Level >= OptimizationLevel::O2 && Opts.extra_vectorizer_passes) {
1353 FPM.addPass(EarlyCSEPass());
1354 }
1355 }
1356 // Enhance/cleanup vector code.
1357 FPM.addPass(VectorCombinePass());
1358
1359 if (!isFullLTOPostLink(LTOPhase)) {
1360 FPM.addPass(InstCombinePass());
1361 // Unroll small loops to hide loop backedge latency and saturate any
1362 // parallel execution resources of an out-of-order processor. We also then
1363 // need to clean up redundancies and loop invariant code.
1364 // FIXME: It would be really good to use a loop-integrated instruction
1365 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1366 // across the loop nests.
1367 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1368 if (Opts.enable_unroll_and_jam && PTO.LoopUnrolling) {
1370 LoopUnrollAndJamPass(static_cast<int>(Level))));
1371 }
1372 FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1373 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1374 PTO.ForgetAllSCEVInLoopUnroll)));
1375 FPM.addPass(WarnMissedTransformationsPass());
1376 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1377 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1378 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1379 // NOTE: we are very late in the pipeline, and we don't have any LICM
1380 // or SimplifyCFG passes scheduled after us, that would cleanup
1381 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1382
1383 // We also turn on struct to vector canonicalization here, which allows
1384 // converting allocas of homogeneous structs into vector allocas when the
1385 // allocas' users are all memory intrinsics. This allows promotion in some
1386 // cases because structs cannot promote to SSA values, but vectors can. We
1387 // only turn this on after memcpyopt runs because this might hinder
1388 // memcpyopt's optimizations if done before. Look at the documentation for
1389 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1390 FPM.addPass(SROAPass(SROAOptions(SROAOptions::PreserveCFG,
1391 /*AggregateToVector=*/true)));
1392 }
1393
1394 FPM.addPass(InferAlignmentPass());
1395 FPM.addPass(InstCombinePass());
1396
1397 // This is needed for two reasons:
1398 // 1. It works around problems that instcombine introduces, such as sinking
1399 // expensive FP divides into loops containing multiplications using the
1400 // divide result.
1401 // 2. It helps to clean up some loop-invariant code created by the loop
1402 // unroll pass when IsFullLTO=false.
1404 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1405 /*AllowSpeculation=*/true),
1406 /*UseMemorySSA=*/true));
1407
1408 // Now that we've vectorized and unrolled loops, we may have more refined
1409 // alignment information, try to re-derive it here.
1410 FPM.addPass(AlignmentFromAssumptionsPass());
1411}
1412
1415 ThinOrFullLTOPhase LTOPhase) {
1417
1418 // Run partial inlining pass to partially inline functions that have
1419 // large bodies.
1420 if (Opts.enable_partial_inlining)
1422
1423 // Remove avail extern fns and globals definitions since we aren't compiling
1424 // an object file for later LTO. For LTO we want to preserve these so they
1425 // are eligible for inlining at link-time. Note if they are unreferenced they
1426 // will be removed by GlobalDCE later, so this only impacts referenced
1427 // available externally globals. Eventually they will be suppressed during
1428 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1429 // may make globals referenced by available external functions dead and saves
1430 // running remaining passes on the eliminated functions. These should be
1431 // preserved during prelinking for link-time inlining decisions.
1432 if (!isLTOPreLink(LTOPhase))
1434
1435 // Do RPO function attribute inference across the module to forward-propagate
1436 // attributes where applicable.
1437 // FIXME: Is this really an optimization rather than a canonicalization?
1438 if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
1440 else
1442
1443 // Do a post inline PGO instrumentation and use pass. This is a context
1444 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1445 // cross-module inline has not been done yet. The context sensitive
1446 // instrumentation is after all the inlines are done.
1447 if (!isLTOPreLink(LTOPhase) && PGOOpt) {
1448 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1449 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1450 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1451 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
1452 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1453 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1454 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1455 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1456 }
1457
1458 // Re-compute GlobalsAA here prior to function passes. This is particularly
1459 // useful as the above will have inlined, DCE'ed, and function-attr
1460 // propagated everything. We should at this point have a reasonably minimal
1461 // and richly annotated call graph. By computing aliasing and mod/ref
1462 // information for all local globals here, the late loop passes and notably
1463 // the vectorizer will be able to use them to help recognize vectorizable
1464 // memory operations.
1465 if (Opts.enable_global_analyses)
1467
1468 invokeOptimizerEarlyEPCallbacks(MPM, Level, LTOPhase);
1469
1470 FunctionPassManager OptimizePM;
1471
1472 // Only drop unnecessary assumes post-inline and post-link, as otherwise
1473 // additional uses of the affected value may be introduced through inlining
1474 // and CSE.
1475 if (!isLTOPreLink(LTOPhase))
1476 OptimizePM.addPass(DropUnnecessaryAssumesPass());
1477
1478 // Scheduling LoopVersioningLICM when inlining is over, because after that
1479 // we may see more accurate aliasing. Reason to run this late is that too
1480 // early versioning may prevent further inlining due to increase of code
1481 // size. Other optimizations which runs later might get benefit of no-alias
1482 // assumption in clone loop.
1483 if (Opts.enable_loop_versioning_licm) {
1484 OptimizePM.addPass(
1486 // LoopVersioningLICM pass might increase new LICM opportunities.
1488 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1489 /*AllowSpeculation=*/true),
1490 /*USeMemorySSA=*/true));
1491 }
1492
1493 OptimizePM.addPass(Float2IntPass());
1494 // Defer until LTO post-link where some constants may become known.
1495 if (!isLTOPreLink(LTOPhase))
1497
1498 if (Opts.enable_matrix) {
1499 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1500 OptimizePM.addPass(EarlyCSEPass());
1501 }
1502
1503 // CHR pass should only be applied with the profile information.
1504 // The check is to check the profile summary information in CHR.
1505 if (Opts.enable_chr && Level == OptimizationLevel::O3)
1506 OptimizePM.addPass(ControlHeightReductionPass());
1507
1508 // FIXME: We need to run some loop optimizations to re-rotate loops after
1509 // simplifycfg and others undo their rotation.
1510
1511 // Optimize the loop execution. These passes operate on entire loop nests
1512 // rather than on each loop in an inside-out manner, and so they are actually
1513 // function passes.
1514
1515 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1516
1517 LoopPassManager LPM;
1518 // First rotate loops that may have been un-rotated by prior passes.
1519 // Disable header duplication at -Oz.
1520 LPM.addPass(LoopRotatePass(/*EnableLoopHeaderDuplication=*/true,
1521 isLTOPreLink(LTOPhase),
1522 /*CheckExitCount=*/true));
1523 // Some loops may have become dead by now. Try to delete them.
1524 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1525 // this may need to be revisited once we run GVN before loop deletion
1526 // in the simplification pipeline.
1527 LPM.addPass(LoopDeletionPass());
1528
1529 if (PTO.LoopInterchange)
1530 LPM.addPass(LoopInterchangePass());
1531
1532 OptimizePM.addPass(
1533 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
1534
1535 // FIXME: This may not be the right place in the pipeline.
1536 // We need to have the data to support the right place.
1537 if (PTO.LoopFusion)
1538 OptimizePM.addPass(LoopFusePass());
1539
1540 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1541 // into separate loop that would otherwise inhibit vectorization. This is
1542 // currently only performed for loops marked with the metadata
1543 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1544 OptimizePM.addPass(LoopDistributePass());
1545
1546 // Populates the VFABI attribute with the scalar-to-vector mappings
1547 // from the TargetLibraryInfo.
1548 OptimizePM.addPass(InjectTLIMappings());
1549
1550 addVectorPasses(Level, OptimizePM, LTOPhase);
1551
1552 invokeVectorizerEndEPCallbacks(OptimizePM, Level);
1553
1554 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1555 // canonicalization pass that enables other optimizations. As a result,
1556 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1557 // result too early.
1558 OptimizePM.addPass(LoopSinkPass());
1559
1560 // And finally clean up LCSSA form before generating code.
1561 OptimizePM.addPass(InstSimplifyPass());
1562
1563 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1564 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1565 // flattening of blocks.
1566 OptimizePM.addPass(DivRemPairsPass());
1567
1568 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
1569 // TODO: move this further up so that it can be optimized by GVN, etc.
1570 if (Opts.enable_mergeicmps)
1571 OptimizePM.addPass(MergeICmpsPass());
1572 OptimizePM.addPass(ExpandMemCmpPass());
1573
1574 // Try to annotate calls that were created during optimization.
1575 OptimizePM.addPass(
1576 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
1577
1578 // LoopSink (and other loop passes since the last simplifyCFG) might have
1579 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1580 OptimizePM.addPass(
1582 .convertSwitchRangeToICmp(true)
1583 .convertSwitchToArithmetic(true)
1584 .speculateUnpredictables(true)
1585 .hoistLoadsStoresWithCondFaulting(true)));
1586
1587 // Add the core optimizing pipeline.
1588 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1589 PTO.EagerlyInvalidateAnalyses));
1590
1591 // AllocToken transforms heap allocation calls; this needs to run late after
1592 // other allocation call transformations (such as those in InstCombine).
1593 if (!isLTOPreLink(LTOPhase))
1594 MPM.addPass(AllocTokenPass());
1595
1596 invokeOptimizerLastEPCallbacks(MPM, Level, LTOPhase);
1597
1598 // Run the Instrumentor pass late.
1599 if (Opts.enable_instrumentor)
1600 MPM.addPass(InstrumentorPass(FS));
1601
1602 // Split out cold code. Splitting is done late to avoid hiding context from
1603 // other optimizations and inadvertently regressing performance. The tradeoff
1604 // is that this has a higher code size cost than splitting early.
1605 if (Opts.hot_cold_split && !isLTOPreLink(LTOPhase))
1607
1608 // Now we need to do some global optimization transforms.
1609 // FIXME: It would seem like these should come first in the optimization
1610 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1611 // ordering here.
1612 MPM.addPass(GlobalDCEPass());
1614
1615 // Merge functions if requested. It has a better chance to merge functions
1616 // after ConstantMerge folded jump tables.
1617 if (PTO.MergeFunctions)
1619
1620 if (PTO.CallGraphProfile && !isLTOPreLink(LTOPhase))
1621 MPM.addPass(CGProfilePass(isLTOPostLink(LTOPhase)));
1622
1623 // RelLookupTableConverterPass runs later in LTO post-link pipeline.
1624 if (!isLTOPreLink(LTOPhase))
1626
1627 // Add devirtualization pass only when LTO is not enabled, as otherwise
1628 // the pass is already enabled in the LTO pipeline.
1629 if (PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
1630 // TODO: explore a better pipeline configuration that can improve
1631 // compilation time overhead.
1632 // FIXME: move this earlier (lots of pass ordering tests will need fixing)
1633 MPM.addPass(AssignGUIDPass());
1635 /*ExportSummary*/ nullptr,
1636 /*ImportSummary*/ nullptr,
1637 /*DevirtSpeculatively*/ PTO.DevirtualizeSpeculatively));
1639 // Given that the devirtualization creates more opportunities for inlining,
1640 // we run the Inliner again here to maximize the optimization gain we
1641 // get from devirtualization.
1642 // Also, we can't run devirtualization before inlining because the
1643 // devirtualization depends on the passes optimizing/eliminating vtable GVs
1644 // and those passes are only effective after inlining.
1646 }
1647
1648 // Attach !implicit.ref metadata from all functions to copyright strings.
1650
1651 return MPM;
1652}
1653
1657 if (Level == OptimizationLevel::O0)
1658 return buildO0DefaultPipeline(Level, Phase);
1659
1661 addPipelineStartPasses(MPM, Opts);
1662 // Currently this pipeline is only invoked in an LTO pre link pass or when we
1663 // are not running LTO. If that changes the below checks may need updating.
1665
1666 // If we are invoking this in non-LTO mode, remove any MemProf related
1667 // attributes and metadata, as we don't know whether we are linking with
1668 // a library containing the necessary interfaces.
1671
1672 // Convert @llvm.global.annotations to !annotation metadata.
1674
1675 // Force any function attributes we want the rest of the pipeline to observe.
1677
1678 if (Opts.opt_pipeline_trigger_crash)
1680
1681 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1683
1684 // Apply module pipeline start EP callback.
1686
1687 // Add the core simplification pipeline.
1689
1690 // Now add the optimization pipeline.
1692
1693 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1694 PGOOpt->Action == PGOOptions::SampleUse)
1696
1697 // Emit annotation remarks.
1699
1700 if (isLTOPreLink(Phase))
1701 addRequiredLTOPreLinkPasses(MPM);
1702
1703 addPipelineEndPasses(MPM, Opts);
1704 return MPM;
1705}
1706
1709 bool EmitSummary, bool Verify) {
1711
1712 addPipelineStartPasses(MPM, Opts);
1713
1714 if (ThinLTO)
1716 else
1718 // AssignGUIDPass attaches !guid metadata (MD_unique_id) to global objects,
1719 // triggering the bitcode writer to emit a METADATA_KIND_BLOCK. Standard LTO
1720 // bitcode emission runs VerifierPass by default, which registers metadata
1721 // kind IDs in LLVMContext. Running VerifierPass here before EmbedBitcodePass
1722 // to get the same behavior.
1723 if (Verify)
1724 MPM.addPass(VerifierPass());
1725 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1726
1727 // Perform any cleanups to the IR that aren't suitable for per TU compilation,
1728 // like removing CFI/WPD related instructions. Note, we reuse
1729 // DropTypeTestsPass to clean up type tests rather than duplicate that logic
1730 // in FatLtoCleanup; checked-load cleanup is shared the other way, with
1731 // FatLtoCleanup calling lowertypetests::cleanUpTypeCheckedLoad.
1732 MPM.addPass(FatLtoCleanup());
1733
1734 // If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
1735 // object code, only in the bitcode section, so drop it before we run
1736 // module optimization and generate machine code. If llvm.type.test() isn't in
1737 // the IR, this won't do anything.
1739
1740 // Use the ThinLTO post-link pipeline with sample profiling
1741 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1742 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1743 else {
1744 // ModuleSimplification does not run the coroutine passes for
1745 // ThinLTOPreLink, so we need the coroutine passes to run for ThinLTO
1746 // builds, otherwise they will miscompile.
1747 if (ThinLTO) {
1748 // TODO: replace w/ buildCoroWrapper() when it takes phase and level into
1749 // consideration.
1750 CGSCCPassManager CGPM;
1754 MPM.addPass(CoroCleanupPass());
1755 }
1756
1757 // otherwise, just use module optimization
1758 MPM.addPass(
1760 // Emit annotation remarks.
1762 }
1763
1764 addPipelineEndPasses(MPM, Opts);
1765
1766 return MPM;
1767}
1768
1771 if (Level == OptimizationLevel::O0)
1773
1775
1776 addPipelineStartPasses(MPM, Opts);
1777
1778 // Convert @llvm.global.annotations to !annotation metadata.
1780
1781 // Force any function attributes we want the rest of the pipeline to observe.
1783
1784 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1786
1787 // Apply module pipeline start EP callback.
1789
1790 // If we are planning to perform ThinLTO later, we don't bloat the code with
1791 // unrolling/vectorization/... now. Just simplify the module as much as we
1792 // can.
1795 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1796 // thinlto use the contextual info to perform imports; then use the contextual
1797 // profile in the post-thinlink phase.
1798 if (!UseCtxProfile.empty()) {
1799 addRequiredLTOPreLinkPasses(MPM);
1800 return MPM;
1801 }
1802
1803 // Run partial inlining pass to partially inline functions that have
1804 // large bodies.
1805 // FIXME: It isn't clear whether this is really the right place to run this
1806 // in ThinLTO. Because there is another canonicalization and simplification
1807 // phase that will run after the thin link, running this here ends up with
1808 // less information than will be available later and it may grow functions in
1809 // ways that aren't beneficial.
1810 if (Opts.enable_partial_inlining)
1812
1813 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1814 PGOOpt->Action == PGOOptions::SampleUse)
1816
1817 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1818 // optimization is going to be done in PostLink stage, but clang can't add
1819 // callbacks there in case of in-process ThinLTO called by linker.
1824
1825 // Emit annotation remarks.
1827
1828 // Attach !implicit.ref metadata from all functions to copyright strings.
1830
1831 addRequiredLTOPreLinkPasses(MPM);
1832
1833 addPipelineEndPasses(MPM, Opts);
1834
1835 return MPM;
1836}
1837
1839 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1841
1842 addPipelineStartPasses(MPM, Opts);
1843
1845
1846 // If we are invoking this without a summary index noting that we are linking
1847 // with a library containing the necessary APIs, remove any MemProf related
1848 // attributes and metadata.
1849 if (!ImportSummary || !ImportSummary->withSupportsHotColdNew())
1851
1852 if (ImportSummary) {
1853 // For ThinLTO we must apply the context disambiguation decisions early, to
1854 // ensure we can correctly match the callsites to summary data.
1857 ImportSummary, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1858
1859 // These passes import type identifier resolutions for whole-program
1860 // devirtualization and CFI. They must run early because other passes may
1861 // disturb the specific instruction patterns that these passes look for,
1862 // creating dependencies on resolutions that may not appear in the summary.
1863 //
1864 // For example, GVN may transform the pattern assume(type.test) appearing in
1865 // two basic blocks into assume(phi(type.test, type.test)), which would
1866 // transform a dependency on a WPD resolution into a dependency on a type
1867 // identifier resolution for CFI.
1868 //
1869 // Also, WPD has access to more precise information than ICP and can
1870 // devirtualize more effectively, so it should operate on the IR first.
1871 //
1872 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1873 // metadata and intrinsics.
1874 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1875 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1876 }
1877
1878 if (Level == OptimizationLevel::O0) {
1879 // Run a second time to clean up any type tests left behind by WPD for use
1880 // in ICP.
1883
1884 // AllocToken transforms heap allocation calls; this needs to run late after
1885 // other allocation call transformations (such as those in InstCombine).
1886 MPM.addPass(AllocTokenPass());
1887
1888 // Drop available_externally and unreferenced globals. This is necessary
1889 // with ThinLTO in order to avoid leaving undefined references to dead
1890 // globals in the object file.
1892 MPM.addPass(GlobalDCEPass());
1893
1895
1896 return MPM;
1897 }
1898 if (!UseCtxProfile.empty()) {
1899 MPM.addPass(
1901 } else {
1902 // Add the core simplification pipeline.
1905 }
1906 // Now add the optimization pipeline.
1909
1911
1912 // Emit annotation remarks.
1914
1915 addPipelineEndPasses(MPM, Opts);
1916
1917 return MPM;
1918}
1919
1922 // FIXME: We should use a customized pre-link pipeline!
1923 return buildPerModuleDefaultPipeline(Level,
1925}
1926
1929 ModuleSummaryIndex *ExportSummary) {
1931
1932 addPipelineStartPasses(MPM, Opts);
1933
1935
1936 // If we are invoking this without a summary index noting that we are linking
1937 // with a library containing the necessary APIs, remove any MemProf related
1938 // attributes and metadata.
1939 if (!ExportSummary || !ExportSummary->withSupportsHotColdNew())
1941
1942 // Create a function that performs CFI checks for cross-DSO calls with targets
1943 // in the current module.
1944 MPM.addPass(CrossDSOCFIPass());
1945
1946 if (Level == OptimizationLevel::O0) {
1947 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1948 // metadata and intrinsics.
1949 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1950 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1951 // Run a second time to clean up any type tests left behind by WPD for use
1952 // in ICP.
1954
1956
1957 // AllocToken transforms heap allocation calls; this needs to run late after
1958 // other allocation call transformations (such as those in InstCombine).
1959 MPM.addPass(AllocTokenPass());
1960
1962
1963 // Emit annotation remarks.
1965
1966 return MPM;
1967 }
1968
1969 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1970 // Load sample profile before running the LTO optimization pipeline.
1971 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1972 PGOOpt->ProfileRemappingFile,
1974 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1975 // RequireAnalysisPass for PSI before subsequent non-module passes.
1977 }
1978
1979 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
1981
1982 // Remove unused virtual tables to improve the quality of code generated by
1983 // whole-program devirtualization and bitset lowering.
1984 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
1985
1986 // Do basic inference of function attributes from known properties of system
1987 // libraries and other oracles.
1989
1990 if (Level >= OptimizationLevel::O2) {
1992 CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
1993
1994 // Indirect call promotion. This should promote all the targets that are
1995 // left by the earlier promotion pass that promotes intra-module targets.
1996 // This two-step promotion is to save the compile time. For LTO, it should
1997 // produce the same result as if we only do promotion here.
1999 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2000
2001 // Promoting by-reference arguments to by-value exposes more constants to
2002 // IPSCCP.
2003 CGSCCPassManager CGPM;
2004 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT)
2006 else
2009 CGPM.addPass(
2012
2013 // Propagate constants at call sites into the functions they call. This
2014 // opens opportunities for globalopt (and inlining) by substituting function
2015 // pointers passed as arguments to direct uses of functions.
2016 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/true)));
2017
2018 // Attach metadata to indirect call sites indicating the set of functions
2019 // they may target at run-time. This should follow IPSCCP.
2021 }
2022
2023 // Do RPO function attribute inference across the module to forward-propagate
2024 // attributes where applicable.
2025 // FIXME: Is this really an optimization rather than a canonicalization?
2026 if (Opts.attributor_enable & AttributorRunOption::MODULE_LIGHT)
2028 else
2030
2031 // Use in-range annotations on GEP indices to split globals where beneficial.
2032 MPM.addPass(GlobalSplitPass());
2033
2034 // Run whole program optimization of virtual call when the list of callees
2035 // is fixed.
2036 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2037
2039 // Stop here at -O1.
2040 if (Level == OptimizationLevel::O1) {
2042 LowerConstantIntrinsicsPass(), PTO.EagerlyInvalidateAnalyses));
2043
2044 // The LowerTypeTestsPass needs to run to lower type metadata and the
2045 // type.test intrinsics. The pass does nothing if CFI is disabled.
2046 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2047 // Run a second time to clean up any type tests left behind by WPD for use
2048 // in ICP (which is performed earlier than this in the regular LTO
2049 // pipeline).
2051
2053
2054 // AllocToken transforms heap allocation calls; this needs to run late after
2055 // other allocation call transformations (such as those in InstCombine).
2056 MPM.addPass(AllocTokenPass());
2057
2059
2060 // Emit annotation remarks.
2062
2063 addPipelineEndPasses(MPM, Opts);
2064
2065 return MPM;
2066 }
2067
2068 // TODO: Skip to match buildCoroWrapper.
2069 MPM.addPass(CoroEarlyPass());
2070
2071 // Optimize globals to try and fold them into constants.
2072 MPM.addPass(GlobalOptPass());
2073
2074 // Promote any localized globals to SSA registers.
2076
2077 // Linking modules together can lead to duplicate global constant, only
2078 // keep one copy of each constant.
2080
2081 // Remove unused arguments from functions.
2083
2084 // Reduce the code after globalopt and ipsccp. Both can open up significant
2085 // simplification opportunities, and both can propagate functions through
2086 // function pointers. When this happens, we often have to resolve varargs
2087 // calls, etc, so let instcombine do this.
2088 FunctionPassManager PeepholeFPM;
2089 PeepholeFPM.addPass(InstCombinePass());
2090 if (Level >= OptimizationLevel::O2)
2091 PeepholeFPM.addPass(AggressiveInstCombinePass());
2092 invokePeepholeEPCallbacks(PeepholeFPM, Level);
2093
2094 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
2095 PTO.EagerlyInvalidateAnalyses));
2096
2097 // Lower variadic functions for supported targets prior to inlining.
2099
2100 // Note: historically, the PruneEH pass was run first to deduce nounwind and
2101 // generally clean up exception handling overhead. It isn't clear this is
2102 // valuable as the inliner doesn't currently care whether it is inlining an
2103 // invoke or a call.
2104 // Run the inliner now.
2106
2107 // Perform context disambiguation after inlining, since that would reduce the
2108 // amount of additional cloning required to distinguish the allocation
2109 // contexts.
2112 /*Summary=*/nullptr,
2113 PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2114
2115 // Optimize globals again after we ran the inliner.
2116 MPM.addPass(GlobalOptPass());
2117
2118 // Run the OpenMPOpt pass again after global optimizations.
2120
2121 // Garbage collect dead functions.
2122 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2123
2124 // If we didn't decide to inline a function, check to see if we can
2125 // transform it to pass arguments by value instead of by reference.
2126 CGSCCPassManager CGPM;
2132
2134 // The IPO Passes may leave cruft around. Clean up after them.
2135 FPM.addPass(InstCombinePass());
2136 invokePeepholeEPCallbacks(FPM, Level);
2137
2138 if (Opts.enable_constraint_elimination)
2140
2142
2143 // Do a post inline PGO instrumentation and use pass. This is a context
2144 // sensitive PGO pass.
2145 if (PGOOpt) {
2146 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
2147 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
2148 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2149 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
2150 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
2151 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
2152 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2153 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
2154 }
2155
2156 // Break up allocas
2158
2159 // LTO provides additional opportunities for tailcall elimination due to
2160 // link-time inlining, and visibility of nocapture attribute.
2161 FPM.addPass(
2162 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
2163
2164 // Run a few AA driver optimizations here and now to cleanup the code.
2165 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
2166 PTO.EagerlyInvalidateAnalyses));
2167
2168 if (Opts.attributor_enable & AttributorRunOption::CGSCC_LIGHT) {
2169 MPM.addPass(
2171 } else {
2172 MPM.addPass(
2174 }
2175
2176 // Require the GlobalsAA analysis for the module so we can query it within
2177 // MainFPM.
2178 if (Opts.enable_global_analyses) {
2180 // Invalidate AAManager so it can be recreated and pick up the newly
2181 // available GlobalsAA.
2182 MPM.addPass(
2184 }
2185
2186 FunctionPassManager MainFPM;
2188 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
2189 /*AllowSpeculation=*/true),
2190 /*USeMemorySSA=*/true));
2191
2192 if (Opts.enable_newgvn)
2193 MainFPM.addPass(NewGVNPass());
2194 else
2195 MainFPM.addPass(GVNPass());
2196
2197 // Remove dead memcpy()'s.
2198 MainFPM.addPass(MemCpyOptPass());
2199
2200 // Nuke dead stores.
2201 MainFPM.addPass(DSEPass());
2202 MainFPM.addPass(MoveAutoInitPass());
2204
2206
2207 invokeVectorizerStartEPCallbacks(MainFPM, Level);
2208
2209 LoopPassManager LPM;
2210 if (Opts.enable_loop_flatten && Level >= OptimizationLevel::O2)
2211 LPM.addPass(LoopFlattenPass());
2212 LPM.addPass(IndVarSimplifyPass());
2213 LPM.addPass(LoopDeletionPass());
2214 // FIXME: Add loop interchange.
2215
2216 // Unroll small loops and perform peeling.
2217 LPM.addPass(LoopFullUnrollPass(static_cast<int>(Level),
2218 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
2219 PTO.ForgetAllSCEVInLoopUnroll));
2220 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2221 // *All* loop passes must preserve it, in order to be able to use it.
2222 MainFPM.addPass(
2223 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
2224
2225 MainFPM.addPass(LoopDistributePass());
2226
2227 addVectorPasses(Level, MainFPM, ThinOrFullLTOPhase::FullLTOPostLink);
2228
2229 invokeVectorizerEndEPCallbacks(MainFPM, Level);
2230
2231 // Run the OpenMPOpt CGSCC pass again late.
2234
2235 invokePeepholeEPCallbacks(MainFPM, Level);
2236 MainFPM.addPass(JumpThreadingPass());
2237 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
2238 PTO.EagerlyInvalidateAnalyses));
2239
2240 // Lower type metadata and the type.test intrinsic. This pass supports
2241 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2242 // to be run at link time if CFI is enabled. This pass does nothing if
2243 // CFI is disabled.
2244 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2245 // Run a second time to clean up any type tests left behind by WPD for use
2246 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2248
2249 // Enable splitting late in the FullLTO post-link pipeline.
2250 if (Opts.hot_cold_split)
2252
2253 // Add late LTO optimization passes.
2254 FunctionPassManager LateFPM;
2255
2256 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2257 // canonicalization pass that enables other optimizations. As a result,
2258 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2259 // result too early.
2260 LateFPM.addPass(LoopSinkPass());
2261
2262 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2263 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2264 // flattening of blocks.
2265 LateFPM.addPass(DivRemPairsPass());
2266
2267 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
2268 // TODO: move this further up so that it can be optimized by GVN, etc.
2269 if (Opts.enable_mergeicmps)
2270 LateFPM.addPass(MergeICmpsPass());
2271 LateFPM.addPass(ExpandMemCmpPass());
2272
2273 // Delete basic blocks, which optimization passes may have killed.
2275 .convertSwitchRangeToICmp(true)
2276 .convertSwitchToArithmetic(true)
2277 .hoistCommonInsts(true)
2278 .speculateUnpredictables(true)));
2279 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2280
2281 // Drop bodies of available eternally objects to improve GlobalDCE.
2283
2284 // Now that we have optimized the program, discard unreachable functions.
2285 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2286
2287 if (PTO.MergeFunctions)
2289
2291
2292 if (PTO.CallGraphProfile)
2293 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2294
2295 MPM.addPass(CoroCleanupPass());
2296
2297 // AllocToken transforms heap allocation calls; this needs to run late after
2298 // other allocation call transformations (such as those in InstCombine).
2299 MPM.addPass(AllocTokenPass());
2300
2302
2303 // Emit annotation remarks.
2305
2306 addPipelineEndPasses(MPM, Opts);
2307
2308 return MPM;
2309}
2310
2314 assert(Level == OptimizationLevel::O0 &&
2315 "buildO0DefaultPipeline should only be used with O0");
2316
2318
2319 addPipelineStartPasses(MPM, Opts);
2320
2321 // Perform pseudo probe instrumentation in O0 mode. This is for the
2322 // consistency between different build modes. For example, a LTO build can be
2323 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2324 // the postlink will require pseudo probe instrumentation in the prelink.
2325 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2327
2328 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2329 PGOOpt->Action == PGOOptions::IRUse))
2331 MPM,
2332 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2333 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2334 PGOOpt->ProfileRemappingFile);
2335
2336 // Instrument function entry and exit before all inlining.
2338 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2339
2341
2342 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2344
2345 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2346 // Explicitly disable sample loader inlining and use flattened profile in O0
2347 // pipeline.
2348 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2349 PGOOpt->ProfileRemappingFile,
2351 /*DisableSampleProfileInlining=*/true,
2352 /*UseFlattenedProfile=*/true));
2353 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2354 // RequireAnalysisPass for PSI before subsequent non-module passes.
2356 }
2357
2359
2360 // Build a minimal pipeline based on the semantics required by LLVM,
2361 // which is just that always inlining occurs. Further, disable generating
2362 // lifetime intrinsics to avoid enabling further optimizations during
2363 // code generation.
2365 /*InsertLifetimeIntrinsics=*/false));
2366
2367 if (PTO.MergeFunctions)
2369
2370 if (Opts.enable_matrix)
2371 MPM.addPass(
2373
2374 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2375 CGSCCPassManager CGPM;
2377 if (!CGPM.isEmpty())
2379 }
2380 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2381 LoopPassManager LPM;
2383 if (!LPM.isEmpty()) {
2385 createFunctionToLoopPassAdaptor(std::move(LPM))));
2386 }
2387 }
2388 if (!LoopOptimizerEndEPCallbacks.empty()) {
2389 LoopPassManager LPM;
2391 if (!LPM.isEmpty()) {
2393 createFunctionToLoopPassAdaptor(std::move(LPM))));
2394 }
2395 }
2396 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2399 if (!FPM.isEmpty())
2400 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2401 }
2402
2404
2405 if (!VectorizerStartEPCallbacks.empty()) {
2408 if (!FPM.isEmpty())
2409 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2410 }
2411
2412 if (!VectorizerEndEPCallbacks.empty()) {
2415 if (!FPM.isEmpty())
2416 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2417 }
2418
2420
2421 // AllocToken transforms heap allocation calls; this needs to run late after
2422 // other allocation call transformations (such as those in InstCombine).
2423 if (!isLTOPreLink(Phase))
2424 MPM.addPass(AllocTokenPass());
2425
2427
2428 if (Opts.enable_instrumentor)
2429 MPM.addPass(InstrumentorPass(FS));
2430
2431 // Attach !implicit.ref metadata from all functions to copyright strings.
2433
2434 if (isLTOPreLink(Phase))
2435 addRequiredLTOPreLinkPasses(MPM);
2436
2437 // Emit annotation remarks.
2439
2440 addPipelineEndPasses(MPM, Opts);
2441
2442 return MPM;
2443}
2444
2446 AAManager AA;
2447
2448 // The order in which these are registered determines their priority when
2449 // being queried.
2450
2451 // Add any target-specific alias analyses that should be run early.
2452 if (TM)
2453 TM->registerEarlyDefaultAliasAnalyses(AA);
2454
2455 // First we register the basic alias analysis that provides the majority of
2456 // per-function local AA logic. This is a stateless, on-demand local set of
2457 // AA techniques.
2458 AA.registerFunctionAnalysis<BasicAA>();
2459
2460 // Next we query fast, specialized alias analyses that wrap IR-embedded
2461 // information about aliasing.
2462 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2463 AA.registerFunctionAnalysis<TypeBasedAA>();
2464
2465 // Add support for querying global aliasing information when available.
2466 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2467 // analysis, all that the `AAManager` can do is query for any *cached*
2468 // results from `GlobalsAA` through a readonly proxy.
2469 if (Opts.enable_global_analyses)
2470 AA.registerModuleAnalysis<GlobalsAA>();
2471
2472 // Add target-specific alias analyses.
2473 if (TM)
2474 TM->registerDefaultAliasAnalyses(AA);
2475
2476 return AA;
2477}
2478
2479bool PassBuilder::isInstrumentedPGOUse() const {
2480 return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2481 !UseCtxProfile.empty();
2482}
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 addAnnotationRemarksPass(ModulePassManager &MPM)
static CoroConditionalWrapper buildCoroWrapper(ThinOrFullLTOPhase Phase)
static bool isFullLTOPostLink(ThinOrFullLTOPhase Phase)
static void addModuleInlinerPass(ModulePassManager &MPM, const PassesOptions &Opts, OptimizationLevel Level, 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.
This class implements a trivial dead store elimination.
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:73
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:81
CGSCCPassManager & getPM()
Allow adding more CGSCC passes, besides inlining.
Definition Inliner.h:78
void addLateModulePass(T Pass)
Add a module pass that runs after the CGSCC passes.
Definition Inliner.h:86
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.
unsigned LicmMssaNoAccForPromotionCap
Tuning option to disable promotion to scalars in LICM with MemorySSA, if the number of access is too ...
Definition PassBuilder.h:89
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition PassBuilder.h:67
int InlinerThreshold
Tuning option to override the default inliner threshold.
bool LoopFusion
Tuning option to enable/disable loop fusion. Its default value is false.
Definition PassBuilder.h:77
PipelineTuningOptions()
Constructor sets pipeline tuning defaults based on the global values of the library options.
Definition PassBuilder.h:51
bool CallGraphProfile
Tuning option to enable/disable call graph profile.
Definition PassBuilder.h:93
bool MergeFunctions
Tuning option to enable/disable function merging.
bool ForgetAllSCEVInLoopUnroll
Tuning option to forget all SCEV loops in LoopUnroll.
Definition PassBuilder.h:81
unsigned LicmMssaOptCap
Tuning option to cap the number of calls to retrive clobbering accesses in MemorySSA,...
Definition PassBuilder.h:85
bool LoopInterleaving
Tuning option to set loop interleaving on/off, set based on opt level.
Definition PassBuilder.h:59
bool LoopUnrolling
Tuning option to enable/disable loop unrolling. Its default value is true.
Definition PassBuilder.h:70
bool LoopInterchange
Tuning option to enable/disable loop interchange.
Definition PassBuilder.h:74
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:63
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:164
@ 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 unsigned getLicmMssaNoAccForPromotionCap(const cl::LibraryOptionsContext *LibraryOptions)
Returns -licm-mssa-max-acc-promotion of LibraryOptions, or its global value if null.
Definition LICM.cpp:125
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 bool getForgetSCEVInLoopUnroll(const cl::LibraryOptionsContext *LibraryOptions)
Returns -forget-scev-loop-unroll of LibraryOptions, or its global value if null.
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 unsigned getLicmMssaOptCap(const cl::LibraryOptionsContext *LibraryOptions)
Returns -licm-mssa-optimization-cap of LibraryOptions, or its global value if null.
Definition LICM.cpp:120
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.
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 InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
LLVM_ABI InlineParams getInlineParamsFromOptLevel(unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
cl::opt< unsigned > MaxDevirtIterations("max-devirt-iterations", cl::ReallyHidden, cl::init(4))
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:207
std::optional< int > OptSizeHintThreshold
Threshold to use for callees with inline hint, when the caller is optimized for size.
Definition InlineCost.h:216
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition InlineCost.h:228
std::optional< bool > IgnoreProfile
Indicate whether to ignore profile information.
Definition InlineCost.h:249
int DefaultThreshold
The default threshold to start with for a callee.
Definition InlineCost.h:209
std::optional< bool > EnableDeferral
Indicate whether we should allow inline deferral.
Definition InlineCost.h:241
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition InlineCost.h:212
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.