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