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 "llvm/ADT/Statistic.h"
28#include "llvm/IR/PassManager.h"
29#include "llvm/IR/Verifier.h"
30#include "llvm/Pass.h"
157
158using namespace llvm;
159
160namespace llvm {
161
163 "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
164 cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
166 "Heuristics-based inliner version"),
168 "Use development mode (runtime-loadable model)"),
170 "Use release mode (AOT-compiled model)")));
171
172/// Flag to enable inline deferral during PGO.
173static cl::opt<bool>
174 EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
176 cl::desc("Enable inline deferral during PGO"));
177
178static cl::opt<bool> EnableModuleInliner("enable-module-inliner",
179 cl::init(false), cl::Hidden,
180 cl::desc("Enable module inliner"));
181
183 "mandatory-inlining-first", cl::init(false), cl::Hidden,
184 cl::desc("Perform mandatory inlinings module-wide, before performing "
185 "inlining"));
186
188 "eagerly-invalidate-analyses", cl::init(true), cl::Hidden,
189 cl::desc("Eagerly invalidate more analyses in default pipelines"));
190
192 "enable-merge-functions", cl::init(false), cl::Hidden,
193 cl::desc("Enable function merging as part of the optimization pipeline"));
194
196 "enable-post-pgo-loop-rotation", cl::init(true), cl::Hidden,
197 cl::desc("Run the loop rotation transformation after PGO instrumentation"));
198
199static cl::opt<bool>
200 TriggerCrash("opt-pipeline-trigger-crash", cl::init(false), cl::Hidden,
201 cl::desc("Trigger crash in optimization pipeline"));
202
204 "enable-global-analyses", cl::init(true), cl::Hidden,
205 cl::desc("Enable inter-procedural analyses"));
206
207static cl::opt<bool> RunPartialInlining("enable-partial-inlining",
208 cl::init(false), cl::Hidden,
209 cl::desc("Run Partial inlining pass"));
210
212 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
213 cl::desc("Run cleanup optimization passes after vectorization"));
214
215static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
216 cl::desc("Run the NewGVN pass"));
217
218static cl::opt<bool>
219 EnableLoopInterchange("enable-loopinterchange", cl::init(true), cl::Hidden,
220 cl::desc("Enable the LoopInterchange Pass"));
221
222static cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam",
223 cl::init(false), cl::Hidden,
224 cl::desc("Enable Unroll And Jam Pass"));
225
226static cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
228 cl::desc("Enable the LoopFlatten Pass"));
229
230static cl::opt<bool>
231 EnableInstrumentor("enable-instrumentor", cl::init(false), cl::Hidden,
232 cl::desc("Enable the Instrumentor Pass"));
233
234static cl::opt<bool>
235 EnableDFAJumpThreading("enable-dfa-jump-thread",
236 cl::desc("Enable DFA jump threading"),
237 cl::init(true), cl::Hidden);
238
239static cl::opt<bool>
240 EnableHotColdSplit("hot-cold-split",
241 cl::desc("Enable hot-cold splitting pass"));
242
243static cl::opt<bool>
244 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
245 cl::desc("Disable pre-instrumentation inliner"));
246
248 "preinline-threshold", cl::Hidden, cl::init(75),
249 cl::desc("Control the amount of inlining in pre-instrumentation inliner "
250 "(default = 75)"));
251
252static cl::opt<bool>
253 EnableGVNHoist("enable-gvn-hoist",
254 cl::desc("Enable the GVN hoisting pass (default = off)"));
255
256static cl::opt<bool>
257 EnableGVNSink("enable-gvn-sink",
258 cl::desc("Enable the GVN sinking pass (default = off)"));
259
261 "enable-jump-table-to-switch", cl::init(true),
262 cl::desc("Enable JumpTableToSwitch pass (default = true)"));
263
264// This option is used in simplifying testing SampleFDO optimizations for
265// profile loading.
266static cl::opt<bool>
267 EnableCHR("enable-chr", cl::init(true), cl::Hidden,
268 cl::desc("Enable control height reduction optimization (CHR)"));
269
271 "flattened-profile-used", cl::init(false), cl::Hidden,
272 cl::desc("Indicate the sample profile being used is flattened, i.e., "
273 "no inline hierarchy exists in the profile"));
274
275static cl::opt<bool>
276 EnableMatrix("enable-matrix", cl::init(false), cl::Hidden,
277 cl::desc("Enable lowering of the matrix intrinsics"));
278
280 "enable-mergeicmps", cl::init(true), cl::Hidden,
281 cl::desc("Enable MergeICmps pass in the optimization pipeline"));
282
284 "enable-constraint-elimination", cl::init(true), cl::Hidden,
285 cl::desc(
286 "Enable pass to eliminate conditions based on linear constraints"));
287
289 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
290 cl::desc("Enable the attributor inter-procedural deduction pass"),
292 "enable all full attributor runs"),
294 "enable all attributor-light runs"),
296 "enable module-wide attributor runs"),
298 "enable module-wide attributor-light runs"),
300 "enable call graph SCC attributor runs"),
302 "enable call graph SCC attributor-light runs"),
303 clEnumValN(AttributorRunOption::NONE, "none",
304 "disable attributor runs")));
305
307 "enable-sampled-instrumentation", cl::init(false), cl::Hidden,
308 cl::desc("Enable profile instrumentation sampling (default = off)"));
310 "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
311 cl::desc("Enable the experimental Loop Versioning LICM pass"));
312
314 "instrument-cold-function-only-path", cl::init(""),
315 cl::desc("File path for cold function only instrumentation(requires use "
316 "with --pgo-instrument-cold-function-only)"),
317 cl::Hidden);
318
319// TODO: There is a similar flag in WPD pass, we should consolidate them by
320// parsing the option only once in PassBuilder and share it across both places.
322 "enable-devirtualize-speculatively",
323 cl::desc("Enable speculative devirtualization optimization"),
324 cl::init(false));
325
328
330} // namespace llvm
331
349
350namespace llvm {
352} // namespace llvm
353
355 OptimizationLevel Level) {
356 for (auto &C : PeepholeEPCallbacks)
357 C(FPM, Level);
358}
361 for (auto &C : LateLoopOptimizationsEPCallbacks)
362 C(LPM, Level);
363}
365 OptimizationLevel Level) {
366 for (auto &C : LoopOptimizerEndEPCallbacks)
367 C(LPM, Level);
368}
371 for (auto &C : ScalarOptimizerLateEPCallbacks)
372 C(FPM, Level);
373}
375 OptimizationLevel Level) {
376 for (auto &C : CGSCCOptimizerLateEPCallbacks)
377 C(CGPM, Level);
378}
380 OptimizationLevel Level) {
381 for (auto &C : VectorizerStartEPCallbacks)
382 C(FPM, Level);
383}
385 OptimizationLevel Level) {
386 for (auto &C : VectorizerEndEPCallbacks)
387 C(FPM, Level);
388}
390 OptimizationLevel Level,
392 for (auto &C : OptimizerEarlyEPCallbacks)
393 C(MPM, Level, Phase);
394}
396 OptimizationLevel Level,
398 for (auto &C : OptimizerLastEPCallbacks)
399 C(MPM, Level, Phase);
400}
403 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
404 C(MPM, Level);
405}
408 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
409 C(MPM, Level);
410}
412 OptimizationLevel Level) {
413 for (auto &C : PipelineStartEPCallbacks)
414 C(MPM, Level);
415}
418 for (auto &C : PipelineEarlySimplificationEPCallbacks)
419 C(MPM, Level, Phase);
420}
421
422// Get IR stats with InstCount before/after the optimization pipeline
424 bool IsPreOptimization) {
425 if (AreStatisticsEnabled()) {
426 MPM.addPass(
429 FunctionPropertiesStatisticsPass(IsPreOptimization)));
430 }
431}
432
433// Helper to add AnnotationRemarksPass.
437
438// Helper to check if the current compilation phase is preparing for LTO
443
444// Helper to check if the current compilation phase is preparing for FullLTO
445[[maybe_unused]] static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase) {
447}
448
449// Helper to check if the current compilation phase is preparing for ThinLTO
453
454// Helper to check if the current compilation phase is LTO backend
459
460// Helper to check if the current compilation phase is FullLTO backend
464
465// Helper to check if the current compilation phase is ThinLTO backend
469
470// Helper to wrap conditionally Coro passes.
472 // TODO: Skip passes according to Phase.
473 ModulePassManager CoroPM;
474 CoroPM.addPass(CoroEarlyPass());
475 CGSCCPassManager CGPM;
476 CGPM.addPass(CoroSplitPass());
477 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
478 CoroPM.addPass(CoroCleanupPass());
479 CoroPM.addPass(GlobalDCEPass());
480 return CoroConditionalWrapper(std::move(CoroPM));
481}
482
483// TODO: Investigate the cost/benefit of tail call elimination on debugging.
485PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
487
489
491 FPM.addPass(CountVisitsPass());
492
493 // Form SSA out of local memory accesses after breaking apart aggregates into
494 // scalars.
495 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
496
497 // Catch trivial redundancies
498 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
499
500 // Hoisting of scalars and load expressions.
501 FPM.addPass(
502 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
503 FPM.addPass(InstCombinePass());
504
505 FPM.addPass(LibCallsShrinkWrapPass());
506
507 invokePeepholeEPCallbacks(FPM, Level);
508
509 FPM.addPass(
510 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
511
512 // Form canonically associated expression trees, and simplify the trees using
513 // basic mathematical properties. For example, this will form (nearly)
514 // minimal multiplication trees.
515 FPM.addPass(ReassociatePass());
516
517 // Add the primary loop simplification pipeline.
518 // FIXME: Currently this is split into two loop pass pipelines because we run
519 // some function passes in between them. These can and should be removed
520 // and/or replaced by scheduling the loop pass equivalents in the correct
521 // positions. But those equivalent passes aren't powerful enough yet.
522 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
523 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
524 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
525 // `LoopInstSimplify`.
526 LoopPassManager LPM1, LPM2;
527
528 // Simplify the loop body. We do this initially to clean up after other loop
529 // passes run, either when iterating on a loop or on inner loops with
530 // implications on the outer loop.
531 LPM1.addPass(LoopInstSimplifyPass());
532 LPM1.addPass(LoopSimplifyCFGPass());
533
534 // Try to remove as much code from the loop header as possible,
535 // to reduce amount of IR that will have to be duplicated. However,
536 // do not perform speculative hoisting the first time as LICM
537 // will destroy metadata that may not need to be destroyed if run
538 // after loop rotation.
539 // TODO: Investigate promotion cap for O1.
540 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
541 /*AllowSpeculation=*/false));
542
543 LPM1.addPass(
544 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
545 // TODO: Investigate promotion cap for O1.
546 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
547 /*AllowSpeculation=*/true));
548 LPM1.addPass(SimpleLoopUnswitchPass());
550 LPM1.addPass(LoopFlattenPass());
551
552 LPM2.addPass(LoopIdiomRecognizePass());
553 LPM2.addPass(IndVarSimplifyPass());
554
556
557 LPM2.addPass(LoopDeletionPass());
558
559 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
560 // because it changes IR to makes profile annotation in back compile
561 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
562 // attributes so we need to make sure and allow the full unroll pass to pay
563 // attention to it.
564 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
565 PGOOpt->Action != PGOOptions::SampleUse)
566 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
567 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
568 PTO.ForgetAllSCEVInLoopUnroll));
569
571
572 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
573 /*UseMemorySSA=*/true));
574 FPM.addPass(
575 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
576 FPM.addPass(InstCombinePass());
577 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
578 // *All* loop passes must preserve it, in order to be able to use it.
579 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
580 /*UseMemorySSA=*/false));
581
582 // Delete small array after loop unroll.
583 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
584
585 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
586 FPM.addPass(MemCpyOptPass());
587
588 // Sparse conditional constant propagation.
589 // FIXME: It isn't clear why we do this *after* loop passes rather than
590 // before...
591 FPM.addPass(SCCPPass());
592
593 // Delete dead bit computations (instcombine runs after to fold away the dead
594 // computations, and then ADCE will run later to exploit any new DCE
595 // opportunities that creates).
596 FPM.addPass(BDCEPass());
597
598 // Run instcombine after redundancy and dead bit elimination to exploit
599 // opportunities opened up by them.
600 FPM.addPass(InstCombinePass());
601 invokePeepholeEPCallbacks(FPM, Level);
602
603 FPM.addPass(CoroElidePass());
604
606
607 // Finally, do an expensive DCE pass to catch all the dead code exposed by
608 // the simplifications and basic cleanup after all the simplifications.
609 // TODO: Investigate if this is too expensive.
610 FPM.addPass(ADCEPass());
611 FPM.addPass(
612 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
613 FPM.addPass(InstCombinePass());
614 invokePeepholeEPCallbacks(FPM, Level);
615
616 return FPM;
617}
618
622 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
623
624 // The O1 pipeline has a separate pipeline creation function to simplify
625 // construction readability.
626 if (Level == OptimizationLevel::O1)
627 return buildO1FunctionSimplificationPipeline(Level, Phase);
628
630
633
634 // Form SSA out of local memory accesses after breaking apart aggregates into
635 // scalars.
637
638 // Catch trivial redundancies
639 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
642
643 // Hoisting of scalars and load expressions.
644 if (EnableGVNHoist)
645 FPM.addPass(GVNHoistPass());
646
647 // Global value numbering based sinking.
648 if (EnableGVNSink) {
649 FPM.addPass(GVNSinkPass());
650 FPM.addPass(
651 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
652 }
653
654 // Speculative execution if the target has divergent branches; otherwise nop.
655 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
656
657 // Optimize based on known information about branches, and cleanup afterward.
660
661 // Jump table to switch conversion.
664
665 FPM.addPass(
666 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
670
671 invokePeepholeEPCallbacks(FPM, Level);
672
673 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
674 // using the size value profile. Don't perform this when optimizing for size.
675 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse)
677
678 FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
679 isInstrumentedPGOUse()));
680 FPM.addPass(
681 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
682
683 // Form canonically associated expression trees, and simplify the trees using
684 // basic mathematical properties. For example, this will form (nearly)
685 // minimal multiplication trees.
687
690
691 // Add the primary loop simplification pipeline.
692 // FIXME: Currently this is split into two loop pass pipelines because we run
693 // some function passes in between them. These can and should be removed
694 // and/or replaced by scheduling the loop pass equivalents in the correct
695 // positions. But those equivalent passes aren't powerful enough yet.
696 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
697 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
698 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
699 // `LoopInstSimplify`.
700 LoopPassManager LPM1, LPM2;
701
702 // Simplify the loop body. We do this initially to clean up after other loop
703 // passes run, either when iterating on a loop or on inner loops with
704 // implications on the outer loop.
705 LPM1.addPass(LoopInstSimplifyPass());
706 LPM1.addPass(LoopSimplifyCFGPass());
707
708 // Try to remove as much code from the loop header as possible,
709 // to reduce amount of IR that will have to be duplicated. However,
710 // do not perform speculative hoisting the first time as LICM
711 // will destroy metadata that may not need to be destroyed if run
712 // after loop rotation.
713 // TODO: Investigate promotion cap for O1.
714 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
715 /*AllowSpeculation=*/false));
716
717 LPM1.addPass(
718 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
719 // TODO: Investigate promotion cap for O1.
720 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
721 /*AllowSpeculation=*/true));
722 LPM1.addPass(
723 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
725 LPM1.addPass(LoopFlattenPass());
726
727 LPM2.addPass(LoopIdiomRecognizePass());
728 LPM2.addPass(IndVarSimplifyPass());
729
730 {
732 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
734 LPM2.addPass(std::move(ExtraPasses));
735 }
736
738
739 LPM2.addPass(LoopDeletionPass());
740
741 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
742 // because it changes IR to makes profile annotation in back compile
743 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
744 // attributes so we need to make sure and allow the full unroll pass to pay
745 // attention to it.
746 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
747 PGOOpt->Action != PGOOptions::SampleUse)
748 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
749 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
750 PTO.ForgetAllSCEVInLoopUnroll));
751
753
754 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
755 /*UseMemorySSA=*/true));
756 FPM.addPass(
757 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
759 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
760 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
761 // *All* loop passes must preserve it, in order to be able to use it.
762 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
763 /*UseMemorySSA=*/false));
764
765 // Delete small array after loop unroll.
767
768 // Try vectorization/scalarization transforms that are both improvements
769 // themselves and can allow further folds with GVN and InstCombine.
770 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
771
772 // Eliminate redundancies.
774 if (RunNewGVN)
775 FPM.addPass(NewGVNPass());
776 else
777 FPM.addPass(GVNPass());
778
779 // Sparse conditional constant propagation.
780 // FIXME: It isn't clear why we do this *after* loop passes rather than
781 // before...
782 FPM.addPass(SCCPPass());
783
784 // Delete dead bit computations (instcombine runs after to fold away the dead
785 // computations, and then ADCE will run later to exploit any new DCE
786 // opportunities that creates).
787 FPM.addPass(BDCEPass());
788
789 // Run instcombine after redundancy and dead bit elimination to exploit
790 // opportunities opened up by them.
792 invokePeepholeEPCallbacks(FPM, Level);
793
794 // Re-consider control flow based optimizations after redundancy elimination,
795 // redo DCE, etc.
798
801
802 // Finally, do an expensive DCE pass to catch all the dead code exposed by
803 // the simplifications and basic cleanup after all the simplifications.
804 // TODO: Investigate if this is too expensive.
805 FPM.addPass(ADCEPass());
806
807 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
808 FPM.addPass(MemCpyOptPass());
809
810 FPM.addPass(DSEPass());
812
814 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
815 /*AllowSpeculation=*/true),
816 /*UseMemorySSA=*/true));
817
818 FPM.addPass(CoroElidePass());
819
821
823 .convertSwitchRangeToICmp(true)
824 .convertSwitchToArithmetic(true)
825 .hoistCommonInsts(true)
826 .sinkCommonInsts(true)));
828 invokePeepholeEPCallbacks(FPM, Level);
829
830 return FPM;
831}
832
833void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
836 MPM.addPass(AssignGUIDPass());
837}
838
839void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
840 OptimizationLevel Level,
841 ThinOrFullLTOPhase LTOPhase) {
842 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
844 return;
845 InlineParams IP;
846
848
849 // FIXME: The hint threshold has the same value used by the regular inliner
850 // when not optimzing for size. This should probably be lowered after
851 // performance testing.
852 // FIXME: this comment is cargo culted from the old pass manager, revisit).
853 IP.HintThreshold = 325;
856 IP, /* MandatoryFirst */ true,
858 CGSCCPassManager &CGPipeline = MIWP.getPM();
859
861 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
862 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
863 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
864 true))); // Merge & remove basic blocks.
865 FPM.addPass(InstCombinePass()); // Combine silly sequences.
866 invokePeepholeEPCallbacks(FPM, Level);
867
868 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
869 std::move(FPM), PTO.EagerlyInvalidateAnalyses));
870
871 MPM.addPass(std::move(MIWP));
872
873 // Delete anything that is now dead to make sure that we don't instrument
874 // dead code. Instrumentation can end up keeping dead code around and
875 // dramatically increase code size.
876 MPM.addPass(GlobalDCEPass());
877}
878
879void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
880 OptimizationLevel Level) {
882 // Disable header duplication in loop rotation at -Oz.
884 createFunctionToLoopPassAdaptor(LoopRotatePass(),
885 /*UseMemorySSA=*/false),
886 PTO.EagerlyInvalidateAnalyses));
887 }
888}
889
890void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
891 OptimizationLevel Level, bool RunProfileGen,
892 bool IsCS, bool AtomicCounterUpdate,
893 std::string ProfileFile,
894 std::string ProfileRemappingFile) {
895 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
896
897 if (!RunProfileGen) {
898 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
899 MPM.addPass(
900 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
901 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
902 // RequireAnalysisPass for PSI before subsequent non-module passes.
903 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
904 return;
905 }
906
907 // Perform PGO instrumentation.
908 MPM.addPass(PGOInstrumentationGen(IsCS ? PGOInstrumentationType::CSFDO
910
911 addPostPGOLoopRotation(MPM, Level);
912 // Add the profile lowering pass.
913 InstrProfOptions Options;
914 if (!ProfileFile.empty())
915 Options.InstrProfileOutput = ProfileFile;
916 // Do counter promotion at Level greater than O0.
917 Options.DoCounterPromotion = true;
918 Options.UseBFIInPromotion = IsCS;
919 if (EnableSampledInstr) {
920 Options.Sampling = true;
921 // With sampling, there is little beneifit to enable counter promotion.
922 // But note that sampling does work with counter promotion.
923 Options.DoCounterPromotion = false;
924 }
925 Options.Atomic = AtomicCounterUpdate;
926 MPM.addPass(InstrProfilingLoweringPass(Options, IsCS));
927}
928
930 bool RunProfileGen, bool IsCS,
931 bool AtomicCounterUpdate,
932 std::string ProfileFile,
933 std::string ProfileRemappingFile) {
934 if (!RunProfileGen) {
935 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
936 MPM.addPass(
937 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
938 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
939 // RequireAnalysisPass for PSI before subsequent non-module passes.
941 return;
942 }
943
944 // Perform PGO instrumentation.
947 // Add the profile lowering pass.
949 if (!ProfileFile.empty())
950 Options.InstrProfileOutput = ProfileFile;
951 // Do not do counter promotion at O0.
952 Options.DoCounterPromotion = false;
953 Options.UseBFIInPromotion = IsCS;
954 Options.Atomic = AtomicCounterUpdate;
956}
957
959 return getInlineParamsFromOptLevel(static_cast<unsigned>(Level));
960}
961
965 InlineParams IP;
966 if (PTO.InlinerThreshold == -1)
968 else
969 IP = getInlineParams(PTO.InlinerThreshold);
970 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
971 // set hot-caller threshold to 0 to disable hot
972 // callsite inline (as much as possible [1]) because it makes
973 // profile annotation in the backend inaccurate.
974 //
975 // [1] Note the cost of a function could be below zero due to erased
976 // prologue / epilogue.
977 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
979
980 if (PGOOpt)
982
986
987 // Require the GlobalsAA analysis for the module so we can query it within
988 // the CGSCC pipeline.
990 MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
991 // Invalidate AAManager so it can be recreated and pick up the newly
992 // available GlobalsAA.
993 MIWP.addModulePass(
995 }
996
997 // Require the ProfileSummaryAnalysis for the module so we can query it within
998 // the inliner pass.
1000
1001 // Now begin the main postorder CGSCC pipeline.
1002 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
1003 // manager and trying to emulate its precise behavior. Much of this doesn't
1004 // make a lot of sense and we should revisit the core CGSCC structure.
1005 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
1006
1007 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1008 // generally clean up exception handling overhead. It isn't clear this is
1009 // valuable as the inliner doesn't currently care whether it is inlining an
1010 // invoke or a call.
1011
1013 MainCGPipeline.addPass(AttributorCGSCCPass());
1015 MainCGPipeline.addPass(AttributorLightCGSCCPass());
1016
1017 // Deduce function attributes. We do another run of this after the function
1018 // simplification pipeline, so this only needs to run when it could affect the
1019 // function simplification pipeline, which is only the case with recursive
1020 // functions.
1021 MainCGPipeline.addPass(PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
1022
1023 // When at O3 add argument promotion to the pass pipeline.
1024 // FIXME: It isn't at all clear why this should be limited to O3.
1025 if (Level == OptimizationLevel::O3)
1026 MainCGPipeline.addPass(ArgumentPromotionPass());
1027
1028 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
1029 // there are no OpenMP runtime calls present in the module.
1030 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
1031 MainCGPipeline.addPass(OpenMPOptCGSCCPass(Phase));
1032
1033 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
1034
1035 // Add the core function simplification pipeline nested inside the
1036 // CGSCC walk.
1039 PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
1040
1041 // Finally, deduce any function attributes based on the fully simplified
1042 // function.
1043 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
1044
1045 // Mark that the function is fully simplified and that it shouldn't be
1046 // simplified again if we somehow revisit it due to CGSCC mutations unless
1047 // it's been modified since.
1050
1051 if (!isThinLTOPreLink(Phase)) {
1052 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
1053 MainCGPipeline.addPass(CoroAnnotationElidePass());
1054 }
1055
1056 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
1057 MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
1059
1060 return MIWP;
1061}
1062
1067
1069 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
1070 // set hot-caller threshold to 0 to disable hot
1071 // callsite inline (as much as possible [1]) because it makes
1072 // profile annotation in the backend inaccurate.
1073 //
1074 // [1] Note the cost of a function could be below zero due to erased
1075 // prologue / epilogue.
1076 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1077 IP.HotCallSiteThreshold = 0;
1078
1079 if (PGOOpt)
1081
1082 // The inline deferral logic is used to avoid losing some
1083 // inlining chance in future. It is helpful in SCC inliner, in which
1084 // inlining is processed in bottom-up order.
1085 // While in module inliner, the inlining order is a priority-based order
1086 // by default. The inline deferral is unnecessary there. So we disable the
1087 // inline deferral logic in module inliner.
1088 IP.EnableDeferral = false;
1089
1092 MPM.addPass(GlobalOptPass());
1093 MPM.addPass(GlobalDCEPass());
1094 MPM.addPass(AssignGUIDPass());
1095 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
1096 }
1097
1100 PTO.EagerlyInvalidateAnalyses));
1101
1102 if (!isThinLTOPreLink(Phase)) {
1105 MPM.addPass(
1107 }
1108
1109 return MPM;
1110}
1111
1115 assert(Level != OptimizationLevel::O0 &&
1116 "Should not be used for O0 pipeline");
1117
1119 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
1120
1122
1123 // Place pseudo probe instrumentation as the first pass of the pipeline to
1124 // minimize the impact of optimization changes.
1125 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && !isThinLTOPostLink(Phase))
1127
1128 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1129
1130 // In ThinLTO mode, when flattened profile is used, all the available
1131 // profile information will be annotated in PreLink phase so there is
1132 // no need to load the profile again in PostLink.
1133 bool LoadSampleProfile =
1134 HasSampleProfile && !(FlattenedProfileUsed && isThinLTOPostLink(Phase));
1135
1136 // During the ThinLTO backend phase we perform early indirect call promotion
1137 // here, before globalopt. Otherwise imported available_externally functions
1138 // look unreferenced and are removed. If we are going to load the sample
1139 // profile then defer until later.
1140 // TODO: See if we can move later and consolidate with the location where
1141 // we perform ICP when we are loading a sample profile.
1142 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1143 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1144 // determine whether the new direct calls are annotated with prof metadata.
1145 // Ideally this should be determined from whether the IR is annotated with
1146 // sample profile, and not whether the a sample profile was provided on the
1147 // command line. E.g. for flattened profiles where we will not be reloading
1148 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1149 // provide the sample profile file.
1150 if (isThinLTOPostLink(Phase) && !LoadSampleProfile)
1151 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1152
1153 // Create an early function pass manager to cleanup the output of the
1154 // frontend. Not necessary with LTO post link pipelines since the pre link
1155 // pipeline already cleaned up the frontend output.
1156 if (!isThinLTOPostLink(Phase)) {
1157 // Do basic inference of function attributes from known properties of system
1158 // libraries and other oracles.
1160 MPM.addPass(CoroEarlyPass());
1161
1162 FunctionPassManager EarlyFPM;
1163 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1164 // Lower llvm.expect to metadata before attempting transforms.
1165 // Compare/branch metadata may alter the behavior of passes like
1166 // SimplifyCFG.
1168 EarlyFPM.addPass(SimplifyCFGPass());
1170 EarlyFPM.addPass(EarlyCSEPass());
1171 if (Level == OptimizationLevel::O3)
1172 EarlyFPM.addPass(CallSiteSplittingPass());
1174 std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
1175 }
1176
1177 if (LoadSampleProfile) {
1178 // Annotate sample profile right after early FPM to ensure freshness of
1179 // the debug info.
1181 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS));
1182 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1183 // RequireAnalysisPass for PSI before subsequent non-module passes.
1185 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1186 // for the profile annotation to be accurate in the LTO backend.
1187 if (!isLTOPreLink(Phase))
1188 // We perform early indirect call promotion here, before globalopt.
1189 // This is important for the ThinLTO backend phase because otherwise
1190 // imported available_externally functions look unreferenced and are
1191 // removed.
1192 MPM.addPass(
1193 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1194 }
1195
1196 // Try to perform OpenMP specific optimizations on the module. This is a
1197 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1199
1201 MPM.addPass(AttributorPass());
1204
1205 // Lower type metadata and the type.test intrinsic in the ThinLTO
1206 // post link pipeline after ICP. This is to enable usage of the type
1207 // tests in ICP sequences.
1210
1212
1213 // Interprocedural constant propagation now that basic cleanup has occurred
1214 // and prior to optimizing globals.
1215 // FIXME: This position in the pipeline hasn't been carefully considered in
1216 // years, it should be re-analyzed.
1217 MPM.addPass(
1218 IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/!isLTOPreLink(Phase))));
1219
1220 // Attach metadata to indirect call sites indicating the set of functions
1221 // they may target at run-time. This should follow IPSCCP.
1223
1224 // Optimize globals to try and fold them into constants.
1225 MPM.addPass(GlobalOptPass());
1226
1227 // Create a small function pass pipeline to cleanup after all the global
1228 // optimizations.
1229 FunctionPassManager GlobalCleanupPM;
1230 // FIXME: Should this instead by a run of SROA?
1231 GlobalCleanupPM.addPass(PromotePass());
1232 GlobalCleanupPM.addPass(InstCombinePass());
1233 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1234 GlobalCleanupPM.addPass(
1235 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1236 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
1237 PTO.EagerlyInvalidateAnalyses));
1238
1239 // We already asserted this happens in non-FullLTOPostLink earlier.
1240 const bool IsPreLink = !isThinLTOPostLink(Phase);
1241 // Enable contextual profiling instrumentation.
1242 const bool IsCtxProfGen =
1244 const bool IsPGOPreLink = !IsCtxProfGen && PGOOpt && IsPreLink;
1245 const bool IsPGOInstrGen =
1246 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1247 const bool IsPGOInstrUse =
1248 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1249 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1250 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1251 // enable ctx profiling from the frontend.
1253 "Enabling both instrumented PGO and contextual instrumentation is not "
1254 "supported.");
1255 const bool IsCtxProfUse = !UseCtxProfile.empty() && isThinLTOPreLink(Phase);
1256
1257 assert(
1259 "--instrument-cold-function-only-path is provided but "
1260 "--pgo-instrument-cold-function-only is not enabled");
1261 const bool IsColdFuncOnlyInstrGen = PGOInstrumentColdFunctionOnly &&
1262 IsPGOPreLink &&
1264
1265 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1266 IsCtxProfUse || IsColdFuncOnlyInstrGen)
1267 addPreInlinerPasses(MPM, Level, Phase);
1268
1269 // Add all the requested passes for instrumentation PGO, if requested.
1270 if (IsPGOInstrGen || IsPGOInstrUse) {
1271 addPGOInstrPasses(MPM, Level,
1272 /*RunProfileGen=*/IsPGOInstrGen,
1273 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1274 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1275 } else if (IsCtxProfGen || IsCtxProfUse) {
1277 // In pre-link, we just want the instrumented IR. We use the contextual
1278 // profile in the post-thinlink phase.
1279 // The instrumentation will be removed in post-thinlink after IPO.
1280 if (IsCtxProfUse) {
1281 MPM.addPass(AssignGUIDPass());
1282 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
1283 return MPM;
1284 }
1285 // Block further inlining in the instrumented ctxprof case. This avoids
1286 // confusingly collecting profiles for the same GUID corresponding to
1287 // different variants of the function. We could do like PGO and identify
1288 // functions by a (GUID, Hash) tuple, but since the ctxprof "use" waits for
1289 // thinlto to happen before performing any further optimizations, it's
1290 // unnecessary to collect profiles for non-prevailing copies.
1292 addPostPGOLoopRotation(MPM, Level);
1293 MPM.addPass(AssignGUIDPass());
1295 } else if (IsColdFuncOnlyInstrGen) {
1296 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
1297 /* AtomicCounterUpdate */ false,
1299 /* ProfileRemappingFile */ "");
1300 }
1301
1302 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1303 MPM.addPass(PGOIndirectCallPromotion(false, false));
1304
1305 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1306 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile,
1308
1309 if (IsMemprofUse)
1310 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS));
1311
1312 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse ||
1313 PGOOpt->Action == PGOOptions::SampleUse))
1314 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1315
1316 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1317
1320 else
1321 MPM.addPass(buildInlinerPipeline(Level, Phase));
1322
1323 // Remove any dead arguments exposed by cleanups, constant folding globals,
1324 // and argument promotion.
1326
1329
1330 if (!isThinLTOPreLink(Phase))
1331 MPM.addPass(CoroCleanupPass());
1332
1333 // Optimize globals now that functions are fully simplified.
1334 MPM.addPass(GlobalOptPass());
1335 MPM.addPass(GlobalDCEPass());
1336
1337 return MPM;
1338}
1339
1340/// TODO: Should LTO cause any differences to this set of passes?
1341void PassBuilder::addVectorPasses(OptimizationLevel Level,
1343 ThinOrFullLTOPhase LTOPhase) {
1346
1347 // Drop dereferenceable assumes after vectorization, as they are no longer
1348 // needed and can inhibit further optimization.
1349 if (!isLTOPreLink(LTOPhase))
1350 FPM.addPass(DropUnnecessaryAssumesPass(/*DropDereferenceable=*/true));
1351
1353 if (isFullLTOPostLink(LTOPhase)) {
1354 // The vectorizer may have significantly shortened a loop body; unroll
1355 // again. Unroll small loops to hide loop backedge latency and saturate any
1356 // parallel execution resources of an out-of-order processor. We also then
1357 // need to clean up redundancies and loop invariant code.
1358 // FIXME: It would be really good to use a loop-integrated instruction
1359 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1360 // across the loop nests.
1361 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1364 LoopUnrollAndJamPass(static_cast<int>(Level))));
1366 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1369 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1370 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1371 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1372 // NOTE: we are very late in the pipeline, and we don't have any LICM
1373 // or SimplifyCFG passes scheduled after us, that would cleanup
1374 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1375
1376 // We also turn on struct to vector canonicalization here, which allows
1377 // converting allocas of homogeneous structs into vector allocas when the
1378 // allocas' users are all memory intrinsics. This allows promotion in some
1379 // cases because structs cannot promote to SSA values, but vectors can. We
1380 // only turn this on after memcpyopt runs because this might hinder
1381 // memcpyopt's optimizations if done before. Look at the documentation for
1382 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1384 /*AggregateToVector=*/true)));
1385 }
1386
1387 if (!isFullLTOPostLink(LTOPhase)) {
1388 // Eliminate loads by forwarding stores from the previous iteration to loads
1389 // of the current iteration.
1391 }
1392 // Cleanup after the loop optimization passes.
1393 FPM.addPass(InstCombinePass());
1394
1396 ExtraFunctionPassManager<ShouldRunExtraVectorPasses> ExtraPasses;
1397 // At higher optimization levels, try to clean up any runtime overlap and
1398 // alignment checks inserted by the vectorizer. We want to track correlated
1399 // runtime checks for two inner loops in the same outer loop, fold any
1400 // common computations, hoist loop-invariant aspects out of any outer loop,
1401 // and unswitch the runtime checks if possible. Once hoisted, we may have
1402 // dead (or speculatable) control flows or more combining opportunities.
1403 ExtraPasses.addPass(EarlyCSEPass());
1404 ExtraPasses.addPass(CorrelatedValuePropagationPass());
1405 ExtraPasses.addPass(InstCombinePass());
1406 LoopPassManager LPM;
1407 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1408 /*AllowSpeculation=*/true));
1409 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1411 ExtraPasses.addPass(
1412 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true));
1413 ExtraPasses.addPass(
1414 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1415 ExtraPasses.addPass(InstCombinePass());
1416 FPM.addPass(std::move(ExtraPasses));
1417 }
1418
1419 // Now that we've formed fast to execute loop structures, we do further
1420 // optimizations. These are run afterward as they might block doing complex
1421 // analyses and transforms such as what are needed for loop vectorization.
1422
1423 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1424 // GVN, loop transforms, and others have already run, so it's now better to
1425 // convert to more optimized IR using more aggressive simplify CFG options.
1426 // The extra sinking transform can create larger basic blocks, so do this
1427 // before SLP vectorization.
1428 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1429 .forwardSwitchCondToPhi(true)
1430 .convertSwitchRangeToICmp(true)
1431 .convertSwitchToArithmetic(true)
1432 .convertSwitchToLookupTable(true)
1433 .needCanonicalLoops(false)
1434 .hoistCommonInsts(true)
1435 .sinkCommonInsts(true)));
1436
1437 if (isFullLTOPostLink(LTOPhase)) {
1438 FPM.addPass(SCCPPass());
1439 FPM.addPass(InstCombinePass());
1440 FPM.addPass(BDCEPass());
1441 }
1442
1443 // Optimize parallel scalar instruction chains into SIMD instructions.
1444 if (PTO.SLPVectorization) {
1445 FPM.addPass(SLPVectorizerPass());
1447 FPM.addPass(EarlyCSEPass());
1448 }
1449 }
1450 // Enhance/cleanup vector code.
1451 FPM.addPass(VectorCombinePass());
1452
1453 if (!isFullLTOPostLink(LTOPhase)) {
1454 FPM.addPass(InstCombinePass());
1455 // Unroll small loops to hide loop backedge latency and saturate any
1456 // parallel execution resources of an out-of-order processor. We also then
1457 // need to clean up redundancies and loop invariant code.
1458 // FIXME: It would be really good to use a loop-integrated instruction
1459 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1460 // across the loop nests.
1461 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1462 if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1464 LoopUnrollAndJamPass(static_cast<int>(Level))));
1465 }
1466 FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1467 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1468 PTO.ForgetAllSCEVInLoopUnroll)));
1469 FPM.addPass(WarnMissedTransformationsPass());
1470 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1471 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1472 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1473 // NOTE: we are very late in the pipeline, and we don't have any LICM
1474 // or SimplifyCFG passes scheduled after us, that would cleanup
1475 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1476
1477 // We also turn on struct to vector canonicalization here, which allows
1478 // converting allocas of homogeneous structs into vector allocas when the
1479 // allocas' users are all memory intrinsics. This allows promotion in some
1480 // cases because structs cannot promote to SSA values, but vectors can. We
1481 // only turn this on after memcpyopt runs because this might hinder
1482 // memcpyopt's optimizations if done before. Look at the documentation for
1483 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1484 FPM.addPass(SROAPass(SROAOptions(SROAOptions::PreserveCFG,
1485 /*AggregateToVector=*/true)));
1486 }
1487
1488 FPM.addPass(InferAlignmentPass());
1489 FPM.addPass(InstCombinePass());
1490
1491 // This is needed for two reasons:
1492 // 1. It works around problems that instcombine introduces, such as sinking
1493 // expensive FP divides into loops containing multiplications using the
1494 // divide result.
1495 // 2. It helps to clean up some loop-invariant code created by the loop
1496 // unroll pass when IsFullLTO=false.
1498 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1499 /*AllowSpeculation=*/true),
1500 /*UseMemorySSA=*/true));
1501
1502 // Now that we've vectorized and unrolled loops, we may have more refined
1503 // alignment information, try to re-derive it here.
1504 FPM.addPass(AlignmentFromAssumptionsPass());
1505}
1506
1509 ThinOrFullLTOPhase LTOPhase) {
1511
1512 // Run partial inlining pass to partially inline functions that have
1513 // large bodies.
1516
1517 // Remove avail extern fns and globals definitions since we aren't compiling
1518 // an object file for later LTO. For LTO we want to preserve these so they
1519 // are eligible for inlining at link-time. Note if they are unreferenced they
1520 // will be removed by GlobalDCE later, so this only impacts referenced
1521 // available externally globals. Eventually they will be suppressed during
1522 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1523 // may make globals referenced by available external functions dead and saves
1524 // running remaining passes on the eliminated functions. These should be
1525 // preserved during prelinking for link-time inlining decisions.
1526 if (!isLTOPreLink(LTOPhase))
1528
1529 // Do RPO function attribute inference across the module to forward-propagate
1530 // attributes where applicable.
1531 // FIXME: Is this really an optimization rather than a canonicalization?
1533
1534 // Do a post inline PGO instrumentation and use pass. This is a context
1535 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1536 // cross-module inline has not been done yet. The context sensitive
1537 // instrumentation is after all the inlines are done.
1538 if (!isLTOPreLink(LTOPhase) && PGOOpt) {
1539 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1540 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1541 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1542 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
1543 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1544 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1545 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1546 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1547 }
1548
1549 // Re-compute GlobalsAA here prior to function passes. This is particularly
1550 // useful as the above will have inlined, DCE'ed, and function-attr
1551 // propagated everything. We should at this point have a reasonably minimal
1552 // and richly annotated call graph. By computing aliasing and mod/ref
1553 // information for all local globals here, the late loop passes and notably
1554 // the vectorizer will be able to use them to help recognize vectorizable
1555 // memory operations.
1558
1559 invokeOptimizerEarlyEPCallbacks(MPM, Level, LTOPhase);
1560
1561 FunctionPassManager OptimizePM;
1562
1563 // Only drop unnecessary assumes post-inline and post-link, as otherwise
1564 // additional uses of the affected value may be introduced through inlining
1565 // and CSE.
1566 if (!isLTOPreLink(LTOPhase))
1567 OptimizePM.addPass(DropUnnecessaryAssumesPass());
1568
1569 // Scheduling LoopVersioningLICM when inlining is over, because after that
1570 // we may see more accurate aliasing. Reason to run this late is that too
1571 // early versioning may prevent further inlining due to increase of code
1572 // size. Other optimizations which runs later might get benefit of no-alias
1573 // assumption in clone loop.
1575 OptimizePM.addPass(
1577 // LoopVersioningLICM pass might increase new LICM opportunities.
1579 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1580 /*AllowSpeculation=*/true),
1581 /*USeMemorySSA=*/true));
1582 }
1583
1584 OptimizePM.addPass(Float2IntPass());
1586
1587 if (EnableMatrix) {
1588 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1589 OptimizePM.addPass(EarlyCSEPass());
1590 }
1591
1592 // CHR pass should only be applied with the profile information.
1593 // The check is to check the profile summary information in CHR.
1594 if (EnableCHR && Level == OptimizationLevel::O3)
1595 OptimizePM.addPass(ControlHeightReductionPass());
1596
1597 // FIXME: We need to run some loop optimizations to re-rotate loops after
1598 // simplifycfg and others undo their rotation.
1599
1600 // Optimize the loop execution. These passes operate on entire loop nests
1601 // rather than on each loop in an inside-out manner, and so they are actually
1602 // function passes.
1603
1604 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1605
1606 LoopPassManager LPM;
1607 // First rotate loops that may have been un-rotated by prior passes.
1608 // Disable header duplication at -Oz.
1609 LPM.addPass(LoopRotatePass(/*EnableLoopHeaderDuplication=*/true,
1610 isLTOPreLink(LTOPhase),
1611 /*CheckExitCount=*/true));
1612 // Some loops may have become dead by now. Try to delete them.
1613 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1614 // this may need to be revisited once we run GVN before loop deletion
1615 // in the simplification pipeline.
1616 LPM.addPass(LoopDeletionPass());
1617
1618 if (PTO.LoopInterchange)
1619 LPM.addPass(LoopInterchangePass());
1620
1621 OptimizePM.addPass(
1622 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
1623
1624 // FIXME: This may not be the right place in the pipeline.
1625 // We need to have the data to support the right place.
1626 if (PTO.LoopFusion)
1627 OptimizePM.addPass(LoopFusePass());
1628
1629 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1630 // into separate loop that would otherwise inhibit vectorization. This is
1631 // currently only performed for loops marked with the metadata
1632 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1633 OptimizePM.addPass(LoopDistributePass());
1634
1635 // Populates the VFABI attribute with the scalar-to-vector mappings
1636 // from the TargetLibraryInfo.
1637 OptimizePM.addPass(InjectTLIMappings());
1638
1639 addVectorPasses(Level, OptimizePM, LTOPhase);
1640
1641 invokeVectorizerEndEPCallbacks(OptimizePM, Level);
1642
1643 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1644 // canonicalization pass that enables other optimizations. As a result,
1645 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1646 // result too early.
1647 OptimizePM.addPass(LoopSinkPass());
1648
1649 // And finally clean up LCSSA form before generating code.
1650 OptimizePM.addPass(InstSimplifyPass());
1651
1652 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1653 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1654 // flattening of blocks.
1655 OptimizePM.addPass(DivRemPairsPass());
1656
1657 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
1658 // TODO: move this furter up so that it can be optimized by GVN, etc.
1659 if (EnableMergeICmps)
1660 OptimizePM.addPass(MergeICmpsPass());
1661 OptimizePM.addPass(ExpandMemCmpPass());
1662
1663 // Try to annotate calls that were created during optimization.
1664 OptimizePM.addPass(
1665 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
1666
1667 // LoopSink (and other loop passes since the last simplifyCFG) might have
1668 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1669 OptimizePM.addPass(
1671 .convertSwitchRangeToICmp(true)
1672 .convertSwitchToArithmetic(true)
1673 .speculateUnpredictables(true)
1674 .hoistLoadsStoresWithCondFaulting(true)));
1675
1676 // Add the core optimizing pipeline.
1677 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1678 PTO.EagerlyInvalidateAnalyses));
1679
1680 // AllocToken transforms heap allocation calls; this needs to run late after
1681 // other allocation call transformations (such as those in InstCombine).
1682 if (!isLTOPreLink(LTOPhase))
1683 MPM.addPass(AllocTokenPass());
1684
1685 invokeOptimizerLastEPCallbacks(MPM, Level, LTOPhase);
1686
1687 // Run the Instrumentor pass late.
1689 MPM.addPass(InstrumentorPass(FS));
1690
1691 // Split out cold code. Splitting is done late to avoid hiding context from
1692 // other optimizations and inadvertently regressing performance. The tradeoff
1693 // is that this has a higher code size cost than splitting early.
1694 if (EnableHotColdSplit && !isLTOPreLink(LTOPhase))
1696
1697 // Now we need to do some global optimization transforms.
1698 // FIXME: It would seem like these should come first in the optimization
1699 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1700 // ordering here.
1701 MPM.addPass(GlobalDCEPass());
1703
1704 // Merge functions if requested. It has a better chance to merge functions
1705 // after ConstantMerge folded jump tables.
1706 if (PTO.MergeFunctions)
1708
1709 if (PTO.CallGraphProfile && !isLTOPreLink(LTOPhase))
1710 MPM.addPass(CGProfilePass(isLTOPostLink(LTOPhase)));
1711
1712 // RelLookupTableConverterPass runs later in LTO post-link pipeline.
1713 if (!isLTOPreLink(LTOPhase))
1715
1716 // Add devirtualization pass only when LTO is not enabled, as otherwise
1717 // the pass is already enabled in the LTO pipeline.
1718 if (PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
1719 // TODO: explore a better pipeline configuration that can improve
1720 // compilation time overhead.
1721 // FIXME: move this earlier (lots of pass ordering tests will need fixing)
1722 MPM.addPass(AssignGUIDPass());
1724 /*ExportSummary*/ nullptr,
1725 /*ImportSummary*/ nullptr,
1726 /*DevirtSpeculatively*/ PTO.DevirtualizeSpeculatively));
1728 // Given that the devirtualization creates more opportunities for inlining,
1729 // we run the Inliner again here to maximize the optimization gain we
1730 // get from devirtualization.
1731 // Also, we can't run devirtualization before inlining because the
1732 // devirtualization depends on the passes optimizing/eliminating vtable GVs
1733 // and those passes are only effective after inlining.
1734 if (EnableModuleInliner) {
1738 } else {
1741 /* MandatoryFirst */ true,
1743 }
1744 }
1745
1746 // Attach !implicit.ref metadata from all functions to copyright strings.
1748
1749 return MPM;
1750}
1751
1755 if (Level == OptimizationLevel::O0)
1756 return buildO0DefaultPipeline(Level, Phase);
1757
1759 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1760 // Currently this pipeline is only invoked in an LTO pre link pass or when we
1761 // are not running LTO. If that changes the below checks may need updating.
1763
1764 // If we are invoking this in non-LTO mode, remove any MemProf related
1765 // attributes and metadata, as we don't know whether we are linking with
1766 // a library containing the necessary interfaces.
1769
1770 // Convert @llvm.global.annotations to !annotation metadata.
1772
1773 // Force any function attributes we want the rest of the pipeline to observe.
1775
1776 if (TriggerCrash)
1778
1779 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1781
1782 // Apply module pipeline start EP callback.
1784
1785 // Add the core simplification pipeline.
1787
1788 // Now add the optimization pipeline.
1790
1791 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1792 PGOOpt->Action == PGOOptions::SampleUse)
1794
1795 // Emit annotation remarks.
1797
1798 if (isLTOPreLink(Phase))
1799 addRequiredLTOPreLinkPasses(MPM);
1800
1801 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1802 return MPM;
1803}
1804
1807 bool EmitSummary, bool Verify) {
1809
1810 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1811
1812 if (ThinLTO)
1814 else
1816 // AssignGUIDPass attaches !guid metadata (MD_unique_id) to global objects,
1817 // triggering the bitcode writer to emit a METADATA_KIND_BLOCK. Standard LTO
1818 // bitcode emission runs VerifierPass by default, which registers metadata
1819 // kind IDs in LLVMContext. Running VerifierPass here before EmbedBitcodePass
1820 // to get the same behavior.
1821 if (Verify)
1822 MPM.addPass(VerifierPass());
1823 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1824
1825 // Perform any cleanups to the IR that aren't suitable for per TU compilation,
1826 // like removing CFI/WPD related instructions. Note, we reuse
1827 // DropTypeTestsPass to clean up type tests rather than duplicate that logic
1828 // in FatLtoCleanup.
1829 MPM.addPass(FatLtoCleanup());
1830
1831 // If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
1832 // object code, only in the bitcode section, so drop it before we run
1833 // module optimization and generate machine code. If llvm.type.test() isn't in
1834 // the IR, this won't do anything.
1836
1837 // Use the ThinLTO post-link pipeline with sample profiling
1838 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1839 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1840 else {
1841 // ModuleSimplification does not run the coroutine passes for
1842 // ThinLTOPreLink, so we need the coroutine passes to run for ThinLTO
1843 // builds, otherwise they will miscompile.
1844 if (ThinLTO) {
1845 // TODO: replace w/ buildCoroWrapper() when it takes phase and level into
1846 // consideration.
1847 CGSCCPassManager CGPM;
1851 MPM.addPass(CoroCleanupPass());
1852 }
1853
1854 // otherwise, just use module optimization
1855 MPM.addPass(
1857 // Emit annotation remarks.
1859 }
1860
1861 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1862
1863 return MPM;
1864}
1865
1868 if (Level == OptimizationLevel::O0)
1870
1872
1873 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1874
1875 // Convert @llvm.global.annotations to !annotation metadata.
1877
1878 // Force any function attributes we want the rest of the pipeline to observe.
1880
1881 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1883
1884 // Apply module pipeline start EP callback.
1886
1887 // If we are planning to perform ThinLTO later, we don't bloat the code with
1888 // unrolling/vectorization/... now. Just simplify the module as much as we
1889 // can.
1892 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1893 // thinlto use the contextual info to perform imports; then use the contextual
1894 // profile in the post-thinlink phase.
1895 if (!UseCtxProfile.empty()) {
1896 addRequiredLTOPreLinkPasses(MPM);
1897 return MPM;
1898 }
1899
1900 // Run partial inlining pass to partially inline functions that have
1901 // large bodies.
1902 // FIXME: It isn't clear whether this is really the right place to run this
1903 // in ThinLTO. Because there is another canonicalization and simplification
1904 // phase that will run after the thin link, running this here ends up with
1905 // less information than will be available later and it may grow functions in
1906 // ways that aren't beneficial.
1909
1910 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1911 PGOOpt->Action == PGOOptions::SampleUse)
1913
1914 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1915 // optimization is going to be done in PostLink stage, but clang can't add
1916 // callbacks there in case of in-process ThinLTO called by linker.
1921
1922 // Emit annotation remarks.
1924
1925 // Attach !implicit.ref metadata from all functions to copyright strings.
1927
1928 addRequiredLTOPreLinkPasses(MPM);
1929
1930 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1931
1932 return MPM;
1933}
1934
1936 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1938
1939 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1940
1941 // If we are invoking this without a summary index noting that we are linking
1942 // with a library containing the necessary APIs, remove any MemProf related
1943 // attributes and metadata.
1944 if (!ImportSummary || !ImportSummary->withSupportsHotColdNew())
1946
1947 if (ImportSummary) {
1948 // For ThinLTO we must apply the context disambiguation decisions early, to
1949 // ensure we can correctly match the callsites to summary data.
1952 ImportSummary, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1953
1954 // These passes import type identifier resolutions for whole-program
1955 // devirtualization and CFI. They must run early because other passes may
1956 // disturb the specific instruction patterns that these passes look for,
1957 // creating dependencies on resolutions that may not appear in the summary.
1958 //
1959 // For example, GVN may transform the pattern assume(type.test) appearing in
1960 // two basic blocks into assume(phi(type.test, type.test)), which would
1961 // transform a dependency on a WPD resolution into a dependency on a type
1962 // identifier resolution for CFI.
1963 //
1964 // Also, WPD has access to more precise information than ICP and can
1965 // devirtualize more effectively, so it should operate on the IR first.
1966 //
1967 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1968 // metadata and intrinsics.
1969 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1970 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1971 }
1972
1973 if (Level == OptimizationLevel::O0) {
1974 // Run a second time to clean up any type tests left behind by WPD for use
1975 // in ICP.
1978
1979 // AllocToken transforms heap allocation calls; this needs to run late after
1980 // other allocation call transformations (such as those in InstCombine).
1981 MPM.addPass(AllocTokenPass());
1982
1983 // Drop available_externally and unreferenced globals. This is necessary
1984 // with ThinLTO in order to avoid leaving undefined references to dead
1985 // globals in the object file.
1987 MPM.addPass(GlobalDCEPass());
1988 return MPM;
1989 }
1990 if (!UseCtxProfile.empty()) {
1991 MPM.addPass(
1993 } else {
1994 // Add the core simplification pipeline.
1997 }
1998 // Now add the optimization pipeline.
2001
2002 // Emit annotation remarks.
2004
2005 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2006
2007 return MPM;
2008}
2009
2012 // FIXME: We should use a customized pre-link pipeline!
2013 return buildPerModuleDefaultPipeline(Level,
2015}
2016
2019 ModuleSummaryIndex *ExportSummary) {
2021
2022 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2023
2025
2026 // If we are invoking this without a summary index noting that we are linking
2027 // with a library containing the necessary APIs, remove any MemProf related
2028 // attributes and metadata.
2029 if (!ExportSummary || !ExportSummary->withSupportsHotColdNew())
2031
2032 // Create a function that performs CFI checks for cross-DSO calls with targets
2033 // in the current module.
2034 MPM.addPass(CrossDSOCFIPass());
2035
2036 if (Level == OptimizationLevel::O0) {
2037 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
2038 // metadata and intrinsics.
2039 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2040 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2041 // Run a second time to clean up any type tests left behind by WPD for use
2042 // in ICP.
2044
2046
2047 // AllocToken transforms heap allocation calls; this needs to run late after
2048 // other allocation call transformations (such as those in InstCombine).
2049 MPM.addPass(AllocTokenPass());
2050
2052
2053 // Emit annotation remarks.
2055
2056 return MPM;
2057 }
2058
2059 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2060 // Load sample profile before running the LTO optimization pipeline.
2061 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2062 PGOOpt->ProfileRemappingFile,
2064 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2065 // RequireAnalysisPass for PSI before subsequent non-module passes.
2067 }
2068
2069 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
2071
2072 // Remove unused virtual tables to improve the quality of code generated by
2073 // whole-program devirtualization and bitset lowering.
2074 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2075
2076 // Do basic inference of function attributes from known properties of system
2077 // libraries and other oracles.
2079
2080 if (Level >= OptimizationLevel::O2) {
2082 CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
2083
2084 // Indirect call promotion. This should promote all the targets that are
2085 // left by the earlier promotion pass that promotes intra-module targets.
2086 // This two-step promotion is to save the compile time. For LTO, it should
2087 // produce the same result as if we only do promotion here.
2089 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2090
2091 // Promoting by-reference arguments to by-value exposes more constants to
2092 // IPSCCP.
2093 CGSCCPassManager CGPM;
2096 CGPM.addPass(
2099
2100 // Propagate constants at call sites into the functions they call. This
2101 // opens opportunities for globalopt (and inlining) by substituting function
2102 // pointers passed as arguments to direct uses of functions.
2103 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/true)));
2104
2105 // Attach metadata to indirect call sites indicating the set of functions
2106 // they may target at run-time. This should follow IPSCCP.
2108 }
2109
2110 // Do RPO function attribute inference across the module to forward-propagate
2111 // attributes where applicable.
2112 // FIXME: Is this really an optimization rather than a canonicalization?
2114
2115 // Use in-range annotations on GEP indices to split globals where beneficial.
2116 MPM.addPass(GlobalSplitPass());
2117
2118 // Run whole program optimization of virtual call when the list of callees
2119 // is fixed.
2120 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2121
2123 // Stop here at -O1.
2124 if (Level == OptimizationLevel::O1) {
2125 // The LowerTypeTestsPass needs to run to lower type metadata and the
2126 // type.test intrinsics. The pass does nothing if CFI is disabled.
2127 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2128 // Run a second time to clean up any type tests left behind by WPD for use
2129 // in ICP (which is performed earlier than this in the regular LTO
2130 // pipeline).
2132
2134
2135 // AllocToken transforms heap allocation calls; this needs to run late after
2136 // other allocation call transformations (such as those in InstCombine).
2137 MPM.addPass(AllocTokenPass());
2138
2140
2141 // Emit annotation remarks.
2143
2144 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2145
2146 return MPM;
2147 }
2148
2149 // TODO: Skip to match buildCoroWrapper.
2150 MPM.addPass(CoroEarlyPass());
2151
2152 // Optimize globals to try and fold them into constants.
2153 MPM.addPass(GlobalOptPass());
2154
2155 // Promote any localized globals to SSA registers.
2157
2158 // Linking modules together can lead to duplicate global constant, only
2159 // keep one copy of each constant.
2161
2162 // Remove unused arguments from functions.
2164
2165 // Reduce the code after globalopt and ipsccp. Both can open up significant
2166 // simplification opportunities, and both can propagate functions through
2167 // function pointers. When this happens, we often have to resolve varargs
2168 // calls, etc, so let instcombine do this.
2169 FunctionPassManager PeepholeFPM;
2170 PeepholeFPM.addPass(InstCombinePass());
2171 if (Level >= OptimizationLevel::O2)
2172 PeepholeFPM.addPass(AggressiveInstCombinePass());
2173 invokePeepholeEPCallbacks(PeepholeFPM, Level);
2174
2175 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
2176 PTO.EagerlyInvalidateAnalyses));
2177
2178 // Lower variadic functions for supported targets prior to inlining.
2180
2181 // Note: historically, the PruneEH pass was run first to deduce nounwind and
2182 // generally clean up exception handling overhead. It isn't clear this is
2183 // valuable as the inliner doesn't currently care whether it is inlining an
2184 // invoke or a call.
2185 // Run the inliner now.
2186 if (EnableModuleInliner) {
2190 } else {
2193 /* MandatoryFirst */ true,
2196 }
2197
2198 // Perform context disambiguation after inlining, since that would reduce the
2199 // amount of additional cloning required to distinguish the allocation
2200 // contexts.
2203 /*Summary=*/nullptr,
2204 PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2205
2206 // Optimize globals again after we ran the inliner.
2207 MPM.addPass(GlobalOptPass());
2208
2209 // Run the OpenMPOpt pass again after global optimizations.
2211
2212 // Garbage collect dead functions.
2213 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2214
2215 // If we didn't decide to inline a function, check to see if we can
2216 // transform it to pass arguments by value instead of by reference.
2217 CGSCCPassManager CGPM;
2223
2225 // The IPO Passes may leave cruft around. Clean up after them.
2226 FPM.addPass(InstCombinePass());
2227 invokePeepholeEPCallbacks(FPM, Level);
2228
2231
2233
2234 // Do a post inline PGO instrumentation and use pass. This is a context
2235 // sensitive PGO pass.
2236 if (PGOOpt) {
2237 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
2238 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
2239 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2240 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
2241 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
2242 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
2243 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2244 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
2245 }
2246
2247 // Break up allocas
2249
2250 // LTO provides additional opportunities for tailcall elimination due to
2251 // link-time inlining, and visibility of nocapture attribute.
2252 FPM.addPass(
2253 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
2254
2255 // Run a few AA driver optimizations here and now to cleanup the code.
2256 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
2257 PTO.EagerlyInvalidateAnalyses));
2258
2259 MPM.addPass(
2261
2262 // Require the GlobalsAA analysis for the module so we can query it within
2263 // MainFPM.
2266 // Invalidate AAManager so it can be recreated and pick up the newly
2267 // available GlobalsAA.
2268 MPM.addPass(
2270 }
2271
2272 FunctionPassManager MainFPM;
2274 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
2275 /*AllowSpeculation=*/true),
2276 /*USeMemorySSA=*/true));
2277
2278 if (RunNewGVN)
2279 MainFPM.addPass(NewGVNPass());
2280 else
2281 MainFPM.addPass(GVNPass());
2282
2283 // Remove dead memcpy()'s.
2284 MainFPM.addPass(MemCpyOptPass());
2285
2286 // Nuke dead stores.
2287 MainFPM.addPass(DSEPass());
2288 MainFPM.addPass(MoveAutoInitPass());
2290
2291 invokeVectorizerStartEPCallbacks(MainFPM, Level);
2292
2293 LoopPassManager LPM;
2295 LPM.addPass(LoopFlattenPass());
2296 LPM.addPass(IndVarSimplifyPass());
2297 LPM.addPass(LoopDeletionPass());
2298 // FIXME: Add loop interchange.
2299
2300 // Unroll small loops and perform peeling.
2301 LPM.addPass(LoopFullUnrollPass(static_cast<int>(Level),
2302 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
2303 PTO.ForgetAllSCEVInLoopUnroll));
2304 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2305 // *All* loop passes must preserve it, in order to be able to use it.
2306 MainFPM.addPass(
2307 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
2308
2309 MainFPM.addPass(LoopDistributePass());
2310
2311 addVectorPasses(Level, MainFPM, ThinOrFullLTOPhase::FullLTOPostLink);
2312
2313 invokeVectorizerEndEPCallbacks(MainFPM, Level);
2314
2315 // Run the OpenMPOpt CGSCC pass again late.
2318
2319 invokePeepholeEPCallbacks(MainFPM, Level);
2320 MainFPM.addPass(JumpThreadingPass());
2321 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
2322 PTO.EagerlyInvalidateAnalyses));
2323
2324 // Lower type metadata and the type.test intrinsic. This pass supports
2325 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2326 // to be run at link time if CFI is enabled. This pass does nothing if
2327 // CFI is disabled.
2328 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2329 // Run a second time to clean up any type tests left behind by WPD for use
2330 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2332
2333 // Enable splitting late in the FullLTO post-link pipeline.
2336
2337 // Add late LTO optimization passes.
2338 FunctionPassManager LateFPM;
2339
2340 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2341 // canonicalization pass that enables other optimizations. As a result,
2342 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2343 // result too early.
2344 LateFPM.addPass(LoopSinkPass());
2345
2346 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2347 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2348 // flattening of blocks.
2349 LateFPM.addPass(DivRemPairsPass());
2350
2351 // Delete basic blocks, which optimization passes may have killed.
2353 .convertSwitchRangeToICmp(true)
2354 .convertSwitchToArithmetic(true)
2355 .hoistCommonInsts(true)
2356 .speculateUnpredictables(true)));
2357 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2358
2359 // Drop bodies of available eternally objects to improve GlobalDCE.
2361
2362 // Now that we have optimized the program, discard unreachable functions.
2363 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2364
2365 if (PTO.MergeFunctions)
2367
2369
2370 if (PTO.CallGraphProfile)
2371 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2372
2373 MPM.addPass(CoroCleanupPass());
2374
2375 // AllocToken transforms heap allocation calls; this needs to run late after
2376 // other allocation call transformations (such as those in InstCombine).
2377 MPM.addPass(AllocTokenPass());
2378
2380
2381 // Emit annotation remarks.
2383
2384 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2385
2386 return MPM;
2387}
2388
2392 assert(Level == OptimizationLevel::O0 &&
2393 "buildO0DefaultPipeline should only be used with O0");
2394
2396
2397 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2398
2399 // Perform pseudo probe instrumentation in O0 mode. This is for the
2400 // consistency between different build modes. For example, a LTO build can be
2401 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2402 // the postlink will require pseudo probe instrumentation in the prelink.
2403 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2405
2406 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2407 PGOOpt->Action == PGOOptions::IRUse))
2409 MPM,
2410 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2411 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2412 PGOOpt->ProfileRemappingFile);
2413
2414 // Instrument function entry and exit before all inlining.
2416 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2417
2419
2420 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2422
2423 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2424 // Explicitly disable sample loader inlining and use flattened profile in O0
2425 // pipeline.
2426 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2427 PGOOpt->ProfileRemappingFile,
2429 /*DisableSampleProfileInlining=*/true,
2430 /*UseFlattenedProfile=*/true));
2431 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2432 // RequireAnalysisPass for PSI before subsequent non-module passes.
2434 }
2435
2437
2438 // Build a minimal pipeline based on the semantics required by LLVM,
2439 // which is just that always inlining occurs. Further, disable generating
2440 // lifetime intrinsics to avoid enabling further optimizations during
2441 // code generation.
2443 /*InsertLifetimeIntrinsics=*/false));
2444
2445 if (PTO.MergeFunctions)
2447
2448 if (EnableMatrix)
2449 MPM.addPass(
2451
2452 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2453 CGSCCPassManager CGPM;
2455 if (!CGPM.isEmpty())
2457 }
2458 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2459 LoopPassManager LPM;
2461 if (!LPM.isEmpty()) {
2463 createFunctionToLoopPassAdaptor(std::move(LPM))));
2464 }
2465 }
2466 if (!LoopOptimizerEndEPCallbacks.empty()) {
2467 LoopPassManager LPM;
2469 if (!LPM.isEmpty()) {
2471 createFunctionToLoopPassAdaptor(std::move(LPM))));
2472 }
2473 }
2474 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2477 if (!FPM.isEmpty())
2478 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2479 }
2480
2482
2483 if (!VectorizerStartEPCallbacks.empty()) {
2486 if (!FPM.isEmpty())
2487 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2488 }
2489
2490 if (!VectorizerEndEPCallbacks.empty()) {
2493 if (!FPM.isEmpty())
2494 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2495 }
2496
2498
2499 // AllocToken transforms heap allocation calls; this needs to run late after
2500 // other allocation call transformations (such as those in InstCombine).
2501 if (!isLTOPreLink(Phase))
2502 MPM.addPass(AllocTokenPass());
2503
2505
2507 MPM.addPass(InstrumentorPass(FS));
2508
2509 // Attach !implicit.ref metadata from all functions to copyright strings.
2511
2512 if (isLTOPreLink(Phase))
2513 addRequiredLTOPreLinkPasses(MPM);
2514
2515 // Emit annotation remarks.
2517
2518 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2519
2520 return MPM;
2521}
2522
2524 AAManager AA;
2525
2526 // The order in which these are registered determines their priority when
2527 // being queried.
2528
2529 // Add any target-specific alias analyses that should be run early.
2530 if (TM)
2531 TM->registerEarlyDefaultAliasAnalyses(AA);
2532
2533 // First we register the basic alias analysis that provides the majority of
2534 // per-function local AA logic. This is a stateless, on-demand local set of
2535 // AA techniques.
2536 AA.registerFunctionAnalysis<BasicAA>();
2537
2538 // Next we query fast, specialized alias analyses that wrap IR-embedded
2539 // information about aliasing.
2540 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2541 AA.registerFunctionAnalysis<TypeBasedAA>();
2542
2543 // Add support for querying global aliasing information when available.
2544 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2545 // analysis, all that the `AAManager` can do is query for any *cached*
2546 // results from `GlobalsAA` through a readonly proxy.
2548 AA.registerModuleAnalysis<GlobalsAA>();
2549
2550 // Add target-specific alias analyses.
2551 if (TM)
2552 TM->registerDefaultAliasAnalyses(AA);
2553
2554 return AA;
2555}
2556
2557bool PassBuilder::isInstrumentedPGOUse() const {
2558 return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2559 !UseCtxProfile.empty();
2560}
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.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
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 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 bool isThinLTOPostLink(ThinOrFullLTOPhase Phase)
static void addAnnotationRemarksPass(ModulePassManager &MPM)
static CoroConditionalWrapper buildCoroWrapper(ThinOrFullLTOPhase Phase)
static bool isFullLTOPostLink(ThinOrFullLTOPhase Phase)
static bool isThinLTOPreLink(ThinOrFullLTOPhase Phase)
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
static void instructionCountersPass(ModulePassManager &MPM, bool IsPreOptimization)
static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase)
static bool isLTOPostLink(ThinOrFullLTOPhase Phase)
This file implements relative lookup table converter that converts lookup tables to relative lookup t...
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
This file provides the interface for the pseudo probe implementation for AutoFDO.
This file provides the interface for the sampled PGO loader pass.
This is the interface for a metadata-based scoped no-alias analysis.
This file provides the interface for the pass responsible for both simplifying and canonicalizing the...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
This is the interface for a metadata-based TBAA.
A manager for alias analyses.
A module pass that rewrites heap allocations to use token-enabled allocation functions based on vario...
Definition AllocToken.h:36
Inlines functions marked as "always_inline".
Argument promotion pass.
Analysis pass providing a never-invalidated alias analysis result.
Simple pass that canonicalizes aliases.
A pass that merges duplicate global constants into a single constant.
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.
The core GVN pass object.
Definition GVN.h:123
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:66
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
Class to hold module path string table and global value map, and encapsulate methods for operating on...
Simple pass that provides a name to every anonymous globals.
Additional 'norecurse' attribute deduction during postlink LTO phase.
OpenMP optimizations pass.
Definition OpenMPOpt.h:42
static LLVM_ABI bool isCtxIRPGOInstrEnabled()
The indirect function call promotion pass.
The instrumentation (profile-instr-gen) pass for IR based PGO.
The instrumentation (profile-instr-gen) pass for IR based PGO.
The profile annotation (profile-instr-use) pass for IR based PGO.
The profile size based optimization pass for memory intrinsics.
Pass to remove unused function declarations.
LLVM_ABI void invokeFullLinkTimeOptimizationLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI ModuleInlinerWrapperPass buildInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining as well as the inlining-driven cleanups.
LLVM_ABI void invokeOptimizerEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase)
LLVM_ABI ModulePassManager buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO, bool EmitSummary, bool Verify=true)
Build a fat object default optimization pipeline.
LLVM_ABI void invokeVectorizerStartEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI AAManager buildDefaultAAPipeline()
Build the default AAManager with the default alias analysis pipeline registered.
LLVM_ABI void invokeCGSCCOptimizerLateEPCallbacks(CGSCCPassManager &CGPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, ThinLTO-targeting default optimization pipeline to a pass manager.
LLVM_ABI void addPGOInstrPassesForO0(ModulePassManager &MPM, bool RunProfileGen, bool IsCS, bool AtomicCounterUpdate, std::string ProfileFile, std::string ProfileRemappingFile)
Add PGOInstrumenation passes for O0 only.
LLVM_ABI void invokeScalarOptimizerLateEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI ModulePassManager buildPerModuleDefaultPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase=ThinOrFullLTOPhase::None)
Build a per-module default optimization pipeline.
LLVM_ABI void invokePipelineStartEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
LLVM_ABI void invokeVectorizerEndEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
LLVM_ABI 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 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:78
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition PassBuilder.h:56
int InlinerThreshold
Tuning option to override the default inliner threshold.
Definition PassBuilder.h:92
bool LoopFusion
Tuning option to enable/disable loop fusion. Its default value is false.
Definition PassBuilder.h:66
bool CallGraphProfile
Tuning option to enable/disable call graph profile.
Definition PassBuilder.h:82
bool MergeFunctions
Tuning option to enable/disable function merging.
Definition PassBuilder.h:89
bool ForgetAllSCEVInLoopUnroll
Tuning option to forget all SCEV loops in LoopUnroll.
Definition PassBuilder.h:70
unsigned LicmMssaOptCap
Tuning option to cap the number of calls to retrive clobbering accesses in MemorySSA,...
Definition PassBuilder.h:74
bool LoopInterleaving
Tuning option to set loop interleaving on/off, set based on opt level.
Definition PassBuilder.h:48
LLVM_ABI PipelineTuningOptions()
Constructor sets pipeline tuning defaults based on cl::opts.
bool LoopUnrolling
Tuning option to enable/disable loop unrolling. Its default value is true.
Definition PassBuilder.h:59
bool LoopInterchange
Tuning option to enable/disable loop interchange.
Definition PassBuilder.h:63
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:52
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:133
Interfaces for registering analysis passes, producing common pass manager configurations,...
Abstract Attribute helper functions.
Definition Attributor.h:165
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
@ 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
static cl::opt< bool > RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden, cl::desc("Run the NewGVN pass"))
static cl::opt< bool > DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden, cl::desc("Disable pre-instrumentation inliner"))
static cl::opt< bool > EnableDFAJumpThreading("enable-dfa-jump-thread", cl::desc("Enable DFA jump threading"), cl::init(true), cl::Hidden)
static cl::opt< bool > PerformMandatoryInliningsFirst("mandatory-inlining-first", cl::init(false), cl::Hidden, cl::desc("Perform mandatory inlinings module-wide, before performing " "inlining"))
static cl::opt< bool > RunPartialInlining("enable-partial-inlining", cl::init(false), cl::Hidden, cl::desc("Run Partial inlining pass"))
static cl::opt< bool > EnableGVNSink("enable-gvn-sink", cl::desc("Enable the GVN sinking pass (default = off)"))
static cl::opt< bool > EnableModuleInliner("enable-module-inliner", cl::init(false), cl::Hidden, cl::desc("Enable module inliner"))
static cl::opt< bool > EnableEagerlyInvalidateAnalyses("eagerly-invalidate-analyses", cl::init(true), cl::Hidden, cl::desc("Eagerly invalidate more analyses in default pipelines"))
static cl::opt< bool > EnableMatrix("enable-matrix", cl::init(false), cl::Hidden, cl::desc("Enable lowering of the matrix intrinsics"))
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
static cl::opt< bool > EnableSampledInstr("enable-sampled-instrumentation", cl::init(false), cl::Hidden, cl::desc("Enable profile instrumentation sampling (default = off)"))
static cl::opt< bool > EnableLoopFlatten("enable-loop-flatten", cl::init(false), cl::Hidden, cl::desc("Enable the LoopFlatten Pass"))
@ 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...
static cl::opt< InliningAdvisorMode > UseInlineAdvisor("enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden, cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"), cl::values(clEnumValN(InliningAdvisorMode::Default, "default", "Heuristics-based inliner version"), clEnumValN(InliningAdvisorMode::Development, "development", "Use development mode (runtime-loadable model)"), clEnumValN(InliningAdvisorMode::Release, "release", "Use release mode (AOT-compiled model)")))
static cl::opt< bool > EnableJumpTableToSwitch("enable-jump-table-to-switch", cl::init(true), cl::desc("Enable JumpTableToSwitch pass (default = true)"))
PassManager< LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, CGSCCUpdateResult & > CGSCCPassManager
The CGSCC pass manager.
static cl::opt< bool > EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false), cl::Hidden, cl::desc("Enable Unroll And Jam Pass"))
@ CGSCC_LIGHT
@ MODULE_LIGHT
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition Pass.h:77
@ FullLTOPreLink
Full LTO prelink phase.
Definition Pass.h:85
@ ThinLTOPostLink
ThinLTO postlink (backend compile) phase.
Definition Pass.h:83
@ None
No LTO/ThinLTO behavior needed.
Definition Pass.h:79
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
Definition Pass.h:87
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
Definition Pass.h:81
PassManager< Loop, LoopAnalysisManager, LoopStandardAnalysisResults &, LPMUpdater & > LoopPassManager
The Loop pass manager.
static cl::opt< bool > EnableConstraintElimination("enable-constraint-elimination", cl::init(true), cl::Hidden, cl::desc("Enable pass to eliminate conditions based on linear constraints"))
ModuleToPostOrderCGSCCPassAdaptor createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass)
A function to deduce a function pass type and wrap it in the templated adaptor.
static cl::opt< bool > EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true), cl::Hidden, cl::desc("Enable inline deferral during PGO"))
Flag to enable inline deferral during PGO.
FunctionToLoopPassAdaptor createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
CGSCCToFunctionPassAdaptor createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false, bool NoRerun=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
LLVM_ABI cl::opt< bool > ForgetSCEVInLoopUnroll
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
static cl::opt< bool > EnablePostPGOLoopRotation("enable-post-pgo-loop-rotation", cl::init(true), cl::Hidden, cl::desc("Run the loop rotation transformation after PGO instrumentation"))
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
static cl::opt< std::string > InstrumentColdFuncOnlyPath("instrument-cold-function-only-path", cl::init(""), cl::desc("File path for cold function only instrumentation(requires use " "with --pgo-instrument-cold-function-only)"), cl::Hidden)
static cl::opt< bool > EnableGlobalAnalyses("enable-global-analyses", cl::init(true), cl::Hidden, cl::desc("Enable inter-procedural analyses"))
static cl::opt< bool > FlattenedProfileUsed("flattened-profile-used", cl::init(false), cl::Hidden, cl::desc("Indicate the sample profile being used is flattened, i.e., " "no inline hierarchy exists in the profile"))
static cl::opt< AttributorRunOption > AttributorRun("attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE), cl::desc("Enable the attributor inter-procedural deduction pass"), cl::values(clEnumValN(AttributorRunOption::FULL, "full", "enable all full attributor runs"), clEnumValN(AttributorRunOption::LIGHT, "light", "enable all attributor-light runs"), clEnumValN(AttributorRunOption::MODULE, "module", "enable module-wide attributor runs"), clEnumValN(AttributorRunOption::MODULE_LIGHT, "module-light", "enable module-wide attributor-light runs"), clEnumValN(AttributorRunOption::CGSCC, "cgscc", "enable call graph SCC attributor runs"), clEnumValN(AttributorRunOption::CGSCC_LIGHT, "cgscc-light", "enable call graph SCC attributor-light runs"), clEnumValN(AttributorRunOption::NONE, "none", "disable attributor runs")))
static cl::opt< bool > EnableLoopInterchange("enable-loopinterchange", cl::init(true), cl::Hidden, cl::desc("Enable the LoopInterchange Pass"))
static cl::opt< bool > ExtraVectorizerPasses("extra-vectorizer-passes", cl::init(false), cl::Hidden, cl::desc("Run cleanup optimization passes after vectorization"))
static cl::opt< bool > EnableHotColdSplit("hot-cold-split", cl::desc("Enable hot-cold splitting pass"))
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
static cl::opt< bool > TriggerCrash("opt-pipeline-trigger-crash", cl::init(false), cl::Hidden, cl::desc("Trigger crash in optimization pipeline"))
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.
cl::opt< bool > PGOInstrumentColdFunctionOnly
static cl::opt< bool > EnableCHR("enable-chr", cl::init(true), cl::Hidden, cl::desc("Enable control height reduction optimization (CHR)"))
static cl::opt< bool > EnableMergeFunctions("enable-merge-functions", cl::init(false), cl::Hidden, cl::desc("Enable function merging as part of the optimization pipeline"))
static cl::opt< bool > EnableDevirtualizeSpeculatively("enable-devirtualize-speculatively", cl::desc("Enable speculative devirtualization optimization"), cl::init(false))
static cl::opt< bool > EnableGVNHoist("enable-gvn-hoist", cl::desc("Enable the GVN hoisting pass (default = off)"))
LLVM_ABI cl::opt< unsigned > SetLicmMssaNoAccForPromotionCap
LLVM_ABI InlineParams getInlineParamsFromOptLevel(unsigned OptLevel)
Generate the parameters to tune the inline cost analysis based on command line options.
static cl::opt< int > PreInlineThreshold("preinline-threshold", cl::Hidden, cl::init(75), cl::desc("Control the amount of inlining in pre-instrumentation inliner " "(default = 75)"))
static cl::opt< bool > UseLoopVersioningLICM("enable-loop-versioning-licm", cl::init(false), cl::Hidden, cl::desc("Enable the experimental Loop Versioning LICM pass"))
cl::opt< unsigned > MaxDevirtIterations("max-devirt-iterations", cl::ReallyHidden, cl::init(4))
LLVM_ABI cl::opt< unsigned > SetLicmMssaOptCap
static cl::opt< bool > EnableInstrumentor("enable-instrumentor", cl::init(false), cl::Hidden, cl::desc("Enable the Instrumentor Pass"))
static cl::opt< bool > EnableMergeICmps("enable-mergeicmps", cl::init(true), cl::Hidden, cl::desc("Enable MergeICmps pass in the optimization pipeline"))
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 GVN.h:521
Uses an "inverted" value numbering to decide the similarity of expressions and sinks similar expressi...
Definition GVN.h:528
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.