xref: /freebsd-src/contrib/llvm-project/llvm/lib/Passes/PassBuilderPipelines.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1349cc55cSDimitry Andric //===- Construction of pass pipelines -------------------------------------===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric /// \file
9349cc55cSDimitry Andric ///
10349cc55cSDimitry Andric /// This file provides the implementation of the PassBuilder based on our
11349cc55cSDimitry Andric /// static pass registry as well as related functionality. It also provides
12349cc55cSDimitry Andric /// helpers to aid in analyzing, debugging, and testing passes and pass
13349cc55cSDimitry Andric /// pipelines.
14349cc55cSDimitry Andric ///
15349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
16349cc55cSDimitry Andric 
17*06c3fb27SDimitry Andric #include "llvm/ADT/Statistic.h"
18349cc55cSDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
19349cc55cSDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
20349cc55cSDimitry Andric #include "llvm/Analysis/CGSCCPassManager.h"
21349cc55cSDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
22349cc55cSDimitry Andric #include "llvm/Analysis/InlineAdvisor.h"
23349cc55cSDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
24349cc55cSDimitry Andric #include "llvm/Analysis/ScopedNoAliasAA.h"
25349cc55cSDimitry Andric #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
26349cc55cSDimitry Andric #include "llvm/IR/PassManager.h"
27349cc55cSDimitry Andric #include "llvm/Passes/OptimizationLevel.h"
28349cc55cSDimitry Andric #include "llvm/Passes/PassBuilder.h"
29349cc55cSDimitry Andric #include "llvm/Support/CommandLine.h"
30349cc55cSDimitry Andric #include "llvm/Support/ErrorHandling.h"
31349cc55cSDimitry Andric #include "llvm/Support/PGOOptions.h"
32*06c3fb27SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
33349cc55cSDimitry Andric #include "llvm/Target/TargetMachine.h"
34349cc55cSDimitry Andric #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
35349cc55cSDimitry Andric #include "llvm/Transforms/Coroutines/CoroCleanup.h"
3681ad6265SDimitry Andric #include "llvm/Transforms/Coroutines/CoroConditionalWrapper.h"
37349cc55cSDimitry Andric #include "llvm/Transforms/Coroutines/CoroEarly.h"
38349cc55cSDimitry Andric #include "llvm/Transforms/Coroutines/CoroElide.h"
39349cc55cSDimitry Andric #include "llvm/Transforms/Coroutines/CoroSplit.h"
40349cc55cSDimitry Andric #include "llvm/Transforms/IPO/AlwaysInliner.h"
41349cc55cSDimitry Andric #include "llvm/Transforms/IPO/Annotation2Metadata.h"
42349cc55cSDimitry Andric #include "llvm/Transforms/IPO/ArgumentPromotion.h"
43349cc55cSDimitry Andric #include "llvm/Transforms/IPO/Attributor.h"
44349cc55cSDimitry Andric #include "llvm/Transforms/IPO/CalledValuePropagation.h"
45349cc55cSDimitry Andric #include "llvm/Transforms/IPO/ConstantMerge.h"
46349cc55cSDimitry Andric #include "llvm/Transforms/IPO/CrossDSOCFI.h"
47349cc55cSDimitry Andric #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
48349cc55cSDimitry Andric #include "llvm/Transforms/IPO/ElimAvailExtern.h"
49*06c3fb27SDimitry Andric #include "llvm/Transforms/IPO/EmbedBitcodePass.h"
50349cc55cSDimitry Andric #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
51349cc55cSDimitry Andric #include "llvm/Transforms/IPO/FunctionAttrs.h"
52349cc55cSDimitry Andric #include "llvm/Transforms/IPO/GlobalDCE.h"
53349cc55cSDimitry Andric #include "llvm/Transforms/IPO/GlobalOpt.h"
54349cc55cSDimitry Andric #include "llvm/Transforms/IPO/GlobalSplit.h"
55349cc55cSDimitry Andric #include "llvm/Transforms/IPO/HotColdSplitting.h"
56349cc55cSDimitry Andric #include "llvm/Transforms/IPO/IROutliner.h"
57349cc55cSDimitry Andric #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
58349cc55cSDimitry Andric #include "llvm/Transforms/IPO/Inliner.h"
59349cc55cSDimitry Andric #include "llvm/Transforms/IPO/LowerTypeTests.h"
60*06c3fb27SDimitry Andric #include "llvm/Transforms/IPO/MemProfContextDisambiguation.h"
61349cc55cSDimitry Andric #include "llvm/Transforms/IPO/MergeFunctions.h"
62349cc55cSDimitry Andric #include "llvm/Transforms/IPO/ModuleInliner.h"
63349cc55cSDimitry Andric #include "llvm/Transforms/IPO/OpenMPOpt.h"
64349cc55cSDimitry Andric #include "llvm/Transforms/IPO/PartialInlining.h"
65349cc55cSDimitry Andric #include "llvm/Transforms/IPO/SCCP.h"
66349cc55cSDimitry Andric #include "llvm/Transforms/IPO/SampleProfile.h"
67349cc55cSDimitry Andric #include "llvm/Transforms/IPO/SampleProfileProbe.h"
68349cc55cSDimitry Andric #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
69349cc55cSDimitry Andric #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
70349cc55cSDimitry Andric #include "llvm/Transforms/InstCombine/InstCombine.h"
71349cc55cSDimitry Andric #include "llvm/Transforms/Instrumentation/CGProfile.h"
72349cc55cSDimitry Andric #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
73349cc55cSDimitry Andric #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
74349cc55cSDimitry Andric #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
75349cc55cSDimitry Andric #include "llvm/Transforms/Instrumentation/MemProfiler.h"
76349cc55cSDimitry Andric #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
77349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/ADCE.h"
78349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
79349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
80349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/BDCE.h"
81349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
82349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/ConstraintElimination.h"
83349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
84349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/DFAJumpThreading.h"
85349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
86349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/DivRemPairs.h"
87349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/EarlyCSE.h"
88349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/Float2Int.h"
89349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/GVN.h"
90349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/IndVarSimplify.h"
91349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
92349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/JumpThreading.h"
93349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LICM.h"
94349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopDeletion.h"
95349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopDistribute.h"
96349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopFlatten.h"
97349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
98349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
99349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopInterchange.h"
100349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
101349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopPassManager.h"
102349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopRotation.h"
103349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
104349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopSink.h"
105349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
106349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
107349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
108349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
109349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
110349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
111349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
112349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/NewGVN.h"
113349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/Reassociate.h"
114349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/SCCP.h"
115349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/SROA.h"
116349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
117349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/SimplifyCFG.h"
118349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
119349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
120349cc55cSDimitry Andric #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
121349cc55cSDimitry Andric #include "llvm/Transforms/Utils/AddDiscriminators.h"
122349cc55cSDimitry Andric #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
123349cc55cSDimitry Andric #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
124*06c3fb27SDimitry Andric #include "llvm/Transforms/Utils/CountVisits.h"
125349cc55cSDimitry Andric #include "llvm/Transforms/Utils/InjectTLIMappings.h"
126349cc55cSDimitry Andric #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
127349cc55cSDimitry Andric #include "llvm/Transforms/Utils/Mem2Reg.h"
128*06c3fb27SDimitry Andric #include "llvm/Transforms/Utils/MoveAutoInit.h"
129349cc55cSDimitry Andric #include "llvm/Transforms/Utils/NameAnonGlobals.h"
130349cc55cSDimitry Andric #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
131349cc55cSDimitry Andric #include "llvm/Transforms/Utils/SimplifyCFGOptions.h"
132349cc55cSDimitry Andric #include "llvm/Transforms/Vectorize/LoopVectorize.h"
133349cc55cSDimitry Andric #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
134349cc55cSDimitry Andric #include "llvm/Transforms/Vectorize/VectorCombine.h"
135349cc55cSDimitry Andric 
136349cc55cSDimitry Andric using namespace llvm;
137349cc55cSDimitry Andric 
138349cc55cSDimitry Andric static cl::opt<InliningAdvisorMode> UseInlineAdvisor(
139349cc55cSDimitry Andric     "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
140349cc55cSDimitry Andric     cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
141349cc55cSDimitry Andric     cl::values(clEnumValN(InliningAdvisorMode::Default, "default",
142bdd1243dSDimitry Andric                           "Heuristics-based inliner version"),
143349cc55cSDimitry Andric                clEnumValN(InliningAdvisorMode::Development, "development",
144bdd1243dSDimitry Andric                           "Use development mode (runtime-loadable model)"),
145349cc55cSDimitry Andric                clEnumValN(InliningAdvisorMode::Release, "release",
146bdd1243dSDimitry Andric                           "Use release mode (AOT-compiled model)")));
147349cc55cSDimitry Andric 
148349cc55cSDimitry Andric static cl::opt<bool> EnableSyntheticCounts(
14981ad6265SDimitry Andric     "enable-npm-synthetic-counts", cl::Hidden,
150349cc55cSDimitry Andric     cl::desc("Run synthetic function entry count generation "
151349cc55cSDimitry Andric              "pass"));
152349cc55cSDimitry Andric 
153349cc55cSDimitry Andric /// Flag to enable inline deferral during PGO.
154349cc55cSDimitry Andric static cl::opt<bool>
155349cc55cSDimitry Andric     EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
156349cc55cSDimitry Andric                             cl::Hidden,
157349cc55cSDimitry Andric                             cl::desc("Enable inline deferral during PGO"));
158349cc55cSDimitry Andric 
159349cc55cSDimitry Andric static cl::opt<bool> EnableModuleInliner("enable-module-inliner",
160349cc55cSDimitry Andric                                          cl::init(false), cl::Hidden,
161349cc55cSDimitry Andric                                          cl::desc("Enable module inliner"));
162349cc55cSDimitry Andric 
163349cc55cSDimitry Andric static cl::opt<bool> PerformMandatoryInliningsFirst(
16481ad6265SDimitry Andric     "mandatory-inlining-first", cl::init(true), cl::Hidden,
165349cc55cSDimitry Andric     cl::desc("Perform mandatory inlinings module-wide, before performing "
166bdd1243dSDimitry Andric              "inlining"));
167349cc55cSDimitry Andric 
168349cc55cSDimitry Andric static cl::opt<bool> EnableEagerlyInvalidateAnalyses(
169349cc55cSDimitry Andric     "eagerly-invalidate-analyses", cl::init(true), cl::Hidden,
170349cc55cSDimitry Andric     cl::desc("Eagerly invalidate more analyses in default pipelines"));
171349cc55cSDimitry Andric 
1720eae32dcSDimitry Andric static cl::opt<bool> EnableMergeFunctions(
1730eae32dcSDimitry Andric     "enable-merge-functions", cl::init(false), cl::Hidden,
1740eae32dcSDimitry Andric     cl::desc("Enable function merging as part of the optimization pipeline"));
1750eae32dcSDimitry Andric 
176bdd1243dSDimitry Andric static cl::opt<bool> EnablePostPGOLoopRotation(
177bdd1243dSDimitry Andric     "enable-post-pgo-loop-rotation", cl::init(true), cl::Hidden,
178bdd1243dSDimitry Andric     cl::desc("Run the loop rotation transformation after PGO instrumentation"));
179bdd1243dSDimitry Andric 
180bdd1243dSDimitry Andric static cl::opt<bool> EnableGlobalAnalyses(
181bdd1243dSDimitry Andric     "enable-global-analyses", cl::init(true), cl::Hidden,
182bdd1243dSDimitry Andric     cl::desc("Enable inter-procedural analyses"));
183bdd1243dSDimitry Andric 
184bdd1243dSDimitry Andric static cl::opt<bool>
185bdd1243dSDimitry Andric     RunPartialInlining("enable-partial-inlining", cl::init(false), cl::Hidden,
186bdd1243dSDimitry Andric                        cl::desc("Run Partial inlinining pass"));
187bdd1243dSDimitry Andric 
188bdd1243dSDimitry Andric static cl::opt<bool> ExtraVectorizerPasses(
189bdd1243dSDimitry Andric     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
190bdd1243dSDimitry Andric     cl::desc("Run cleanup optimization passes after vectorization"));
191bdd1243dSDimitry Andric 
192bdd1243dSDimitry Andric static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
193bdd1243dSDimitry Andric                                cl::desc("Run the NewGVN pass"));
194bdd1243dSDimitry Andric 
195bdd1243dSDimitry Andric static cl::opt<bool> EnableLoopInterchange(
196bdd1243dSDimitry Andric     "enable-loopinterchange", cl::init(false), cl::Hidden,
197bdd1243dSDimitry Andric     cl::desc("Enable the experimental LoopInterchange Pass"));
198bdd1243dSDimitry Andric 
199bdd1243dSDimitry Andric static cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam",
200bdd1243dSDimitry Andric                                         cl::init(false), cl::Hidden,
201bdd1243dSDimitry Andric                                         cl::desc("Enable Unroll And Jam Pass"));
202bdd1243dSDimitry Andric 
203bdd1243dSDimitry Andric static cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
204bdd1243dSDimitry Andric                                        cl::Hidden,
205bdd1243dSDimitry Andric                                        cl::desc("Enable the LoopFlatten Pass"));
206bdd1243dSDimitry Andric 
207bdd1243dSDimitry Andric static cl::opt<bool>
208bdd1243dSDimitry Andric     EnableDFAJumpThreading("enable-dfa-jump-thread",
209bdd1243dSDimitry Andric                            cl::desc("Enable DFA jump threading"),
210bdd1243dSDimitry Andric                            cl::init(false), cl::Hidden);
211bdd1243dSDimitry Andric 
212bdd1243dSDimitry Andric static cl::opt<bool>
213bdd1243dSDimitry Andric     EnableHotColdSplit("hot-cold-split",
214bdd1243dSDimitry Andric                        cl::desc("Enable hot-cold splitting pass"));
215bdd1243dSDimitry Andric 
216bdd1243dSDimitry Andric static cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false),
217bdd1243dSDimitry Andric                                       cl::Hidden,
218bdd1243dSDimitry Andric                                       cl::desc("Enable ir outliner pass"));
219bdd1243dSDimitry Andric 
220bdd1243dSDimitry Andric static cl::opt<bool>
221bdd1243dSDimitry Andric     DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
222bdd1243dSDimitry Andric                       cl::desc("Disable pre-instrumentation inliner"));
223bdd1243dSDimitry Andric 
224bdd1243dSDimitry Andric static cl::opt<int> PreInlineThreshold(
225bdd1243dSDimitry Andric     "preinline-threshold", cl::Hidden, cl::init(75),
226bdd1243dSDimitry Andric     cl::desc("Control the amount of inlining in pre-instrumentation inliner "
227bdd1243dSDimitry Andric              "(default = 75)"));
228bdd1243dSDimitry Andric 
229bdd1243dSDimitry Andric static cl::opt<bool>
230bdd1243dSDimitry Andric     EnableGVNHoist("enable-gvn-hoist",
231bdd1243dSDimitry Andric                    cl::desc("Enable the GVN hoisting pass (default = off)"));
232bdd1243dSDimitry Andric 
233bdd1243dSDimitry Andric static cl::opt<bool>
234bdd1243dSDimitry Andric     EnableGVNSink("enable-gvn-sink",
235bdd1243dSDimitry Andric                   cl::desc("Enable the GVN sinking pass (default = off)"));
236bdd1243dSDimitry Andric 
237bdd1243dSDimitry Andric // This option is used in simplifying testing SampleFDO optimizations for
238bdd1243dSDimitry Andric // profile loading.
239bdd1243dSDimitry Andric static cl::opt<bool>
240bdd1243dSDimitry Andric     EnableCHR("enable-chr", cl::init(true), cl::Hidden,
241bdd1243dSDimitry Andric               cl::desc("Enable control height reduction optimization (CHR)"));
242bdd1243dSDimitry Andric 
243bdd1243dSDimitry Andric static cl::opt<bool> FlattenedProfileUsed(
244bdd1243dSDimitry Andric     "flattened-profile-used", cl::init(false), cl::Hidden,
245bdd1243dSDimitry Andric     cl::desc("Indicate the sample profile being used is flattened, i.e., "
246bdd1243dSDimitry Andric              "no inline hierachy exists in the profile"));
247bdd1243dSDimitry Andric 
248bdd1243dSDimitry Andric static cl::opt<bool> EnableOrderFileInstrumentation(
249bdd1243dSDimitry Andric     "enable-order-file-instrumentation", cl::init(false), cl::Hidden,
250bdd1243dSDimitry Andric     cl::desc("Enable order file instrumentation (default = off)"));
251bdd1243dSDimitry Andric 
252bdd1243dSDimitry Andric static cl::opt<bool>
253bdd1243dSDimitry Andric     EnableMatrix("enable-matrix", cl::init(false), cl::Hidden,
254bdd1243dSDimitry Andric                  cl::desc("Enable lowering of the matrix intrinsics"));
255bdd1243dSDimitry Andric 
256bdd1243dSDimitry Andric static cl::opt<bool> EnableConstraintElimination(
257*06c3fb27SDimitry Andric     "enable-constraint-elimination", cl::init(true), cl::Hidden,
258bdd1243dSDimitry Andric     cl::desc(
259bdd1243dSDimitry Andric         "Enable pass to eliminate conditions based on linear constraints"));
260bdd1243dSDimitry Andric 
261bdd1243dSDimitry Andric static cl::opt<AttributorRunOption> AttributorRun(
262bdd1243dSDimitry Andric     "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
263bdd1243dSDimitry Andric     cl::desc("Enable the attributor inter-procedural deduction pass"),
264bdd1243dSDimitry Andric     cl::values(clEnumValN(AttributorRunOption::ALL, "all",
265bdd1243dSDimitry Andric                           "enable all attributor runs"),
266bdd1243dSDimitry Andric                clEnumValN(AttributorRunOption::MODULE, "module",
267bdd1243dSDimitry Andric                           "enable module-wide attributor runs"),
268bdd1243dSDimitry Andric                clEnumValN(AttributorRunOption::CGSCC, "cgscc",
269bdd1243dSDimitry Andric                           "enable call graph SCC attributor runs"),
270bdd1243dSDimitry Andric                clEnumValN(AttributorRunOption::NONE, "none",
271bdd1243dSDimitry Andric                           "disable attributor runs")));
272bdd1243dSDimitry Andric 
273*06c3fb27SDimitry Andric cl::opt<bool> EnableMemProfContextDisambiguation(
274*06c3fb27SDimitry Andric     "enable-memprof-context-disambiguation", cl::init(false), cl::Hidden,
275*06c3fb27SDimitry Andric     cl::ZeroOrMore, cl::desc("Enable MemProf context disambiguation"));
276*06c3fb27SDimitry Andric 
277349cc55cSDimitry Andric PipelineTuningOptions::PipelineTuningOptions() {
278349cc55cSDimitry Andric   LoopInterleaving = true;
279349cc55cSDimitry Andric   LoopVectorization = true;
280349cc55cSDimitry Andric   SLPVectorization = false;
281349cc55cSDimitry Andric   LoopUnrolling = true;
282349cc55cSDimitry Andric   ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
283349cc55cSDimitry Andric   LicmMssaOptCap = SetLicmMssaOptCap;
284349cc55cSDimitry Andric   LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
285349cc55cSDimitry Andric   CallGraphProfile = true;
286*06c3fb27SDimitry Andric   UnifiedLTO = false;
2870eae32dcSDimitry Andric   MergeFunctions = EnableMergeFunctions;
288bdd1243dSDimitry Andric   InlinerThreshold = -1;
289349cc55cSDimitry Andric   EagerlyInvalidateAnalyses = EnableEagerlyInvalidateAnalyses;
290349cc55cSDimitry Andric }
291349cc55cSDimitry Andric 
292349cc55cSDimitry Andric namespace llvm {
293349cc55cSDimitry Andric extern cl::opt<unsigned> MaxDevirtIterations;
294349cc55cSDimitry Andric extern cl::opt<bool> EnableKnowledgeRetention;
295349cc55cSDimitry Andric } // namespace llvm
296349cc55cSDimitry Andric 
297349cc55cSDimitry Andric void PassBuilder::invokePeepholeEPCallbacks(FunctionPassManager &FPM,
298349cc55cSDimitry Andric                                             OptimizationLevel Level) {
299349cc55cSDimitry Andric   for (auto &C : PeepholeEPCallbacks)
300349cc55cSDimitry Andric     C(FPM, Level);
301349cc55cSDimitry Andric }
302*06c3fb27SDimitry Andric void PassBuilder::invokeLateLoopOptimizationsEPCallbacks(
303*06c3fb27SDimitry Andric     LoopPassManager &LPM, OptimizationLevel Level) {
304*06c3fb27SDimitry Andric   for (auto &C : LateLoopOptimizationsEPCallbacks)
305*06c3fb27SDimitry Andric     C(LPM, Level);
306*06c3fb27SDimitry Andric }
307*06c3fb27SDimitry Andric void PassBuilder::invokeLoopOptimizerEndEPCallbacks(LoopPassManager &LPM,
308*06c3fb27SDimitry Andric                                                     OptimizationLevel Level) {
309*06c3fb27SDimitry Andric   for (auto &C : LoopOptimizerEndEPCallbacks)
310*06c3fb27SDimitry Andric     C(LPM, Level);
311*06c3fb27SDimitry Andric }
312*06c3fb27SDimitry Andric void PassBuilder::invokeScalarOptimizerLateEPCallbacks(
313*06c3fb27SDimitry Andric     FunctionPassManager &FPM, OptimizationLevel Level) {
314*06c3fb27SDimitry Andric   for (auto &C : ScalarOptimizerLateEPCallbacks)
315*06c3fb27SDimitry Andric     C(FPM, Level);
316*06c3fb27SDimitry Andric }
317*06c3fb27SDimitry Andric void PassBuilder::invokeCGSCCOptimizerLateEPCallbacks(CGSCCPassManager &CGPM,
318*06c3fb27SDimitry Andric                                                       OptimizationLevel Level) {
319*06c3fb27SDimitry Andric   for (auto &C : CGSCCOptimizerLateEPCallbacks)
320*06c3fb27SDimitry Andric     C(CGPM, Level);
321*06c3fb27SDimitry Andric }
322*06c3fb27SDimitry Andric void PassBuilder::invokeVectorizerStartEPCallbacks(FunctionPassManager &FPM,
323*06c3fb27SDimitry Andric                                                    OptimizationLevel Level) {
324*06c3fb27SDimitry Andric   for (auto &C : VectorizerStartEPCallbacks)
325*06c3fb27SDimitry Andric     C(FPM, Level);
326*06c3fb27SDimitry Andric }
327*06c3fb27SDimitry Andric void PassBuilder::invokeOptimizerEarlyEPCallbacks(ModulePassManager &MPM,
328*06c3fb27SDimitry Andric                                                   OptimizationLevel Level) {
329*06c3fb27SDimitry Andric   for (auto &C : OptimizerEarlyEPCallbacks)
330*06c3fb27SDimitry Andric     C(MPM, Level);
331*06c3fb27SDimitry Andric }
332*06c3fb27SDimitry Andric void PassBuilder::invokeOptimizerLastEPCallbacks(ModulePassManager &MPM,
333*06c3fb27SDimitry Andric                                                  OptimizationLevel Level) {
334*06c3fb27SDimitry Andric   for (auto &C : OptimizerLastEPCallbacks)
335*06c3fb27SDimitry Andric     C(MPM, Level);
336*06c3fb27SDimitry Andric }
337*06c3fb27SDimitry Andric void PassBuilder::invokeFullLinkTimeOptimizationEarlyEPCallbacks(
338*06c3fb27SDimitry Andric     ModulePassManager &MPM, OptimizationLevel Level) {
339*06c3fb27SDimitry Andric   for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
340*06c3fb27SDimitry Andric     C(MPM, Level);
341*06c3fb27SDimitry Andric }
342*06c3fb27SDimitry Andric void PassBuilder::invokeFullLinkTimeOptimizationLastEPCallbacks(
343*06c3fb27SDimitry Andric     ModulePassManager &MPM, OptimizationLevel Level) {
344*06c3fb27SDimitry Andric   for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
345*06c3fb27SDimitry Andric     C(MPM, Level);
346*06c3fb27SDimitry Andric }
347*06c3fb27SDimitry Andric void PassBuilder::invokePipelineStartEPCallbacks(ModulePassManager &MPM,
348*06c3fb27SDimitry Andric                                                  OptimizationLevel Level) {
349*06c3fb27SDimitry Andric   for (auto &C : PipelineStartEPCallbacks)
350*06c3fb27SDimitry Andric     C(MPM, Level);
351*06c3fb27SDimitry Andric }
352*06c3fb27SDimitry Andric void PassBuilder::invokePipelineEarlySimplificationEPCallbacks(
353*06c3fb27SDimitry Andric     ModulePassManager &MPM, OptimizationLevel Level) {
354*06c3fb27SDimitry Andric   for (auto &C : PipelineEarlySimplificationEPCallbacks)
355*06c3fb27SDimitry Andric     C(MPM, Level);
356*06c3fb27SDimitry Andric }
357349cc55cSDimitry Andric 
358349cc55cSDimitry Andric // Helper to add AnnotationRemarksPass.
359349cc55cSDimitry Andric static void addAnnotationRemarksPass(ModulePassManager &MPM) {
36081ad6265SDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass()));
361349cc55cSDimitry Andric }
362349cc55cSDimitry Andric 
363349cc55cSDimitry Andric // Helper to check if the current compilation phase is preparing for LTO
364349cc55cSDimitry Andric static bool isLTOPreLink(ThinOrFullLTOPhase Phase) {
365349cc55cSDimitry Andric   return Phase == ThinOrFullLTOPhase::ThinLTOPreLink ||
366349cc55cSDimitry Andric          Phase == ThinOrFullLTOPhase::FullLTOPreLink;
367349cc55cSDimitry Andric }
368349cc55cSDimitry Andric 
369349cc55cSDimitry Andric // TODO: Investigate the cost/benefit of tail call elimination on debugging.
370349cc55cSDimitry Andric FunctionPassManager
371349cc55cSDimitry Andric PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
372349cc55cSDimitry Andric                                                    ThinOrFullLTOPhase Phase) {
373349cc55cSDimitry Andric 
374349cc55cSDimitry Andric   FunctionPassManager FPM;
375349cc55cSDimitry Andric 
376*06c3fb27SDimitry Andric   if (AreStatisticsEnabled())
377*06c3fb27SDimitry Andric     FPM.addPass(CountVisitsPass());
378*06c3fb27SDimitry Andric 
379349cc55cSDimitry Andric   // Form SSA out of local memory accesses after breaking apart aggregates into
380349cc55cSDimitry Andric   // scalars.
381bdd1243dSDimitry Andric   FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
382349cc55cSDimitry Andric 
383349cc55cSDimitry Andric   // Catch trivial redundancies
384349cc55cSDimitry Andric   FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
385349cc55cSDimitry Andric 
386349cc55cSDimitry Andric   // Hoisting of scalars and load expressions.
387fb03ea46SDimitry Andric   FPM.addPass(
388fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
389349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
390349cc55cSDimitry Andric 
391349cc55cSDimitry Andric   FPM.addPass(LibCallsShrinkWrapPass());
392349cc55cSDimitry Andric 
393349cc55cSDimitry Andric   invokePeepholeEPCallbacks(FPM, Level);
394349cc55cSDimitry Andric 
395fb03ea46SDimitry Andric   FPM.addPass(
396fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
397349cc55cSDimitry Andric 
398349cc55cSDimitry Andric   // Form canonically associated expression trees, and simplify the trees using
399349cc55cSDimitry Andric   // basic mathematical properties. For example, this will form (nearly)
400349cc55cSDimitry Andric   // minimal multiplication trees.
401349cc55cSDimitry Andric   FPM.addPass(ReassociatePass());
402349cc55cSDimitry Andric 
403349cc55cSDimitry Andric   // Add the primary loop simplification pipeline.
404349cc55cSDimitry Andric   // FIXME: Currently this is split into two loop pass pipelines because we run
405349cc55cSDimitry Andric   // some function passes in between them. These can and should be removed
406349cc55cSDimitry Andric   // and/or replaced by scheduling the loop pass equivalents in the correct
407349cc55cSDimitry Andric   // positions. But those equivalent passes aren't powerful enough yet.
408349cc55cSDimitry Andric   // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
409349cc55cSDimitry Andric   // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
410349cc55cSDimitry Andric   // fully replace `SimplifyCFGPass`, and the closest to the other we have is
411349cc55cSDimitry Andric   // `LoopInstSimplify`.
412349cc55cSDimitry Andric   LoopPassManager LPM1, LPM2;
413349cc55cSDimitry Andric 
414349cc55cSDimitry Andric   // Simplify the loop body. We do this initially to clean up after other loop
415349cc55cSDimitry Andric   // passes run, either when iterating on a loop or on inner loops with
416349cc55cSDimitry Andric   // implications on the outer loop.
417349cc55cSDimitry Andric   LPM1.addPass(LoopInstSimplifyPass());
418349cc55cSDimitry Andric   LPM1.addPass(LoopSimplifyCFGPass());
419349cc55cSDimitry Andric 
420349cc55cSDimitry Andric   // Try to remove as much code from the loop header as possible,
421fb03ea46SDimitry Andric   // to reduce amount of IR that will have to be duplicated. However,
422fb03ea46SDimitry Andric   // do not perform speculative hoisting the first time as LICM
423fb03ea46SDimitry Andric   // will destroy metadata that may not need to be destroyed if run
424fb03ea46SDimitry Andric   // after loop rotation.
425349cc55cSDimitry Andric   // TODO: Investigate promotion cap for O1.
426fb03ea46SDimitry Andric   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
427fb03ea46SDimitry Andric                         /*AllowSpeculation=*/false));
428349cc55cSDimitry Andric 
429349cc55cSDimitry Andric   LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true,
430349cc55cSDimitry Andric                               isLTOPreLink(Phase)));
431349cc55cSDimitry Andric   // TODO: Investigate promotion cap for O1.
432fb03ea46SDimitry Andric   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
433fb03ea46SDimitry Andric                         /*AllowSpeculation=*/true));
434349cc55cSDimitry Andric   LPM1.addPass(SimpleLoopUnswitchPass());
43504eeddc0SDimitry Andric   if (EnableLoopFlatten)
43604eeddc0SDimitry Andric     LPM1.addPass(LoopFlattenPass());
437349cc55cSDimitry Andric 
438349cc55cSDimitry Andric   LPM2.addPass(LoopIdiomRecognizePass());
439349cc55cSDimitry Andric   LPM2.addPass(IndVarSimplifyPass());
440349cc55cSDimitry Andric 
441*06c3fb27SDimitry Andric   invokeLateLoopOptimizationsEPCallbacks(LPM2, Level);
442349cc55cSDimitry Andric 
443349cc55cSDimitry Andric   LPM2.addPass(LoopDeletionPass());
444349cc55cSDimitry Andric 
445349cc55cSDimitry Andric   if (EnableLoopInterchange)
446349cc55cSDimitry Andric     LPM2.addPass(LoopInterchangePass());
447349cc55cSDimitry Andric 
448349cc55cSDimitry Andric   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
449349cc55cSDimitry Andric   // because it changes IR to makes profile annotation in back compile
450349cc55cSDimitry Andric   // inaccurate. The normal unroller doesn't pay attention to forced full unroll
451349cc55cSDimitry Andric   // attributes so we need to make sure and allow the full unroll pass to pay
452349cc55cSDimitry Andric   // attention to it.
453349cc55cSDimitry Andric   if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
454349cc55cSDimitry Andric       PGOOpt->Action != PGOOptions::SampleUse)
455349cc55cSDimitry Andric     LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
456349cc55cSDimitry Andric                                     /* OnlyWhenForced= */ !PTO.LoopUnrolling,
457349cc55cSDimitry Andric                                     PTO.ForgetAllSCEVInLoopUnroll));
458349cc55cSDimitry Andric 
459*06c3fb27SDimitry Andric   invokeLoopOptimizerEndEPCallbacks(LPM2, Level);
460349cc55cSDimitry Andric 
461349cc55cSDimitry Andric   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
462349cc55cSDimitry Andric                                               /*UseMemorySSA=*/true,
463349cc55cSDimitry Andric                                               /*UseBlockFrequencyInfo=*/true));
464fb03ea46SDimitry Andric   FPM.addPass(
465fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
466349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
467349cc55cSDimitry Andric   // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
468349cc55cSDimitry Andric   // *All* loop passes must preserve it, in order to be able to use it.
469349cc55cSDimitry Andric   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
470349cc55cSDimitry Andric                                               /*UseMemorySSA=*/false,
471349cc55cSDimitry Andric                                               /*UseBlockFrequencyInfo=*/false));
472349cc55cSDimitry Andric 
473349cc55cSDimitry Andric   // Delete small array after loop unroll.
474bdd1243dSDimitry Andric   FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
475349cc55cSDimitry Andric 
476349cc55cSDimitry Andric   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
477349cc55cSDimitry Andric   FPM.addPass(MemCpyOptPass());
478349cc55cSDimitry Andric 
479349cc55cSDimitry Andric   // Sparse conditional constant propagation.
480349cc55cSDimitry Andric   // FIXME: It isn't clear why we do this *after* loop passes rather than
481349cc55cSDimitry Andric   // before...
482349cc55cSDimitry Andric   FPM.addPass(SCCPPass());
483349cc55cSDimitry Andric 
484349cc55cSDimitry Andric   // Delete dead bit computations (instcombine runs after to fold away the dead
485349cc55cSDimitry Andric   // computations, and then ADCE will run later to exploit any new DCE
486349cc55cSDimitry Andric   // opportunities that creates).
487349cc55cSDimitry Andric   FPM.addPass(BDCEPass());
488349cc55cSDimitry Andric 
489349cc55cSDimitry Andric   // Run instcombine after redundancy and dead bit elimination to exploit
490349cc55cSDimitry Andric   // opportunities opened up by them.
491349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
492349cc55cSDimitry Andric   invokePeepholeEPCallbacks(FPM, Level);
493349cc55cSDimitry Andric 
494349cc55cSDimitry Andric   FPM.addPass(CoroElidePass());
495349cc55cSDimitry Andric 
496*06c3fb27SDimitry Andric   invokeScalarOptimizerLateEPCallbacks(FPM, Level);
497349cc55cSDimitry Andric 
498349cc55cSDimitry Andric   // Finally, do an expensive DCE pass to catch all the dead code exposed by
499349cc55cSDimitry Andric   // the simplifications and basic cleanup after all the simplifications.
500349cc55cSDimitry Andric   // TODO: Investigate if this is too expensive.
501349cc55cSDimitry Andric   FPM.addPass(ADCEPass());
502fb03ea46SDimitry Andric   FPM.addPass(
503fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
504349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
505349cc55cSDimitry Andric   invokePeepholeEPCallbacks(FPM, Level);
506349cc55cSDimitry Andric 
507349cc55cSDimitry Andric   return FPM;
508349cc55cSDimitry Andric }
509349cc55cSDimitry Andric 
510349cc55cSDimitry Andric FunctionPassManager
511349cc55cSDimitry Andric PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
512349cc55cSDimitry Andric                                                  ThinOrFullLTOPhase Phase) {
513349cc55cSDimitry Andric   assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
514349cc55cSDimitry Andric 
515349cc55cSDimitry Andric   // The O1 pipeline has a separate pipeline creation function to simplify
516349cc55cSDimitry Andric   // construction readability.
517349cc55cSDimitry Andric   if (Level.getSpeedupLevel() == 1)
518349cc55cSDimitry Andric     return buildO1FunctionSimplificationPipeline(Level, Phase);
519349cc55cSDimitry Andric 
520349cc55cSDimitry Andric   FunctionPassManager FPM;
521349cc55cSDimitry Andric 
522*06c3fb27SDimitry Andric   if (AreStatisticsEnabled())
523*06c3fb27SDimitry Andric     FPM.addPass(CountVisitsPass());
524*06c3fb27SDimitry Andric 
525349cc55cSDimitry Andric   // Form SSA out of local memory accesses after breaking apart aggregates into
526349cc55cSDimitry Andric   // scalars.
527bdd1243dSDimitry Andric   FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
528349cc55cSDimitry Andric 
529349cc55cSDimitry Andric   // Catch trivial redundancies
530349cc55cSDimitry Andric   FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
531349cc55cSDimitry Andric   if (EnableKnowledgeRetention)
532349cc55cSDimitry Andric     FPM.addPass(AssumeSimplifyPass());
533349cc55cSDimitry Andric 
534349cc55cSDimitry Andric   // Hoisting of scalars and load expressions.
535349cc55cSDimitry Andric   if (EnableGVNHoist)
536349cc55cSDimitry Andric     FPM.addPass(GVNHoistPass());
537349cc55cSDimitry Andric 
538349cc55cSDimitry Andric   // Global value numbering based sinking.
539349cc55cSDimitry Andric   if (EnableGVNSink) {
540349cc55cSDimitry Andric     FPM.addPass(GVNSinkPass());
541fb03ea46SDimitry Andric     FPM.addPass(
542fb03ea46SDimitry Andric         SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
543349cc55cSDimitry Andric   }
544349cc55cSDimitry Andric 
545349cc55cSDimitry Andric   // Speculative execution if the target has divergent branches; otherwise nop.
546349cc55cSDimitry Andric   FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
547349cc55cSDimitry Andric 
548349cc55cSDimitry Andric   // Optimize based on known information about branches, and cleanup afterward.
549349cc55cSDimitry Andric   FPM.addPass(JumpThreadingPass());
550349cc55cSDimitry Andric   FPM.addPass(CorrelatedValuePropagationPass());
551349cc55cSDimitry Andric 
552fb03ea46SDimitry Andric   FPM.addPass(
553fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
5540eae32dcSDimitry Andric   FPM.addPass(InstCombinePass());
555349cc55cSDimitry Andric   FPM.addPass(AggressiveInstCombinePass());
556349cc55cSDimitry Andric 
557bdd1243dSDimitry Andric   if (EnableConstraintElimination)
558bdd1243dSDimitry Andric     FPM.addPass(ConstraintEliminationPass());
559bdd1243dSDimitry Andric 
560349cc55cSDimitry Andric   if (!Level.isOptimizingForSize())
561349cc55cSDimitry Andric     FPM.addPass(LibCallsShrinkWrapPass());
562349cc55cSDimitry Andric 
563349cc55cSDimitry Andric   invokePeepholeEPCallbacks(FPM, Level);
564349cc55cSDimitry Andric 
565349cc55cSDimitry Andric   // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
566349cc55cSDimitry Andric   // using the size value profile. Don't perform this when optimizing for size.
567349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
568349cc55cSDimitry Andric       !Level.isOptimizingForSize())
569349cc55cSDimitry Andric     FPM.addPass(PGOMemOPSizeOpt());
570349cc55cSDimitry Andric 
571349cc55cSDimitry Andric   FPM.addPass(TailCallElimPass());
572fb03ea46SDimitry Andric   FPM.addPass(
573fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
574349cc55cSDimitry Andric 
575349cc55cSDimitry Andric   // Form canonically associated expression trees, and simplify the trees using
576349cc55cSDimitry Andric   // basic mathematical properties. For example, this will form (nearly)
577349cc55cSDimitry Andric   // minimal multiplication trees.
578349cc55cSDimitry Andric   FPM.addPass(ReassociatePass());
579349cc55cSDimitry Andric 
580349cc55cSDimitry Andric   // Add the primary loop simplification pipeline.
581349cc55cSDimitry Andric   // FIXME: Currently this is split into two loop pass pipelines because we run
582349cc55cSDimitry Andric   // some function passes in between them. These can and should be removed
583349cc55cSDimitry Andric   // and/or replaced by scheduling the loop pass equivalents in the correct
584349cc55cSDimitry Andric   // positions. But those equivalent passes aren't powerful enough yet.
585349cc55cSDimitry Andric   // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
586349cc55cSDimitry Andric   // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
587349cc55cSDimitry Andric   // fully replace `SimplifyCFGPass`, and the closest to the other we have is
588349cc55cSDimitry Andric   // `LoopInstSimplify`.
589349cc55cSDimitry Andric   LoopPassManager LPM1, LPM2;
590349cc55cSDimitry Andric 
591349cc55cSDimitry Andric   // Simplify the loop body. We do this initially to clean up after other loop
592349cc55cSDimitry Andric   // passes run, either when iterating on a loop or on inner loops with
593349cc55cSDimitry Andric   // implications on the outer loop.
594349cc55cSDimitry Andric   LPM1.addPass(LoopInstSimplifyPass());
595349cc55cSDimitry Andric   LPM1.addPass(LoopSimplifyCFGPass());
596349cc55cSDimitry Andric 
597349cc55cSDimitry Andric   // Try to remove as much code from the loop header as possible,
598fb03ea46SDimitry Andric   // to reduce amount of IR that will have to be duplicated. However,
599fb03ea46SDimitry Andric   // do not perform speculative hoisting the first time as LICM
600fb03ea46SDimitry Andric   // will destroy metadata that may not need to be destroyed if run
601fb03ea46SDimitry Andric   // after loop rotation.
602349cc55cSDimitry Andric   // TODO: Investigate promotion cap for O1.
603fb03ea46SDimitry Andric   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
604fb03ea46SDimitry Andric                         /*AllowSpeculation=*/false));
605349cc55cSDimitry Andric 
606349cc55cSDimitry Andric   // Disable header duplication in loop rotation at -Oz.
607349cc55cSDimitry Andric   LPM1.addPass(
608349cc55cSDimitry Andric       LoopRotatePass(Level != OptimizationLevel::Oz, isLTOPreLink(Phase)));
609349cc55cSDimitry Andric   // TODO: Investigate promotion cap for O1.
610fb03ea46SDimitry Andric   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
611fb03ea46SDimitry Andric                         /*AllowSpeculation=*/true));
612349cc55cSDimitry Andric   LPM1.addPass(
613*06c3fb27SDimitry Andric       SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3));
61404eeddc0SDimitry Andric   if (EnableLoopFlatten)
61504eeddc0SDimitry Andric     LPM1.addPass(LoopFlattenPass());
61604eeddc0SDimitry Andric 
617349cc55cSDimitry Andric   LPM2.addPass(LoopIdiomRecognizePass());
618349cc55cSDimitry Andric   LPM2.addPass(IndVarSimplifyPass());
619349cc55cSDimitry Andric 
620*06c3fb27SDimitry Andric   invokeLateLoopOptimizationsEPCallbacks(LPM2, Level);
621349cc55cSDimitry Andric 
622349cc55cSDimitry Andric   LPM2.addPass(LoopDeletionPass());
623349cc55cSDimitry Andric 
624349cc55cSDimitry Andric   if (EnableLoopInterchange)
625349cc55cSDimitry Andric     LPM2.addPass(LoopInterchangePass());
626349cc55cSDimitry Andric 
627349cc55cSDimitry Andric   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
628349cc55cSDimitry Andric   // because it changes IR to makes profile annotation in back compile
629349cc55cSDimitry Andric   // inaccurate. The normal unroller doesn't pay attention to forced full unroll
630349cc55cSDimitry Andric   // attributes so we need to make sure and allow the full unroll pass to pay
631349cc55cSDimitry Andric   // attention to it.
632349cc55cSDimitry Andric   if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
633349cc55cSDimitry Andric       PGOOpt->Action != PGOOptions::SampleUse)
634349cc55cSDimitry Andric     LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
635349cc55cSDimitry Andric                                     /* OnlyWhenForced= */ !PTO.LoopUnrolling,
636349cc55cSDimitry Andric                                     PTO.ForgetAllSCEVInLoopUnroll));
637349cc55cSDimitry Andric 
638*06c3fb27SDimitry Andric   invokeLoopOptimizerEndEPCallbacks(LPM2, Level);
639349cc55cSDimitry Andric 
640349cc55cSDimitry Andric   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
641349cc55cSDimitry Andric                                               /*UseMemorySSA=*/true,
642349cc55cSDimitry Andric                                               /*UseBlockFrequencyInfo=*/true));
643fb03ea46SDimitry Andric   FPM.addPass(
644fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
645349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
646349cc55cSDimitry Andric   // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
647349cc55cSDimitry Andric   // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
648349cc55cSDimitry Andric   // *All* loop passes must preserve it, in order to be able to use it.
649349cc55cSDimitry Andric   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
650349cc55cSDimitry Andric                                               /*UseMemorySSA=*/false,
651349cc55cSDimitry Andric                                               /*UseBlockFrequencyInfo=*/false));
652349cc55cSDimitry Andric 
653349cc55cSDimitry Andric   // Delete small array after loop unroll.
654bdd1243dSDimitry Andric   FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
655349cc55cSDimitry Andric 
656bdd1243dSDimitry Andric   // Try vectorization/scalarization transforms that are both improvements
657bdd1243dSDimitry Andric   // themselves and can allow further folds with GVN and InstCombine.
658bdd1243dSDimitry Andric   FPM.addPass(VectorCombinePass(/*TryEarlyFoldsOnly=*/true));
659349cc55cSDimitry Andric 
660349cc55cSDimitry Andric   // Eliminate redundancies.
661349cc55cSDimitry Andric   FPM.addPass(MergedLoadStoreMotionPass());
662349cc55cSDimitry Andric   if (RunNewGVN)
663349cc55cSDimitry Andric     FPM.addPass(NewGVNPass());
664349cc55cSDimitry Andric   else
665349cc55cSDimitry Andric     FPM.addPass(GVNPass());
666349cc55cSDimitry Andric 
667349cc55cSDimitry Andric   // Sparse conditional constant propagation.
668349cc55cSDimitry Andric   // FIXME: It isn't clear why we do this *after* loop passes rather than
669349cc55cSDimitry Andric   // before...
670349cc55cSDimitry Andric   FPM.addPass(SCCPPass());
671349cc55cSDimitry Andric 
672349cc55cSDimitry Andric   // Delete dead bit computations (instcombine runs after to fold away the dead
673349cc55cSDimitry Andric   // computations, and then ADCE will run later to exploit any new DCE
674349cc55cSDimitry Andric   // opportunities that creates).
675349cc55cSDimitry Andric   FPM.addPass(BDCEPass());
676349cc55cSDimitry Andric 
677349cc55cSDimitry Andric   // Run instcombine after redundancy and dead bit elimination to exploit
678349cc55cSDimitry Andric   // opportunities opened up by them.
679349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
680349cc55cSDimitry Andric   invokePeepholeEPCallbacks(FPM, Level);
681349cc55cSDimitry Andric 
682349cc55cSDimitry Andric   // Re-consider control flow based optimizations after redundancy elimination,
683349cc55cSDimitry Andric   // redo DCE, etc.
684349cc55cSDimitry Andric   if (EnableDFAJumpThreading && Level.getSizeLevel() == 0)
685349cc55cSDimitry Andric     FPM.addPass(DFAJumpThreadingPass());
686349cc55cSDimitry Andric 
687349cc55cSDimitry Andric   FPM.addPass(JumpThreadingPass());
688349cc55cSDimitry Andric   FPM.addPass(CorrelatedValuePropagationPass());
689349cc55cSDimitry Andric 
690349cc55cSDimitry Andric   // Finally, do an expensive DCE pass to catch all the dead code exposed by
691349cc55cSDimitry Andric   // the simplifications and basic cleanup after all the simplifications.
692349cc55cSDimitry Andric   // TODO: Investigate if this is too expensive.
693349cc55cSDimitry Andric   FPM.addPass(ADCEPass());
694349cc55cSDimitry Andric 
695349cc55cSDimitry Andric   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
696349cc55cSDimitry Andric   FPM.addPass(MemCpyOptPass());
697349cc55cSDimitry Andric 
698349cc55cSDimitry Andric   FPM.addPass(DSEPass());
699*06c3fb27SDimitry Andric   FPM.addPass(MoveAutoInitPass());
700*06c3fb27SDimitry Andric 
701349cc55cSDimitry Andric   FPM.addPass(createFunctionToLoopPassAdaptor(
702fb03ea46SDimitry Andric       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
703fb03ea46SDimitry Andric                /*AllowSpeculation=*/true),
704*06c3fb27SDimitry Andric       /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/false));
705349cc55cSDimitry Andric 
706349cc55cSDimitry Andric   FPM.addPass(CoroElidePass());
707349cc55cSDimitry Andric 
708*06c3fb27SDimitry Andric   invokeScalarOptimizerLateEPCallbacks(FPM, Level);
709349cc55cSDimitry Andric 
710fb03ea46SDimitry Andric   FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
711fb03ea46SDimitry Andric                                   .convertSwitchRangeToICmp(true)
712fb03ea46SDimitry Andric                                   .hoistCommonInsts(true)
713fb03ea46SDimitry Andric                                   .sinkCommonInsts(true)));
714349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
715349cc55cSDimitry Andric   invokePeepholeEPCallbacks(FPM, Level);
716349cc55cSDimitry Andric 
717349cc55cSDimitry Andric   return FPM;
718349cc55cSDimitry Andric }
719349cc55cSDimitry Andric 
720349cc55cSDimitry Andric void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
721349cc55cSDimitry Andric   MPM.addPass(CanonicalizeAliasesPass());
722349cc55cSDimitry Andric   MPM.addPass(NameAnonGlobalPass());
723349cc55cSDimitry Andric }
724349cc55cSDimitry Andric 
725349cc55cSDimitry Andric void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
726349cc55cSDimitry Andric                                     OptimizationLevel Level, bool RunProfileGen,
727349cc55cSDimitry Andric                                     bool IsCS, std::string ProfileFile,
72881ad6265SDimitry Andric                                     std::string ProfileRemappingFile,
729*06c3fb27SDimitry Andric                                     ThinOrFullLTOPhase LTOPhase,
730*06c3fb27SDimitry Andric                                     IntrusiveRefCntPtr<vfs::FileSystem> FS) {
731349cc55cSDimitry Andric   assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
732349cc55cSDimitry Andric   if (!IsCS && !DisablePreInliner) {
733349cc55cSDimitry Andric     InlineParams IP;
734349cc55cSDimitry Andric 
735349cc55cSDimitry Andric     IP.DefaultThreshold = PreInlineThreshold;
736349cc55cSDimitry Andric 
737349cc55cSDimitry Andric     // FIXME: The hint threshold has the same value used by the regular inliner
738349cc55cSDimitry Andric     // when not optimzing for size. This should probably be lowered after
739349cc55cSDimitry Andric     // performance testing.
740349cc55cSDimitry Andric     // FIXME: this comment is cargo culted from the old pass manager, revisit).
741349cc55cSDimitry Andric     IP.HintThreshold = Level.isOptimizingForSize() ? PreInlineThreshold : 325;
74281ad6265SDimitry Andric     ModuleInlinerWrapperPass MIWP(
74381ad6265SDimitry Andric         IP, /* MandatoryFirst */ true,
74481ad6265SDimitry Andric         InlineContext{LTOPhase, InlinePass::EarlyInliner});
745349cc55cSDimitry Andric     CGSCCPassManager &CGPipeline = MIWP.getPM();
746349cc55cSDimitry Andric 
747349cc55cSDimitry Andric     FunctionPassManager FPM;
748bdd1243dSDimitry Andric     FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
749349cc55cSDimitry Andric     FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
750fb03ea46SDimitry Andric     FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
751fb03ea46SDimitry Andric         true)));                    // Merge & remove basic blocks.
752349cc55cSDimitry Andric     FPM.addPass(InstCombinePass()); // Combine silly sequences.
753349cc55cSDimitry Andric     invokePeepholeEPCallbacks(FPM, Level);
754349cc55cSDimitry Andric 
755349cc55cSDimitry Andric     CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
756349cc55cSDimitry Andric         std::move(FPM), PTO.EagerlyInvalidateAnalyses));
757349cc55cSDimitry Andric 
758349cc55cSDimitry Andric     MPM.addPass(std::move(MIWP));
759349cc55cSDimitry Andric 
760349cc55cSDimitry Andric     // Delete anything that is now dead to make sure that we don't instrument
761349cc55cSDimitry Andric     // dead code. Instrumentation can end up keeping dead code around and
762349cc55cSDimitry Andric     // dramatically increase code size.
763349cc55cSDimitry Andric     MPM.addPass(GlobalDCEPass());
764349cc55cSDimitry Andric   }
765349cc55cSDimitry Andric 
766349cc55cSDimitry Andric   if (!RunProfileGen) {
767349cc55cSDimitry Andric     assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
768*06c3fb27SDimitry Andric     MPM.addPass(
769*06c3fb27SDimitry Andric         PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
770349cc55cSDimitry Andric     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
771349cc55cSDimitry Andric     // RequireAnalysisPass for PSI before subsequent non-module passes.
772349cc55cSDimitry Andric     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
773349cc55cSDimitry Andric     return;
774349cc55cSDimitry Andric   }
775349cc55cSDimitry Andric 
776349cc55cSDimitry Andric   // Perform PGO instrumentation.
777349cc55cSDimitry Andric   MPM.addPass(PGOInstrumentationGen(IsCS));
778349cc55cSDimitry Andric 
779bdd1243dSDimitry Andric   if (EnablePostPGOLoopRotation) {
780349cc55cSDimitry Andric     // Disable header duplication in loop rotation at -Oz.
78181ad6265SDimitry Andric     MPM.addPass(createModuleToFunctionPassAdaptor(
78281ad6265SDimitry Andric         createFunctionToLoopPassAdaptor(
78381ad6265SDimitry Andric             LoopRotatePass(Level != OptimizationLevel::Oz),
78481ad6265SDimitry Andric             /*UseMemorySSA=*/false,
78581ad6265SDimitry Andric             /*UseBlockFrequencyInfo=*/false),
786349cc55cSDimitry Andric         PTO.EagerlyInvalidateAnalyses));
787bdd1243dSDimitry Andric   }
788349cc55cSDimitry Andric 
789349cc55cSDimitry Andric   // Add the profile lowering pass.
790349cc55cSDimitry Andric   InstrProfOptions Options;
791349cc55cSDimitry Andric   if (!ProfileFile.empty())
792349cc55cSDimitry Andric     Options.InstrProfileOutput = ProfileFile;
793349cc55cSDimitry Andric   // Do counter promotion at Level greater than O0.
794349cc55cSDimitry Andric   Options.DoCounterPromotion = true;
795349cc55cSDimitry Andric   Options.UseBFIInPromotion = IsCS;
796349cc55cSDimitry Andric   MPM.addPass(InstrProfiling(Options, IsCS));
797349cc55cSDimitry Andric }
798349cc55cSDimitry Andric 
799*06c3fb27SDimitry Andric void PassBuilder::addPGOInstrPassesForO0(
800*06c3fb27SDimitry Andric     ModulePassManager &MPM, bool RunProfileGen, bool IsCS,
801*06c3fb27SDimitry Andric     std::string ProfileFile, std::string ProfileRemappingFile,
802*06c3fb27SDimitry Andric     IntrusiveRefCntPtr<vfs::FileSystem> FS) {
803349cc55cSDimitry Andric   if (!RunProfileGen) {
804349cc55cSDimitry Andric     assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
805*06c3fb27SDimitry Andric     MPM.addPass(
806*06c3fb27SDimitry Andric         PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS, FS));
807349cc55cSDimitry Andric     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
808349cc55cSDimitry Andric     // RequireAnalysisPass for PSI before subsequent non-module passes.
809349cc55cSDimitry Andric     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
810349cc55cSDimitry Andric     return;
811349cc55cSDimitry Andric   }
812349cc55cSDimitry Andric 
813349cc55cSDimitry Andric   // Perform PGO instrumentation.
814349cc55cSDimitry Andric   MPM.addPass(PGOInstrumentationGen(IsCS));
815349cc55cSDimitry Andric   // Add the profile lowering pass.
816349cc55cSDimitry Andric   InstrProfOptions Options;
817349cc55cSDimitry Andric   if (!ProfileFile.empty())
818349cc55cSDimitry Andric     Options.InstrProfileOutput = ProfileFile;
819349cc55cSDimitry Andric   // Do not do counter promotion at O0.
820349cc55cSDimitry Andric   Options.DoCounterPromotion = false;
821349cc55cSDimitry Andric   Options.UseBFIInPromotion = IsCS;
822349cc55cSDimitry Andric   MPM.addPass(InstrProfiling(Options, IsCS));
823349cc55cSDimitry Andric }
824349cc55cSDimitry Andric 
825349cc55cSDimitry Andric static InlineParams getInlineParamsFromOptLevel(OptimizationLevel Level) {
826349cc55cSDimitry Andric   return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel());
827349cc55cSDimitry Andric }
828349cc55cSDimitry Andric 
829349cc55cSDimitry Andric ModuleInlinerWrapperPass
830349cc55cSDimitry Andric PassBuilder::buildInlinerPipeline(OptimizationLevel Level,
831349cc55cSDimitry Andric                                   ThinOrFullLTOPhase Phase) {
832bdd1243dSDimitry Andric   InlineParams IP;
833bdd1243dSDimitry Andric   if (PTO.InlinerThreshold == -1)
834bdd1243dSDimitry Andric     IP = getInlineParamsFromOptLevel(Level);
835bdd1243dSDimitry Andric   else
836bdd1243dSDimitry Andric     IP = getInlineParams(PTO.InlinerThreshold);
83781ad6265SDimitry Andric   // For PreLinkThinLTO + SamplePGO, set hot-caller threshold to 0 to
83881ad6265SDimitry Andric   // disable hot callsite inline (as much as possible [1]) because it makes
83981ad6265SDimitry Andric   // profile annotation in the backend inaccurate.
84081ad6265SDimitry Andric   //
84181ad6265SDimitry Andric   // [1] Note the cost of a function could be below zero due to erased
84281ad6265SDimitry Andric   // prologue / epilogue.
843349cc55cSDimitry Andric   if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
844349cc55cSDimitry Andric       PGOOpt->Action == PGOOptions::SampleUse)
845349cc55cSDimitry Andric     IP.HotCallSiteThreshold = 0;
846349cc55cSDimitry Andric 
847349cc55cSDimitry Andric   if (PGOOpt)
848349cc55cSDimitry Andric     IP.EnableDeferral = EnablePGOInlineDeferral;
849349cc55cSDimitry Andric 
850bdd1243dSDimitry Andric   ModuleInlinerWrapperPass MIWP(IP, PerformMandatoryInliningsFirst,
85181ad6265SDimitry Andric                                 InlineContext{Phase, InlinePass::CGSCCInliner},
852349cc55cSDimitry Andric                                 UseInlineAdvisor, MaxDevirtIterations);
853349cc55cSDimitry Andric 
854349cc55cSDimitry Andric   // Require the GlobalsAA analysis for the module so we can query it within
855349cc55cSDimitry Andric   // the CGSCC pipeline.
856349cc55cSDimitry Andric   MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
857349cc55cSDimitry Andric   // Invalidate AAManager so it can be recreated and pick up the newly available
858349cc55cSDimitry Andric   // GlobalsAA.
859349cc55cSDimitry Andric   MIWP.addModulePass(
860349cc55cSDimitry Andric       createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
861349cc55cSDimitry Andric 
862349cc55cSDimitry Andric   // Require the ProfileSummaryAnalysis for the module so we can query it within
863349cc55cSDimitry Andric   // the inliner pass.
864349cc55cSDimitry Andric   MIWP.addModulePass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
865349cc55cSDimitry Andric 
866349cc55cSDimitry Andric   // Now begin the main postorder CGSCC pipeline.
867349cc55cSDimitry Andric   // FIXME: The current CGSCC pipeline has its origins in the legacy pass
868349cc55cSDimitry Andric   // manager and trying to emulate its precise behavior. Much of this doesn't
869349cc55cSDimitry Andric   // make a lot of sense and we should revisit the core CGSCC structure.
870349cc55cSDimitry Andric   CGSCCPassManager &MainCGPipeline = MIWP.getPM();
871349cc55cSDimitry Andric 
872349cc55cSDimitry Andric   // Note: historically, the PruneEH pass was run first to deduce nounwind and
873349cc55cSDimitry Andric   // generally clean up exception handling overhead. It isn't clear this is
874349cc55cSDimitry Andric   // valuable as the inliner doesn't currently care whether it is inlining an
875349cc55cSDimitry Andric   // invoke or a call.
876349cc55cSDimitry Andric 
877349cc55cSDimitry Andric   if (AttributorRun & AttributorRunOption::CGSCC)
878349cc55cSDimitry Andric     MainCGPipeline.addPass(AttributorCGSCCPass());
879349cc55cSDimitry Andric 
880*06c3fb27SDimitry Andric   // Deduce function attributes. We do another run of this after the function
881*06c3fb27SDimitry Andric   // simplification pipeline, so this only needs to run when it could affect the
882*06c3fb27SDimitry Andric   // function simplification pipeline, which is only the case with recursive
883*06c3fb27SDimitry Andric   // functions.
884*06c3fb27SDimitry Andric   MainCGPipeline.addPass(PostOrderFunctionAttrsPass(/*SkipNonRecursive*/ true));
885349cc55cSDimitry Andric 
886349cc55cSDimitry Andric   // When at O3 add argument promotion to the pass pipeline.
887349cc55cSDimitry Andric   // FIXME: It isn't at all clear why this should be limited to O3.
888349cc55cSDimitry Andric   if (Level == OptimizationLevel::O3)
889349cc55cSDimitry Andric     MainCGPipeline.addPass(ArgumentPromotionPass());
890349cc55cSDimitry Andric 
891349cc55cSDimitry Andric   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
892349cc55cSDimitry Andric   // there are no OpenMP runtime calls present in the module.
893349cc55cSDimitry Andric   if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
894349cc55cSDimitry Andric     MainCGPipeline.addPass(OpenMPOptCGSCCPass());
895349cc55cSDimitry Andric 
896*06c3fb27SDimitry Andric   invokeCGSCCOptimizerLateEPCallbacks(MainCGPipeline, Level);
897349cc55cSDimitry Andric 
898*06c3fb27SDimitry Andric   // Add the core function simplification pipeline nested inside the
899349cc55cSDimitry Andric   // CGSCC walk.
900349cc55cSDimitry Andric   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
901349cc55cSDimitry Andric       buildFunctionSimplificationPipeline(Level, Phase),
902*06c3fb27SDimitry Andric       PTO.EagerlyInvalidateAnalyses, /*NoRerun=*/true));
903*06c3fb27SDimitry Andric 
904*06c3fb27SDimitry Andric   // Finally, deduce any function attributes based on the fully simplified
905*06c3fb27SDimitry Andric   // function.
906*06c3fb27SDimitry Andric   MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
907*06c3fb27SDimitry Andric 
908*06c3fb27SDimitry Andric   // Mark that the function is fully simplified and that it shouldn't be
909*06c3fb27SDimitry Andric   // simplified again if we somehow revisit it due to CGSCC mutations unless
910*06c3fb27SDimitry Andric   // it's been modified since.
911*06c3fb27SDimitry Andric   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
912*06c3fb27SDimitry Andric       RequireAnalysisPass<ShouldNotRunFunctionPassesAnalysis, Function>()));
913349cc55cSDimitry Andric 
914349cc55cSDimitry Andric   MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
915349cc55cSDimitry Andric 
916*06c3fb27SDimitry Andric   // Make sure we don't affect potential future NoRerun CGSCC adaptors.
917349cc55cSDimitry Andric   MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
918349cc55cSDimitry Andric       InvalidateAnalysisPass<ShouldNotRunFunctionPassesAnalysis>()));
919349cc55cSDimitry Andric 
920349cc55cSDimitry Andric   return MIWP;
921349cc55cSDimitry Andric }
922349cc55cSDimitry Andric 
9230eae32dcSDimitry Andric ModulePassManager
924349cc55cSDimitry Andric PassBuilder::buildModuleInlinerPipeline(OptimizationLevel Level,
925349cc55cSDimitry Andric                                         ThinOrFullLTOPhase Phase) {
9260eae32dcSDimitry Andric   ModulePassManager MPM;
9270eae32dcSDimitry Andric 
928349cc55cSDimitry Andric   InlineParams IP = getInlineParamsFromOptLevel(Level);
92981ad6265SDimitry Andric   // For PreLinkThinLTO + SamplePGO, set hot-caller threshold to 0 to
93081ad6265SDimitry Andric   // disable hot callsite inline (as much as possible [1]) because it makes
93181ad6265SDimitry Andric   // profile annotation in the backend inaccurate.
93281ad6265SDimitry Andric   //
93381ad6265SDimitry Andric   // [1] Note the cost of a function could be below zero due to erased
93481ad6265SDimitry Andric   // prologue / epilogue.
935349cc55cSDimitry Andric   if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
936349cc55cSDimitry Andric       PGOOpt->Action == PGOOptions::SampleUse)
937349cc55cSDimitry Andric     IP.HotCallSiteThreshold = 0;
938349cc55cSDimitry Andric 
939349cc55cSDimitry Andric   if (PGOOpt)
940349cc55cSDimitry Andric     IP.EnableDeferral = EnablePGOInlineDeferral;
941349cc55cSDimitry Andric 
942349cc55cSDimitry Andric   // The inline deferral logic is used to avoid losing some
943349cc55cSDimitry Andric   // inlining chance in future. It is helpful in SCC inliner, in which
944349cc55cSDimitry Andric   // inlining is processed in bottom-up order.
945349cc55cSDimitry Andric   // While in module inliner, the inlining order is a priority-based order
946349cc55cSDimitry Andric   // by default. The inline deferral is unnecessary there. So we disable the
947349cc55cSDimitry Andric   // inline deferral logic in module inliner.
948349cc55cSDimitry Andric   IP.EnableDeferral = false;
949349cc55cSDimitry Andric 
95081ad6265SDimitry Andric   MPM.addPass(ModuleInlinerPass(IP, UseInlineAdvisor, Phase));
9510eae32dcSDimitry Andric 
9520eae32dcSDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(
9530eae32dcSDimitry Andric       buildFunctionSimplificationPipeline(Level, Phase),
9540eae32dcSDimitry Andric       PTO.EagerlyInvalidateAnalyses));
9550eae32dcSDimitry Andric 
9560eae32dcSDimitry Andric   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
9570eae32dcSDimitry Andric       CoroSplitPass(Level != OptimizationLevel::O0)));
9580eae32dcSDimitry Andric 
9590eae32dcSDimitry Andric   return MPM;
960349cc55cSDimitry Andric }
961349cc55cSDimitry Andric 
962349cc55cSDimitry Andric ModulePassManager
963349cc55cSDimitry Andric PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
964349cc55cSDimitry Andric                                                ThinOrFullLTOPhase Phase) {
965*06c3fb27SDimitry Andric   assert(Level != OptimizationLevel::O0 &&
966*06c3fb27SDimitry Andric          "Should not be used for O0 pipeline");
967*06c3fb27SDimitry Andric 
968*06c3fb27SDimitry Andric   assert(Phase != ThinOrFullLTOPhase::FullLTOPostLink &&
969*06c3fb27SDimitry Andric          "FullLTOPostLink shouldn't call buildModuleSimplificationPipeline!");
970*06c3fb27SDimitry Andric 
971349cc55cSDimitry Andric   ModulePassManager MPM;
972349cc55cSDimitry Andric 
973349cc55cSDimitry Andric   // Place pseudo probe instrumentation as the first pass of the pipeline to
974349cc55cSDimitry Andric   // minimize the impact of optimization changes.
975349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
976349cc55cSDimitry Andric       Phase != ThinOrFullLTOPhase::ThinLTOPostLink)
977349cc55cSDimitry Andric     MPM.addPass(SampleProfileProbePass(TM));
978349cc55cSDimitry Andric 
979349cc55cSDimitry Andric   bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
980349cc55cSDimitry Andric 
981349cc55cSDimitry Andric   // In ThinLTO mode, when flattened profile is used, all the available
982349cc55cSDimitry Andric   // profile information will be annotated in PreLink phase so there is
983349cc55cSDimitry Andric   // no need to load the profile again in PostLink.
984349cc55cSDimitry Andric   bool LoadSampleProfile =
985349cc55cSDimitry Andric       HasSampleProfile &&
986349cc55cSDimitry Andric       !(FlattenedProfileUsed && Phase == ThinOrFullLTOPhase::ThinLTOPostLink);
987349cc55cSDimitry Andric 
988349cc55cSDimitry Andric   // During the ThinLTO backend phase we perform early indirect call promotion
989349cc55cSDimitry Andric   // here, before globalopt. Otherwise imported available_externally functions
990349cc55cSDimitry Andric   // look unreferenced and are removed. If we are going to load the sample
991349cc55cSDimitry Andric   // profile then defer until later.
992349cc55cSDimitry Andric   // TODO: See if we can move later and consolidate with the location where
993349cc55cSDimitry Andric   // we perform ICP when we are loading a sample profile.
994349cc55cSDimitry Andric   // TODO: We pass HasSampleProfile (whether there was a sample profile file
995349cc55cSDimitry Andric   // passed to the compile) to the SamplePGO flag of ICP. This is used to
996349cc55cSDimitry Andric   // determine whether the new direct calls are annotated with prof metadata.
997349cc55cSDimitry Andric   // Ideally this should be determined from whether the IR is annotated with
998349cc55cSDimitry Andric   // sample profile, and not whether the a sample profile was provided on the
999349cc55cSDimitry Andric   // command line. E.g. for flattened profiles where we will not be reloading
1000349cc55cSDimitry Andric   // the sample profile in the ThinLTO backend, we ideally shouldn't have to
1001349cc55cSDimitry Andric   // provide the sample profile file.
1002349cc55cSDimitry Andric   if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile)
1003349cc55cSDimitry Andric     MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
1004349cc55cSDimitry Andric 
1005*06c3fb27SDimitry Andric   // Create an early function pass manager to cleanup the output of the
1006*06c3fb27SDimitry Andric   // frontend. Not necessary with LTO post link pipelines since the pre link
1007*06c3fb27SDimitry Andric   // pipeline already cleaned up the frontend output.
1008*06c3fb27SDimitry Andric   if (Phase != ThinOrFullLTOPhase::ThinLTOPostLink) {
1009349cc55cSDimitry Andric     // Do basic inference of function attributes from known properties of system
1010349cc55cSDimitry Andric     // libraries and other oracles.
1011349cc55cSDimitry Andric     MPM.addPass(InferFunctionAttrsPass());
101281ad6265SDimitry Andric     MPM.addPass(CoroEarlyPass());
1013349cc55cSDimitry Andric 
1014349cc55cSDimitry Andric     FunctionPassManager EarlyFPM;
1015349cc55cSDimitry Andric     // Lower llvm.expect to metadata before attempting transforms.
1016*06c3fb27SDimitry Andric     // Compare/branch metadata may alter the behavior of passes like
1017*06c3fb27SDimitry Andric     // SimplifyCFG.
1018349cc55cSDimitry Andric     EarlyFPM.addPass(LowerExpectIntrinsicPass());
1019349cc55cSDimitry Andric     EarlyFPM.addPass(SimplifyCFGPass());
1020bdd1243dSDimitry Andric     EarlyFPM.addPass(SROAPass(SROAOptions::ModifyCFG));
1021349cc55cSDimitry Andric     EarlyFPM.addPass(EarlyCSEPass());
1022349cc55cSDimitry Andric     if (Level == OptimizationLevel::O3)
1023349cc55cSDimitry Andric       EarlyFPM.addPass(CallSiteSplittingPass());
1024*06c3fb27SDimitry Andric     MPM.addPass(createModuleToFunctionPassAdaptor(
1025*06c3fb27SDimitry Andric         std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses));
1026*06c3fb27SDimitry Andric   }
1027349cc55cSDimitry Andric 
1028349cc55cSDimitry Andric   if (LoadSampleProfile) {
1029349cc55cSDimitry Andric     // Annotate sample profile right after early FPM to ensure freshness of
1030349cc55cSDimitry Andric     // the debug info.
1031349cc55cSDimitry Andric     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1032349cc55cSDimitry Andric                                         PGOOpt->ProfileRemappingFile, Phase));
1033349cc55cSDimitry Andric     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1034349cc55cSDimitry Andric     // RequireAnalysisPass for PSI before subsequent non-module passes.
1035349cc55cSDimitry Andric     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1036349cc55cSDimitry Andric     // Do not invoke ICP in the LTOPrelink phase as it makes it hard
1037349cc55cSDimitry Andric     // for the profile annotation to be accurate in the LTO backend.
1038*06c3fb27SDimitry Andric     if (!isLTOPreLink(Phase))
1039349cc55cSDimitry Andric       // We perform early indirect call promotion here, before globalopt.
1040349cc55cSDimitry Andric       // This is important for the ThinLTO backend phase because otherwise
1041349cc55cSDimitry Andric       // imported available_externally functions look unreferenced and are
1042349cc55cSDimitry Andric       // removed.
1043349cc55cSDimitry Andric       MPM.addPass(
1044349cc55cSDimitry Andric           PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
1045349cc55cSDimitry Andric   }
1046349cc55cSDimitry Andric 
1047349cc55cSDimitry Andric   // Try to perform OpenMP specific optimizations on the module. This is a
1048349cc55cSDimitry Andric   // (quick!) no-op if there are no OpenMP runtime calls present in the module.
1049349cc55cSDimitry Andric   MPM.addPass(OpenMPOptPass());
1050349cc55cSDimitry Andric 
1051349cc55cSDimitry Andric   if (AttributorRun & AttributorRunOption::MODULE)
1052349cc55cSDimitry Andric     MPM.addPass(AttributorPass());
1053349cc55cSDimitry Andric 
1054349cc55cSDimitry Andric   // Lower type metadata and the type.test intrinsic in the ThinLTO
1055349cc55cSDimitry Andric   // post link pipeline after ICP. This is to enable usage of the type
1056349cc55cSDimitry Andric   // tests in ICP sequences.
1057349cc55cSDimitry Andric   if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink)
1058349cc55cSDimitry Andric     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1059349cc55cSDimitry Andric 
1060*06c3fb27SDimitry Andric   invokePipelineEarlySimplificationEPCallbacks(MPM, Level);
1061349cc55cSDimitry Andric 
1062349cc55cSDimitry Andric   // Interprocedural constant propagation now that basic cleanup has occurred
1063349cc55cSDimitry Andric   // and prior to optimizing globals.
1064349cc55cSDimitry Andric   // FIXME: This position in the pipeline hasn't been carefully considered in
1065349cc55cSDimitry Andric   // years, it should be re-analyzed.
1066*06c3fb27SDimitry Andric   MPM.addPass(IPSCCPPass(
1067*06c3fb27SDimitry Andric               IPSCCPOptions(/*AllowFuncSpec=*/
1068bdd1243dSDimitry Andric                             Level != OptimizationLevel::Os &&
1069*06c3fb27SDimitry Andric                             Level != OptimizationLevel::Oz &&
1070*06c3fb27SDimitry Andric                             !isLTOPreLink(Phase))));
1071349cc55cSDimitry Andric 
1072349cc55cSDimitry Andric   // Attach metadata to indirect call sites indicating the set of functions
1073349cc55cSDimitry Andric   // they may target at run-time. This should follow IPSCCP.
1074349cc55cSDimitry Andric   MPM.addPass(CalledValuePropagationPass());
1075349cc55cSDimitry Andric 
1076349cc55cSDimitry Andric   // Optimize globals to try and fold them into constants.
1077349cc55cSDimitry Andric   MPM.addPass(GlobalOptPass());
1078349cc55cSDimitry Andric 
1079349cc55cSDimitry Andric   // Create a small function pass pipeline to cleanup after all the global
1080349cc55cSDimitry Andric   // optimizations.
1081349cc55cSDimitry Andric   FunctionPassManager GlobalCleanupPM;
1082*06c3fb27SDimitry Andric   // FIXME: Should this instead by a run of SROA?
1083*06c3fb27SDimitry Andric   GlobalCleanupPM.addPass(PromotePass());
1084349cc55cSDimitry Andric   GlobalCleanupPM.addPass(InstCombinePass());
1085349cc55cSDimitry Andric   invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
1086fb03ea46SDimitry Andric   GlobalCleanupPM.addPass(
1087fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1088349cc55cSDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
1089349cc55cSDimitry Andric                                                 PTO.EagerlyInvalidateAnalyses));
1090349cc55cSDimitry Andric 
1091349cc55cSDimitry Andric   // Add all the requested passes for instrumentation PGO, if requested.
1092349cc55cSDimitry Andric   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
1093349cc55cSDimitry Andric       (PGOOpt->Action == PGOOptions::IRInstr ||
1094349cc55cSDimitry Andric        PGOOpt->Action == PGOOptions::IRUse)) {
1095349cc55cSDimitry Andric     addPGOInstrPasses(MPM, Level,
1096349cc55cSDimitry Andric                       /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
1097349cc55cSDimitry Andric                       /* IsCS */ false, PGOOpt->ProfileFile,
1098*06c3fb27SDimitry Andric                       PGOOpt->ProfileRemappingFile, Phase, PGOOpt->FS);
1099349cc55cSDimitry Andric     MPM.addPass(PGOIndirectCallPromotion(false, false));
1100349cc55cSDimitry Andric   }
1101349cc55cSDimitry Andric   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
1102349cc55cSDimitry Andric       PGOOpt->CSAction == PGOOptions::CSIRInstr)
1103349cc55cSDimitry Andric     MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
1104349cc55cSDimitry Andric 
1105*06c3fb27SDimitry Andric   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
1106*06c3fb27SDimitry Andric       !PGOOpt->MemoryProfile.empty())
1107*06c3fb27SDimitry Andric     MPM.addPass(MemProfUsePass(PGOOpt->MemoryProfile, PGOOpt->FS));
1108*06c3fb27SDimitry Andric 
1109349cc55cSDimitry Andric   // Synthesize function entry counts for non-PGO compilation.
1110349cc55cSDimitry Andric   if (EnableSyntheticCounts && !PGOOpt)
1111349cc55cSDimitry Andric     MPM.addPass(SyntheticCountsPropagation());
1112349cc55cSDimitry Andric 
1113349cc55cSDimitry Andric   if (EnableModuleInliner)
1114349cc55cSDimitry Andric     MPM.addPass(buildModuleInlinerPipeline(Level, Phase));
1115349cc55cSDimitry Andric   else
1116349cc55cSDimitry Andric     MPM.addPass(buildInlinerPipeline(Level, Phase));
1117349cc55cSDimitry Andric 
1118bdd1243dSDimitry Andric   // Remove any dead arguments exposed by cleanups, constant folding globals,
1119bdd1243dSDimitry Andric   // and argument promotion.
1120bdd1243dSDimitry Andric   MPM.addPass(DeadArgumentEliminationPass());
1121bdd1243dSDimitry Andric 
112281ad6265SDimitry Andric   MPM.addPass(CoroCleanupPass());
112381ad6265SDimitry Andric 
1124*06c3fb27SDimitry Andric   // Optimize globals now that functions are fully simplified.
1125*06c3fb27SDimitry Andric   MPM.addPass(GlobalOptPass());
1126*06c3fb27SDimitry Andric   MPM.addPass(GlobalDCEPass());
1127349cc55cSDimitry Andric 
1128349cc55cSDimitry Andric   return MPM;
1129349cc55cSDimitry Andric }
1130349cc55cSDimitry Andric 
1131349cc55cSDimitry Andric /// TODO: Should LTO cause any differences to this set of passes?
1132349cc55cSDimitry Andric void PassBuilder::addVectorPasses(OptimizationLevel Level,
1133349cc55cSDimitry Andric                                   FunctionPassManager &FPM, bool IsFullLTO) {
1134349cc55cSDimitry Andric   FPM.addPass(LoopVectorizePass(
1135349cc55cSDimitry Andric       LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
1136349cc55cSDimitry Andric 
1137349cc55cSDimitry Andric   if (IsFullLTO) {
1138349cc55cSDimitry Andric     // The vectorizer may have significantly shortened a loop body; unroll
1139349cc55cSDimitry Andric     // again. Unroll small loops to hide loop backedge latency and saturate any
1140349cc55cSDimitry Andric     // parallel execution resources of an out-of-order processor. We also then
1141349cc55cSDimitry Andric     // need to clean up redundancies and loop invariant code.
1142349cc55cSDimitry Andric     // FIXME: It would be really good to use a loop-integrated instruction
1143349cc55cSDimitry Andric     // combiner for cleanup here so that the unrolling and LICM can be pipelined
1144349cc55cSDimitry Andric     // across the loop nests.
1145349cc55cSDimitry Andric     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1146349cc55cSDimitry Andric     if (EnableUnrollAndJam && PTO.LoopUnrolling)
1147349cc55cSDimitry Andric       FPM.addPass(createFunctionToLoopPassAdaptor(
1148349cc55cSDimitry Andric           LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1149349cc55cSDimitry Andric     FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1150349cc55cSDimitry Andric         Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1151349cc55cSDimitry Andric         PTO.ForgetAllSCEVInLoopUnroll)));
1152349cc55cSDimitry Andric     FPM.addPass(WarnMissedTransformationsPass());
1153bdd1243dSDimitry Andric     // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1154bdd1243dSDimitry Andric     // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1155bdd1243dSDimitry Andric     // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1156bdd1243dSDimitry Andric     // NOTE: we are very late in the pipeline, and we don't have any LICM
1157bdd1243dSDimitry Andric     // or SimplifyCFG passes scheduled after us, that would cleanup
1158bdd1243dSDimitry Andric     // the CFG mess this may created if allowed to modify CFG, so forbid that.
1159bdd1243dSDimitry Andric     FPM.addPass(SROAPass(SROAOptions::PreserveCFG));
1160349cc55cSDimitry Andric   }
1161349cc55cSDimitry Andric 
1162349cc55cSDimitry Andric   if (!IsFullLTO) {
1163349cc55cSDimitry Andric     // Eliminate loads by forwarding stores from the previous iteration to loads
1164349cc55cSDimitry Andric     // of the current iteration.
1165349cc55cSDimitry Andric     FPM.addPass(LoopLoadEliminationPass());
1166349cc55cSDimitry Andric   }
1167349cc55cSDimitry Andric   // Cleanup after the loop optimization passes.
1168349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
1169349cc55cSDimitry Andric 
1170349cc55cSDimitry Andric   if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
11710eae32dcSDimitry Andric     ExtraVectorPassManager ExtraPasses;
1172349cc55cSDimitry Andric     // At higher optimization levels, try to clean up any runtime overlap and
1173349cc55cSDimitry Andric     // alignment checks inserted by the vectorizer. We want to track correlated
1174349cc55cSDimitry Andric     // runtime checks for two inner loops in the same outer loop, fold any
1175349cc55cSDimitry Andric     // common computations, hoist loop-invariant aspects out of any outer loop,
1176349cc55cSDimitry Andric     // and unswitch the runtime checks if possible. Once hoisted, we may have
1177349cc55cSDimitry Andric     // dead (or speculatable) control flows or more combining opportunities.
11780eae32dcSDimitry Andric     ExtraPasses.addPass(EarlyCSEPass());
11790eae32dcSDimitry Andric     ExtraPasses.addPass(CorrelatedValuePropagationPass());
11800eae32dcSDimitry Andric     ExtraPasses.addPass(InstCombinePass());
1181349cc55cSDimitry Andric     LoopPassManager LPM;
1182fb03ea46SDimitry Andric     LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1183fb03ea46SDimitry Andric                          /*AllowSpeculation=*/true));
1184349cc55cSDimitry Andric     LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1185349cc55cSDimitry Andric                                        OptimizationLevel::O3));
11860eae32dcSDimitry Andric     ExtraPasses.addPass(
1187349cc55cSDimitry Andric         createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true,
1188349cc55cSDimitry Andric                                         /*UseBlockFrequencyInfo=*/true));
1189fb03ea46SDimitry Andric     ExtraPasses.addPass(
1190fb03ea46SDimitry Andric         SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
11910eae32dcSDimitry Andric     ExtraPasses.addPass(InstCombinePass());
11920eae32dcSDimitry Andric     FPM.addPass(std::move(ExtraPasses));
1193349cc55cSDimitry Andric   }
1194349cc55cSDimitry Andric 
1195349cc55cSDimitry Andric   // Now that we've formed fast to execute loop structures, we do further
1196349cc55cSDimitry Andric   // optimizations. These are run afterward as they might block doing complex
1197349cc55cSDimitry Andric   // analyses and transforms such as what are needed for loop vectorization.
1198349cc55cSDimitry Andric 
1199349cc55cSDimitry Andric   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1200349cc55cSDimitry Andric   // GVN, loop transforms, and others have already run, so it's now better to
1201349cc55cSDimitry Andric   // convert to more optimized IR using more aggressive simplify CFG options.
1202349cc55cSDimitry Andric   // The extra sinking transform can create larger basic blocks, so do this
1203349cc55cSDimitry Andric   // before SLP vectorization.
1204349cc55cSDimitry Andric   FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1205349cc55cSDimitry Andric                                   .forwardSwitchCondToPhi(true)
1206fb03ea46SDimitry Andric                                   .convertSwitchRangeToICmp(true)
1207349cc55cSDimitry Andric                                   .convertSwitchToLookupTable(true)
1208349cc55cSDimitry Andric                                   .needCanonicalLoops(false)
1209349cc55cSDimitry Andric                                   .hoistCommonInsts(true)
1210349cc55cSDimitry Andric                                   .sinkCommonInsts(true)));
1211349cc55cSDimitry Andric 
1212349cc55cSDimitry Andric   if (IsFullLTO) {
1213349cc55cSDimitry Andric     FPM.addPass(SCCPPass());
1214349cc55cSDimitry Andric     FPM.addPass(InstCombinePass());
1215349cc55cSDimitry Andric     FPM.addPass(BDCEPass());
1216349cc55cSDimitry Andric   }
1217349cc55cSDimitry Andric 
1218349cc55cSDimitry Andric   // Optimize parallel scalar instruction chains into SIMD instructions.
1219349cc55cSDimitry Andric   if (PTO.SLPVectorization) {
1220349cc55cSDimitry Andric     FPM.addPass(SLPVectorizerPass());
1221349cc55cSDimitry Andric     if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1222349cc55cSDimitry Andric       FPM.addPass(EarlyCSEPass());
1223349cc55cSDimitry Andric     }
1224349cc55cSDimitry Andric   }
1225349cc55cSDimitry Andric   // Enhance/cleanup vector code.
1226349cc55cSDimitry Andric   FPM.addPass(VectorCombinePass());
1227349cc55cSDimitry Andric 
1228349cc55cSDimitry Andric   if (!IsFullLTO) {
1229349cc55cSDimitry Andric     FPM.addPass(InstCombinePass());
1230349cc55cSDimitry Andric     // Unroll small loops to hide loop backedge latency and saturate any
1231349cc55cSDimitry Andric     // parallel execution resources of an out-of-order processor. We also then
1232349cc55cSDimitry Andric     // need to clean up redundancies and loop invariant code.
1233349cc55cSDimitry Andric     // FIXME: It would be really good to use a loop-integrated instruction
1234349cc55cSDimitry Andric     // combiner for cleanup here so that the unrolling and LICM can be pipelined
1235349cc55cSDimitry Andric     // across the loop nests.
1236349cc55cSDimitry Andric     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1237349cc55cSDimitry Andric     if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1238349cc55cSDimitry Andric       FPM.addPass(createFunctionToLoopPassAdaptor(
1239349cc55cSDimitry Andric           LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1240349cc55cSDimitry Andric     }
1241349cc55cSDimitry Andric     FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1242349cc55cSDimitry Andric         Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1243349cc55cSDimitry Andric         PTO.ForgetAllSCEVInLoopUnroll)));
1244349cc55cSDimitry Andric     FPM.addPass(WarnMissedTransformationsPass());
1245bdd1243dSDimitry Andric     // Now that we are done with loop unrolling, be it either by LoopVectorizer,
1246bdd1243dSDimitry Andric     // or LoopUnroll passes, some variable-offset GEP's into alloca's could have
1247bdd1243dSDimitry Andric     // become constant-offset, thus enabling SROA and alloca promotion. Do so.
1248bdd1243dSDimitry Andric     // NOTE: we are very late in the pipeline, and we don't have any LICM
1249bdd1243dSDimitry Andric     // or SimplifyCFG passes scheduled after us, that would cleanup
1250bdd1243dSDimitry Andric     // the CFG mess this may created if allowed to modify CFG, so forbid that.
1251bdd1243dSDimitry Andric     FPM.addPass(SROAPass(SROAOptions::PreserveCFG));
1252*06c3fb27SDimitry Andric   }
1253*06c3fb27SDimitry Andric 
1254349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
1255*06c3fb27SDimitry Andric 
1256*06c3fb27SDimitry Andric   // This is needed for two reasons:
1257*06c3fb27SDimitry Andric   //   1. It works around problems that instcombine introduces, such as sinking
1258*06c3fb27SDimitry Andric   //      expensive FP divides into loops containing multiplications using the
1259*06c3fb27SDimitry Andric   //      divide result.
1260*06c3fb27SDimitry Andric   //   2. It helps to clean up some loop-invariant code created by the loop
1261*06c3fb27SDimitry Andric   //      unroll pass when IsFullLTO=false.
1262349cc55cSDimitry Andric   FPM.addPass(createFunctionToLoopPassAdaptor(
1263fb03ea46SDimitry Andric       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1264fb03ea46SDimitry Andric                /*AllowSpeculation=*/true),
1265*06c3fb27SDimitry Andric       /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/false));
1266349cc55cSDimitry Andric 
1267349cc55cSDimitry Andric   // Now that we've vectorized and unrolled loops, we may have more refined
1268349cc55cSDimitry Andric   // alignment information, try to re-derive it here.
1269349cc55cSDimitry Andric   FPM.addPass(AlignmentFromAssumptionsPass());
1270349cc55cSDimitry Andric }
1271349cc55cSDimitry Andric 
1272349cc55cSDimitry Andric ModulePassManager
1273349cc55cSDimitry Andric PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
127481ad6265SDimitry Andric                                              ThinOrFullLTOPhase LTOPhase) {
1275*06c3fb27SDimitry Andric   const bool LTOPreLink = isLTOPreLink(LTOPhase);
1276349cc55cSDimitry Andric   ModulePassManager MPM;
1277349cc55cSDimitry Andric 
1278349cc55cSDimitry Andric   // Run partial inlining pass to partially inline functions that have
1279349cc55cSDimitry Andric   // large bodies.
1280349cc55cSDimitry Andric   if (RunPartialInlining)
1281349cc55cSDimitry Andric     MPM.addPass(PartialInlinerPass());
1282349cc55cSDimitry Andric 
1283349cc55cSDimitry Andric   // Remove avail extern fns and globals definitions since we aren't compiling
1284349cc55cSDimitry Andric   // an object file for later LTO. For LTO we want to preserve these so they
1285349cc55cSDimitry Andric   // are eligible for inlining at link-time. Note if they are unreferenced they
1286349cc55cSDimitry Andric   // will be removed by GlobalDCE later, so this only impacts referenced
1287349cc55cSDimitry Andric   // available externally globals. Eventually they will be suppressed during
1288349cc55cSDimitry Andric   // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1289349cc55cSDimitry Andric   // may make globals referenced by available external functions dead and saves
1290349cc55cSDimitry Andric   // running remaining passes on the eliminated functions. These should be
1291349cc55cSDimitry Andric   // preserved during prelinking for link-time inlining decisions.
1292349cc55cSDimitry Andric   if (!LTOPreLink)
1293349cc55cSDimitry Andric     MPM.addPass(EliminateAvailableExternallyPass());
1294349cc55cSDimitry Andric 
1295349cc55cSDimitry Andric   if (EnableOrderFileInstrumentation)
1296349cc55cSDimitry Andric     MPM.addPass(InstrOrderFilePass());
1297349cc55cSDimitry Andric 
1298349cc55cSDimitry Andric   // Do RPO function attribute inference across the module to forward-propagate
1299349cc55cSDimitry Andric   // attributes where applicable.
1300349cc55cSDimitry Andric   // FIXME: Is this really an optimization rather than a canonicalization?
1301349cc55cSDimitry Andric   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1302349cc55cSDimitry Andric 
1303349cc55cSDimitry Andric   // Do a post inline PGO instrumentation and use pass. This is a context
1304349cc55cSDimitry Andric   // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1305349cc55cSDimitry Andric   // cross-module inline has not been done yet. The context sensitive
1306349cc55cSDimitry Andric   // instrumentation is after all the inlines are done.
1307349cc55cSDimitry Andric   if (!LTOPreLink && PGOOpt) {
1308349cc55cSDimitry Andric     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1309349cc55cSDimitry Andric       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
1310349cc55cSDimitry Andric                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
1311*06c3fb27SDimitry Andric                         PGOOpt->ProfileRemappingFile, LTOPhase, PGOOpt->FS);
1312349cc55cSDimitry Andric     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1313349cc55cSDimitry Andric       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
1314349cc55cSDimitry Andric                         /* IsCS */ true, PGOOpt->ProfileFile,
1315*06c3fb27SDimitry Andric                         PGOOpt->ProfileRemappingFile, LTOPhase, PGOOpt->FS);
1316349cc55cSDimitry Andric   }
1317349cc55cSDimitry Andric 
131881ad6265SDimitry Andric   // Re-compute GlobalsAA here prior to function passes. This is particularly
1319349cc55cSDimitry Andric   // useful as the above will have inlined, DCE'ed, and function-attr
1320349cc55cSDimitry Andric   // propagated everything. We should at this point have a reasonably minimal
1321349cc55cSDimitry Andric   // and richly annotated call graph. By computing aliasing and mod/ref
1322349cc55cSDimitry Andric   // information for all local globals here, the late loop passes and notably
1323349cc55cSDimitry Andric   // the vectorizer will be able to use them to help recognize vectorizable
1324349cc55cSDimitry Andric   // memory operations.
132581ad6265SDimitry Andric   MPM.addPass(RecomputeGlobalsAAPass());
132681ad6265SDimitry Andric 
1327*06c3fb27SDimitry Andric   invokeOptimizerEarlyEPCallbacks(MPM, Level);
1328349cc55cSDimitry Andric 
1329349cc55cSDimitry Andric   FunctionPassManager OptimizePM;
1330349cc55cSDimitry Andric   OptimizePM.addPass(Float2IntPass());
1331349cc55cSDimitry Andric   OptimizePM.addPass(LowerConstantIntrinsicsPass());
1332349cc55cSDimitry Andric 
1333349cc55cSDimitry Andric   if (EnableMatrix) {
1334349cc55cSDimitry Andric     OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1335349cc55cSDimitry Andric     OptimizePM.addPass(EarlyCSEPass());
1336349cc55cSDimitry Andric   }
1337349cc55cSDimitry Andric 
1338*06c3fb27SDimitry Andric   // CHR pass should only be applied with the profile information.
1339*06c3fb27SDimitry Andric   // The check is to check the profile summary information in CHR.
1340*06c3fb27SDimitry Andric   if (EnableCHR && Level == OptimizationLevel::O3)
1341*06c3fb27SDimitry Andric     OptimizePM.addPass(ControlHeightReductionPass());
1342*06c3fb27SDimitry Andric 
1343349cc55cSDimitry Andric   // FIXME: We need to run some loop optimizations to re-rotate loops after
1344349cc55cSDimitry Andric   // simplifycfg and others undo their rotation.
1345349cc55cSDimitry Andric 
1346349cc55cSDimitry Andric   // Optimize the loop execution. These passes operate on entire loop nests
1347349cc55cSDimitry Andric   // rather than on each loop in an inside-out manner, and so they are actually
1348349cc55cSDimitry Andric   // function passes.
1349349cc55cSDimitry Andric 
1350*06c3fb27SDimitry Andric   invokeVectorizerStartEPCallbacks(OptimizePM, Level);
1351349cc55cSDimitry Andric 
1352349cc55cSDimitry Andric   LoopPassManager LPM;
1353349cc55cSDimitry Andric   // First rotate loops that may have been un-rotated by prior passes.
1354349cc55cSDimitry Andric   // Disable header duplication at -Oz.
1355349cc55cSDimitry Andric   LPM.addPass(LoopRotatePass(Level != OptimizationLevel::Oz, LTOPreLink));
1356349cc55cSDimitry Andric   // Some loops may have become dead by now. Try to delete them.
13570eae32dcSDimitry Andric   // FIXME: see discussion in https://reviews.llvm.org/D112851,
13580eae32dcSDimitry Andric   //        this may need to be revisited once we run GVN before loop deletion
13590eae32dcSDimitry Andric   //        in the simplification pipeline.
1360349cc55cSDimitry Andric   LPM.addPass(LoopDeletionPass());
1361349cc55cSDimitry Andric   OptimizePM.addPass(createFunctionToLoopPassAdaptor(
1362349cc55cSDimitry Andric       std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false));
1363349cc55cSDimitry Andric 
1364349cc55cSDimitry Andric   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
1365349cc55cSDimitry Andric   // into separate loop that would otherwise inhibit vectorization.  This is
1366349cc55cSDimitry Andric   // currently only performed for loops marked with the metadata
1367349cc55cSDimitry Andric   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1368349cc55cSDimitry Andric   OptimizePM.addPass(LoopDistributePass());
1369349cc55cSDimitry Andric 
1370349cc55cSDimitry Andric   // Populates the VFABI attribute with the scalar-to-vector mappings
1371349cc55cSDimitry Andric   // from the TargetLibraryInfo.
1372349cc55cSDimitry Andric   OptimizePM.addPass(InjectTLIMappings());
1373349cc55cSDimitry Andric 
1374349cc55cSDimitry Andric   addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false);
1375349cc55cSDimitry Andric 
1376349cc55cSDimitry Andric   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1377349cc55cSDimitry Andric   // canonicalization pass that enables other optimizations. As a result,
1378349cc55cSDimitry Andric   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1379349cc55cSDimitry Andric   // result too early.
1380349cc55cSDimitry Andric   OptimizePM.addPass(LoopSinkPass());
1381349cc55cSDimitry Andric 
1382349cc55cSDimitry Andric   // And finally clean up LCSSA form before generating code.
1383349cc55cSDimitry Andric   OptimizePM.addPass(InstSimplifyPass());
1384349cc55cSDimitry Andric 
1385349cc55cSDimitry Andric   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1386349cc55cSDimitry Andric   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1387349cc55cSDimitry Andric   // flattening of blocks.
1388349cc55cSDimitry Andric   OptimizePM.addPass(DivRemPairsPass());
1389349cc55cSDimitry Andric 
1390972a253aSDimitry Andric   // Try to annotate calls that were created during optimization.
1391972a253aSDimitry Andric   OptimizePM.addPass(TailCallElimPass());
1392972a253aSDimitry Andric 
1393349cc55cSDimitry Andric   // LoopSink (and other loop passes since the last simplifyCFG) might have
1394349cc55cSDimitry Andric   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1395fb03ea46SDimitry Andric   OptimizePM.addPass(
1396fb03ea46SDimitry Andric       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1397349cc55cSDimitry Andric 
1398349cc55cSDimitry Andric   // Add the core optimizing pipeline.
1399349cc55cSDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1400349cc55cSDimitry Andric                                                 PTO.EagerlyInvalidateAnalyses));
1401349cc55cSDimitry Andric 
1402*06c3fb27SDimitry Andric   invokeOptimizerLastEPCallbacks(MPM, Level);
1403349cc55cSDimitry Andric 
14040eae32dcSDimitry Andric   // Split out cold code. Splitting is done late to avoid hiding context from
14050eae32dcSDimitry Andric   // other optimizations and inadvertently regressing performance. The tradeoff
14060eae32dcSDimitry Andric   // is that this has a higher code size cost than splitting early.
14070eae32dcSDimitry Andric   if (EnableHotColdSplit && !LTOPreLink)
14080eae32dcSDimitry Andric     MPM.addPass(HotColdSplittingPass());
14090eae32dcSDimitry Andric 
14100eae32dcSDimitry Andric   // Search the code for similar regions of code. If enough similar regions can
14110eae32dcSDimitry Andric   // be found where extracting the regions into their own function will decrease
14120eae32dcSDimitry Andric   // the size of the program, we extract the regions, a deduplicate the
14130eae32dcSDimitry Andric   // structurally similar regions.
14140eae32dcSDimitry Andric   if (EnableIROutliner)
14150eae32dcSDimitry Andric     MPM.addPass(IROutlinerPass());
14160eae32dcSDimitry Andric 
14170eae32dcSDimitry Andric   // Merge functions if requested.
14180eae32dcSDimitry Andric   if (PTO.MergeFunctions)
14190eae32dcSDimitry Andric     MPM.addPass(MergeFunctionsPass());
14200eae32dcSDimitry Andric 
1421349cc55cSDimitry Andric   // Now we need to do some global optimization transforms.
1422349cc55cSDimitry Andric   // FIXME: It would seem like these should come first in the optimization
1423349cc55cSDimitry Andric   // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1424349cc55cSDimitry Andric   // ordering here.
1425349cc55cSDimitry Andric   MPM.addPass(GlobalDCEPass());
1426349cc55cSDimitry Andric   MPM.addPass(ConstantMergePass());
1427349cc55cSDimitry Andric 
142881ad6265SDimitry Andric   if (PTO.CallGraphProfile && !LTOPreLink)
142981ad6265SDimitry Andric     MPM.addPass(CGProfilePass());
143081ad6265SDimitry Andric 
1431349cc55cSDimitry Andric   // TODO: Relative look table converter pass caused an issue when full lto is
1432349cc55cSDimitry Andric   // enabled. See https://reviews.llvm.org/D94355 for more details.
1433349cc55cSDimitry Andric   // Until the issue fixed, disable this pass during pre-linking phase.
1434349cc55cSDimitry Andric   if (!LTOPreLink)
1435349cc55cSDimitry Andric     MPM.addPass(RelLookupTableConverterPass());
1436349cc55cSDimitry Andric 
1437349cc55cSDimitry Andric   return MPM;
1438349cc55cSDimitry Andric }
1439349cc55cSDimitry Andric 
1440349cc55cSDimitry Andric ModulePassManager
1441349cc55cSDimitry Andric PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
1442349cc55cSDimitry Andric                                            bool LTOPreLink) {
1443*06c3fb27SDimitry Andric   if (Level == OptimizationLevel::O0)
1444*06c3fb27SDimitry Andric     return buildO0DefaultPipeline(Level, LTOPreLink);
1445349cc55cSDimitry Andric 
1446349cc55cSDimitry Andric   ModulePassManager MPM;
1447349cc55cSDimitry Andric 
1448349cc55cSDimitry Andric   // Convert @llvm.global.annotations to !annotation metadata.
1449349cc55cSDimitry Andric   MPM.addPass(Annotation2MetadataPass());
1450349cc55cSDimitry Andric 
1451349cc55cSDimitry Andric   // Force any function attributes we want the rest of the pipeline to observe.
1452349cc55cSDimitry Andric   MPM.addPass(ForceFunctionAttrsPass());
1453349cc55cSDimitry Andric 
1454349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1455349cc55cSDimitry Andric     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1456349cc55cSDimitry Andric 
1457*06c3fb27SDimitry Andric   // Apply module pipeline start EP callback.
1458*06c3fb27SDimitry Andric   invokePipelineStartEPCallbacks(MPM, Level);
1459*06c3fb27SDimitry Andric 
146081ad6265SDimitry Andric   const ThinOrFullLTOPhase LTOPhase = LTOPreLink
146181ad6265SDimitry Andric                                           ? ThinOrFullLTOPhase::FullLTOPreLink
146281ad6265SDimitry Andric                                           : ThinOrFullLTOPhase::None;
1463349cc55cSDimitry Andric   // Add the core simplification pipeline.
146481ad6265SDimitry Andric   MPM.addPass(buildModuleSimplificationPipeline(Level, LTOPhase));
1465349cc55cSDimitry Andric 
1466349cc55cSDimitry Andric   // Now add the optimization pipeline.
146781ad6265SDimitry Andric   MPM.addPass(buildModuleOptimizationPipeline(Level, LTOPhase));
1468349cc55cSDimitry Andric 
1469349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1470349cc55cSDimitry Andric       PGOOpt->Action == PGOOptions::SampleUse)
1471349cc55cSDimitry Andric     MPM.addPass(PseudoProbeUpdatePass());
1472349cc55cSDimitry Andric 
1473349cc55cSDimitry Andric   // Emit annotation remarks.
1474349cc55cSDimitry Andric   addAnnotationRemarksPass(MPM);
1475349cc55cSDimitry Andric 
1476349cc55cSDimitry Andric   if (LTOPreLink)
1477349cc55cSDimitry Andric     addRequiredLTOPreLinkPasses(MPM);
1478*06c3fb27SDimitry Andric   return MPM;
1479*06c3fb27SDimitry Andric }
1480349cc55cSDimitry Andric 
1481*06c3fb27SDimitry Andric ModulePassManager
1482*06c3fb27SDimitry Andric PassBuilder::buildFatLTODefaultPipeline(OptimizationLevel Level, bool ThinLTO,
1483*06c3fb27SDimitry Andric                                         bool EmitSummary) {
1484*06c3fb27SDimitry Andric   ModulePassManager MPM;
1485*06c3fb27SDimitry Andric   MPM.addPass(EmbedBitcodePass(ThinLTO, EmitSummary,
1486*06c3fb27SDimitry Andric                                ThinLTO
1487*06c3fb27SDimitry Andric                                    ? buildThinLTOPreLinkDefaultPipeline(Level)
1488*06c3fb27SDimitry Andric                                    : buildLTOPreLinkDefaultPipeline(Level)));
1489*06c3fb27SDimitry Andric   MPM.addPass(buildPerModuleDefaultPipeline(Level));
1490349cc55cSDimitry Andric   return MPM;
1491349cc55cSDimitry Andric }
1492349cc55cSDimitry Andric 
1493349cc55cSDimitry Andric ModulePassManager
1494349cc55cSDimitry Andric PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
1495*06c3fb27SDimitry Andric   if (Level == OptimizationLevel::O0)
1496*06c3fb27SDimitry Andric     return buildO0DefaultPipeline(Level, /*LTOPreLink*/true);
1497349cc55cSDimitry Andric 
1498349cc55cSDimitry Andric   ModulePassManager MPM;
1499349cc55cSDimitry Andric 
1500349cc55cSDimitry Andric   // Convert @llvm.global.annotations to !annotation metadata.
1501349cc55cSDimitry Andric   MPM.addPass(Annotation2MetadataPass());
1502349cc55cSDimitry Andric 
1503349cc55cSDimitry Andric   // Force any function attributes we want the rest of the pipeline to observe.
1504349cc55cSDimitry Andric   MPM.addPass(ForceFunctionAttrsPass());
1505349cc55cSDimitry Andric 
1506349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1507349cc55cSDimitry Andric     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1508349cc55cSDimitry Andric 
1509349cc55cSDimitry Andric   // Apply module pipeline start EP callback.
1510*06c3fb27SDimitry Andric   invokePipelineStartEPCallbacks(MPM, Level);
1511349cc55cSDimitry Andric 
1512349cc55cSDimitry Andric   // If we are planning to perform ThinLTO later, we don't bloat the code with
1513349cc55cSDimitry Andric   // unrolling/vectorization/... now. Just simplify the module as much as we
1514349cc55cSDimitry Andric   // can.
1515349cc55cSDimitry Andric   MPM.addPass(buildModuleSimplificationPipeline(
1516349cc55cSDimitry Andric       Level, ThinOrFullLTOPhase::ThinLTOPreLink));
1517349cc55cSDimitry Andric 
1518349cc55cSDimitry Andric   // Run partial inlining pass to partially inline functions that have
1519349cc55cSDimitry Andric   // large bodies.
1520349cc55cSDimitry Andric   // FIXME: It isn't clear whether this is really the right place to run this
1521349cc55cSDimitry Andric   // in ThinLTO. Because there is another canonicalization and simplification
1522349cc55cSDimitry Andric   // phase that will run after the thin link, running this here ends up with
1523349cc55cSDimitry Andric   // less information than will be available later and it may grow functions in
1524349cc55cSDimitry Andric   // ways that aren't beneficial.
1525349cc55cSDimitry Andric   if (RunPartialInlining)
1526349cc55cSDimitry Andric     MPM.addPass(PartialInlinerPass());
1527349cc55cSDimitry Andric 
1528349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1529349cc55cSDimitry Andric       PGOOpt->Action == PGOOptions::SampleUse)
1530349cc55cSDimitry Andric     MPM.addPass(PseudoProbeUpdatePass());
1531349cc55cSDimitry Andric 
1532bdd1243dSDimitry Andric   // Handle Optimizer{Early,Last}EPCallbacks added by clang on PreLink. Actual
1533bdd1243dSDimitry Andric   // optimization is going to be done in PostLink stage, but clang can't add
1534bdd1243dSDimitry Andric   // callbacks there in case of in-process ThinLTO called by linker.
1535*06c3fb27SDimitry Andric   invokeOptimizerEarlyEPCallbacks(MPM, Level);
1536*06c3fb27SDimitry Andric   invokeOptimizerLastEPCallbacks(MPM, Level);
1537349cc55cSDimitry Andric 
1538349cc55cSDimitry Andric   // Emit annotation remarks.
1539349cc55cSDimitry Andric   addAnnotationRemarksPass(MPM);
1540349cc55cSDimitry Andric 
1541349cc55cSDimitry Andric   addRequiredLTOPreLinkPasses(MPM);
1542349cc55cSDimitry Andric 
1543349cc55cSDimitry Andric   return MPM;
1544349cc55cSDimitry Andric }
1545349cc55cSDimitry Andric 
1546349cc55cSDimitry Andric ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1547349cc55cSDimitry Andric     OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1548349cc55cSDimitry Andric   ModulePassManager MPM;
1549349cc55cSDimitry Andric 
1550349cc55cSDimitry Andric   if (ImportSummary) {
1551*06c3fb27SDimitry Andric     // For ThinLTO we must apply the context disambiguation decisions early, to
1552*06c3fb27SDimitry Andric     // ensure we can correctly match the callsites to summary data.
1553*06c3fb27SDimitry Andric     if (EnableMemProfContextDisambiguation)
1554*06c3fb27SDimitry Andric       MPM.addPass(MemProfContextDisambiguation(ImportSummary));
1555*06c3fb27SDimitry Andric 
1556349cc55cSDimitry Andric     // These passes import type identifier resolutions for whole-program
1557349cc55cSDimitry Andric     // devirtualization and CFI. They must run early because other passes may
1558349cc55cSDimitry Andric     // disturb the specific instruction patterns that these passes look for,
1559349cc55cSDimitry Andric     // creating dependencies on resolutions that may not appear in the summary.
1560349cc55cSDimitry Andric     //
1561349cc55cSDimitry Andric     // For example, GVN may transform the pattern assume(type.test) appearing in
1562349cc55cSDimitry Andric     // two basic blocks into assume(phi(type.test, type.test)), which would
1563349cc55cSDimitry Andric     // transform a dependency on a WPD resolution into a dependency on a type
1564349cc55cSDimitry Andric     // identifier resolution for CFI.
1565349cc55cSDimitry Andric     //
1566349cc55cSDimitry Andric     // Also, WPD has access to more precise information than ICP and can
1567349cc55cSDimitry Andric     // devirtualize more effectively, so it should operate on the IR first.
1568349cc55cSDimitry Andric     //
1569349cc55cSDimitry Andric     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1570349cc55cSDimitry Andric     // metadata and intrinsics.
1571349cc55cSDimitry Andric     MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1572349cc55cSDimitry Andric     MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1573349cc55cSDimitry Andric   }
1574349cc55cSDimitry Andric 
1575349cc55cSDimitry Andric   if (Level == OptimizationLevel::O0) {
1576349cc55cSDimitry Andric     // Run a second time to clean up any type tests left behind by WPD for use
1577349cc55cSDimitry Andric     // in ICP.
1578349cc55cSDimitry Andric     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1579349cc55cSDimitry Andric     // Drop available_externally and unreferenced globals. This is necessary
1580349cc55cSDimitry Andric     // with ThinLTO in order to avoid leaving undefined references to dead
1581349cc55cSDimitry Andric     // globals in the object file.
1582349cc55cSDimitry Andric     MPM.addPass(EliminateAvailableExternallyPass());
1583349cc55cSDimitry Andric     MPM.addPass(GlobalDCEPass());
1584349cc55cSDimitry Andric     return MPM;
1585349cc55cSDimitry Andric   }
1586349cc55cSDimitry Andric 
1587349cc55cSDimitry Andric   // Add the core simplification pipeline.
1588349cc55cSDimitry Andric   MPM.addPass(buildModuleSimplificationPipeline(
1589349cc55cSDimitry Andric       Level, ThinOrFullLTOPhase::ThinLTOPostLink));
1590349cc55cSDimitry Andric 
1591349cc55cSDimitry Andric   // Now add the optimization pipeline.
159281ad6265SDimitry Andric   MPM.addPass(buildModuleOptimizationPipeline(
159381ad6265SDimitry Andric       Level, ThinOrFullLTOPhase::ThinLTOPostLink));
1594349cc55cSDimitry Andric 
1595349cc55cSDimitry Andric   // Emit annotation remarks.
1596349cc55cSDimitry Andric   addAnnotationRemarksPass(MPM);
1597349cc55cSDimitry Andric 
1598349cc55cSDimitry Andric   return MPM;
1599349cc55cSDimitry Andric }
1600349cc55cSDimitry Andric 
1601349cc55cSDimitry Andric ModulePassManager
1602349cc55cSDimitry Andric PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
1603349cc55cSDimitry Andric   // FIXME: We should use a customized pre-link pipeline!
1604349cc55cSDimitry Andric   return buildPerModuleDefaultPipeline(Level,
1605349cc55cSDimitry Andric                                        /* LTOPreLink */ true);
1606349cc55cSDimitry Andric }
1607349cc55cSDimitry Andric 
1608349cc55cSDimitry Andric ModulePassManager
1609349cc55cSDimitry Andric PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
1610349cc55cSDimitry Andric                                      ModuleSummaryIndex *ExportSummary) {
1611349cc55cSDimitry Andric   ModulePassManager MPM;
1612349cc55cSDimitry Andric 
1613*06c3fb27SDimitry Andric   invokeFullLinkTimeOptimizationEarlyEPCallbacks(MPM, Level);
161481ad6265SDimitry Andric 
1615349cc55cSDimitry Andric   // Create a function that performs CFI checks for cross-DSO calls with targets
1616349cc55cSDimitry Andric   // in the current module.
1617349cc55cSDimitry Andric   MPM.addPass(CrossDSOCFIPass());
1618349cc55cSDimitry Andric 
1619349cc55cSDimitry Andric   if (Level == OptimizationLevel::O0) {
1620349cc55cSDimitry Andric     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1621349cc55cSDimitry Andric     // metadata and intrinsics.
1622349cc55cSDimitry Andric     MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1623349cc55cSDimitry Andric     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1624349cc55cSDimitry Andric     // Run a second time to clean up any type tests left behind by WPD for use
1625349cc55cSDimitry Andric     // in ICP.
1626349cc55cSDimitry Andric     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1627349cc55cSDimitry Andric 
1628*06c3fb27SDimitry Andric     invokeFullLinkTimeOptimizationLastEPCallbacks(MPM, Level);
162981ad6265SDimitry Andric 
1630349cc55cSDimitry Andric     // Emit annotation remarks.
1631349cc55cSDimitry Andric     addAnnotationRemarksPass(MPM);
1632349cc55cSDimitry Andric 
1633349cc55cSDimitry Andric     return MPM;
1634349cc55cSDimitry Andric   }
1635349cc55cSDimitry Andric 
1636349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1637349cc55cSDimitry Andric     // Load sample profile before running the LTO optimization pipeline.
1638349cc55cSDimitry Andric     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1639349cc55cSDimitry Andric                                         PGOOpt->ProfileRemappingFile,
1640349cc55cSDimitry Andric                                         ThinOrFullLTOPhase::FullLTOPostLink));
1641349cc55cSDimitry Andric     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1642349cc55cSDimitry Andric     // RequireAnalysisPass for PSI before subsequent non-module passes.
1643349cc55cSDimitry Andric     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1644349cc55cSDimitry Andric   }
1645349cc55cSDimitry Andric 
16461fd87a68SDimitry Andric   // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
16471ac55f4cSDimitry Andric   MPM.addPass(OpenMPOptPass(ThinOrFullLTOPhase::FullLTOPostLink));
16481fd87a68SDimitry Andric 
1649349cc55cSDimitry Andric   // Remove unused virtual tables to improve the quality of code generated by
1650349cc55cSDimitry Andric   // whole-program devirtualization and bitset lowering.
1651*06c3fb27SDimitry Andric   MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
1652349cc55cSDimitry Andric 
1653349cc55cSDimitry Andric   // Do basic inference of function attributes from known properties of system
1654349cc55cSDimitry Andric   // libraries and other oracles.
1655349cc55cSDimitry Andric   MPM.addPass(InferFunctionAttrsPass());
1656349cc55cSDimitry Andric 
1657349cc55cSDimitry Andric   if (Level.getSpeedupLevel() > 1) {
1658349cc55cSDimitry Andric     MPM.addPass(createModuleToFunctionPassAdaptor(
165981ad6265SDimitry Andric         CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
1660349cc55cSDimitry Andric 
1661349cc55cSDimitry Andric     // Indirect call promotion. This should promote all the targets that are
1662349cc55cSDimitry Andric     // left by the earlier promotion pass that promotes intra-module targets.
1663349cc55cSDimitry Andric     // This two-step promotion is to save the compile time. For LTO, it should
1664349cc55cSDimitry Andric     // produce the same result as if we only do promotion here.
1665349cc55cSDimitry Andric     MPM.addPass(PGOIndirectCallPromotion(
1666349cc55cSDimitry Andric         true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1667349cc55cSDimitry Andric 
1668349cc55cSDimitry Andric     // Propagate constants at call sites into the functions they call.  This
1669349cc55cSDimitry Andric     // opens opportunities for globalopt (and inlining) by substituting function
1670349cc55cSDimitry Andric     // pointers passed as arguments to direct uses of functions.
1671bdd1243dSDimitry Andric     MPM.addPass(IPSCCPPass(IPSCCPOptions(/*AllowFuncSpec=*/
1672bdd1243dSDimitry Andric                                          Level != OptimizationLevel::Os &&
1673bdd1243dSDimitry Andric                                          Level != OptimizationLevel::Oz)));
1674349cc55cSDimitry Andric 
1675349cc55cSDimitry Andric     // Attach metadata to indirect call sites indicating the set of functions
1676349cc55cSDimitry Andric     // they may target at run-time. This should follow IPSCCP.
1677349cc55cSDimitry Andric     MPM.addPass(CalledValuePropagationPass());
1678349cc55cSDimitry Andric   }
1679349cc55cSDimitry Andric 
1680349cc55cSDimitry Andric   // Now deduce any function attributes based in the current code.
1681349cc55cSDimitry Andric   MPM.addPass(
1682349cc55cSDimitry Andric       createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
1683349cc55cSDimitry Andric 
1684349cc55cSDimitry Andric   // Do RPO function attribute inference across the module to forward-propagate
1685349cc55cSDimitry Andric   // attributes where applicable.
1686349cc55cSDimitry Andric   // FIXME: Is this really an optimization rather than a canonicalization?
1687349cc55cSDimitry Andric   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1688349cc55cSDimitry Andric 
1689349cc55cSDimitry Andric   // Use in-range annotations on GEP indices to split globals where beneficial.
1690349cc55cSDimitry Andric   MPM.addPass(GlobalSplitPass());
1691349cc55cSDimitry Andric 
1692349cc55cSDimitry Andric   // Run whole program optimization of virtual call when the list of callees
1693349cc55cSDimitry Andric   // is fixed.
1694349cc55cSDimitry Andric   MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1695349cc55cSDimitry Andric 
1696349cc55cSDimitry Andric   // Stop here at -O1.
1697349cc55cSDimitry Andric   if (Level == OptimizationLevel::O1) {
1698349cc55cSDimitry Andric     // The LowerTypeTestsPass needs to run to lower type metadata and the
1699349cc55cSDimitry Andric     // type.test intrinsics. The pass does nothing if CFI is disabled.
1700349cc55cSDimitry Andric     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1701349cc55cSDimitry Andric     // Run a second time to clean up any type tests left behind by WPD for use
1702349cc55cSDimitry Andric     // in ICP (which is performed earlier than this in the regular LTO
1703349cc55cSDimitry Andric     // pipeline).
1704349cc55cSDimitry Andric     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1705349cc55cSDimitry Andric 
1706*06c3fb27SDimitry Andric     invokeFullLinkTimeOptimizationLastEPCallbacks(MPM, Level);
170781ad6265SDimitry Andric 
1708349cc55cSDimitry Andric     // Emit annotation remarks.
1709349cc55cSDimitry Andric     addAnnotationRemarksPass(MPM);
1710349cc55cSDimitry Andric 
1711349cc55cSDimitry Andric     return MPM;
1712349cc55cSDimitry Andric   }
1713349cc55cSDimitry Andric 
1714349cc55cSDimitry Andric   // Optimize globals to try and fold them into constants.
1715349cc55cSDimitry Andric   MPM.addPass(GlobalOptPass());
1716349cc55cSDimitry Andric 
1717349cc55cSDimitry Andric   // Promote any localized globals to SSA registers.
1718349cc55cSDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1719349cc55cSDimitry Andric 
1720349cc55cSDimitry Andric   // Linking modules together can lead to duplicate global constant, only
1721349cc55cSDimitry Andric   // keep one copy of each constant.
1722349cc55cSDimitry Andric   MPM.addPass(ConstantMergePass());
1723349cc55cSDimitry Andric 
17241ac55f4cSDimitry Andric   // Remove unused arguments from functions.
17251ac55f4cSDimitry Andric   MPM.addPass(DeadArgumentEliminationPass());
17261ac55f4cSDimitry Andric 
1727349cc55cSDimitry Andric   // Reduce the code after globalopt and ipsccp.  Both can open up significant
1728349cc55cSDimitry Andric   // simplification opportunities, and both can propagate functions through
1729349cc55cSDimitry Andric   // function pointers.  When this happens, we often have to resolve varargs
1730349cc55cSDimitry Andric   // calls, etc, so let instcombine do this.
1731349cc55cSDimitry Andric   FunctionPassManager PeepholeFPM;
17320eae32dcSDimitry Andric   PeepholeFPM.addPass(InstCombinePass());
1733*06c3fb27SDimitry Andric   if (Level.getSpeedupLevel() > 1)
1734349cc55cSDimitry Andric     PeepholeFPM.addPass(AggressiveInstCombinePass());
1735349cc55cSDimitry Andric   invokePeepholeEPCallbacks(PeepholeFPM, Level);
1736349cc55cSDimitry Andric 
1737349cc55cSDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
1738349cc55cSDimitry Andric                                                 PTO.EagerlyInvalidateAnalyses));
1739349cc55cSDimitry Andric 
1740349cc55cSDimitry Andric   // Note: historically, the PruneEH pass was run first to deduce nounwind and
1741349cc55cSDimitry Andric   // generally clean up exception handling overhead. It isn't clear this is
1742349cc55cSDimitry Andric   // valuable as the inliner doesn't currently care whether it is inlining an
1743349cc55cSDimitry Andric   // invoke or a call.
1744349cc55cSDimitry Andric   // Run the inliner now.
1745*06c3fb27SDimitry Andric   if (EnableModuleInliner) {
1746*06c3fb27SDimitry Andric     MPM.addPass(ModuleInlinerPass(getInlineParamsFromOptLevel(Level),
1747*06c3fb27SDimitry Andric                                   UseInlineAdvisor,
1748*06c3fb27SDimitry Andric                                   ThinOrFullLTOPhase::FullLTOPostLink));
1749*06c3fb27SDimitry Andric   } else {
175081ad6265SDimitry Andric     MPM.addPass(ModuleInlinerWrapperPass(
175181ad6265SDimitry Andric         getInlineParamsFromOptLevel(Level),
175281ad6265SDimitry Andric         /* MandatoryFirst */ true,
175381ad6265SDimitry Andric         InlineContext{ThinOrFullLTOPhase::FullLTOPostLink,
175481ad6265SDimitry Andric                       InlinePass::CGSCCInliner}));
1755*06c3fb27SDimitry Andric   }
1756*06c3fb27SDimitry Andric 
1757*06c3fb27SDimitry Andric   // Perform context disambiguation after inlining, since that would reduce the
1758*06c3fb27SDimitry Andric   // amount of additional cloning required to distinguish the allocation
1759*06c3fb27SDimitry Andric   // contexts.
1760*06c3fb27SDimitry Andric   if (EnableMemProfContextDisambiguation)
1761*06c3fb27SDimitry Andric     MPM.addPass(MemProfContextDisambiguation());
1762349cc55cSDimitry Andric 
1763349cc55cSDimitry Andric   // Optimize globals again after we ran the inliner.
1764349cc55cSDimitry Andric   MPM.addPass(GlobalOptPass());
1765349cc55cSDimitry Andric 
17661ac55f4cSDimitry Andric   // Run the OpenMPOpt pass again after global optimizations.
17671ac55f4cSDimitry Andric   MPM.addPass(OpenMPOptPass(ThinOrFullLTOPhase::FullLTOPostLink));
17681ac55f4cSDimitry Andric 
1769349cc55cSDimitry Andric   // Garbage collect dead functions.
1770*06c3fb27SDimitry Andric   MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
1771349cc55cSDimitry Andric 
1772349cc55cSDimitry Andric   // If we didn't decide to inline a function, check to see if we can
1773349cc55cSDimitry Andric   // transform it to pass arguments by value instead of by reference.
1774349cc55cSDimitry Andric   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(ArgumentPromotionPass()));
1775349cc55cSDimitry Andric 
1776349cc55cSDimitry Andric   FunctionPassManager FPM;
1777349cc55cSDimitry Andric   // The IPO Passes may leave cruft around. Clean up after them.
1778349cc55cSDimitry Andric   FPM.addPass(InstCombinePass());
1779349cc55cSDimitry Andric   invokePeepholeEPCallbacks(FPM, Level);
1780349cc55cSDimitry Andric 
1781bdd1243dSDimitry Andric   if (EnableConstraintElimination)
1782bdd1243dSDimitry Andric     FPM.addPass(ConstraintEliminationPass());
1783bdd1243dSDimitry Andric 
178481ad6265SDimitry Andric   FPM.addPass(JumpThreadingPass());
1785349cc55cSDimitry Andric 
1786349cc55cSDimitry Andric   // Do a post inline PGO instrumentation and use pass. This is a context
1787349cc55cSDimitry Andric   // sensitive PGO pass.
1788349cc55cSDimitry Andric   if (PGOOpt) {
1789349cc55cSDimitry Andric     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1790349cc55cSDimitry Andric       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
1791349cc55cSDimitry Andric                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
179281ad6265SDimitry Andric                         PGOOpt->ProfileRemappingFile,
1793*06c3fb27SDimitry Andric                         ThinOrFullLTOPhase::FullLTOPostLink, PGOOpt->FS);
1794349cc55cSDimitry Andric     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1795349cc55cSDimitry Andric       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
1796349cc55cSDimitry Andric                         /* IsCS */ true, PGOOpt->ProfileFile,
179781ad6265SDimitry Andric                         PGOOpt->ProfileRemappingFile,
1798*06c3fb27SDimitry Andric                         ThinOrFullLTOPhase::FullLTOPostLink, PGOOpt->FS);
1799349cc55cSDimitry Andric   }
1800349cc55cSDimitry Andric 
1801349cc55cSDimitry Andric   // Break up allocas
1802bdd1243dSDimitry Andric   FPM.addPass(SROAPass(SROAOptions::ModifyCFG));
1803349cc55cSDimitry Andric 
1804349cc55cSDimitry Andric   // LTO provides additional opportunities for tailcall elimination due to
1805349cc55cSDimitry Andric   // link-time inlining, and visibility of nocapture attribute.
1806349cc55cSDimitry Andric   FPM.addPass(TailCallElimPass());
1807349cc55cSDimitry Andric 
1808349cc55cSDimitry Andric   // Run a few AA driver optimizations here and now to cleanup the code.
1809349cc55cSDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
1810349cc55cSDimitry Andric                                                 PTO.EagerlyInvalidateAnalyses));
1811349cc55cSDimitry Andric 
1812349cc55cSDimitry Andric   MPM.addPass(
1813349cc55cSDimitry Andric       createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
1814349cc55cSDimitry Andric 
1815349cc55cSDimitry Andric   // Require the GlobalsAA analysis for the module so we can query it within
1816349cc55cSDimitry Andric   // MainFPM.
1817349cc55cSDimitry Andric   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
1818349cc55cSDimitry Andric   // Invalidate AAManager so it can be recreated and pick up the newly available
1819349cc55cSDimitry Andric   // GlobalsAA.
1820349cc55cSDimitry Andric   MPM.addPass(
1821349cc55cSDimitry Andric       createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
1822349cc55cSDimitry Andric 
1823349cc55cSDimitry Andric   FunctionPassManager MainFPM;
1824349cc55cSDimitry Andric   MainFPM.addPass(createFunctionToLoopPassAdaptor(
1825fb03ea46SDimitry Andric       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1826fb03ea46SDimitry Andric                /*AllowSpeculation=*/true),
1827*06c3fb27SDimitry Andric       /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/false));
1828349cc55cSDimitry Andric 
1829349cc55cSDimitry Andric   if (RunNewGVN)
1830349cc55cSDimitry Andric     MainFPM.addPass(NewGVNPass());
1831349cc55cSDimitry Andric   else
1832349cc55cSDimitry Andric     MainFPM.addPass(GVNPass());
1833349cc55cSDimitry Andric 
1834349cc55cSDimitry Andric   // Remove dead memcpy()'s.
1835349cc55cSDimitry Andric   MainFPM.addPass(MemCpyOptPass());
1836349cc55cSDimitry Andric 
1837349cc55cSDimitry Andric   // Nuke dead stores.
1838349cc55cSDimitry Andric   MainFPM.addPass(DSEPass());
1839*06c3fb27SDimitry Andric   MainFPM.addPass(MoveAutoInitPass());
1840349cc55cSDimitry Andric   MainFPM.addPass(MergedLoadStoreMotionPass());
1841349cc55cSDimitry Andric 
1842349cc55cSDimitry Andric   LoopPassManager LPM;
184304eeddc0SDimitry Andric   if (EnableLoopFlatten && Level.getSpeedupLevel() > 1)
184404eeddc0SDimitry Andric     LPM.addPass(LoopFlattenPass());
1845349cc55cSDimitry Andric   LPM.addPass(IndVarSimplifyPass());
1846349cc55cSDimitry Andric   LPM.addPass(LoopDeletionPass());
1847349cc55cSDimitry Andric   // FIXME: Add loop interchange.
1848349cc55cSDimitry Andric 
1849349cc55cSDimitry Andric   // Unroll small loops and perform peeling.
1850349cc55cSDimitry Andric   LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
1851349cc55cSDimitry Andric                                  /* OnlyWhenForced= */ !PTO.LoopUnrolling,
1852349cc55cSDimitry Andric                                  PTO.ForgetAllSCEVInLoopUnroll));
1853349cc55cSDimitry Andric   // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
1854349cc55cSDimitry Andric   // *All* loop passes must preserve it, in order to be able to use it.
1855349cc55cSDimitry Andric   MainFPM.addPass(createFunctionToLoopPassAdaptor(
1856349cc55cSDimitry Andric       std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true));
1857349cc55cSDimitry Andric 
1858349cc55cSDimitry Andric   MainFPM.addPass(LoopDistributePass());
1859349cc55cSDimitry Andric 
1860349cc55cSDimitry Andric   addVectorPasses(Level, MainFPM, /* IsFullLTO */ true);
1861349cc55cSDimitry Andric 
18621fd87a68SDimitry Andric   // Run the OpenMPOpt CGSCC pass again late.
18631ac55f4cSDimitry Andric   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
18641ac55f4cSDimitry Andric       OpenMPOptCGSCCPass(ThinOrFullLTOPhase::FullLTOPostLink)));
18651fd87a68SDimitry Andric 
1866349cc55cSDimitry Andric   invokePeepholeEPCallbacks(MainFPM, Level);
186781ad6265SDimitry Andric   MainFPM.addPass(JumpThreadingPass());
1868349cc55cSDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
1869349cc55cSDimitry Andric                                                 PTO.EagerlyInvalidateAnalyses));
1870349cc55cSDimitry Andric 
1871349cc55cSDimitry Andric   // Lower type metadata and the type.test intrinsic. This pass supports
1872349cc55cSDimitry Andric   // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1873349cc55cSDimitry Andric   // to be run at link time if CFI is enabled. This pass does nothing if
1874349cc55cSDimitry Andric   // CFI is disabled.
1875349cc55cSDimitry Andric   MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1876349cc55cSDimitry Andric   // Run a second time to clean up any type tests left behind by WPD for use
1877349cc55cSDimitry Andric   // in ICP (which is performed earlier than this in the regular LTO pipeline).
1878349cc55cSDimitry Andric   MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1879349cc55cSDimitry Andric 
1880753f127fSDimitry Andric   // Enable splitting late in the FullLTO post-link pipeline.
1881349cc55cSDimitry Andric   if (EnableHotColdSplit)
1882349cc55cSDimitry Andric     MPM.addPass(HotColdSplittingPass());
1883349cc55cSDimitry Andric 
1884349cc55cSDimitry Andric   // Add late LTO optimization passes.
1885*06c3fb27SDimitry Andric   FunctionPassManager LateFPM;
1886*06c3fb27SDimitry Andric 
1887*06c3fb27SDimitry Andric   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1888*06c3fb27SDimitry Andric   // canonicalization pass that enables other optimizations. As a result,
1889*06c3fb27SDimitry Andric   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1890*06c3fb27SDimitry Andric   // result too early.
1891*06c3fb27SDimitry Andric   LateFPM.addPass(LoopSinkPass());
1892*06c3fb27SDimitry Andric 
1893*06c3fb27SDimitry Andric   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1894*06c3fb27SDimitry Andric   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1895*06c3fb27SDimitry Andric   // flattening of blocks.
1896*06c3fb27SDimitry Andric   LateFPM.addPass(DivRemPairsPass());
1897*06c3fb27SDimitry Andric 
1898349cc55cSDimitry Andric   // Delete basic blocks, which optimization passes may have killed.
1899*06c3fb27SDimitry Andric   LateFPM.addPass(SimplifyCFGPass(
1900fb03ea46SDimitry Andric       SimplifyCFGOptions().convertSwitchRangeToICmp(true).hoistCommonInsts(
1901*06c3fb27SDimitry Andric           true)));
1902*06c3fb27SDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
1903349cc55cSDimitry Andric 
1904349cc55cSDimitry Andric   // Drop bodies of available eternally objects to improve GlobalDCE.
1905349cc55cSDimitry Andric   MPM.addPass(EliminateAvailableExternallyPass());
1906349cc55cSDimitry Andric 
1907349cc55cSDimitry Andric   // Now that we have optimized the program, discard unreachable functions.
1908*06c3fb27SDimitry Andric   MPM.addPass(GlobalDCEPass(/*InLTOPostLink=*/true));
1909349cc55cSDimitry Andric 
1910349cc55cSDimitry Andric   if (PTO.MergeFunctions)
1911349cc55cSDimitry Andric     MPM.addPass(MergeFunctionsPass());
1912349cc55cSDimitry Andric 
191381ad6265SDimitry Andric   if (PTO.CallGraphProfile)
191481ad6265SDimitry Andric     MPM.addPass(CGProfilePass());
191581ad6265SDimitry Andric 
1916*06c3fb27SDimitry Andric   invokeFullLinkTimeOptimizationLastEPCallbacks(MPM, Level);
191781ad6265SDimitry Andric 
1918349cc55cSDimitry Andric   // Emit annotation remarks.
1919349cc55cSDimitry Andric   addAnnotationRemarksPass(MPM);
1920349cc55cSDimitry Andric 
1921349cc55cSDimitry Andric   return MPM;
1922349cc55cSDimitry Andric }
1923349cc55cSDimitry Andric 
1924349cc55cSDimitry Andric ModulePassManager PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level,
1925349cc55cSDimitry Andric                                                       bool LTOPreLink) {
1926349cc55cSDimitry Andric   assert(Level == OptimizationLevel::O0 &&
1927349cc55cSDimitry Andric          "buildO0DefaultPipeline should only be used with O0");
1928349cc55cSDimitry Andric 
1929349cc55cSDimitry Andric   ModulePassManager MPM;
1930349cc55cSDimitry Andric 
1931349cc55cSDimitry Andric   // Perform pseudo probe instrumentation in O0 mode. This is for the
1932349cc55cSDimitry Andric   // consistency between different build modes. For example, a LTO build can be
1933349cc55cSDimitry Andric   // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
1934349cc55cSDimitry Andric   // the postlink will require pseudo probe instrumentation in the prelink.
1935349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
1936349cc55cSDimitry Andric     MPM.addPass(SampleProfileProbePass(TM));
1937349cc55cSDimitry Andric 
1938349cc55cSDimitry Andric   if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1939349cc55cSDimitry Andric                  PGOOpt->Action == PGOOptions::IRUse))
1940349cc55cSDimitry Andric     addPGOInstrPassesForO0(
1941349cc55cSDimitry Andric         MPM,
1942349cc55cSDimitry Andric         /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1943*06c3fb27SDimitry Andric         /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile,
1944*06c3fb27SDimitry Andric         PGOOpt->FS);
1945349cc55cSDimitry Andric 
1946*06c3fb27SDimitry Andric   invokePipelineStartEPCallbacks(MPM, Level);
1947349cc55cSDimitry Andric 
1948349cc55cSDimitry Andric   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1949349cc55cSDimitry Andric     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1950349cc55cSDimitry Andric 
1951*06c3fb27SDimitry Andric   invokePipelineEarlySimplificationEPCallbacks(MPM, Level);
1952349cc55cSDimitry Andric 
1953349cc55cSDimitry Andric   // Build a minimal pipeline based on the semantics required by LLVM,
1954349cc55cSDimitry Andric   // which is just that always inlining occurs. Further, disable generating
1955349cc55cSDimitry Andric   // lifetime intrinsics to avoid enabling further optimizations during
1956349cc55cSDimitry Andric   // code generation.
1957349cc55cSDimitry Andric   MPM.addPass(AlwaysInlinerPass(
1958349cc55cSDimitry Andric       /*InsertLifetimeIntrinsics=*/false));
1959349cc55cSDimitry Andric 
1960349cc55cSDimitry Andric   if (PTO.MergeFunctions)
1961349cc55cSDimitry Andric     MPM.addPass(MergeFunctionsPass());
1962349cc55cSDimitry Andric 
1963349cc55cSDimitry Andric   if (EnableMatrix)
1964349cc55cSDimitry Andric     MPM.addPass(
1965349cc55cSDimitry Andric         createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass(true)));
1966349cc55cSDimitry Andric 
1967349cc55cSDimitry Andric   if (!CGSCCOptimizerLateEPCallbacks.empty()) {
1968349cc55cSDimitry Andric     CGSCCPassManager CGPM;
1969*06c3fb27SDimitry Andric     invokeCGSCCOptimizerLateEPCallbacks(CGPM, Level);
1970349cc55cSDimitry Andric     if (!CGPM.isEmpty())
1971349cc55cSDimitry Andric       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1972349cc55cSDimitry Andric   }
1973349cc55cSDimitry Andric   if (!LateLoopOptimizationsEPCallbacks.empty()) {
1974349cc55cSDimitry Andric     LoopPassManager LPM;
1975*06c3fb27SDimitry Andric     invokeLateLoopOptimizationsEPCallbacks(LPM, Level);
1976349cc55cSDimitry Andric     if (!LPM.isEmpty()) {
1977349cc55cSDimitry Andric       MPM.addPass(createModuleToFunctionPassAdaptor(
1978349cc55cSDimitry Andric           createFunctionToLoopPassAdaptor(std::move(LPM))));
1979349cc55cSDimitry Andric     }
1980349cc55cSDimitry Andric   }
1981349cc55cSDimitry Andric   if (!LoopOptimizerEndEPCallbacks.empty()) {
1982349cc55cSDimitry Andric     LoopPassManager LPM;
1983*06c3fb27SDimitry Andric     invokeLoopOptimizerEndEPCallbacks(LPM, Level);
1984349cc55cSDimitry Andric     if (!LPM.isEmpty()) {
1985349cc55cSDimitry Andric       MPM.addPass(createModuleToFunctionPassAdaptor(
1986349cc55cSDimitry Andric           createFunctionToLoopPassAdaptor(std::move(LPM))));
1987349cc55cSDimitry Andric     }
1988349cc55cSDimitry Andric   }
1989349cc55cSDimitry Andric   if (!ScalarOptimizerLateEPCallbacks.empty()) {
1990349cc55cSDimitry Andric     FunctionPassManager FPM;
1991*06c3fb27SDimitry Andric     invokeScalarOptimizerLateEPCallbacks(FPM, Level);
1992349cc55cSDimitry Andric     if (!FPM.isEmpty())
1993349cc55cSDimitry Andric       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1994349cc55cSDimitry Andric   }
199581ad6265SDimitry Andric 
1996*06c3fb27SDimitry Andric   invokeOptimizerEarlyEPCallbacks(MPM, Level);
199781ad6265SDimitry Andric 
1998349cc55cSDimitry Andric   if (!VectorizerStartEPCallbacks.empty()) {
1999349cc55cSDimitry Andric     FunctionPassManager FPM;
2000*06c3fb27SDimitry Andric     invokeVectorizerStartEPCallbacks(FPM, Level);
2001349cc55cSDimitry Andric     if (!FPM.isEmpty())
2002349cc55cSDimitry Andric       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
2003349cc55cSDimitry Andric   }
2004349cc55cSDimitry Andric 
200581ad6265SDimitry Andric   ModulePassManager CoroPM;
200681ad6265SDimitry Andric   CoroPM.addPass(CoroEarlyPass());
2007349cc55cSDimitry Andric   CGSCCPassManager CGPM;
2008349cc55cSDimitry Andric   CGPM.addPass(CoroSplitPass());
200981ad6265SDimitry Andric   CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
201081ad6265SDimitry Andric   CoroPM.addPass(CoroCleanupPass());
201181ad6265SDimitry Andric   CoroPM.addPass(GlobalDCEPass());
201281ad6265SDimitry Andric   MPM.addPass(CoroConditionalWrapper(std::move(CoroPM)));
2013349cc55cSDimitry Andric 
2014*06c3fb27SDimitry Andric   invokeOptimizerLastEPCallbacks(MPM, Level);
2015349cc55cSDimitry Andric 
2016349cc55cSDimitry Andric   if (LTOPreLink)
2017349cc55cSDimitry Andric     addRequiredLTOPreLinkPasses(MPM);
2018349cc55cSDimitry Andric 
20194824e7fdSDimitry Andric   MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass()));
20204824e7fdSDimitry Andric 
2021349cc55cSDimitry Andric   return MPM;
2022349cc55cSDimitry Andric }
2023349cc55cSDimitry Andric 
2024349cc55cSDimitry Andric AAManager PassBuilder::buildDefaultAAPipeline() {
2025349cc55cSDimitry Andric   AAManager AA;
2026349cc55cSDimitry Andric 
2027349cc55cSDimitry Andric   // The order in which these are registered determines their priority when
2028349cc55cSDimitry Andric   // being queried.
2029349cc55cSDimitry Andric 
2030349cc55cSDimitry Andric   // First we register the basic alias analysis that provides the majority of
2031349cc55cSDimitry Andric   // per-function local AA logic. This is a stateless, on-demand local set of
2032349cc55cSDimitry Andric   // AA techniques.
2033349cc55cSDimitry Andric   AA.registerFunctionAnalysis<BasicAA>();
2034349cc55cSDimitry Andric 
2035349cc55cSDimitry Andric   // Next we query fast, specialized alias analyses that wrap IR-embedded
2036349cc55cSDimitry Andric   // information about aliasing.
2037349cc55cSDimitry Andric   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
2038349cc55cSDimitry Andric   AA.registerFunctionAnalysis<TypeBasedAA>();
2039349cc55cSDimitry Andric 
2040349cc55cSDimitry Andric   // Add support for querying global aliasing information when available.
2041349cc55cSDimitry Andric   // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
2042349cc55cSDimitry Andric   // analysis, all that the `AAManager` can do is query for any *cached*
2043349cc55cSDimitry Andric   // results from `GlobalsAA` through a readonly proxy.
2044bdd1243dSDimitry Andric   if (EnableGlobalAnalyses)
2045349cc55cSDimitry Andric     AA.registerModuleAnalysis<GlobalsAA>();
2046349cc55cSDimitry Andric 
2047349cc55cSDimitry Andric   // Add target-specific alias analyses.
2048349cc55cSDimitry Andric   if (TM)
2049349cc55cSDimitry Andric     TM->registerDefaultAliasAnalyses(AA);
2050349cc55cSDimitry Andric 
2051349cc55cSDimitry Andric   return AA;
2052349cc55cSDimitry Andric }
2053