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