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