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