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"
29#include "llvm/IR/PassManager.h"
30#include "llvm/IR/Verifier.h"
31#include "llvm/Pass.h"
159
160using namespace llvm;
161
162namespace llvm {
163
165 "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
166 cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
168 "Heuristics-based inliner version"),
170 "Use development mode (runtime-loadable model)"),
172 "Use release mode (AOT-compiled model)")));
173
174/// Flag to enable inline deferral during PGO.
175static cl::opt<bool>
176 EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
178 cl::desc("Enable inline deferral during PGO"));
179
180static cl::opt<bool> EnableModuleInliner("enable-module-inliner",
181 cl::init(false), cl::Hidden,
182 cl::desc("Enable module inliner"));
183
185 "mandatory-inlining-first", cl::init(false), cl::Hidden,
186 cl::desc("Perform mandatory inlinings module-wide, before performing "
187 "inlining"));
188
190 "eagerly-invalidate-analyses", cl::init(true), cl::Hidden,
191 cl::desc("Eagerly invalidate more analyses in default pipelines"));
192
194 "enable-merge-functions", cl::init(false), cl::Hidden,
195 cl::desc("Enable function merging as part of the optimization pipeline"));
196
198 "enable-post-pgo-loop-rotation", cl::init(true), cl::Hidden,
199 cl::desc("Run the loop rotation transformation after PGO instrumentation"));
200
201static cl::opt<bool>
202 TriggerCrash("opt-pipeline-trigger-crash", cl::init(false), cl::Hidden,
203 cl::desc("Trigger crash in optimization pipeline"));
204
206 "enable-global-analyses", cl::init(true), cl::Hidden,
207 cl::desc("Enable inter-procedural analyses"));
208
209static cl::opt<bool> RunPartialInlining("enable-partial-inlining",
210 cl::init(false), cl::Hidden,
211 cl::desc("Run Partial inlining pass"));
212
214 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
215 cl::desc("Run cleanup optimization passes after vectorization"));
216
217static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
218 cl::desc("Run the NewGVN pass"));
219
220static cl::opt<bool>
221 EnableLoopInterchange("enable-loopinterchange", cl::init(true), cl::Hidden,
222 cl::desc("Enable the LoopInterchange Pass"));
223
224static cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam",
225 cl::init(false), cl::Hidden,
226 cl::desc("Enable Unroll And Jam Pass"));
227
228static cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
230 cl::desc("Enable the LoopFlatten Pass"));
231
232static cl::opt<bool>
233 EnableInstrumentor("enable-instrumentor", cl::init(false), cl::Hidden,
234 cl::desc("Enable the Instrumentor Pass"));
235
236static cl::opt<bool>
237 EnableDFAJumpThreading("enable-dfa-jump-thread",
238 cl::desc("Enable DFA jump threading"),
239 cl::init(true), cl::Hidden);
240
241static cl::opt<bool>
242 EnableHotColdSplit("hot-cold-split",
243 cl::desc("Enable hot-cold splitting pass"));
244
245static cl::opt<bool>
246 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
247 cl::desc("Disable pre-instrumentation inliner"));
248
250 "preinline-threshold", cl::Hidden, cl::init(75),
251 cl::desc("Control the amount of inlining in pre-instrumentation inliner "
252 "(default = 75)"));
253
254static cl::opt<bool>
255 EnableGVNHoist("enable-gvn-hoist",
256 cl::desc("Enable the GVN hoisting pass (default = off)"));
257
258static cl::opt<bool>
259 EnableGVNSink("enable-gvn-sink",
260 cl::desc("Enable the GVN sinking pass (default = off)"));
261
263 "enable-jump-table-to-switch", cl::init(true),
264 cl::desc("Enable JumpTableToSwitch pass (default = true)"));
265
266// This option is used in simplifying testing SampleFDO optimizations for
267// profile loading.
268static cl::opt<bool>
269 EnableCHR("enable-chr", cl::init(true), cl::Hidden,
270 cl::desc("Enable control height reduction optimization (CHR)"));
271
273 "flattened-profile-used", cl::init(false), cl::Hidden,
274 cl::desc("Indicate the sample profile being used is flattened, i.e., "
275 "no inline hierarchy exists in the profile"));
276
277static cl::opt<bool>
278 EnableMatrix("enable-matrix", cl::init(false), cl::Hidden,
279 cl::desc("Enable lowering of the matrix intrinsics"));
280
282 "enable-mergeicmps", cl::init(true), cl::Hidden,
283 cl::desc("Enable MergeICmps pass in the optimization pipeline"));
284
286 "enable-constraint-elimination", cl::init(true), cl::Hidden,
287 cl::desc(
288 "Enable pass to eliminate conditions based on linear constraints"));
289
291 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
292 cl::desc("Enable the attributor inter-procedural deduction pass"),
294 "enable all full attributor runs"),
296 "enable all attributor-light runs"),
298 "enable module-wide attributor runs"),
300 "enable module-wide attributor-light runs"),
302 "enable call graph SCC attributor runs"),
304 "enable call graph SCC attributor-light runs"),
305 clEnumValN(AttributorRunOption::NONE, "none",
306 "disable attributor runs")));
307
309 "enable-sampled-instrumentation", cl::init(false), cl::Hidden,
310 cl::desc("Enable profile instrumentation sampling (default = off)"));
312 "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
313 cl::desc("Enable the experimental Loop Versioning LICM pass"));
314
316 "instrument-cold-function-only-path", cl::init(""),
317 cl::desc("File path for cold function only instrumentation(requires use "
318 "with --pgo-instrument-cold-function-only)"),
319 cl::Hidden);
320
321// TODO: There is a similar flag in WPD pass, we should consolidate them by
322// parsing the option only once in PassBuilder and share it across both places.
324 "enable-devirtualize-speculatively",
325 cl::desc("Enable speculative devirtualization optimization"),
326 cl::init(false));
327
330
332} // namespace llvm
333
351
352namespace llvm {
354} // namespace llvm
355
357 OptimizationLevel Level) {
358 for (auto &C : PeepholeEPCallbacks)
359 C(FPM, Level);
360}
363 for (auto &C : LateLoopOptimizationsEPCallbacks)
364 C(LPM, Level);
365}
367 OptimizationLevel Level) {
368 for (auto &C : LoopOptimizerEndEPCallbacks)
369 C(LPM, Level);
370}
373 for (auto &C : ScalarOptimizerLateEPCallbacks)
374 C(FPM, Level);
375}
377 OptimizationLevel Level) {
378 for (auto &C : CGSCCOptimizerLateEPCallbacks)
379 C(CGPM, Level);
380}
382 OptimizationLevel Level) {
383 for (auto &C : VectorizerStartEPCallbacks)
384 C(FPM, Level);
385}
387 OptimizationLevel Level) {
388 for (auto &C : VectorizerEndEPCallbacks)
389 C(FPM, Level);
390}
392 OptimizationLevel Level,
394 for (auto &C : OptimizerEarlyEPCallbacks)
395 C(MPM, Level, Phase);
396}
398 OptimizationLevel Level,
400 for (auto &C : OptimizerLastEPCallbacks)
401 C(MPM, Level, Phase);
402}
405 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
406 C(MPM, Level);
407}
410 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
411 C(MPM, Level);
412}
414 OptimizationLevel Level) {
415 for (auto &C : PipelineStartEPCallbacks)
416 C(MPM, Level);
417}
420 for (auto &C : PipelineEarlySimplificationEPCallbacks)
421 C(MPM, Level, Phase);
422}
423
424// Get IR stats with InstCount before/after the optimization pipeline
426 bool IsPreOptimization) {
427 if (AreStatisticsEnabled()) {
428 MPM.addPass(
431 FunctionPropertiesStatisticsPass(IsPreOptimization)));
432 }
433}
434
435// Helper to add AnnotationRemarksPass.
439
440// Helper to check if the current compilation phase is preparing for LTO
445
446// Helper to check if the current compilation phase is preparing for FullLTO
447[[maybe_unused]] static bool isFullLTOPreLink(ThinOrFullLTOPhase Phase) {
449}
450
451// Helper to check if the current compilation phase is preparing for ThinLTO
455
456// Helper to check if the current compilation phase is LTO backend
461
462// Helper to check if the current compilation phase is FullLTO backend
466
467// Helper to check if the current compilation phase is ThinLTO backend
471
472// Helper to wrap conditionally Coro passes.
474 // TODO: Skip passes according to Phase.
475 ModulePassManager CoroPM;
476 CoroPM.addPass(CoroEarlyPass());
477 CGSCCPassManager CGPM;
478 CGPM.addPass(CoroSplitPass());
479 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
480 CoroPM.addPass(CoroCleanupPass());
481 CoroPM.addPass(GlobalDCEPass());
482 return CoroConditionalWrapper(std::move(CoroPM));
483}
484
485// TODO: Investigate the cost/benefit of tail call elimination on debugging.
487PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
489
491
493 FPM.addPass(CountVisitsPass());
494
495 // Form SSA out of local memory accesses after breaking apart aggregates into
496 // scalars.
497 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
498
499 // Catch trivial redundancies
500 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
501
502 // Hoisting of scalars and load expressions.
503 FPM.addPass(
504 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
505 FPM.addPass(InstCombinePass());
506
507 FPM.addPass(LibCallsShrinkWrapPass());
508
509 invokePeepholeEPCallbacks(FPM, Level);
510
511 FPM.addPass(
512 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
513
514 // Form canonically associated expression trees, and simplify the trees using
515 // basic mathematical properties. For example, this will form (nearly)
516 // minimal multiplication trees.
517 FPM.addPass(ReassociatePass());
518
519 // Add the primary loop simplification pipeline.
520 // FIXME: Currently this is split into two loop pass pipelines because we run
521 // some function passes in between them. These can and should be removed
522 // and/or replaced by scheduling the loop pass equivalents in the correct
523 // positions. But those equivalent passes aren't powerful enough yet.
524 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
525 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
526 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
527 // `LoopInstSimplify`.
528 LoopPassManager LPM1, LPM2;
529
530 // Simplify the loop body. We do this initially to clean up after other loop
531 // passes run, either when iterating on a loop or on inner loops with
532 // implications on the outer loop.
533 LPM1.addPass(LoopInstSimplifyPass());
534 LPM1.addPass(LoopSimplifyCFGPass());
535
536 // Try to remove as much code from the loop header as possible,
537 // to reduce amount of IR that will have to be duplicated. However,
538 // do not perform speculative hoisting the first time as LICM
539 // will destroy metadata that may not need to be destroyed if run
540 // after loop rotation.
541 // TODO: Investigate promotion cap for O1.
542 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
543 /*AllowSpeculation=*/false));
544
545 LPM1.addPass(
546 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
547 // TODO: Investigate promotion cap for O1.
548 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
549 /*AllowSpeculation=*/true));
550 LPM1.addPass(SimpleLoopUnswitchPass());
552 LPM1.addPass(LoopFlattenPass());
553
554 LPM2.addPass(LoopIdiomRecognizePass());
555 LPM2.addPass(IndVarSimplifyPass());
556
558
559 LPM2.addPass(LoopDeletionPass());
560
561 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
562 // because it changes IR to makes profile annotation in back compile
563 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
564 // attributes so we need to make sure and allow the full unroll pass to pay
565 // attention to it.
566 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
567 PGOOpt->Action != PGOOptions::SampleUse)
568 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
569 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
570 PTO.ForgetAllSCEVInLoopUnroll));
571
573
574 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
575 /*UseMemorySSA=*/true));
576 FPM.addPass(
577 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
578 FPM.addPass(InstCombinePass());
579 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
580 // *All* loop passes must preserve it, in order to be able to use it.
581 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
582 /*UseMemorySSA=*/false));
583
584 // Delete small array after loop unroll.
585 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
586
587 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
588 FPM.addPass(MemCpyOptPass());
589
590 // Sparse conditional constant propagation.
591 // FIXME: It isn't clear why we do this *after* loop passes rather than
592 // before...
593 FPM.addPass(SCCPPass());
594
595 // Delete dead bit computations (instcombine runs after to fold away the dead
596 // computations, and then ADCE will run later to exploit any new DCE
597 // opportunities that creates).
598 FPM.addPass(BDCEPass());
599
600 // Run instcombine after redundancy and dead bit elimination to exploit
601 // opportunities opened up by them.
602 FPM.addPass(InstCombinePass());
603 invokePeepholeEPCallbacks(FPM, Level);
604
605 FPM.addPass(CoroElidePass());
606
608
609 // Finally, do an expensive DCE pass to catch all the dead code exposed by
610 // the simplifications and basic cleanup after all the simplifications.
611 // TODO: Investigate if this is too expensive.
612 FPM.addPass(ADCEPass());
613 FPM.addPass(
614 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
615 FPM.addPass(InstCombinePass());
616 invokePeepholeEPCallbacks(FPM, Level);
617
618 return FPM;
619}
620
624 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
625
626 // The O1 pipeline has a separate pipeline creation function to simplify
627 // construction readability.
628 if (Level == OptimizationLevel::O1)
629 return buildO1FunctionSimplificationPipeline(Level, Phase);
630
632
635
636 // Form SSA out of local memory accesses after breaking apart aggregates into
637 // scalars.
639
640 // Catch trivial redundancies
641 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
644
645 // Hoisting of scalars and load expressions.
646 if (EnableGVNHoist)
647 FPM.addPass(GVNHoistPass());
648
649 // Global value numbering based sinking.
650 if (EnableGVNSink) {
651 FPM.addPass(GVNSinkPass());
652 FPM.addPass(
653 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
654 }
655
656 // Speculative execution if the target has divergent branches; otherwise nop.
657 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
658
659 // Optimize based on known information about branches, and cleanup afterward.
662
663 // Jump table to switch conversion.
666
667 FPM.addPass(
668 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
672
673 invokePeepholeEPCallbacks(FPM, Level);
674
675 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
676 // using the size value profile. Don't perform this when optimizing for size.
677 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse)
679
680 FPM.addPass(TailCallElimPass(/*UpdateFunctionEntryCount=*/
681 isInstrumentedPGOUse()));
682 FPM.addPass(
683 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
684
685 // Form canonically associated expression trees, and simplify the trees using
686 // basic mathematical properties. For example, this will form (nearly)
687 // minimal multiplication trees.
689
692
693 // Add the primary loop simplification pipeline.
694 // FIXME: Currently this is split into two loop pass pipelines because we run
695 // some function passes in between them. These can and should be removed
696 // and/or replaced by scheduling the loop pass equivalents in the correct
697 // positions. But those equivalent passes aren't powerful enough yet.
698 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
699 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
700 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
701 // `LoopInstSimplify`.
702 LoopPassManager LPM1, LPM2;
703
704 // Simplify the loop body. We do this initially to clean up after other loop
705 // passes run, either when iterating on a loop or on inner loops with
706 // implications on the outer loop.
707 LPM1.addPass(LoopInstSimplifyPass());
708 LPM1.addPass(LoopSimplifyCFGPass());
709
710 // Try to remove as much code from the loop header as possible,
711 // to reduce amount of IR that will have to be duplicated. However,
712 // do not perform speculative hoisting the first time as LICM
713 // will destroy metadata that may not need to be destroyed if run
714 // after loop rotation.
715 // TODO: Investigate promotion cap for O1.
716 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
717 /*AllowSpeculation=*/false));
718
719 LPM1.addPass(
720 LoopRotatePass(/*EnableHeaderDuplication=*/true, isLTOPreLink(Phase)));
721 // TODO: Investigate promotion cap for O1.
722 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
723 /*AllowSpeculation=*/true));
724 LPM1.addPass(
725 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
727 LPM1.addPass(LoopFlattenPass());
728
729 LPM2.addPass(LoopIdiomRecognizePass());
730 LPM2.addPass(IndVarSimplifyPass());
731
732 {
734 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
736 LPM2.addPass(std::move(ExtraPasses));
737 }
738
740
741 LPM2.addPass(LoopDeletionPass());
742
743 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
744 // because it changes IR to makes profile annotation in back compile
745 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
746 // attributes so we need to make sure and allow the full unroll pass to pay
747 // attention to it.
748 if (!isThinLTOPreLink(Phase) || !PGOOpt ||
749 PGOOpt->Action != PGOOptions::SampleUse)
750 LPM2.addPass(LoopFullUnrollPass(static_cast<int>(Level),
751 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
752 PTO.ForgetAllSCEVInLoopUnroll));
753
755
756 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
757 /*UseMemorySSA=*/true));
758 FPM.addPass(
759 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
761 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
762 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
763 // *All* loop passes must preserve it, in order to be able to use it.
764 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
765 /*UseMemorySSA=*/false));
766
767 // Delete small array after loop unroll.
769
770 // Try vectorization/scalarization transforms that are both improvements
771 // themselves and can allow further folds with GVN and InstCombine.
772 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
773
774 // Eliminate redundancies.
776 if (RunNewGVN)
777 FPM.addPass(NewGVNPass());
778 else
779 FPM.addPass(GVNPass());
780
781 // Sparse conditional constant propagation.
782 // FIXME: It isn't clear why we do this *after* loop passes rather than
783 // before...
784 FPM.addPass(SCCPPass());
785
786 // Delete dead bit computations (instcombine runs after to fold away the dead
787 // computations, and then ADCE will run later to exploit any new DCE
788 // opportunities that creates).
789 FPM.addPass(BDCEPass());
790
791 // Run instcombine after redundancy and dead bit elimination to exploit
792 // opportunities opened up by them.
794 invokePeepholeEPCallbacks(FPM, Level);
795
796 // Re-consider control flow based optimizations after redundancy elimination,
797 // redo DCE, etc.
800
803
804 // Finally, do an expensive DCE pass to catch all the dead code exposed by
805 // the simplifications and basic cleanup after all the simplifications.
806 // TODO: Investigate if this is too expensive.
807 FPM.addPass(ADCEPass());
808
809 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
810 FPM.addPass(MemCpyOptPass());
811
812 FPM.addPass(DSEPass());
814
816 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
817 /*AllowSpeculation=*/true),
818 /*UseMemorySSA=*/true));
819
820 FPM.addPass(CoroElidePass());
821
823
825 .convertSwitchRangeToICmp(true)
826 .convertSwitchToArithmetic(true)
827 .hoistCommonInsts(true)
828 .sinkCommonInsts(true)));
830 invokePeepholeEPCallbacks(FPM, Level);
831
832 return FPM;
833}
834
835void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
838 MPM.addPass(AssignGUIDPass());
839}
840
841void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
842 OptimizationLevel Level,
843 ThinOrFullLTOPhase LTOPhase) {
844 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
846 return;
847 InlineParams IP;
848
850
851 // FIXME: The hint threshold has the same value used by the regular inliner
852 // when not optimzing for size. This should probably be lowered after
853 // performance testing.
854 // FIXME: this comment is cargo culted from the old pass manager, revisit).
855 IP.HintThreshold = 325;
858 IP, /* MandatoryFirst */ true,
860 CGSCCPassManager &CGPipeline = MIWP.getPM();
861
863 FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
864 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
865 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
866 true))); // Merge & remove basic blocks.
867 FPM.addPass(InstCombinePass()); // Combine silly sequences.
868 invokePeepholeEPCallbacks(FPM, Level);
869
870 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
871 std::move(FPM), PTO.EagerlyInvalidateAnalyses));
872
873 MPM.addPass(std::move(MIWP));
874
875 // Delete anything that is now dead to make sure that we don't instrument
876 // dead code. Instrumentation can end up keeping dead code around and
877 // dramatically increase code size.
878 MPM.addPass(GlobalDCEPass());
879}
880
881void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
882 OptimizationLevel Level) {
884 // Disable header duplication in loop rotation at -Oz.
886 createFunctionToLoopPassAdaptor(LoopRotatePass(),
887 /*UseMemorySSA=*/false),
888 PTO.EagerlyInvalidateAnalyses));
889 }
890}
891
892void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
893 OptimizationLevel Level, bool RunProfileGen,
894 bool IsCS, bool AtomicCounterUpdate,
895 std::string ProfileFile,
896 std::string ProfileRemappingFile) {
897 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
898
899 if (!RunProfileGen) {
900 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
901 MPM.addPass(
902 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
903 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
904 // RequireAnalysisPass for PSI before subsequent non-module passes.
905 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
906 return;
907 }
908
909 // Perform PGO instrumentation.
910 MPM.addPass(PGOInstrumentationGen(IsCS ? PGOInstrumentationType::CSFDO
912
913 addPostPGOLoopRotation(MPM, Level);
914 // Add the profile lowering pass.
915 InstrProfOptions Options;
916 if (!ProfileFile.empty())
917 Options.InstrProfileOutput = ProfileFile;
918 // Do counter promotion at Level greater than O0.
919 Options.DoCounterPromotion = true;
920 Options.UseBFIInPromotion = IsCS;
921 if (EnableSampledInstr) {
922 Options.Sampling = true;
923 // With sampling, there is little beneifit to enable counter promotion.
924 // But note that sampling does work with counter promotion.
925 Options.DoCounterPromotion = false;
926 }
927 Options.Atomic = AtomicCounterUpdate;
928 MPM.addPass(InstrProfilingLoweringPass(Options, IsCS));
929}
930
932 bool RunProfileGen, bool IsCS,
933 bool AtomicCounterUpdate,
934 std::string ProfileFile,
935 std::string ProfileRemappingFile) {
936 if (!RunProfileGen) {
937 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
938 MPM.addPass(
939 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
940 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
941 // RequireAnalysisPass for PSI before subsequent non-module passes.
943 return;
944 }
945
946 // Perform PGO instrumentation.
949 // Add the profile lowering pass.
951 if (!ProfileFile.empty())
952 Options.InstrProfileOutput = ProfileFile;
953 // Do not do counter promotion at O0.
954 Options.DoCounterPromotion = false;
955 Options.UseBFIInPromotion = IsCS;
956 Options.Atomic = AtomicCounterUpdate;
958}
959
961 return getInlineParamsFromOptLevel(static_cast<unsigned>(Level));
962}
963
967 InlineParams IP;
968 if (PTO.InlinerThreshold == -1)
970 else
971 IP = getInlineParams(PTO.InlinerThreshold);
972 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
973 // set hot-caller threshold to 0 to disable hot
974 // callsite inline (as much as possible [1]) because it makes
975 // profile annotation in the backend inaccurate.
976 //
977 // [1] Note the cost of a function could be below zero due to erased
978 // prologue / epilogue.
979 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
981
982 if (PGOOpt)
984
988
989 // Require the GlobalsAA analysis for the module so we can query it within
990 // the CGSCC pipeline.
992 MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
993 // Invalidate AAManager so it can be recreated and pick up the newly
994 // available GlobalsAA.
995 MIWP.addModulePass(
997 }
998
999 // Require the ProfileSummaryAnalysis for the module so we can query it within
1000 // the inliner pass.
1002
1003 // Now begin the main postorder CGSCC pipeline.
1004 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
1005 // manager and trying to emulate its precise behavior. Much of this doesn't
1006 // make a lot of sense and we should revisit the core CGSCC structure.
1007 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
1008
1009 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1010 // generally clean up exception handling overhead. It isn't clear this is
1011 // valuable as the inliner doesn't currently care whether it is inlining an
1012 // invoke or a call.
1013
1015 MainCGPipeline.addPass(AttributorCGSCCPass());
1017 MainCGPipeline.addPass(AttributorLightCGSCCPass());
1018
1019 // Deduce function attributes. We do another run of this after the function
1020 // simplification pipeline, so this only needs to run when it could affect the
1021 // function simplification pipeline, which is only the case with recursive
1022 // functions.
1023 MainCGPipeline.addPass(PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
1024
1025 // When at O3 add argument promotion to the pass pipeline.
1026 // FIXME: It isn't at all clear why this should be limited to O3.
1027 if (Level == OptimizationLevel::O3)
1028 MainCGPipeline.addPass(ArgumentPromotionPass());
1029
1030 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
1031 // there are no OpenMP runtime calls present in the module.
1032 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
1033 MainCGPipeline.addPass(OpenMPOptCGSCCPass(Phase));
1034
1035 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
1036
1037 // Add the core function simplification pipeline nested inside the
1038 // CGSCC walk.
1041 PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
1042
1043 // Finally, deduce any function attributes based on the fully simplified
1044 // function.
1045 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
1046
1047 // Mark that the function is fully simplified and that it shouldn't be
1048 // simplified again if we somehow revisit it due to CGSCC mutations unless
1049 // it's been modified since.
1052
1053 if (!isThinLTOPreLink(Phase)) {
1054 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
1055 MainCGPipeline.addPass(CoroAnnotationElidePass());
1056 }
1057
1058 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
1059 MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
1061
1062 return MIWP;
1063}
1064
1069
1071 // For PreLinkThinLTO + SamplePGO or PreLinkFullLTO + SamplePGO,
1072 // set hot-caller threshold to 0 to disable hot
1073 // callsite inline (as much as possible [1]) because it makes
1074 // profile annotation in the backend inaccurate.
1075 //
1076 // [1] Note the cost of a function could be below zero due to erased
1077 // prologue / epilogue.
1078 if (isLTOPreLink(Phase) && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1079 IP.HotCallSiteThreshold = 0;
1080
1081 if (PGOOpt)
1083
1084 // The inline deferral logic is used to avoid losing some
1085 // inlining chance in future. It is helpful in SCC inliner, in which
1086 // inlining is processed in bottom-up order.
1087 // While in module inliner, the inlining order is a priority-based order
1088 // by default. The inline deferral is unnecessary there. So we disable the
1089 // inline deferral logic in module inliner.
1090 IP.EnableDeferral = false;
1091
1094 MPM.addPass(GlobalOptPass());
1095 MPM.addPass(GlobalDCEPass());
1096 MPM.addPass(AssignGUIDPass());
1097 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
1098 }
1099
1102 PTO.EagerlyInvalidateAnalyses));
1103
1104 if (!isThinLTOPreLink(Phase)) {
1107 MPM.addPass(
1109 }
1110
1111 return MPM;
1112}
1113
1117 assert(Level != OptimizationLevel::O0 &&
1118 "Should not be used for O0 pipeline");
1119
1121 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
1122
1124
1125 // Place pseudo probe instrumentation as the first pass of the pipeline to
1126 // minimize the impact of optimization changes.
1127 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && !isThinLTOPostLink(Phase))
1129
1130 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1131
1132 // In ThinLTO mode, when flattened profile is used, all the available
1133 // profile information will be annotated in PreLink phase so there is
1134 // no need to load the profile again in PostLink.
1135 bool LoadSampleProfile =
1136 HasSampleProfile && !(FlattenedProfileUsed && isThinLTOPostLink(Phase));
1137
1138 // During the ThinLTO backend phase we perform early indirect call promotion
1139 // here, before globalopt. Otherwise imported available_externally functions
1140 // look unreferenced and are removed. If we are going to load the sample
1141 // profile then defer until later.
1142 // TODO: See if we can move later and consolidate with the location where
1143 // we perform ICP when we are loading a sample profile.
1144 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1145 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1146 // determine whether the new direct calls are annotated with prof metadata.
1147 // Ideally this should be determined from whether the IR is annotated with
1148 // sample profile, and not whether the a sample profile was provided on the
1149 // command line. E.g. for flattened profiles where we will not be reloading
1150 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1151 // provide the sample profile file.
1152 if (isThinLTOPostLink(Phase) && !LoadSampleProfile)
1153 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1154
1155 // Create an early function pass manager to cleanup the output of the
1156 // frontend. Not necessary with LTO post link pipelines since the pre link
1157 // pipeline already cleaned up the frontend output.
1158 if (!isThinLTOPostLink(Phase)) {
1159 // Do basic inference of function attributes from known properties of system
1160 // libraries and other oracles.
1162 MPM.addPass(CoroEarlyPass());
1163
1164 FunctionPassManager EarlyFPM;
1165 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1166 // Lower llvm.expect to metadata before attempting transforms.
1167 // Compare/branch metadata may alter the behavior of passes like
1168 // SimplifyCFG.
1170 EarlyFPM.addPass(SimplifyCFGPass());
1172 EarlyFPM.addPass(EarlyCSEPass());
1173 if (Level == OptimizationLevel::O3)
1174 EarlyFPM.addPass(CallSiteSplittingPass());
1176 std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
1177 }
1178
1179 if (LoadSampleProfile) {
1180 // Annotate sample profile right after early FPM to ensure freshness of
1181 // the debug info.
1183 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile, Phase, FS));
1184 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1185 // RequireAnalysisPass for PSI before subsequent non-module passes.
1187 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1188 // for the profile annotation to be accurate in the LTO backend.
1189 if (!isLTOPreLink(Phase))
1190 // We perform early indirect call promotion here, before globalopt.
1191 // This is important for the ThinLTO backend phase because otherwise
1192 // imported available_externally functions look unreferenced and are
1193 // removed.
1194 MPM.addPass(
1195 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1196 }
1197
1198 // Try to perform OpenMP specific optimizations on the module. This is a
1199 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1201
1203 MPM.addPass(AttributorPass());
1206
1207 // Lower type metadata and the type.test intrinsic in the ThinLTO
1208 // post link pipeline after ICP. This is to enable usage of the type
1209 // tests in ICP sequences.
1212
1214
1215 // Interprocedural constant propagation now that basic cleanup has occurred
1216 // and prior to optimizing globals.
1217 // FIXME: This position in the pipeline hasn't been carefully considered in
1218 // years, it should be re-analyzed.
1219 MPM.addPass(
1220 IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/!isLTOPreLink(Phase))));
1221
1222 // Attach metadata to indirect call sites indicating the set of functions
1223 // they may target at run-time. This should follow IPSCCP.
1225
1226 // Optimize globals to try and fold them into constants.
1227 MPM.addPass(GlobalOptPass());
1228
1229 // Create a small function pass pipeline to cleanup after all the global
1230 // optimizations.
1231 FunctionPassManager GlobalCleanupPM;
1232 // FIXME: Should this instead by a run of SROA?
1233 GlobalCleanupPM.addPass(PromotePass());
1234 GlobalCleanupPM.addPass(InstCombinePass());
1235 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1236 GlobalCleanupPM.addPass(
1237 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1238 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
1239 PTO.EagerlyInvalidateAnalyses));
1240
1241 // We already asserted this happens in non-FullLTOPostLink earlier.
1242 const bool IsPreLink = !isThinLTOPostLink(Phase);
1243 // Enable contextual profiling instrumentation.
1244 const bool IsCtxProfGen =
1246 const bool IsPGOPreLink = !IsCtxProfGen && PGOOpt && IsPreLink;
1247 const bool IsPGOInstrGen =
1248 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1249 const bool IsPGOInstrUse =
1250 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1251 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1252 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1253 // enable ctx profiling from the frontend.
1255 "Enabling both instrumented PGO and contextual instrumentation is not "
1256 "supported.");
1257 const bool IsCtxProfUse = !UseCtxProfile.empty() && isThinLTOPreLink(Phase);
1258
1259 assert(
1261 "--instrument-cold-function-only-path is provided but "
1262 "--pgo-instrument-cold-function-only is not enabled");
1263 const bool IsColdFuncOnlyInstrGen = PGOInstrumentColdFunctionOnly &&
1264 IsPGOPreLink &&
1266
1267 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1268 IsCtxProfUse || IsColdFuncOnlyInstrGen)
1269 addPreInlinerPasses(MPM, Level, Phase);
1270
1271 // Add all the requested passes for instrumentation PGO, if requested.
1272 if (IsPGOInstrGen || IsPGOInstrUse) {
1273 addPGOInstrPasses(MPM, Level,
1274 /*RunProfileGen=*/IsPGOInstrGen,
1275 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1276 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1277 } else if (IsCtxProfGen || IsCtxProfUse) {
1279 // In pre-link, we just want the instrumented IR. We use the contextual
1280 // profile in the post-thinlink phase.
1281 // The instrumentation will be removed in post-thinlink after IPO.
1282 if (IsCtxProfUse) {
1283 MPM.addPass(AssignGUIDPass());
1284 MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
1285 return MPM;
1286 }
1287 // Block further inlining in the instrumented ctxprof case. This avoids
1288 // confusingly collecting profiles for the same GUID corresponding to
1289 // different variants of the function. We could do like PGO and identify
1290 // functions by a (GUID, Hash) tuple, but since the ctxprof "use" waits for
1291 // thinlto to happen before performing any further optimizations, it's
1292 // unnecessary to collect profiles for non-prevailing copies.
1294 addPostPGOLoopRotation(MPM, Level);
1295 MPM.addPass(AssignGUIDPass());
1297 } else if (IsColdFuncOnlyInstrGen) {
1298 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
1299 /* AtomicCounterUpdate */ false,
1301 /* ProfileRemappingFile */ "");
1302 }
1303
1304 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1305 MPM.addPass(PGOIndirectCallPromotion(false, false));
1306
1307 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1308 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile,
1310
1311 if (IsMemprofUse)
1312 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, FS));
1313
1314 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRUse ||
1315 PGOOpt->Action == PGOOptions::SampleUse))
1316 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1317
1318 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1319
1322 else
1323 MPM.addPass(buildInlinerPipeline(Level, Phase));
1324
1325 // Remove any dead arguments exposed by cleanups, constant folding globals,
1326 // and argument promotion.
1328
1331
1332 if (!isThinLTOPreLink(Phase))
1333 MPM.addPass(CoroCleanupPass());
1334
1335 // Optimize globals now that functions are fully simplified.
1336 MPM.addPass(GlobalOptPass());
1337 MPM.addPass(GlobalDCEPass());
1338
1339 return MPM;
1340}
1341
1342/// TODO: Should LTO cause any differences to this set of passes?
1343void PassBuilder::addVectorPasses(OptimizationLevel Level,
1345 ThinOrFullLTOPhase LTOPhase) {
1348
1349 // Drop dereferenceable assumes after vectorization, as they are no longer
1350 // needed and can inhibit further optimization.
1351 if (!isLTOPreLink(LTOPhase))
1352 FPM.addPass(DropUnnecessaryAssumesPass(/*DropDereferenceable=*/true));
1353
1355 if (isFullLTOPostLink(LTOPhase)) {
1356 // The vectorizer may have significantly shortened a loop body; unroll
1357 // again. Unroll small loops to hide loop backedge latency and saturate any
1358 // parallel execution resources of an out-of-order processor. We also then
1359 // need to clean up redundancies and loop invariant code.
1360 // FIXME: It would be really good to use a loop-integrated instruction
1361 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1362 // across the loop nests.
1363 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1366 LoopUnrollAndJamPass(static_cast<int>(Level))));
1368 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1371 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1372 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1373 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1374 // NOTE: we are very late in the pipeline, and we don't have any LICM
1375 // or SimplifyCFG passes scheduled after us, that would cleanup
1376 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1377
1378 // We also turn on struct to vector canonicalization here, which allows
1379 // converting allocas of homogeneous structs into vector allocas when the
1380 // allocas' users are all memory intrinsics. This allows promotion in some
1381 // cases because structs cannot promote to SSA values, but vectors can. We
1382 // only turn this on after memcpyopt runs because this might hinder
1383 // memcpyopt's optimizations if done before. Look at the documentation for
1384 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1386 /*AggregateToVector=*/true)));
1387 }
1388
1389 if (!isFullLTOPostLink(LTOPhase)) {
1390 // Eliminate loads by forwarding stores from the previous iteration to loads
1391 // of the current iteration.
1393 }
1394 // Cleanup after the loop optimization passes.
1395 FPM.addPass(InstCombinePass());
1396
1398 ExtraFunctionPassManager<ShouldRunExtraVectorPasses> ExtraPasses;
1399 // At higher optimization levels, try to clean up any runtime overlap and
1400 // alignment checks inserted by the vectorizer. We want to track correlated
1401 // runtime checks for two inner loops in the same outer loop, fold any
1402 // common computations, hoist loop-invariant aspects out of any outer loop,
1403 // and unswitch the runtime checks if possible. Once hoisted, we may have
1404 // dead (or speculatable) control flows or more combining opportunities.
1405 ExtraPasses.addPass(EarlyCSEPass());
1406 ExtraPasses.addPass(CorrelatedValuePropagationPass());
1407 ExtraPasses.addPass(InstCombinePass());
1408 LoopPassManager LPM;
1409 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1410 /*AllowSpeculation=*/true));
1411 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1413 ExtraPasses.addPass(
1414 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true));
1415 ExtraPasses.addPass(
1416 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1417 ExtraPasses.addPass(InstCombinePass());
1418 FPM.addPass(std::move(ExtraPasses));
1419 }
1420
1421 // Now that we've formed fast to execute loop structures, we do further
1422 // optimizations. These are run afterward as they might block doing complex
1423 // analyses and transforms such as what are needed for loop vectorization.
1424
1425 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1426 // GVN, loop transforms, and others have already run, so it's now better to
1427 // convert to more optimized IR using more aggressive simplify CFG options.
1428 // The extra sinking transform can create larger basic blocks, so do this
1429 // before SLP vectorization.
1430 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1431 .forwardSwitchCondToPhi(true)
1432 .convertSwitchRangeToICmp(true)
1433 .convertSwitchToArithmetic(true)
1434 .convertSwitchToLookupTable(true)
1435 .needCanonicalLoops(false)
1436 .hoistCommonInsts(true)
1437 .sinkCommonInsts(true)));
1438
1439 if (isFullLTOPostLink(LTOPhase)) {
1440 FPM.addPass(SCCPPass());
1441 FPM.addPass(InstCombinePass());
1442 FPM.addPass(BDCEPass());
1443 }
1444
1445 // Optimize parallel scalar instruction chains into SIMD instructions.
1446 if (PTO.SLPVectorization) {
1447 FPM.addPass(SLPVectorizerPass());
1449 FPM.addPass(EarlyCSEPass());
1450 }
1451 }
1452 // Enhance/cleanup vector code.
1453 FPM.addPass(VectorCombinePass());
1454
1455 if (!isFullLTOPostLink(LTOPhase)) {
1456 FPM.addPass(InstCombinePass());
1457 // Unroll small loops to hide loop backedge latency and saturate any
1458 // parallel execution resources of an out-of-order processor. We also then
1459 // need to clean up redundancies and loop invariant code.
1460 // FIXME: It would be really good to use a loop-integrated instruction
1461 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1462 // across the loop nests.
1463 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1464 if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1466 LoopUnrollAndJamPass(static_cast<int>(Level))));
1467 }
1468 FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1469 static_cast<int>(Level), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1470 PTO.ForgetAllSCEVInLoopUnroll)));
1471 FPM.addPass(WarnMissedTransformationsPass());
1472 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1473 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1474 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1475 // NOTE: we are very late in the pipeline, and we don't have any LICM
1476 // or SimplifyCFG passes scheduled after us, that would cleanup
1477 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1478
1479 // We also turn on struct to vector canonicalization here, which allows
1480 // converting allocas of homogeneous structs into vector allocas when the
1481 // allocas' users are all memory intrinsics. This allows promotion in some
1482 // cases because structs cannot promote to SSA values, but vectors can. We
1483 // only turn this on after memcpyopt runs because this might hinder
1484 // memcpyopt's optimizations if done before. Look at the documentation for
1485 // `tryCanonicalizeStructToVector` in SROA.cpp to see why.
1486 FPM.addPass(SROAPass(SROAOptions(SROAOptions::PreserveCFG,
1487 /*AggregateToVector=*/true)));
1488 }
1489
1490 FPM.addPass(InferAlignmentPass());
1491 FPM.addPass(InstCombinePass());
1492
1493 // This is needed for two reasons:
1494 // 1. It works around problems that instcombine introduces, such as sinking
1495 // expensive FP divides into loops containing multiplications using the
1496 // divide result.
1497 // 2. It helps to clean up some loop-invariant code created by the loop
1498 // unroll pass when IsFullLTO=false.
1500 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1501 /*AllowSpeculation=*/true),
1502 /*UseMemorySSA=*/true));
1503
1504 // Now that we've vectorized and unrolled loops, we may have more refined
1505 // alignment information, try to re-derive it here.
1506 FPM.addPass(AlignmentFromAssumptionsPass());
1507}
1508
1511 ThinOrFullLTOPhase LTOPhase) {
1513
1514 // Run partial inlining pass to partially inline functions that have
1515 // large bodies.
1518
1519 // Remove avail extern fns and globals definitions since we aren't compiling
1520 // an object file for later LTO. For LTO we want to preserve these so they
1521 // are eligible for inlining at link-time. Note if they are unreferenced they
1522 // will be removed by GlobalDCE later, so this only impacts referenced
1523 // available externally globals. Eventually they will be suppressed during
1524 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1525 // may make globals referenced by available external functions dead and saves
1526 // running remaining passes on the eliminated functions. These should be
1527 // preserved during prelinking for link-time inlining decisions.
1528 if (!isLTOPreLink(LTOPhase))
1530
1531 // Do RPO function attribute inference across the module to forward-propagate
1532 // attributes where applicable.
1533 // FIXME: Is this really an optimization rather than a canonicalization?
1535
1536 // Do a post inline PGO instrumentation and use pass. This is a context
1537 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1538 // cross-module inline has not been done yet. The context sensitive
1539 // instrumentation is after all the inlines are done.
1540 if (!isLTOPreLink(LTOPhase) && PGOOpt) {
1541 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1542 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1543 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1544 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
1545 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1546 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1547 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1548 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1549 }
1550
1551 // Re-compute GlobalsAA here prior to function passes. This is particularly
1552 // useful as the above will have inlined, DCE'ed, and function-attr
1553 // propagated everything. We should at this point have a reasonably minimal
1554 // and richly annotated call graph. By computing aliasing and mod/ref
1555 // information for all local globals here, the late loop passes and notably
1556 // the vectorizer will be able to use them to help recognize vectorizable
1557 // memory operations.
1560
1561 invokeOptimizerEarlyEPCallbacks(MPM, Level, LTOPhase);
1562
1563 FunctionPassManager OptimizePM;
1564
1565 // Only drop unnecessary assumes post-inline and post-link, as otherwise
1566 // additional uses of the affected value may be introduced through inlining
1567 // and CSE.
1568 if (!isLTOPreLink(LTOPhase))
1569 OptimizePM.addPass(DropUnnecessaryAssumesPass());
1570
1571 // Scheduling LoopVersioningLICM when inlining is over, because after that
1572 // we may see more accurate aliasing. Reason to run this late is that too
1573 // early versioning may prevent further inlining due to increase of code
1574 // size. Other optimizations which runs later might get benefit of no-alias
1575 // assumption in clone loop.
1577 OptimizePM.addPass(
1579 // LoopVersioningLICM pass might increase new LICM opportunities.
1581 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1582 /*AllowSpeculation=*/true),
1583 /*USeMemorySSA=*/true));
1584 }
1585
1586 OptimizePM.addPass(Float2IntPass());
1588
1589 if (EnableMatrix) {
1590 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1591 OptimizePM.addPass(EarlyCSEPass());
1592 }
1593
1594 // CHR pass should only be applied with the profile information.
1595 // The check is to check the profile summary information in CHR.
1596 if (EnableCHR && Level == OptimizationLevel::O3)
1597 OptimizePM.addPass(ControlHeightReductionPass());
1598
1599 // FIXME: We need to run some loop optimizations to re-rotate loops after
1600 // simplifycfg and others undo their rotation.
1601
1602 // Optimize the loop execution. These passes operate on entire loop nests
1603 // rather than on each loop in an inside-out manner, and so they are actually
1604 // function passes.
1605
1606 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1607
1608 LoopPassManager LPM;
1609 // First rotate loops that may have been un-rotated by prior passes.
1610 // Disable header duplication at -Oz.
1611 LPM.addPass(LoopRotatePass(/*EnableLoopHeaderDuplication=*/true,
1612 isLTOPreLink(LTOPhase),
1613 /*CheckExitCount=*/true));
1614 // Some loops may have become dead by now. Try to delete them.
1615 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1616 // this may need to be revisited once we run GVN before loop deletion
1617 // in the simplification pipeline.
1618 LPM.addPass(LoopDeletionPass());
1619
1620 if (PTO.LoopInterchange)
1621 LPM.addPass(LoopInterchangePass());
1622
1623 OptimizePM.addPass(
1624 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
1625
1626 // FIXME: This may not be the right place in the pipeline.
1627 // We need to have the data to support the right place.
1628 if (PTO.LoopFusion)
1629 OptimizePM.addPass(LoopFusePass());
1630
1631 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1632 // into separate loop that would otherwise inhibit vectorization. This is
1633 // currently only performed for loops marked with the metadata
1634 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1635 OptimizePM.addPass(LoopDistributePass());
1636
1637 // Populates the VFABI attribute with the scalar-to-vector mappings
1638 // from the TargetLibraryInfo.
1639 OptimizePM.addPass(InjectTLIMappings());
1640
1641 addVectorPasses(Level, OptimizePM, LTOPhase);
1642
1643 invokeVectorizerEndEPCallbacks(OptimizePM, Level);
1644
1645 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1646 // canonicalization pass that enables other optimizations. As a result,
1647 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1648 // result too early.
1649 OptimizePM.addPass(LoopSinkPass());
1650
1651 // And finally clean up LCSSA form before generating code.
1652 OptimizePM.addPass(InstSimplifyPass());
1653
1654 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1655 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1656 // flattening of blocks.
1657 OptimizePM.addPass(DivRemPairsPass());
1658
1659 // Merge adjacent icmps into memcmp, then expand memcmp to loads/compares.
1660 // TODO: move this furter up so that it can be optimized by GVN, etc.
1661 if (EnableMergeICmps)
1662 OptimizePM.addPass(MergeICmpsPass());
1663 OptimizePM.addPass(ExpandMemCmpPass());
1664
1665 // Try to annotate calls that were created during optimization.
1666 OptimizePM.addPass(
1667 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
1668
1669 // LoopSink (and other loop passes since the last simplifyCFG) might have
1670 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1671 OptimizePM.addPass(
1673 .convertSwitchRangeToICmp(true)
1674 .convertSwitchToArithmetic(true)
1675 .speculateUnpredictables(true)
1676 .hoistLoadsStoresWithCondFaulting(true)));
1677
1678 // Add the core optimizing pipeline.
1679 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1680 PTO.EagerlyInvalidateAnalyses));
1681
1682 // AllocToken transforms heap allocation calls; this needs to run late after
1683 // other allocation call transformations (such as those in InstCombine).
1684 if (!isLTOPreLink(LTOPhase))
1685 MPM.addPass(AllocTokenPass());
1686
1687 invokeOptimizerLastEPCallbacks(MPM, Level, LTOPhase);
1688
1689 // Run the Instrumentor pass late.
1691 MPM.addPass(InstrumentorPass(FS));
1692
1693 // Split out cold code. Splitting is done late to avoid hiding context from
1694 // other optimizations and inadvertently regressing performance. The tradeoff
1695 // is that this has a higher code size cost than splitting early.
1696 if (EnableHotColdSplit && !isLTOPreLink(LTOPhase))
1698
1699 // Now we need to do some global optimization transforms.
1700 // FIXME: It would seem like these should come first in the optimization
1701 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1702 // ordering here.
1703 MPM.addPass(GlobalDCEPass());
1705
1706 // Merge functions if requested. It has a better chance to merge functions
1707 // after ConstantMerge folded jump tables.
1708 if (PTO.MergeFunctions)
1710
1711 if (PTO.CallGraphProfile && !isLTOPreLink(LTOPhase))
1712 MPM.addPass(CGProfilePass(isLTOPostLink(LTOPhase)));
1713
1714 // RelLookupTableConverterPass runs later in LTO post-link pipeline.
1715 if (!isLTOPreLink(LTOPhase))
1717
1718 // Add devirtualization pass only when LTO is not enabled, as otherwise
1719 // the pass is already enabled in the LTO pipeline.
1720 if (PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
1721 // TODO: explore a better pipeline configuration that can improve
1722 // compilation time overhead.
1723 // FIXME: move this earlier (lots of pass ordering tests will need fixing)
1724 MPM.addPass(AssignGUIDPass());
1726 /*ExportSummary*/ nullptr,
1727 /*ImportSummary*/ nullptr,
1728 /*DevirtSpeculatively*/ PTO.DevirtualizeSpeculatively));
1730 // Given that the devirtualization creates more opportunities for inlining,
1731 // we run the Inliner again here to maximize the optimization gain we
1732 // get from devirtualization.
1733 // Also, we can't run devirtualization before inlining because the
1734 // devirtualization depends on the passes optimizing/eliminating vtable GVs
1735 // and those passes are only effective after inlining.
1736 if (EnableModuleInliner) {
1740 } else {
1743 /* MandatoryFirst */ true,
1745 }
1746 }
1747
1748 // Attach !implicit.ref metadata from all functions to copyright strings.
1750
1751 return MPM;
1752}
1753
1757 if (Level == OptimizationLevel::O0)
1758 return buildO0DefaultPipeline(Level, Phase);
1759
1761 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1762 // Currently this pipeline is only invoked in an LTO pre link pass or when we
1763 // are not running LTO. If that changes the below checks may need updating.
1765
1766 // If we are invoking this in non-LTO mode, remove any MemProf related
1767 // attributes and metadata, as we don't know whether we are linking with
1768 // a library containing the necessary interfaces.
1771
1772 // Convert @llvm.global.annotations to !annotation metadata.
1774
1775 // Force any function attributes we want the rest of the pipeline to observe.
1777
1778 if (TriggerCrash)
1780
1781 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1783
1784 // Apply module pipeline start EP callback.
1786
1787 // Add the core simplification pipeline.
1789
1790 // Now add the optimization pipeline.
1792
1793 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1794 PGOOpt->Action == PGOOptions::SampleUse)
1796
1797 // Emit annotation remarks.
1799
1800 if (isLTOPreLink(Phase))
1801 addRequiredLTOPreLinkPasses(MPM);
1802
1803 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1804 return MPM;
1805}
1806
1809 bool EmitSummary, bool Verify) {
1811
1812 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1813
1814 if (ThinLTO)
1816 else
1818 // AssignGUIDPass attaches !guid metadata (MD_unique_id) to global objects,
1819 // triggering the bitcode writer to emit a METADATA_KIND_BLOCK. Standard LTO
1820 // bitcode emission runs VerifierPass by default, which registers metadata
1821 // kind IDs in LLVMContext. Running VerifierPass here before EmbedBitcodePass
1822 // to get the same behavior.
1823 if (Verify)
1824 MPM.addPass(VerifierPass());
1825 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1826
1827 // Perform any cleanups to the IR that aren't suitable for per TU compilation,
1828 // like removing CFI/WPD related instructions. Note, we reuse
1829 // DropTypeTestsPass to clean up type tests rather than duplicate that logic
1830 // in FatLtoCleanup.
1831 MPM.addPass(FatLtoCleanup());
1832
1833 // If we're doing FatLTO w/ CFI enabled, we don't want the type tests in the
1834 // object code, only in the bitcode section, so drop it before we run
1835 // module optimization and generate machine code. If llvm.type.test() isn't in
1836 // the IR, this won't do anything.
1838
1839 // Use the ThinLTO post-link pipeline with sample profiling
1840 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1841 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1842 else {
1843 // ModuleSimplification does not run the coroutine passes for
1844 // ThinLTOPreLink, so we need the coroutine passes to run for ThinLTO
1845 // builds, otherwise they will miscompile.
1846 if (ThinLTO) {
1847 // TODO: replace w/ buildCoroWrapper() when it takes phase and level into
1848 // consideration.
1849 CGSCCPassManager CGPM;
1853 MPM.addPass(CoroCleanupPass());
1854 }
1855
1856 // otherwise, just use module optimization
1857 MPM.addPass(
1859 // Emit annotation remarks.
1861 }
1862
1863 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1864
1865 return MPM;
1866}
1867
1870 if (Level == OptimizationLevel::O0)
1872
1874
1875 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1876
1877 // Convert @llvm.global.annotations to !annotation metadata.
1879
1880 // Force any function attributes we want the rest of the pipeline to observe.
1882
1883 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1885
1886 // Apply module pipeline start EP callback.
1888
1889 // If we are planning to perform ThinLTO later, we don't bloat the code with
1890 // unrolling/vectorization/... now. Just simplify the module as much as we
1891 // can.
1894 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1895 // thinlto use the contextual info to perform imports; then use the contextual
1896 // profile in the post-thinlink phase.
1897 if (!UseCtxProfile.empty()) {
1898 addRequiredLTOPreLinkPasses(MPM);
1899 return MPM;
1900 }
1901
1902 // Run partial inlining pass to partially inline functions that have
1903 // large bodies.
1904 // FIXME: It isn't clear whether this is really the right place to run this
1905 // in ThinLTO. Because there is another canonicalization and simplification
1906 // phase that will run after the thin link, running this here ends up with
1907 // less information than will be available later and it may grow functions in
1908 // ways that aren't beneficial.
1911
1912 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1913 PGOOpt->Action == PGOOptions::SampleUse)
1915
1916 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1917 // optimization is going to be done in PostLink stage, but clang can't add
1918 // callbacks there in case of in-process ThinLTO called by linker.
1923
1924 // Emit annotation remarks.
1926
1927 // Attach !implicit.ref metadata from all functions to copyright strings.
1929
1930 addRequiredLTOPreLinkPasses(MPM);
1931
1932 instructionCountersPass(MPM, /* IsPreOptimization */ false);
1933
1934 return MPM;
1935}
1936
1938 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1940
1941 instructionCountersPass(MPM, /* IsPreOptimization */ true);
1942
1943 // If we are invoking this without a summary index noting that we are linking
1944 // with a library containing the necessary APIs, remove any MemProf related
1945 // attributes and metadata.
1946 if (!ImportSummary || !ImportSummary->withSupportsHotColdNew())
1948
1949 if (ImportSummary) {
1950 // For ThinLTO we must apply the context disambiguation decisions early, to
1951 // ensure we can correctly match the callsites to summary data.
1954 ImportSummary, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1955
1956 // These passes import type identifier resolutions for whole-program
1957 // devirtualization and CFI. They must run early because other passes may
1958 // disturb the specific instruction patterns that these passes look for,
1959 // creating dependencies on resolutions that may not appear in the summary.
1960 //
1961 // For example, GVN may transform the pattern assume(type.test) appearing in
1962 // two basic blocks into assume(phi(type.test, type.test)), which would
1963 // transform a dependency on a WPD resolution into a dependency on a type
1964 // identifier resolution for CFI.
1965 //
1966 // Also, WPD has access to more precise information than ICP and can
1967 // devirtualize more effectively, so it should operate on the IR first.
1968 //
1969 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1970 // metadata and intrinsics.
1971 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1972 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1973 }
1974
1975 if (Level == OptimizationLevel::O0) {
1976 // Run a second time to clean up any type tests left behind by WPD for use
1977 // in ICP.
1980
1981 // AllocToken transforms heap allocation calls; this needs to run late after
1982 // other allocation call transformations (such as those in InstCombine).
1983 MPM.addPass(AllocTokenPass());
1984
1985 // Drop available_externally and unreferenced globals. This is necessary
1986 // with ThinLTO in order to avoid leaving undefined references to dead
1987 // globals in the object file.
1989 MPM.addPass(GlobalDCEPass());
1990 return MPM;
1991 }
1992 if (!UseCtxProfile.empty()) {
1993 MPM.addPass(
1995 } else {
1996 // Add the core simplification pipeline.
1999 }
2000 // Now add the optimization pipeline.
2003
2004 // Emit annotation remarks.
2006
2007 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2008
2009 return MPM;
2010}
2011
2014 // FIXME: We should use a customized pre-link pipeline!
2015 return buildPerModuleDefaultPipeline(Level,
2017}
2018
2021 ModuleSummaryIndex *ExportSummary) {
2023
2024 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2025
2027
2028 // If we are invoking this without a summary index noting that we are linking
2029 // with a library containing the necessary APIs, remove any MemProf related
2030 // attributes and metadata.
2031 if (!ExportSummary || !ExportSummary->withSupportsHotColdNew())
2033
2034 // Create a function that performs CFI checks for cross-DSO calls with targets
2035 // in the current module.
2036 MPM.addPass(CrossDSOCFIPass());
2037
2038 if (Level == OptimizationLevel::O0) {
2039 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
2040 // metadata and intrinsics.
2041 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2042 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2043 // Run a second time to clean up any type tests left behind by WPD for use
2044 // in ICP.
2046
2048
2049 // AllocToken transforms heap allocation calls; this needs to run late after
2050 // other allocation call transformations (such as those in InstCombine).
2051 MPM.addPass(AllocTokenPass());
2052
2054
2055 // Emit annotation remarks.
2057
2058 return MPM;
2059 }
2060
2061 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2062 // Load sample profile before running the LTO optimization pipeline.
2063 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2064 PGOOpt->ProfileRemappingFile,
2066 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2067 // RequireAnalysisPass for PSI before subsequent non-module passes.
2069 }
2070
2071 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
2073
2074 // Remove unused virtual tables to improve the quality of code generated by
2075 // whole-program devirtualization and bitset lowering.
2076 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2077
2078 // Do basic inference of function attributes from known properties of system
2079 // libraries and other oracles.
2081
2082 if (Level >= OptimizationLevel::O2) {
2084 CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
2085
2086 // Indirect call promotion. This should promote all the targets that are
2087 // left by the earlier promotion pass that promotes intra-module targets.
2088 // This two-step promotion is to save the compile time. For LTO, it should
2089 // produce the same result as if we only do promotion here.
2091 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2092
2093 // Promoting by-reference arguments to by-value exposes more constants to
2094 // IPSCCP.
2095 CGSCCPassManager CGPM;
2098 CGPM.addPass(
2101
2102 // Propagate constants at call sites into the functions they call. This
2103 // opens opportunities for globalopt (and inlining) by substituting function
2104 // pointers passed as arguments to direct uses of functions.
2105 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/true)));
2106
2107 // Attach metadata to indirect call sites indicating the set of functions
2108 // they may target at run-time. This should follow IPSCCP.
2110 }
2111
2112 // Do RPO function attribute inference across the module to forward-propagate
2113 // attributes where applicable.
2114 // FIXME: Is this really an optimization rather than a canonicalization?
2116
2117 // Use in-range annotations on GEP indices to split globals where beneficial.
2118 MPM.addPass(GlobalSplitPass());
2119
2120 // Run whole program optimization of virtual call when the list of callees
2121 // is fixed.
2122 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
2123
2125 // Stop here at -O1.
2126 if (Level == OptimizationLevel::O1) {
2127 // The LowerTypeTestsPass needs to run to lower type metadata and the
2128 // type.test intrinsics. The pass does nothing if CFI is disabled.
2129 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2130 // Run a second time to clean up any type tests left behind by WPD for use
2131 // in ICP (which is performed earlier than this in the regular LTO
2132 // pipeline).
2134
2136
2137 // AllocToken transforms heap allocation calls; this needs to run late after
2138 // other allocation call transformations (such as those in InstCombine).
2139 MPM.addPass(AllocTokenPass());
2140
2142
2143 // Emit annotation remarks.
2145
2146 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2147
2148 return MPM;
2149 }
2150
2151 // TODO: Skip to match buildCoroWrapper.
2152 MPM.addPass(CoroEarlyPass());
2153
2154 // Optimize globals to try and fold them into constants.
2155 MPM.addPass(GlobalOptPass());
2156
2157 // Promote any localized globals to SSA registers.
2159
2160 // Linking modules together can lead to duplicate global constant, only
2161 // keep one copy of each constant.
2163
2164 // Remove unused arguments from functions.
2166
2167 // Reduce the code after globalopt and ipsccp. Both can open up significant
2168 // simplification opportunities, and both can propagate functions through
2169 // function pointers. When this happens, we often have to resolve varargs
2170 // calls, etc, so let instcombine do this.
2171 FunctionPassManager PeepholeFPM;
2172 PeepholeFPM.addPass(InstCombinePass());
2173 if (Level >= OptimizationLevel::O2)
2174 PeepholeFPM.addPass(AggressiveInstCombinePass());
2175 invokePeepholeEPCallbacks(PeepholeFPM, Level);
2176
2177 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
2178 PTO.EagerlyInvalidateAnalyses));
2179
2180 // Lower variadic functions for supported targets prior to inlining.
2182
2183 // Note: historically, the PruneEH pass was run first to deduce nounwind and
2184 // generally clean up exception handling overhead. It isn't clear this is
2185 // valuable as the inliner doesn't currently care whether it is inlining an
2186 // invoke or a call.
2187 // Run the inliner now.
2188 if (EnableModuleInliner) {
2192 } else {
2195 /* MandatoryFirst */ true,
2198 }
2199
2200 // Perform context disambiguation after inlining, since that would reduce the
2201 // amount of additional cloning required to distinguish the allocation
2202 // contexts.
2205 /*Summary=*/nullptr,
2206 PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
2207
2208 // Optimize globals again after we ran the inliner.
2209 MPM.addPass(GlobalOptPass());
2210
2211 // Run the OpenMPOpt pass again after global optimizations.
2213
2214 // Garbage collect dead functions.
2215 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2216
2217 // If we didn't decide to inline a function, check to see if we can
2218 // transform it to pass arguments by value instead of by reference.
2219 CGSCCPassManager CGPM;
2225
2227 // The IPO Passes may leave cruft around. Clean up after them.
2228 FPM.addPass(InstCombinePass());
2229 invokePeepholeEPCallbacks(FPM, Level);
2230
2233
2235
2236 // Do a post inline PGO instrumentation and use pass. This is a context
2237 // sensitive PGO pass.
2238 if (PGOOpt) {
2239 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
2240 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
2241 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2242 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile);
2243 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
2244 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
2245 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
2246 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
2247 }
2248
2249 // Break up allocas
2251
2252 // LTO provides additional opportunities for tailcall elimination due to
2253 // link-time inlining, and visibility of nocapture attribute.
2254 FPM.addPass(
2255 TailCallElimPass(/*UpdateFunctionEntryCount=*/isInstrumentedPGOUse()));
2256
2257 // Run a few AA driver optimizations here and now to cleanup the code.
2258 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
2259 PTO.EagerlyInvalidateAnalyses));
2260
2261 MPM.addPass(
2263
2264 // Require the GlobalsAA analysis for the module so we can query it within
2265 // MainFPM.
2268 // Invalidate AAManager so it can be recreated and pick up the newly
2269 // available GlobalsAA.
2270 MPM.addPass(
2272 }
2273
2274 FunctionPassManager MainFPM;
2276 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
2277 /*AllowSpeculation=*/true),
2278 /*USeMemorySSA=*/true));
2279
2280 if (RunNewGVN)
2281 MainFPM.addPass(NewGVNPass());
2282 else
2283 MainFPM.addPass(GVNPass());
2284
2285 // Remove dead memcpy()'s.
2286 MainFPM.addPass(MemCpyOptPass());
2287
2288 // Nuke dead stores.
2289 MainFPM.addPass(DSEPass());
2290 MainFPM.addPass(MoveAutoInitPass());
2292
2293 invokeVectorizerStartEPCallbacks(MainFPM, Level);
2294
2295 LoopPassManager LPM;
2297 LPM.addPass(LoopFlattenPass());
2298 LPM.addPass(IndVarSimplifyPass());
2299 LPM.addPass(LoopDeletionPass());
2300 // FIXME: Add loop interchange.
2301
2302 // Unroll small loops and perform peeling.
2303 LPM.addPass(LoopFullUnrollPass(static_cast<int>(Level),
2304 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
2305 PTO.ForgetAllSCEVInLoopUnroll));
2306 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2307 // *All* loop passes must preserve it, in order to be able to use it.
2308 MainFPM.addPass(
2309 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/false));
2310
2311 MainFPM.addPass(LoopDistributePass());
2312
2313 addVectorPasses(Level, MainFPM, ThinOrFullLTOPhase::FullLTOPostLink);
2314
2315 invokeVectorizerEndEPCallbacks(MainFPM, Level);
2316
2317 // Run the OpenMPOpt CGSCC pass again late.
2320
2321 invokePeepholeEPCallbacks(MainFPM, Level);
2322 MainFPM.addPass(JumpThreadingPass());
2323 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
2324 PTO.EagerlyInvalidateAnalyses));
2325
2326 // Lower type metadata and the type.test intrinsic. This pass supports
2327 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2328 // to be run at link time if CFI is enabled. This pass does nothing if
2329 // CFI is disabled.
2330 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2331 // Run a second time to clean up any type tests left behind by WPD for use
2332 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2334
2335 // Enable splitting late in the FullLTO post-link pipeline.
2338
2339 // Add late LTO optimization passes.
2340 FunctionPassManager LateFPM;
2341
2342 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2343 // canonicalization pass that enables other optimizations. As a result,
2344 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2345 // result too early.
2346 LateFPM.addPass(LoopSinkPass());
2347
2348 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2349 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2350 // flattening of blocks.
2351 LateFPM.addPass(DivRemPairsPass());
2352
2353 // Delete basic blocks, which optimization passes may have killed.
2355 .convertSwitchRangeToICmp(true)
2356 .convertSwitchToArithmetic(true)
2357 .hoistCommonInsts(true)
2358 .speculateUnpredictables(true)));
2359 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2360
2361 // Drop bodies of available eternally objects to improve GlobalDCE.
2363
2364 // Now that we have optimized the program, discard unreachable functions.
2365 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2366
2367 if (PTO.MergeFunctions)
2369
2371
2372 if (PTO.CallGraphProfile)
2373 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2374
2375 MPM.addPass(CoroCleanupPass());
2376
2377 // AllocToken transforms heap allocation calls; this needs to run late after
2378 // other allocation call transformations (such as those in InstCombine).
2379 MPM.addPass(AllocTokenPass());
2380
2382
2383 // Emit annotation remarks.
2385
2386 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2387
2388 return MPM;
2389}
2390
2394 assert(Level == OptimizationLevel::O0 &&
2395 "buildO0DefaultPipeline should only be used with O0");
2396
2398
2399 instructionCountersPass(MPM, /* IsPreOptimization */ true);
2400
2401 // Perform pseudo probe instrumentation in O0 mode. This is for the
2402 // consistency between different build modes. For example, a LTO build can be
2403 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2404 // the postlink will require pseudo probe instrumentation in the prelink.
2405 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2407
2408 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2409 PGOOpt->Action == PGOOptions::IRUse))
2411 MPM,
2412 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2413 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2414 PGOOpt->ProfileRemappingFile);
2415
2416 // Instrument function entry and exit before all inlining.
2418 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2419
2421
2422 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2424
2425 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
2426 // Explicitly disable sample loader inlining and use flattened profile in O0
2427 // pipeline.
2428 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
2429 PGOOpt->ProfileRemappingFile,
2431 /*DisableSampleProfileInlining=*/true,
2432 /*UseFlattenedProfile=*/true));
2433 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
2434 // RequireAnalysisPass for PSI before subsequent non-module passes.
2436 }
2437
2439
2440 // Build a minimal pipeline based on the semantics required by LLVM,
2441 // which is just that always inlining occurs. Further, disable generating
2442 // lifetime intrinsics to avoid enabling further optimizations during
2443 // code generation.
2445 /*InsertLifetimeIntrinsics=*/false));
2446
2447 if (PTO.MergeFunctions)
2449
2450 if (EnableMatrix)
2451 MPM.addPass(
2453
2454 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2455 CGSCCPassManager CGPM;
2457 if (!CGPM.isEmpty())
2459 }
2460 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2461 LoopPassManager LPM;
2463 if (!LPM.isEmpty()) {
2465 createFunctionToLoopPassAdaptor(std::move(LPM))));
2466 }
2467 }
2468 if (!LoopOptimizerEndEPCallbacks.empty()) {
2469 LoopPassManager LPM;
2471 if (!LPM.isEmpty()) {
2473 createFunctionToLoopPassAdaptor(std::move(LPM))));
2474 }
2475 }
2476 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2479 if (!FPM.isEmpty())
2480 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2481 }
2482
2484
2485 if (!VectorizerStartEPCallbacks.empty()) {
2488 if (!FPM.isEmpty())
2489 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2490 }
2491
2492 if (!VectorizerEndEPCallbacks.empty()) {
2495 if (!FPM.isEmpty())
2496 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2497 }
2498
2500
2501 // AllocToken transforms heap allocation calls; this needs to run late after
2502 // other allocation call transformations (such as those in InstCombine).
2503 if (!isLTOPreLink(Phase))
2504 MPM.addPass(AllocTokenPass());
2505
2507
2509 MPM.addPass(InstrumentorPass(FS));
2510
2511 // Attach !implicit.ref metadata from all functions to copyright strings.
2513
2514 if (isLTOPreLink(Phase))
2515 addRequiredLTOPreLinkPasses(MPM);
2516
2517 // Emit annotation remarks.
2519
2520 instructionCountersPass(MPM, /* IsPreOptimization */ false);
2521
2522 return MPM;
2523}
2524
2526 AAManager AA;
2527
2528 // The order in which these are registered determines their priority when
2529 // being queried.
2530
2531 // Add any target-specific alias analyses that should be run early.
2532 if (TM)
2533 TM->registerEarlyDefaultAliasAnalyses(AA);
2534
2535 // First we register the basic alias analysis that provides the majority of
2536 // per-function local AA logic. This is a stateless, on-demand local set of
2537 // AA techniques.
2538 AA.registerFunctionAnalysis<BasicAA>();
2539
2540 // Next we query fast, specialized alias analyses that wrap IR-embedded
2541 // information about aliasing.
2542 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2543 AA.registerFunctionAnalysis<TypeBasedAA>();
2544
2545 // Add support for querying global aliasing information when available.
2546 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2547 // analysis, all that the `AAManager` can do is query for any *cached*
2548 // results from `GlobalsAA` through a readonly proxy.
2550 AA.registerModuleAnalysis<GlobalsAA>();
2551
2552 // Add target-specific alias analyses.
2553 if (TM)
2554 TM->registerDefaultAliasAnalyses(AA);
2555
2556 return AA;
2557}
2558
2559bool PassBuilder::isInstrumentedPGOUse() const {
2560 return (PGOOpt && PGOOpt->Action == PGOOptions::IRUse) ||
2561 !UseCtxProfile.empty();
2562}
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.
Defines the virtual file system interface vfs::FileSystem.
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.