LLVM 20.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"
27#include "llvm/IR/PassManager.h"
144
145using namespace llvm;
146
148 "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
149 cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
150 cl::values(clEnumValN(InliningAdvisorMode::Default, "default",
151 "Heuristics-based inliner version"),
152 clEnumValN(InliningAdvisorMode::Development, "development",
153 "Use development mode (runtime-loadable model)"),
154 clEnumValN(InliningAdvisorMode::Release, "release",
155 "Use release mode (AOT-compiled model)")));
156
158 "enable-npm-synthetic-counts", cl::Hidden,
159 cl::desc("Run synthetic function entry count generation "
160 "pass"));
161
162/// Flag to enable inline deferral during PGO.
163static cl::opt<bool>
164 EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
166 cl::desc("Enable inline deferral during PGO"));
167
168static cl::opt<bool> EnableModuleInliner("enable-module-inliner",
169 cl::init(false), cl::Hidden,
170 cl::desc("Enable module inliner"));
171
173 "mandatory-inlining-first", cl::init(false), cl::Hidden,
174 cl::desc("Perform mandatory inlinings module-wide, before performing "
175 "inlining"));
176
178 "eagerly-invalidate-analyses", cl::init(true), cl::Hidden,
179 cl::desc("Eagerly invalidate more analyses in default pipelines"));
180
182 "enable-merge-functions", cl::init(false), cl::Hidden,
183 cl::desc("Enable function merging as part of the optimization pipeline"));
184
186 "enable-post-pgo-loop-rotation", cl::init(true), cl::Hidden,
187 cl::desc("Run the loop rotation transformation after PGO instrumentation"));
188
190 "enable-global-analyses", cl::init(true), cl::Hidden,
191 cl::desc("Enable inter-procedural analyses"));
192
193static cl::opt<bool>
194 RunPartialInlining("enable-partial-inlining", cl::init(false), cl::Hidden,
195 cl::desc("Run Partial inlinining pass"));
196
198 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
199 cl::desc("Run cleanup optimization passes after vectorization"));
200
201static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
202 cl::desc("Run the NewGVN pass"));
203
205 "enable-loopinterchange", cl::init(false), cl::Hidden,
206 cl::desc("Enable the experimental LoopInterchange Pass"));
207
208static cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam",
209 cl::init(false), cl::Hidden,
210 cl::desc("Enable Unroll And Jam Pass"));
211
212static cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
214 cl::desc("Enable the LoopFlatten Pass"));
215
216// Experimentally allow loop header duplication. This should allow for better
217// optimization at Oz, since loop-idiom recognition can then recognize things
218// like memcpy. If this ends up being useful for many targets, we should drop
219// this flag and make a code generation option that can be controlled
220// independent of the opt level and exposed through the frontend.
222 "enable-loop-header-duplication", cl::init(false), cl::Hidden,
223 cl::desc("Enable loop header duplication at any optimization level"));
224
225static cl::opt<bool>
226 EnableDFAJumpThreading("enable-dfa-jump-thread",
227 cl::desc("Enable DFA jump threading"),
228 cl::init(false), cl::Hidden);
229
230// TODO: turn on and remove flag
232 "enable-pgo-force-function-attrs",
233 cl::desc("Enable pass to set function attributes based on PGO profiles"),
234 cl::init(false));
235
236static cl::opt<bool>
237 EnableHotColdSplit("hot-cold-split",
238 cl::desc("Enable hot-cold splitting pass"));
239
240static cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false),
242 cl::desc("Enable ir outliner pass"));
243
244static cl::opt<bool>
245 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
246 cl::desc("Disable pre-instrumentation inliner"));
247
249 "preinline-threshold", cl::Hidden, cl::init(75),
250 cl::desc("Control the amount of inlining in pre-instrumentation inliner "
251 "(default = 75)"));
252
253static cl::opt<bool>
254 EnableGVNHoist("enable-gvn-hoist",
255 cl::desc("Enable the GVN hoisting pass (default = off)"));
256
257static cl::opt<bool>
258 EnableGVNSink("enable-gvn-sink",
259 cl::desc("Enable the GVN sinking pass (default = off)"));
260
262 "enable-jump-table-to-switch",
263 cl::desc("Enable JumpTableToSwitch pass (default = off)"));
264
265// This option is used in simplifying testing SampleFDO optimizations for
266// profile loading.
267static cl::opt<bool>
268 EnableCHR("enable-chr", cl::init(true), cl::Hidden,
269 cl::desc("Enable control height reduction optimization (CHR)"));
270
272 "flattened-profile-used", cl::init(false), cl::Hidden,
273 cl::desc("Indicate the sample profile being used is flattened, i.e., "
274 "no inline hierachy exists in the profile"));
275
277 "enable-order-file-instrumentation", cl::init(false), cl::Hidden,
278 cl::desc("Enable order file instrumentation (default = off)"));
279
280static cl::opt<bool>
281 EnableMatrix("enable-matrix", cl::init(false), cl::Hidden,
282 cl::desc("Enable lowering of the matrix intrinsics"));
283
285 "enable-constraint-elimination", cl::init(true), cl::Hidden,
286 cl::desc(
287 "Enable pass to eliminate conditions based on linear constraints"));
288
290 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
291 cl::desc("Enable the attributor inter-procedural deduction pass"),
292 cl::values(clEnumValN(AttributorRunOption::ALL, "all",
293 "enable all attributor runs"),
294 clEnumValN(AttributorRunOption::MODULE, "module",
295 "enable module-wide attributor runs"),
296 clEnumValN(AttributorRunOption::CGSCC, "cgscc",
297 "enable call graph SCC attributor runs"),
298 clEnumValN(AttributorRunOption::NONE, "none",
299 "disable attributor runs")));
300
302 "enable-sampled-instrumentation", cl::init(false), cl::Hidden,
303 cl::desc("Enable profile instrumentation sampling (default = off)"));
305 "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
306 cl::desc("Enable the experimental Loop Versioning LICM pass"));
307
309
310namespace llvm {
312
314} // namespace llvm
315
317 LoopInterleaving = true;
318 LoopVectorization = true;
319 SLPVectorization = false;
320 LoopUnrolling = true;
324 CallGraphProfile = true;
325 UnifiedLTO = false;
327 InlinerThreshold = -1;
329}
330
331namespace llvm {
333} // namespace llvm
334
336 OptimizationLevel Level) {
337 for (auto &C : PeepholeEPCallbacks)
338 C(FPM, Level);
339}
342 for (auto &C : LateLoopOptimizationsEPCallbacks)
343 C(LPM, Level);
344}
346 OptimizationLevel Level) {
347 for (auto &C : LoopOptimizerEndEPCallbacks)
348 C(LPM, Level);
349}
352 for (auto &C : ScalarOptimizerLateEPCallbacks)
353 C(FPM, Level);
354}
356 OptimizationLevel Level) {
357 for (auto &C : CGSCCOptimizerLateEPCallbacks)
358 C(CGPM, Level);
359}
361 OptimizationLevel Level) {
362 for (auto &C : VectorizerStartEPCallbacks)
363 C(FPM, Level);
364}
366 OptimizationLevel Level) {
367 for (auto &C : OptimizerEarlyEPCallbacks)
368 C(MPM, Level);
369}
371 OptimizationLevel Level) {
372 for (auto &C : OptimizerLastEPCallbacks)
373 C(MPM, Level);
374}
377 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
378 C(MPM, Level);
379}
382 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
383 C(MPM, Level);
384}
386 OptimizationLevel Level) {
387 for (auto &C : PipelineStartEPCallbacks)
388 C(MPM, Level);
389}
392 for (auto &C : PipelineEarlySimplificationEPCallbacks)
393 C(MPM, Level);
394}
395
396// Helper to add AnnotationRemarksPass.
399}
400
401// Helper to check if the current compilation phase is preparing for LTO
405}
406
407// TODO: Investigate the cost/benefit of tail call elimination on debugging.
409PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
411
413
416
417 // Form SSA out of local memory accesses after breaking apart aggregates into
418 // scalars.
420
421 // Catch trivial redundancies
422 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
423
424 // Hoisting of scalars and load expressions.
425 FPM.addPass(
426 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
428
430
431 invokePeepholeEPCallbacks(FPM, Level);
432
433 FPM.addPass(
434 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
435
436 // Form canonically associated expression trees, and simplify the trees using
437 // basic mathematical properties. For example, this will form (nearly)
438 // minimal multiplication trees.
440
441 // Add the primary loop simplification pipeline.
442 // FIXME: Currently this is split into two loop pass pipelines because we run
443 // some function passes in between them. These can and should be removed
444 // and/or replaced by scheduling the loop pass equivalents in the correct
445 // positions. But those equivalent passes aren't powerful enough yet.
446 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
447 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
448 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
449 // `LoopInstSimplify`.
450 LoopPassManager LPM1, LPM2;
451
452 // Simplify the loop body. We do this initially to clean up after other loop
453 // passes run, either when iterating on a loop or on inner loops with
454 // implications on the outer loop.
457
458 // Try to remove as much code from the loop header as possible,
459 // to reduce amount of IR that will have to be duplicated. However,
460 // do not perform speculative hoisting the first time as LICM
461 // will destroy metadata that may not need to be destroyed if run
462 // after loop rotation.
463 // TODO: Investigate promotion cap for O1.
465 /*AllowSpeculation=*/false));
466
467 LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true,
469 // TODO: Investigate promotion cap for O1.
471 /*AllowSpeculation=*/true));
474 LPM1.addPass(LoopFlattenPass());
475
478
480
482
485
486 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
487 // because it changes IR to makes profile annotation in back compile
488 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
489 // attributes so we need to make sure and allow the full unroll pass to pay
490 // attention to it.
491 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
492 PGOOpt->Action != PGOOptions::SampleUse)
493 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
494 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
496
498
499 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
500 /*UseMemorySSA=*/true,
501 /*UseBlockFrequencyInfo=*/true));
502 FPM.addPass(
503 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
505 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
506 // *All* loop passes must preserve it, in order to be able to use it.
507 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
508 /*UseMemorySSA=*/false,
509 /*UseBlockFrequencyInfo=*/false));
510
511 // Delete small array after loop unroll.
513
514 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
515 FPM.addPass(MemCpyOptPass());
516
517 // Sparse conditional constant propagation.
518 // FIXME: It isn't clear why we do this *after* loop passes rather than
519 // before...
520 FPM.addPass(SCCPPass());
521
522 // Delete dead bit computations (instcombine runs after to fold away the dead
523 // computations, and then ADCE will run later to exploit any new DCE
524 // opportunities that creates).
525 FPM.addPass(BDCEPass());
526
527 // Run instcombine after redundancy and dead bit elimination to exploit
528 // opportunities opened up by them.
530 invokePeepholeEPCallbacks(FPM, Level);
531
532 FPM.addPass(CoroElidePass());
533
535
536 // Finally, do an expensive DCE pass to catch all the dead code exposed by
537 // the simplifications and basic cleanup after all the simplifications.
538 // TODO: Investigate if this is too expensive.
539 FPM.addPass(ADCEPass());
540 FPM.addPass(
541 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
543 invokePeepholeEPCallbacks(FPM, Level);
544
545 return FPM;
546}
547
551 assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
552
553 // The O1 pipeline has a separate pipeline creation function to simplify
554 // construction readability.
555 if (Level.getSpeedupLevel() == 1)
556 return buildO1FunctionSimplificationPipeline(Level, Phase);
557
559
562
563 // Form SSA out of local memory accesses after breaking apart aggregates into
564 // scalars.
566
567 // Catch trivial redundancies
568 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
571
572 // Hoisting of scalars and load expressions.
573 if (EnableGVNHoist)
574 FPM.addPass(GVNHoistPass());
575
576 // Global value numbering based sinking.
577 if (EnableGVNSink) {
578 FPM.addPass(GVNSinkPass());
579 FPM.addPass(
580 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
581 }
582
583 // Speculative execution if the target has divergent branches; otherwise nop.
584 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
585
586 // Optimize based on known information about branches, and cleanup afterward.
589
590 // Jump table to switch conversion.
593
594 FPM.addPass(
595 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
598
599 if (!Level.isOptimizingForSize())
601
602 invokePeepholeEPCallbacks(FPM, Level);
603
604 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
605 // using the size value profile. Don't perform this when optimizing for size.
606 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
607 !Level.isOptimizingForSize())
609
611 FPM.addPass(
612 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
613
614 // Form canonically associated expression trees, and simplify the trees using
615 // basic mathematical properties. For example, this will form (nearly)
616 // minimal multiplication trees.
618
621
622 // Add the primary loop simplification pipeline.
623 // FIXME: Currently this is split into two loop pass pipelines because we run
624 // some function passes in between them. These can and should be removed
625 // and/or replaced by scheduling the loop pass equivalents in the correct
626 // positions. But those equivalent passes aren't powerful enough yet.
627 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
628 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
629 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
630 // `LoopInstSimplify`.
631 LoopPassManager LPM1, LPM2;
632
633 // Simplify the loop body. We do this initially to clean up after other loop
634 // passes run, either when iterating on a loop or on inner loops with
635 // implications on the outer loop.
638
639 // Try to remove as much code from the loop header as possible,
640 // to reduce amount of IR that will have to be duplicated. However,
641 // do not perform speculative hoisting the first time as LICM
642 // will destroy metadata that may not need to be destroyed if run
643 // after loop rotation.
644 // TODO: Investigate promotion cap for O1.
646 /*AllowSpeculation=*/false));
647
648 // Disable header duplication in loop rotation at -Oz.
650 Level != OptimizationLevel::Oz,
652 // TODO: Investigate promotion cap for O1.
654 /*AllowSpeculation=*/true));
655 LPM1.addPass(
656 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
658 LPM1.addPass(LoopFlattenPass());
659
662
663 {
665 ExtraPasses.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
667 LPM2.addPass(std::move(ExtraPasses));
668 }
669
671
673
676
677 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
678 // because it changes IR to makes profile annotation in back compile
679 // inaccurate. The normal unroller doesn't pay attention to forced full unroll
680 // attributes so we need to make sure and allow the full unroll pass to pay
681 // attention to it.
682 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
683 PGOOpt->Action != PGOOptions::SampleUse)
684 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
685 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
687
689
690 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
691 /*UseMemorySSA=*/true,
692 /*UseBlockFrequencyInfo=*/true));
693 FPM.addPass(
694 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
696 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
697 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
698 // *All* loop passes must preserve it, in order to be able to use it.
699 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
700 /*UseMemorySSA=*/false,
701 /*UseBlockFrequencyInfo=*/false));
702
703 // Delete small array after loop unroll.
705
706 // Try vectorization/scalarization transforms that are both improvements
707 // themselves and can allow further folds with GVN and InstCombine.
708 FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
709
710 // Eliminate redundancies.
712 if (RunNewGVN)
713 FPM.addPass(NewGVNPass());
714 else
715 FPM.addPass(GVNPass());
716
717 // Sparse conditional constant propagation.
718 // FIXME: It isn't clear why we do this *after* loop passes rather than
719 // before...
720 FPM.addPass(SCCPPass());
721
722 // Delete dead bit computations (instcombine runs after to fold away the dead
723 // computations, and then ADCE will run later to exploit any new DCE
724 // opportunities that creates).
725 FPM.addPass(BDCEPass());
726
727 // Run instcombine after redundancy and dead bit elimination to exploit
728 // opportunities opened up by them.
730 invokePeepholeEPCallbacks(FPM, Level);
731
732 // Re-consider control flow based optimizations after redundancy elimination,
733 // redo DCE, etc.
736
739
740 // Finally, do an expensive DCE pass to catch all the dead code exposed by
741 // the simplifications and basic cleanup after all the simplifications.
742 // TODO: Investigate if this is too expensive.
743 FPM.addPass(ADCEPass());
744
745 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
746 FPM.addPass(MemCpyOptPass());
747
748 FPM.addPass(DSEPass());
750
753 /*AllowSpeculation=*/true),
754 /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/false));
755
756 FPM.addPass(CoroElidePass());
757
759
761 .convertSwitchRangeToICmp(true)
762 .hoistCommonInsts(true)
763 .sinkCommonInsts(true)));
765 invokePeepholeEPCallbacks(FPM, Level);
766
767 return FPM;
768}
769
770void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
773}
774
775void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
776 OptimizationLevel Level,
777 ThinOrFullLTOPhase LTOPhase) {
778 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
780 return;
781 InlineParams IP;
782
784
785 // FIXME: The hint threshold has the same value used by the regular inliner
786 // when not optimzing for size. This should probably be lowered after
787 // performance testing.
788 // FIXME: this comment is cargo culted from the old pass manager, revisit).
789 IP.HintThreshold = Level.isOptimizingForSize() ? PreInlineThreshold : 325;
791 IP, /* MandatoryFirst */ true,
793 CGSCCPassManager &CGPipeline = MIWP.getPM();
794
797 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
798 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
799 true))); // Merge & remove basic blocks.
800 FPM.addPass(InstCombinePass()); // Combine silly sequences.
801 invokePeepholeEPCallbacks(FPM, Level);
802
803 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
804 std::move(FPM), PTO.EagerlyInvalidateAnalyses));
805
806 MPM.addPass(std::move(MIWP));
807
808 // Delete anything that is now dead to make sure that we don't instrument
809 // dead code. Instrumentation can end up keeping dead code around and
810 // dramatically increase code size.
812}
813
814void PassBuilder::addPostPGOLoopRotation(ModulePassManager &MPM,
815 OptimizationLevel Level) {
817 // Disable header duplication in loop rotation at -Oz.
821 Level != OptimizationLevel::Oz),
822 /*UseMemorySSA=*/false,
823 /*UseBlockFrequencyInfo=*/false),
825 }
826}
827
828void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
829 OptimizationLevel Level, bool RunProfileGen,
830 bool IsCS, bool AtomicCounterUpdate,
831 std::string ProfileFile,
832 std::string ProfileRemappingFile,
834 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
835
836 if (!RunProfileGen) {
837 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
838 MPM.addPass(
839 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
840 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
841 // RequireAnalysisPass for PSI before subsequent non-module passes.
843 return;
844 }
845
846 // Perform PGO instrumentation.
848
849 addPostPGOLoopRotation(MPM, Level);
850 // Add the profile lowering pass.
852 if (!ProfileFile.empty())
853 Options.InstrProfileOutput = ProfileFile;
854 // Do counter promotion at Level greater than O0.
855 Options.DoCounterPromotion = true;
856 Options.UseBFIInPromotion = IsCS;
857 if (EnableSampledInstr) {
858 Options.Sampling = true;
859 // With sampling, there is little beneifit to enable counter promotion.
860 // But note that sampling does work with counter promotion.
861 Options.DoCounterPromotion = false;
862 }
863 Options.Atomic = AtomicCounterUpdate;
865}
866
868 ModulePassManager &MPM, bool RunProfileGen, bool IsCS,
869 bool AtomicCounterUpdate, std::string ProfileFile,
870 std::string ProfileRemappingFile, IntrusiveRefCntPtr<vfs::FileSystem> FS) {
871 if (!RunProfileGen) {
872 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
873 MPM.addPass(
874 PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
875 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
876 // RequireAnalysisPass for PSI before subsequent non-module passes.
878 return;
879 }
880
881 // Perform PGO instrumentation.
883 // Add the profile lowering pass.
885 if (!ProfileFile.empty())
886 Options.InstrProfileOutput = ProfileFile;
887 // Do not do counter promotion at O0.
888 Options.DoCounterPromotion = false;
889 Options.UseBFIInPromotion = IsCS;
890 Options.Atomic = AtomicCounterUpdate;
892}
893
895 return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel());
896}
897
901 InlineParams IP;
902 if (PTO.InlinerThreshold == -1)
903 IP = getInlineParamsFromOptLevel(Level);
904 else
906 // For PreLinkThinLTO + SamplePGO, set hot-caller threshold to 0 to
907 // disable hot callsite inline (as much as possible [1]) because it makes
908 // profile annotation in the backend inaccurate.
909 //
910 // [1] Note the cost of a function could be below zero due to erased
911 // prologue / epilogue.
912 if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
913 PGOOpt->Action == PGOOptions::SampleUse)
915
916 if (PGOOpt)
918
922
923 // Require the GlobalsAA analysis for the module so we can query it within
924 // the CGSCC pipeline.
927 // Invalidate AAManager so it can be recreated and pick up the newly
928 // available GlobalsAA.
929 MIWP.addModulePass(
931 }
932
933 // Require the ProfileSummaryAnalysis for the module so we can query it within
934 // the inliner pass.
936
937 // Now begin the main postorder CGSCC pipeline.
938 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
939 // manager and trying to emulate its precise behavior. Much of this doesn't
940 // make a lot of sense and we should revisit the core CGSCC structure.
941 CGSCCPassManager &MainCGPipeline = MIWP.getPM();
942
943 // Note: historically, the PruneEH pass was run first to deduce nounwind and
944 // generally clean up exception handling overhead. It isn't clear this is
945 // valuable as the inliner doesn't currently care whether it is inlining an
946 // invoke or a call.
947
949 MainCGPipeline.addPass(AttributorCGSCCPass());
950
951 // Deduce function attributes. We do another run of this after the function
952 // simplification pipeline, so this only needs to run when it could affect the
953 // function simplification pipeline, which is only the case with recursive
954 // functions.
955 MainCGPipeline.addPass(PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
956
957 // When at O3 add argument promotion to the pass pipeline.
958 // FIXME: It isn't at all clear why this should be limited to O3.
959 if (Level == OptimizationLevel::O3)
960 MainCGPipeline.addPass(ArgumentPromotionPass());
961
962 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
963 // there are no OpenMP runtime calls present in the module.
964 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
965 MainCGPipeline.addPass(OpenMPOptCGSCCPass());
966
967 invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
968
969 // Add the core function simplification pipeline nested inside the
970 // CGSCC walk.
973 PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
974
975 // Finally, deduce any function attributes based on the fully simplified
976 // function.
977 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
978
979 // Mark that the function is fully simplified and that it shouldn't be
980 // simplified again if we somehow revisit it due to CGSCC mutations unless
981 // it's been modified since.
984
986 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
987
988 // Make sure we don't affect potential future NoRerun CGSCC adaptors.
989 MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
991
992 return MIWP;
993}
994
999
1001 // For PreLinkThinLTO + SamplePGO, set hot-caller threshold to 0 to
1002 // disable hot callsite inline (as much as possible [1]) because it makes
1003 // profile annotation in the backend inaccurate.
1004 //
1005 // [1] Note the cost of a function could be below zero due to erased
1006 // prologue / epilogue.
1007 if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
1008 PGOOpt->Action == PGOOptions::SampleUse)
1009 IP.HotCallSiteThreshold = 0;
1010
1011 if (PGOOpt)
1013
1014 // The inline deferral logic is used to avoid losing some
1015 // inlining chance in future. It is helpful in SCC inliner, in which
1016 // inlining is processed in bottom-up order.
1017 // While in module inliner, the inlining order is a priority-based order
1018 // by default. The inline deferral is unnecessary there. So we disable the
1019 // inline deferral logic in module inliner.
1020 IP.EnableDeferral = false;
1021
1023
1027
1031
1032 return MPM;
1033}
1034
1038 assert(Level != OptimizationLevel::O0 &&
1039 "Should not be used for O0 pipeline");
1040
1042 "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
1043
1045
1046 // Place pseudo probe instrumentation as the first pass of the pipeline to
1047 // minimize the impact of optimization changes.
1048 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1051
1052 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
1053
1054 // In ThinLTO mode, when flattened profile is used, all the available
1055 // profile information will be annotated in PreLink phase so there is
1056 // no need to load the profile again in PostLink.
1057 bool LoadSampleProfile =
1058 HasSampleProfile &&
1060
1061 // During the ThinLTO backend phase we perform early indirect call promotion
1062 // here, before globalopt. Otherwise imported available_externally functions
1063 // look unreferenced and are removed. If we are going to load the sample
1064 // profile then defer until later.
1065 // TODO: See if we can move later and consolidate with the location where
1066 // we perform ICP when we are loading a sample profile.
1067 // TODO: We pass HasSampleProfile (whether there was a sample profile file
1068 // passed to the compile) to the SamplePGO flag of ICP. This is used to
1069 // determine whether the new direct calls are annotated with prof metadata.
1070 // Ideally this should be determined from whether the IR is annotated with
1071 // sample profile, and not whether the a sample profile was provided on the
1072 // command line. E.g. for flattened profiles where we will not be reloading
1073 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1074 // provide the sample profile file.
1075 if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile)
1076 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1077
1078 // Create an early function pass manager to cleanup the output of the
1079 // frontend. Not necessary with LTO post link pipelines since the pre link
1080 // pipeline already cleaned up the frontend output.
1082 // Do basic inference of function attributes from known properties of system
1083 // libraries and other oracles.
1086
1087 FunctionPassManager EarlyFPM;
1088 EarlyFPM.addPass(EntryExitInstrumenterPass(/*PostInlining=*/false));
1089 // Lower llvm.expect to metadata before attempting transforms.
1090 // Compare/branch metadata may alter the behavior of passes like
1091 // SimplifyCFG.
1093 EarlyFPM.addPass(SimplifyCFGPass());
1095 EarlyFPM.addPass(EarlyCSEPass());
1096 if (Level == OptimizationLevel::O3)
1097 EarlyFPM.addPass(CallSiteSplittingPass());
1099 std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
1100 }
1101
1102 if (LoadSampleProfile) {
1103 // Annotate sample profile right after early FPM to ensure freshness of
1104 // the debug info.
1105 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1106 PGOOpt->ProfileRemappingFile, Phase));
1107 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1108 // RequireAnalysisPass for PSI before subsequent non-module passes.
1110 // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1111 // for the profile annotation to be accurate in the LTO backend.
1112 if (!isLTOPreLink(Phase))
1113 // We perform early indirect call promotion here, before globalopt.
1114 // This is important for the ThinLTO backend phase because otherwise
1115 // imported available_externally functions look unreferenced and are
1116 // removed.
1117 MPM.addPass(
1118 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1119 }
1120
1121 // Try to perform OpenMP specific optimizations on the module. This is a
1122 // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1124
1127
1128 // Lower type metadata and the type.test intrinsic in the ThinLTO
1129 // post link pipeline after ICP. This is to enable usage of the type
1130 // tests in ICP sequences.
1132 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1133
1135
1136 // Interprocedural constant propagation now that basic cleanup has occurred
1137 // and prior to optimizing globals.
1138 // FIXME: This position in the pipeline hasn't been carefully considered in
1139 // years, it should be re-analyzed.
1141 IPSCCPOptions(/*AllowFuncSpec=*/
1142 Level != OptimizationLevel::Os &&
1143 Level != OptimizationLevel::Oz &&
1144 !isLTOPreLink(Phase))));
1145
1146 // Attach metadata to indirect call sites indicating the set of functions
1147 // they may target at run-time. This should follow IPSCCP.
1149
1150 // Optimize globals to try and fold them into constants.
1152
1153 // Create a small function pass pipeline to cleanup after all the global
1154 // optimizations.
1155 FunctionPassManager GlobalCleanupPM;
1156 // FIXME: Should this instead by a run of SROA?
1157 GlobalCleanupPM.addPass(PromotePass());
1158 GlobalCleanupPM.addPass(InstCombinePass());
1159 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1160 GlobalCleanupPM.addPass(
1161 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1162 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
1164
1165 // We already asserted this happens in non-FullLTOPostLink earlier.
1166 const bool IsPreLink = Phase != ThinOrFullLTOPhase::ThinLTOPostLink;
1167 const bool IsPGOPreLink = PGOOpt && IsPreLink;
1168 const bool IsPGOInstrGen =
1169 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRInstr;
1170 const bool IsPGOInstrUse =
1171 IsPGOPreLink && PGOOpt->Action == PGOOptions::IRUse;
1172 const bool IsMemprofUse = IsPGOPreLink && !PGOOpt->MemoryProfile.empty();
1173 // We don't want to mix pgo ctx gen and pgo gen; we also don't currently
1174 // enable ctx profiling from the frontend.
1176 "Enabling both instrumented PGO and contextual instrumentation is not "
1177 "supported.");
1178 // Enable contextual profiling instrumentation.
1179 const bool IsCtxProfGen = !IsPGOInstrGen && IsPreLink &&
1181 const bool IsCtxProfUse = !UseCtxProfile.empty() && !PGOOpt &&
1183
1184 if (IsPGOInstrGen || IsPGOInstrUse || IsMemprofUse || IsCtxProfGen ||
1185 IsCtxProfUse)
1186 addPreInlinerPasses(MPM, Level, Phase);
1187
1188 // Add all the requested passes for instrumentation PGO, if requested.
1189 if (IsPGOInstrGen || IsPGOInstrUse) {
1190 addPGOInstrPasses(MPM, Level,
1191 /*RunProfileGen=*/IsPGOInstrGen,
1192 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate,
1193 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile,
1194 PGOOpt->FS);
1195 } else if (IsCtxProfGen || IsCtxProfUse) {
1197 // In pre-link, we just want the instrumented IR. We use the contextual
1198 // profile in the post-thinlink phase.
1199 // The instrumentation will be removed in post-thinlink after IPO.
1200 // FIXME(mtrofin): move AssignGUIDPass if there is agreement to use this
1201 // mechanism for GUIDs.
1203 if (IsCtxProfUse)
1204 return MPM;
1205 addPostPGOLoopRotation(MPM, Level);
1207 }
1208
1209 if (IsPGOInstrGen || IsPGOInstrUse || IsCtxProfGen)
1210 MPM.addPass(PGOIndirectCallPromotion(false, false));
1211
1212 if (IsPGOPreLink && PGOOpt->CSAction == PGOOptions::CSIRInstr)
1213 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile,
1215
1216 if (IsMemprofUse)
1217 MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, PGOOpt->FS));
1218
1219 // Synthesize function entry counts for non-PGO compilation.
1220 if (EnableSyntheticCounts && !PGOOpt)
1222
1223 if (EnablePGOForceFunctionAttrs && PGOOpt)
1224 MPM.addPass(PGOForceFunctionAttrsPass(PGOOpt->ColdOptType));
1225
1226 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/true));
1227
1230 else
1232
1233 // Remove any dead arguments exposed by cleanups, constant folding globals,
1234 // and argument promotion.
1236
1239
1240 // Optimize globals now that functions are fully simplified.
1243
1244 return MPM;
1245}
1246
1247/// TODO: Should LTO cause any differences to this set of passes?
1248void PassBuilder::addVectorPasses(OptimizationLevel Level,
1249 FunctionPassManager &FPM, bool IsFullLTO) {
1252
1255 if (IsFullLTO) {
1256 // The vectorizer may have significantly shortened a loop body; unroll
1257 // again. Unroll small loops to hide loop backedge latency and saturate any
1258 // parallel execution resources of an out-of-order processor. We also then
1259 // need to clean up redundancies and loop invariant code.
1260 // FIXME: It would be really good to use a loop-integrated instruction
1261 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1262 // across the loop nests.
1263 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1266 LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1268 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1271 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1272 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1273 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1274 // NOTE: we are very late in the pipeline, and we don't have any LICM
1275 // or SimplifyCFG passes scheduled after us, that would cleanup
1276 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1278 }
1279
1280 if (!IsFullLTO) {
1281 // Eliminate loads by forwarding stores from the previous iteration to loads
1282 // of the current iteration.
1284 }
1285 // Cleanup after the loop optimization passes.
1286 FPM.addPass(InstCombinePass());
1287
1288 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1289 ExtraVectorPassManager ExtraPasses;
1290 // At higher optimization levels, try to clean up any runtime overlap and
1291 // alignment checks inserted by the vectorizer. We want to track correlated
1292 // runtime checks for two inner loops in the same outer loop, fold any
1293 // common computations, hoist loop-invariant aspects out of any outer loop,
1294 // and unswitch the runtime checks if possible. Once hoisted, we may have
1295 // dead (or speculatable) control flows or more combining opportunities.
1296 ExtraPasses.addPass(EarlyCSEPass());
1298 ExtraPasses.addPass(InstCombinePass());
1299 LoopPassManager LPM;
1301 /*AllowSpeculation=*/true));
1302 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1304 ExtraPasses.addPass(
1305 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true,
1306 /*UseBlockFrequencyInfo=*/true));
1307 ExtraPasses.addPass(
1308 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1309 ExtraPasses.addPass(InstCombinePass());
1310 FPM.addPass(std::move(ExtraPasses));
1311 }
1312
1313 // Now that we've formed fast to execute loop structures, we do further
1314 // optimizations. These are run afterward as they might block doing complex
1315 // analyses and transforms such as what are needed for loop vectorization.
1316
1317 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1318 // GVN, loop transforms, and others have already run, so it's now better to
1319 // convert to more optimized IR using more aggressive simplify CFG options.
1320 // The extra sinking transform can create larger basic blocks, so do this
1321 // before SLP vectorization.
1323 .forwardSwitchCondToPhi(true)
1324 .convertSwitchRangeToICmp(true)
1325 .convertSwitchToLookupTable(true)
1326 .needCanonicalLoops(false)
1327 .hoistCommonInsts(true)
1328 .sinkCommonInsts(true)));
1329
1330 if (IsFullLTO) {
1331 FPM.addPass(SCCPPass());
1332 FPM.addPass(InstCombinePass());
1333 FPM.addPass(BDCEPass());
1334 }
1335
1336 // Optimize parallel scalar instruction chains into SIMD instructions.
1337 if (PTO.SLPVectorization) {
1339 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1340 FPM.addPass(EarlyCSEPass());
1341 }
1342 }
1343 // Enhance/cleanup vector code.
1345
1346 if (!IsFullLTO) {
1347 FPM.addPass(InstCombinePass());
1348 // Unroll small loops to hide loop backedge latency and saturate any
1349 // parallel execution resources of an out-of-order processor. We also then
1350 // need to clean up redundancies and loop invariant code.
1351 // FIXME: It would be really good to use a loop-integrated instruction
1352 // combiner for cleanup here so that the unrolling and LICM can be pipelined
1353 // across the loop nests.
1354 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1355 if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1357 LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1358 }
1360 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1363 // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1364 // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1365 // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1366 // NOTE: we are very late in the pipeline, and we don't have any LICM
1367 // or SimplifyCFG passes scheduled after us, that would cleanup
1368 // the CFG mess this may created if allowed to modify CFG, so forbid that.
1370 }
1371
1374 FPM.addPass(InstCombinePass());
1375
1376 // This is needed for two reasons:
1377 // 1. It works around problems that instcombine introduces, such as sinking
1378 // expensive FP divides into loops containing multiplications using the
1379 // divide result.
1380 // 2. It helps to clean up some loop-invariant code created by the loop
1381 // unroll pass when IsFullLTO=false.
1384 /*AllowSpeculation=*/true),
1385 /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/false));
1386
1387 // Now that we've vectorized and unrolled loops, we may have more refined
1388 // alignment information, try to re-derive it here.
1390}
1391
1394 ThinOrFullLTOPhase LTOPhase) {
1395 const bool LTOPreLink = isLTOPreLink(LTOPhase);
1397
1398 // Run partial inlining pass to partially inline functions that have
1399 // large bodies.
1402
1403 // Remove avail extern fns and globals definitions since we aren't compiling
1404 // an object file for later LTO. For LTO we want to preserve these so they
1405 // are eligible for inlining at link-time. Note if they are unreferenced they
1406 // will be removed by GlobalDCE later, so this only impacts referenced
1407 // available externally globals. Eventually they will be suppressed during
1408 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1409 // may make globals referenced by available external functions dead and saves
1410 // running remaining passes on the eliminated functions. These should be
1411 // preserved during prelinking for link-time inlining decisions.
1412 if (!LTOPreLink)
1414
1417
1418 // Do RPO function attribute inference across the module to forward-propagate
1419 // attributes where applicable.
1420 // FIXME: Is this really an optimization rather than a canonicalization?
1422
1423 // Do a post inline PGO instrumentation and use pass. This is a context
1424 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1425 // cross-module inline has not been done yet. The context sensitive
1426 // instrumentation is after all the inlines are done.
1427 if (!LTOPreLink && PGOOpt) {
1428 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1429 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1430 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1431 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile,
1432 PGOOpt->FS);
1433 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1434 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1435 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1436 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile,
1437 PGOOpt->FS);
1438 }
1439
1440 // Re-compute GlobalsAA here prior to function passes. This is particularly
1441 // useful as the above will have inlined, DCE'ed, and function-attr
1442 // propagated everything. We should at this point have a reasonably minimal
1443 // and richly annotated call graph. By computing aliasing and mod/ref
1444 // information for all local globals here, the late loop passes and notably
1445 // the vectorizer will be able to use them to help recognize vectorizable
1446 // memory operations.
1449
1451
1452 FunctionPassManager OptimizePM;
1453 // Scheduling LoopVersioningLICM when inlining is over, because after that
1454 // we may see more accurate aliasing. Reason to run this late is that too
1455 // early versioning may prevent further inlining due to increase of code
1456 // size. Other optimizations which runs later might get benefit of no-alias
1457 // assumption in clone loop.
1459 OptimizePM.addPass(
1461 // LoopVersioningLICM pass might increase new LICM opportunities.
1464 /*AllowSpeculation=*/true),
1465 /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/false));
1466 }
1467
1468 OptimizePM.addPass(Float2IntPass());
1470
1471 if (EnableMatrix) {
1472 OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1473 OptimizePM.addPass(EarlyCSEPass());
1474 }
1475
1476 // CHR pass should only be applied with the profile information.
1477 // The check is to check the profile summary information in CHR.
1478 if (EnableCHR && Level == OptimizationLevel::O3)
1479 OptimizePM.addPass(ControlHeightReductionPass());
1480
1481 // FIXME: We need to run some loop optimizations to re-rotate loops after
1482 // simplifycfg and others undo their rotation.
1483
1484 // Optimize the loop execution. These passes operate on entire loop nests
1485 // rather than on each loop in an inside-out manner, and so they are actually
1486 // function passes.
1487
1488 invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1489
1490 LoopPassManager LPM;
1491 // First rotate loops that may have been un-rotated by prior passes.
1492 // Disable header duplication at -Oz.
1494 Level != OptimizationLevel::Oz,
1495 LTOPreLink));
1496 // Some loops may have become dead by now. Try to delete them.
1497 // FIXME: see discussion in https://reviews.llvm.org/D112851,
1498 // this may need to be revisited once we run GVN before loop deletion
1499 // in the simplification pipeline.
1502 std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false));
1503
1504 // Distribute loops to allow partial vectorization. I.e. isolate dependences
1505 // into separate loop that would otherwise inhibit vectorization. This is
1506 // currently only performed for loops marked with the metadata
1507 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1508 OptimizePM.addPass(LoopDistributePass());
1509
1510 // Populates the VFABI attribute with the scalar-to-vector mappings
1511 // from the TargetLibraryInfo.
1512 OptimizePM.addPass(InjectTLIMappings());
1513
1514 addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false);
1515
1516 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1517 // canonicalization pass that enables other optimizations. As a result,
1518 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1519 // result too early.
1520 OptimizePM.addPass(LoopSinkPass());
1521
1522 // And finally clean up LCSSA form before generating code.
1523 OptimizePM.addPass(InstSimplifyPass());
1524
1525 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1526 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1527 // flattening of blocks.
1528 OptimizePM.addPass(DivRemPairsPass());
1529
1530 // Try to annotate calls that were created during optimization.
1531 OptimizePM.addPass(TailCallElimPass());
1532
1533 // LoopSink (and other loop passes since the last simplifyCFG) might have
1534 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1536 .convertSwitchRangeToICmp(true)
1537 .speculateUnpredictables(true)));
1538
1539 // Add the core optimizing pipeline.
1540 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1542
1544
1545 // Split out cold code. Splitting is done late to avoid hiding context from
1546 // other optimizations and inadvertently regressing performance. The tradeoff
1547 // is that this has a higher code size cost than splitting early.
1548 if (EnableHotColdSplit && !LTOPreLink)
1550
1551 // Search the code for similar regions of code. If enough similar regions can
1552 // be found where extracting the regions into their own function will decrease
1553 // the size of the program, we extract the regions, a deduplicate the
1554 // structurally similar regions.
1555 if (EnableIROutliner)
1557
1558 // Now we need to do some global optimization transforms.
1559 // FIXME: It would seem like these should come first in the optimization
1560 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1561 // ordering here.
1564
1565 // Merge functions if requested. It has a better chance to merge functions
1566 // after ConstantMerge folded jump tables.
1567 if (PTO.MergeFunctions)
1569
1570 if (PTO.CallGraphProfile && !LTOPreLink)
1573
1574 // TODO: Relative look table converter pass caused an issue when full lto is
1575 // enabled. See https://reviews.llvm.org/D94355 for more details.
1576 // Until the issue fixed, disable this pass during pre-linking phase.
1577 if (!LTOPreLink)
1579
1580 return MPM;
1581}
1582
1585 bool LTOPreLink) {
1586 if (Level == OptimizationLevel::O0)
1587 return buildO0DefaultPipeline(Level, LTOPreLink);
1588
1590
1591 // Convert @llvm.global.annotations to !annotation metadata.
1593
1594 // Force any function attributes we want the rest of the pipeline to observe.
1596
1597 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1599
1600 // Apply module pipeline start EP callback.
1602
1603 const ThinOrFullLTOPhase LTOPhase = LTOPreLink
1606 // Add the core simplification pipeline.
1608
1609 // Now add the optimization pipeline.
1611
1612 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1613 PGOOpt->Action == PGOOptions::SampleUse)
1615
1616 // Emit annotation remarks.
1618
1619 if (LTOPreLink)
1620 addRequiredLTOPreLinkPasses(MPM);
1621 return MPM;
1622}
1623
1626 bool EmitSummary) {
1628 if (ThinLTO)
1630 else
1632 MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary));
1633
1634 // Use the ThinLTO post-link pipeline with sample profiling
1635 if (ThinLTO && PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)
1636 MPM.addPass(buildThinLTODefaultPipeline(Level, /*ImportSummary=*/nullptr));
1637 else {
1638 // otherwise, just use module optimization
1639 MPM.addPass(
1641 // Emit annotation remarks.
1643 }
1644 return MPM;
1645}
1646
1649 if (Level == OptimizationLevel::O0)
1650 return buildO0DefaultPipeline(Level, /*LTOPreLink*/true);
1651
1653
1654 // Convert @llvm.global.annotations to !annotation metadata.
1656
1657 // Force any function attributes we want the rest of the pipeline to observe.
1659
1660 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1662
1663 // Apply module pipeline start EP callback.
1665
1666 // If we are planning to perform ThinLTO later, we don't bloat the code with
1667 // unrolling/vectorization/... now. Just simplify the module as much as we
1668 // can.
1671 // In pre-link, for ctx prof use, we stop here with an instrumented IR. We let
1672 // thinlto use the contextual info to perform imports; then use the contextual
1673 // profile in the post-thinlink phase.
1674 if (!UseCtxProfile.empty() && !PGOOpt) {
1675 addRequiredLTOPreLinkPasses(MPM);
1676 return MPM;
1677 }
1678
1679 // Run partial inlining pass to partially inline functions that have
1680 // large bodies.
1681 // FIXME: It isn't clear whether this is really the right place to run this
1682 // in ThinLTO. Because there is another canonicalization and simplification
1683 // phase that will run after the thin link, running this here ends up with
1684 // less information than will be available later and it may grow functions in
1685 // ways that aren't beneficial.
1688
1689 if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1690 PGOOpt->Action == PGOOptions::SampleUse)
1692
1693 // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1694 // optimization is going to be done in PostLink stage, but clang can't add
1695 // callbacks there in case of in-process ThinLTO called by linker.
1698
1699 // Emit annotation remarks.
1701
1702 addRequiredLTOPreLinkPasses(MPM);
1703
1704 return MPM;
1705}
1706
1708 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1710
1711 if (ImportSummary) {
1712 // For ThinLTO we must apply the context disambiguation decisions early, to
1713 // ensure we can correctly match the callsites to summary data.
1716
1717 // These passes import type identifier resolutions for whole-program
1718 // devirtualization and CFI. They must run early because other passes may
1719 // disturb the specific instruction patterns that these passes look for,
1720 // creating dependencies on resolutions that may not appear in the summary.
1721 //
1722 // For example, GVN may transform the pattern assume(type.test) appearing in
1723 // two basic blocks into assume(phi(type.test, type.test)), which would
1724 // transform a dependency on a WPD resolution into a dependency on a type
1725 // identifier resolution for CFI.
1726 //
1727 // Also, WPD has access to more precise information than ICP and can
1728 // devirtualize more effectively, so it should operate on the IR first.
1729 //
1730 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1731 // metadata and intrinsics.
1732 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1733 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1734 }
1735
1736 if (Level == OptimizationLevel::O0) {
1737 // Run a second time to clean up any type tests left behind by WPD for use
1738 // in ICP.
1739 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1740 // Drop available_externally and unreferenced globals. This is necessary
1741 // with ThinLTO in order to avoid leaving undefined references to dead
1742 // globals in the object file.
1745 return MPM;
1746 }
1747
1748 // Add the core simplification pipeline.
1751
1752 // Now add the optimization pipeline.
1755
1756 // Emit annotation remarks.
1758
1759 return MPM;
1760}
1761
1764 // FIXME: We should use a customized pre-link pipeline!
1765 return buildPerModuleDefaultPipeline(Level,
1766 /* LTOPreLink */ true);
1767}
1768
1771 ModuleSummaryIndex *ExportSummary) {
1773
1775
1776 // Create a function that performs CFI checks for cross-DSO calls with targets
1777 // in the current module.
1779
1780 if (Level == OptimizationLevel::O0) {
1781 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1782 // metadata and intrinsics.
1783 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1784 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1785 // Run a second time to clean up any type tests left behind by WPD for use
1786 // in ICP.
1787 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1788
1790
1791 // Emit annotation remarks.
1793
1794 return MPM;
1795 }
1796
1797 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1798 // Load sample profile before running the LTO optimization pipeline.
1799 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1800 PGOOpt->ProfileRemappingFile,
1802 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1803 // RequireAnalysisPass for PSI before subsequent non-module passes.
1805 }
1806
1807 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
1809
1810 // Remove unused virtual tables to improve the quality of code generated by
1811 // whole-program devirtualization and bitset lowering.
1812 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
1813
1814 // Do basic inference of function attributes from known properties of system
1815 // libraries and other oracles.
1817
1818 if (Level.getSpeedupLevel() > 1) {
1821
1822 // Indirect call promotion. This should promote all the targets that are
1823 // left by the earlier promotion pass that promotes intra-module targets.
1824 // This two-step promotion is to save the compile time. For LTO, it should
1825 // produce the same result as if we only do promotion here.
1827 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1828
1829 // Propagate constants at call sites into the functions they call. This
1830 // opens opportunities for globalopt (and inlining) by substituting function
1831 // pointers passed as arguments to direct uses of functions.
1832 MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/
1833 Level != OptimizationLevel::Os &&
1834 Level != OptimizationLevel::Oz)));
1835
1836 // Attach metadata to indirect call sites indicating the set of functions
1837 // they may target at run-time. This should follow IPSCCP.
1839 }
1840
1841 // Now deduce any function attributes based in the current code.
1842 MPM.addPass(
1844
1845 // Do RPO function attribute inference across the module to forward-propagate
1846 // attributes where applicable.
1847 // FIXME: Is this really an optimization rather than a canonicalization?
1849
1850 // Use in-range annotations on GEP indices to split globals where beneficial.
1852
1853 // Run whole program optimization of virtual call when the list of callees
1854 // is fixed.
1855 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1856
1857 // Stop here at -O1.
1858 if (Level == OptimizationLevel::O1) {
1859 // The LowerTypeTestsPass needs to run to lower type metadata and the
1860 // type.test intrinsics. The pass does nothing if CFI is disabled.
1861 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1862 // Run a second time to clean up any type tests left behind by WPD for use
1863 // in ICP (which is performed earlier than this in the regular LTO
1864 // pipeline).
1865 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1866
1868
1869 // Emit annotation remarks.
1871
1872 return MPM;
1873 }
1874
1875 // Optimize globals to try and fold them into constants.
1877
1878 // Promote any localized globals to SSA registers.
1880
1881 // Linking modules together can lead to duplicate global constant, only
1882 // keep one copy of each constant.
1884
1885 // Remove unused arguments from functions.
1887
1888 // Reduce the code after globalopt and ipsccp. Both can open up significant
1889 // simplification opportunities, and both can propagate functions through
1890 // function pointers. When this happens, we often have to resolve varargs
1891 // calls, etc, so let instcombine do this.
1892 FunctionPassManager PeepholeFPM;
1893 PeepholeFPM.addPass(InstCombinePass());
1894 if (Level.getSpeedupLevel() > 1)
1895 PeepholeFPM.addPass(AggressiveInstCombinePass());
1896 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1897
1898 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
1900
1901 // Lower variadic functions for supported targets prior to inlining.
1903
1904 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1905 // generally clean up exception handling overhead. It isn't clear this is
1906 // valuable as the inliner doesn't currently care whether it is inlining an
1907 // invoke or a call.
1908 // Run the inliner now.
1909 if (EnableModuleInliner) {
1913 } else {
1916 /* MandatoryFirst */ true,
1919 }
1920
1921 // Perform context disambiguation after inlining, since that would reduce the
1922 // amount of additional cloning required to distinguish the allocation
1923 // contexts.
1926
1927 // Optimize globals again after we ran the inliner.
1929
1930 // Run the OpenMPOpt pass again after global optimizations.
1932
1933 // Garbage collect dead functions.
1934 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
1935
1936 // If we didn't decide to inline a function, check to see if we can
1937 // transform it to pass arguments by value instead of by reference.
1939
1941 // The IPO Passes may leave cruft around. Clean up after them.
1942 FPM.addPass(InstCombinePass());
1943 invokePeepholeEPCallbacks(FPM, Level);
1944
1947
1949
1950 // Do a post inline PGO instrumentation and use pass. This is a context
1951 // sensitive PGO pass.
1952 if (PGOOpt) {
1953 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1954 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/true,
1955 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1956 PGOOpt->CSProfileGenFile, PGOOpt->ProfileRemappingFile,
1957 PGOOpt->FS);
1958 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1959 addPGOInstrPasses(MPM, Level, /*RunProfileGen=*/false,
1960 /*IsCS=*/true, PGOOpt->AtomicCounterUpdate,
1961 PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile,
1962 PGOOpt->FS);
1963 }
1964
1965 // Break up allocas
1967
1968 // LTO provides additional opportunities for tailcall elimination due to
1969 // link-time inlining, and visibility of nocapture attribute.
1971
1972 // Run a few AA driver optimizations here and now to cleanup the code.
1975
1976 MPM.addPass(
1978
1979 // Require the GlobalsAA analysis for the module so we can query it within
1980 // MainFPM.
1983 // Invalidate AAManager so it can be recreated and pick up the newly
1984 // available GlobalsAA.
1985 MPM.addPass(
1987 }
1988
1989 FunctionPassManager MainFPM;
1992 /*AllowSpeculation=*/true),
1993 /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/false));
1994
1995 if (RunNewGVN)
1996 MainFPM.addPass(NewGVNPass());
1997 else
1998 MainFPM.addPass(GVNPass());
1999
2000 // Remove dead memcpy()'s.
2001 MainFPM.addPass(MemCpyOptPass());
2002
2003 // Nuke dead stores.
2004 MainFPM.addPass(DSEPass());
2005 MainFPM.addPass(MoveAutoInitPass());
2007
2008 LoopPassManager LPM;
2009 if (EnableLoopFlatten && Level.getSpeedupLevel() > 1)
2010 LPM.addPass(LoopFlattenPass());
2013 // FIXME: Add loop interchange.
2014
2015 // Unroll small loops and perform peeling.
2016 LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
2017 /* OnlyWhenForced= */ !PTO.LoopUnrolling,
2019 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
2020 // *All* loop passes must preserve it, in order to be able to use it.
2022 std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true));
2023
2024 MainFPM.addPass(LoopDistributePass());
2025
2026 addVectorPasses(Level, MainFPM, /* IsFullLTO */ true);
2027
2028 // Run the OpenMPOpt CGSCC pass again late.
2031
2032 invokePeepholeEPCallbacks(MainFPM, Level);
2033 MainFPM.addPass(JumpThreadingPass());
2036
2037 // Lower type metadata and the type.test intrinsic. This pass supports
2038 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
2039 // to be run at link time if CFI is enabled. This pass does nothing if
2040 // CFI is disabled.
2041 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
2042 // Run a second time to clean up any type tests left behind by WPD for use
2043 // in ICP (which is performed earlier than this in the regular LTO pipeline).
2044 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
2045
2046 // Enable splitting late in the FullLTO post-link pipeline.
2049
2050 // Add late LTO optimization passes.
2051 FunctionPassManager LateFPM;
2052
2053 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
2054 // canonicalization pass that enables other optimizations. As a result,
2055 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
2056 // result too early.
2057 LateFPM.addPass(LoopSinkPass());
2058
2059 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
2060 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
2061 // flattening of blocks.
2062 LateFPM.addPass(DivRemPairsPass());
2063
2064 // Delete basic blocks, which optimization passes may have killed.
2066 .convertSwitchRangeToICmp(true)
2067 .hoistCommonInsts(true)
2068 .speculateUnpredictables(true)));
2069 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
2070
2071 // Drop bodies of available eternally objects to improve GlobalDCE.
2073
2074 // Now that we have optimized the program, discard unreachable functions.
2075 MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
2076
2077 if (PTO.MergeFunctions)
2079
2080 if (PTO.CallGraphProfile)
2081 MPM.addPass(CGProfilePass(/*InLTOPostLink=*/true));
2082
2084
2085 // Emit annotation remarks.
2087
2088 return MPM;
2089}
2090
2092 bool LTOPreLink) {
2093 assert(Level == OptimizationLevel::O0 &&
2094 "buildO0DefaultPipeline should only be used with O0");
2095
2097
2098 // Perform pseudo probe instrumentation in O0 mode. This is for the
2099 // consistency between different build modes. For example, a LTO build can be
2100 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
2101 // the postlink will require pseudo probe instrumentation in the prelink.
2102 if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
2104
2105 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
2106 PGOOpt->Action == PGOOptions::IRUse))
2108 MPM,
2109 /*RunProfileGen=*/(PGOOpt->Action == PGOOptions::IRInstr),
2110 /*IsCS=*/false, PGOOpt->AtomicCounterUpdate, PGOOpt->ProfileFile,
2111 PGOOpt->ProfileRemappingFile, PGOOpt->FS);
2112
2113 // Instrument function entry and exit before all inlining.
2115 EntryExitInstrumenterPass(/*PostInlining=*/false)));
2116
2118
2119 if (PGOOpt && PGOOpt->DebugInfoForProfiling)
2121
2123
2124 // Build a minimal pipeline based on the semantics required by LLVM,
2125 // which is just that always inlining occurs. Further, disable generating
2126 // lifetime intrinsics to avoid enabling further optimizations during
2127 // code generation.
2129 /*InsertLifetimeIntrinsics=*/false));
2130
2131 if (PTO.MergeFunctions)
2133
2134 if (EnableMatrix)
2135 MPM.addPass(
2137
2138 if (!CGSCCOptimizerLateEPCallbacks.empty()) {
2139 CGSCCPassManager CGPM;
2141 if (!CGPM.isEmpty())
2143 }
2144 if (!LateLoopOptimizationsEPCallbacks.empty()) {
2145 LoopPassManager LPM;
2147 if (!LPM.isEmpty()) {
2149 createFunctionToLoopPassAdaptor(std::move(LPM))));
2150 }
2151 }
2152 if (!LoopOptimizerEndEPCallbacks.empty()) {
2153 LoopPassManager LPM;
2155 if (!LPM.isEmpty()) {
2157 createFunctionToLoopPassAdaptor(std::move(LPM))));
2158 }
2159 }
2160 if (!ScalarOptimizerLateEPCallbacks.empty()) {
2163 if (!FPM.isEmpty())
2165 }
2166
2168
2169 if (!VectorizerStartEPCallbacks.empty()) {
2172 if (!FPM.isEmpty())
2174 }
2175
2176 ModulePassManager CoroPM;
2177 CoroPM.addPass(CoroEarlyPass());
2178 CGSCCPassManager CGPM;
2179 CGPM.addPass(CoroSplitPass());
2180 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
2181 CoroPM.addPass(CoroCleanupPass());
2182 CoroPM.addPass(GlobalDCEPass());
2183 MPM.addPass(CoroConditionalWrapper(std::move(CoroPM)));
2184
2186
2187 if (LTOPreLink)
2188 addRequiredLTOPreLinkPasses(MPM);
2189
2191
2192 return MPM;
2193}
2194
2196 AAManager AA;
2197
2198 // The order in which these are registered determines their priority when
2199 // being queried.
2200
2201 // First we register the basic alias analysis that provides the majority of
2202 // per-function local AA logic. This is a stateless, on-demand local set of
2203 // AA techniques.
2205
2206 // Next we query fast, specialized alias analyses that wrap IR-embedded
2207 // information about aliasing.
2210
2211 // Add support for querying global aliasing information when available.
2212 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2213 // analysis, all that the `AAManager` can do is query for any *cached*
2214 // results from `GlobalsAA` through a readonly proxy.
2217
2218 // Add target-specific alias analyses.
2219 if (TM)
2221
2222 return AA;
2223}
aarch64 falkor hwpf fix Falkor HW Prefetch Fix Late Phase
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.
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)
Definition: CommandLine.h:686
cl::opt< std::string > UseCtxProfile("use-ctx-profile", cl::init(""), cl::Hidden, cl::desc("Use the specified contextual profile file"))
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 ...
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...
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 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.
ModulePassManager MPM
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 > EnableGlobalAnalyses("enable-global-analyses", cl::init(true), cl::Hidden, cl::desc("Enable inter-procedural analyses"))
static cl::opt< bool > EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden, cl::desc("Enable ir outliner pass"))
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 > EnableEagerlyInvalidateAnalyses("eagerly-invalidate-analyses", cl::init(true), cl::Hidden, cl::desc("Eagerly invalidate more analyses in default pipelines"))
static cl::opt< bool > ExtraVectorizerPasses("extra-vectorizer-passes", cl::init(false), cl::Hidden, cl::desc("Run cleanup optimization passes after vectorization"))
static void addAnnotationRemarksPass(ModulePassManager &MPM)
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"))
static InlineParams getInlineParamsFromOptLevel(OptimizationLevel Level)
static cl::opt< bool > EnableGVNSink("enable-gvn-sink", cl::desc("Enable the GVN sinking pass (default = off)"))
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 inlinining pass"))
static cl::opt< bool > EnableGVNHoist("enable-gvn-hoist", cl::desc("Enable the GVN hoisting pass (default = off)"))
cl::opt< std::string > UseCtxProfile
static cl::opt< bool > EnableDFAJumpThreading("enable-dfa-jump-thread", cl::desc("Enable DFA jump threading"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableCHR("enable-chr", cl::init(true), cl::Hidden, cl::desc("Enable control height reduction optimization (CHR)"))
static cl::opt< bool > EnableHotColdSplit("hot-cold-split", cl::desc("Enable hot-cold splitting pass"))
static cl::opt< bool > EnableLoopInterchange("enable-loopinterchange", cl::init(false), cl::Hidden, cl::desc("Enable the experimental LoopInterchange Pass"))
static cl::opt< bool > EnableSampledInstr("enable-sampled-instrumentation", cl::init(false), cl::Hidden, cl::desc("Enable profile instrumentation sampling (default = off)"))
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 > EnableLoopHeaderDuplication("enable-loop-header-duplication", cl::init(false), cl::Hidden, cl::desc("Enable loop header duplication at any optimization level"))
static cl::opt< bool > EnablePGOForceFunctionAttrs("enable-pgo-force-function-attrs", cl::desc("Enable pass to set function attributes based on PGO profiles"), cl::init(false))
static cl::opt< bool > EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false), cl::Hidden, cl::desc("Enable Unroll And Jam Pass"))
static cl::opt< bool > EnableModuleInliner("enable-module-inliner", cl::init(false), cl::Hidden, cl::desc("Enable module inliner"))
static cl::opt< bool > EnableMatrix("enable-matrix", cl::init(false), cl::Hidden, cl::desc("Enable lowering of the matrix intrinsics"))
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::ALL, "all", "enable all attributor runs"), clEnumValN(AttributorRunOption::MODULE, "module", "enable module-wide attributor runs"), clEnumValN(AttributorRunOption::CGSCC, "cgscc", "enable call graph SCC attributor runs"), clEnumValN(AttributorRunOption::NONE, "none", "disable attributor runs")))
static cl::opt< bool > EnableOrderFileInstrumentation("enable-order-file-instrumentation", cl::init(false), cl::Hidden, cl::desc("Enable order file instrumentation (default = off)"))
static cl::opt< bool > UseLoopVersioningLICM("enable-loop-versioning-licm", cl::init(false), cl::Hidden, cl::desc("Enable the experimental Loop Versioning LICM pass"))
static cl::opt< bool > EnableSyntheticCounts("enable-npm-synthetic-counts", cl::Hidden, cl::desc("Run synthetic function entry count generation " "pass"))
static bool isLTOPreLink(ThinOrFullLTOPhase Phase)
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.
static cl::opt< bool > EnableJumpTableToSwitch("enable-jump-table-to-switch", cl::desc("Enable JumpTableToSwitch pass (default = off)"))
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 > FlattenedProfileUsed("flattened-profile-used", cl::init(false), cl::Hidden, cl::desc("Indicate the sample profile being used is flattened, i.e., " "no inline hierachy exists in the profile"))
static cl::opt< bool > EnableConstraintElimination("enable-constraint-elimination", cl::init(true), cl::Hidden, cl::desc("Enable pass to eliminate conditions based on linear constraints"))
static cl::opt< bool > EnableLoopFlatten("enable-loop-flatten", cl::init(false), cl::Hidden, cl::desc("Enable the LoopFlatten Pass"))
This header defines various interfaces for pass management in LLVM.
This file implements relative lookup table converter that converts lookup tables to relative lookup t...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
void registerFunctionAnalysis()
Register a specific AA result.
void registerModuleAnalysis()
Register a specific AA result.
Inlines functions marked as "always_inline".
Definition: AlwaysInliner.h:32
Argument promotion pass.
Assign a GUID to functions as metadata.
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.
Definition: ConstantMerge.h:29
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.
The core GVN pass object.
Definition: GVN.h:117
Pass to remove unused function declarations.
Definition: GlobalDCE.h:36
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
Pass to outline similar regions.
Definition: IROutliner.h:444
Run instruction simplification across each instruction in the function.
The instrumentation pass for recording function order.
Instrumentation based profiling lowering pass.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This pass performs 'jump threading', which looks at blocks that have multiple predecessors and multip...
Definition: JumpThreading.h:79
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.
Definition: LoopRotation.h:24
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.
Merge identical functions.
The module inliner pass for the new pass manager.
Definition: ModuleInliner.h:27
Module pass, wrapping the inliner pass.
Definition: Inliner.h:62
void addModulePass(T Pass)
Add a module pass that runs before the CGSCC passes.
Definition: Inliner.h:78
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.
OpenMP optimizations pass.
Definition: OpenMPOpt.h:42
static const OptimizationLevel O3
Optimize for fast execution as much as possible.
static const OptimizationLevel Oz
A very specialized mode that will optimize for code size at any and all costs.
static const OptimizationLevel O0
Disable as many optimizations as possible.
static const OptimizationLevel Os
Similar to O2 but tries to optimize for small code size instead of fast execution without triggering ...
static const OptimizationLevel O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
static const OptimizationLevel O1
Optimize quickly without destroying debuggability.
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.
ModulePassManager buildO0DefaultPipeline(OptimizationLevel Level, bool LTOPreLink=false)
Build an O0 pipeline with the minimal semantically required passes.
void invokeFullLinkTimeOptimizationLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
ModuleInlinerWrapperPass buildInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining as well as the inlining-driven cleanups.
void invokeOptimizerLastEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
void invokeVectorizerStartEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
AAManager buildDefaultAAPipeline()
Build the default AAManager with the default alias analysis pipeline registered.
void invokeCGSCCOptimizerLateEPCallbacks(CGSCCPassManager &CGPM, OptimizationLevel Level)
ModulePassManager buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, ThinLTO-targeting default optimization pipeline to a pass manager.
void invokeScalarOptimizerLateEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
ModulePassManager buildPerModuleDefaultPipeline(OptimizationLevel Level, bool LTOPreLink=false)
Build a per-module default optimization pipeline.
void invokePipelineStartEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
FunctionPassManager buildFunctionSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the core LLVM function canonicalization and simplification pipeline.
void invokePeepholeEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level)
void invokeLoopOptimizerEndEPCallbacks(LoopPassManager &LPM, OptimizationLevel Level)
ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
ModulePassManager buildModuleInlinerPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the module pipeline that performs inlining with module inliner pass.
ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary)
Build a ThinLTO default optimization pipeline to a pass manager.
void invokeLateLoopOptimizationsEPCallbacks(LoopPassManager &LPM, OptimizationLevel Level)
void invokeOptimizerEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
void invokePipelineEarlySimplificationEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
void invokeFullLinkTimeOptimizationEarlyEPCallbacks(ModulePassManager &MPM, OptimizationLevel Level)
ModulePassManager buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO, bool EmitSummary)
Build a fat object default optimization pipeline.
ModulePassManager buildModuleSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase)
Construct the core LLVM module canonicalization and simplification pipeline.
ModulePassManager buildModuleOptimizationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase LTOPhase)
Construct the core LLVM module optimization pipeline.
void addPGOInstrPassesForO0(ModulePassManager &MPM, bool RunProfileGen, bool IsCS, bool AtomicCounterUpdate, std::string ProfileFile, std::string ProfileRemappingFile, IntrusiveRefCntPtr< vfs::FileSystem > FS)
Add PGOInstrumenation passes for O0 only.
ModulePassManager buildLTOPreLinkDefaultPipeline(OptimizationLevel Level)
Build a pre-link, LTO-targeting default optimization pipeline to a pass manager.
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t< is_detected< HasRunOnLoopT, PassT >::value > addPass(PassT &&Pass)
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
Definition: PassManager.h:195
bool isEmpty() const
Returns if the pass manager contains any passes.
Definition: PassManager.h:217
unsigned LicmMssaNoAccForPromotionCap
Tuning option to disable promotion to scalars in LICM with MemorySSA, if the number of access is too ...
Definition: PassBuilder.h:74
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition: PassBuilder.h:59
int InlinerThreshold
Tuning option to override the default inliner threshold.
Definition: PassBuilder.h:88
bool CallGraphProfile
Tuning option to enable/disable call graph profile.
Definition: PassBuilder.h:78
bool MergeFunctions
Tuning option to enable/disable function merging.
Definition: PassBuilder.h:85
bool ForgetAllSCEVInLoopUnroll
Tuning option to forget all SCEV loops in LoopUnroll.
Definition: PassBuilder.h:66
unsigned LicmMssaOptCap
Tuning option to cap the number of calls to retrive clobbering accesses in MemorySSA,...
Definition: PassBuilder.h:70
bool LoopInterleaving
Tuning option to set loop interleaving on/off, set based on opt level.
Definition: PassBuilder.h:51
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:62
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition: PassBuilder.h:55
Reassociate commutative expressions.
Definition: Reassociate.h:85
A pass to do RPO deduction and propagation of function attributes.
Definition: FunctionAttrs.h:73
This pass performs function-level constant propagation and merging.
Definition: SCCP.h:29
The sample profiler data loader pass.
Definition: SampleProfile.h:39
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:29
virtual void registerDefaultAliasAnalyses(AAManager &)
Allow the target to register alias analyses with the AAManager for use with the new pass manager.
Analysis pass providing a never-invalidated alias analysis result.
Optimize scalar/vector interactions in IR using target cost models.
Definition: VectorCombine.h:23
Interfaces for registering analysis passes, producing common pass manager configurations,...
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:711
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
cl::opt< bool > EnableKnowledgeRetention
ModuleToFunctionPassAdaptor createModuleToFunctionPassAdaptor(FunctionPassT &&Pass, bool EagerlyInvalidate=false)
A function to deduce a function pass type and wrap it in the templated adaptor.
Definition: PassManager.h:848
@ MODULE
Definition: Attributor.h:6419
@ CGSCC
Definition: Attributor.h:6420
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
Definition: Pass.h:76
@ FullLTOPreLink
Full LTO prelink phase.
@ ThinLTOPostLink
ThinLTO postlink (backend compile) phase.
@ None
No LTO/ThinLTO behavior needed.
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
ModuleToPostOrderCGSCCPassAdaptor createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass)
A function to deduce a function 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.
cl::opt< bool > ForgetSCEVInLoopUnroll
bool AreStatisticsEnabled()
Check if statistics are enabled.
Definition: Statistic.cpp:139
cl::opt< bool > EnableInferAlignmentPass
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
cl::opt< unsigned > SetLicmMssaNoAccForPromotionCap
std::enable_if_t< is_detected< HasRunOnLoopT, LoopPassT >::value, FunctionToLoopPassAdaptor > createFunctionToLoopPassAdaptor(LoopPassT &&Pass, bool UseMemorySSA=false, bool UseBlockFrequencyInfo=false, bool UseBranchProbabilityInfo=false)
A function to deduce a loop pass type and wrap it in the templated adaptor.
cl::opt< unsigned > MaxDevirtIterations("max-devirt-iterations", cl::ReallyHidden, cl::init(4))
cl::opt< unsigned > SetLicmMssaOptCap
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.
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:30
A pass manager to run a set of extra function simplification passes after vectorization,...
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:392
Uses an "inverted" value numbering to decide the similarity of expressions and sinks similar expressi...
Definition: GVN.h:399
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,...
Definition: InlineAdvisor.h:59
Thresholds to tune inline cost analysis.
Definition: InlineCost.h:206
std::optional< int > HotCallSiteThreshold
Threshold to use when the callsite is considered hot.
Definition: InlineCost.h:223
int DefaultThreshold
The default threshold to start with for a callee.
Definition: InlineCost.h:208
std::optional< bool > EnableDeferral
Indicate whether we should allow inline deferral.
Definition: InlineCost.h:236
std::optional< int > HintThreshold
Threshold to use for callees with inline hint.
Definition: InlineCost.h:211
Options for the frontend instrumentation based profiling pass.
A no-op pass template which simply forces a specific analysis result to be invalidated.
Definition: PassManager.h:901
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.
Definition: FunctionAttrs.h:49
A utility pass template to force an analysis result to be available.
Definition: PassManager.h:874