1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the PassManagerBuilder class, which is used to set up a
10 // "standard" optimization sequence suitable for languages like C and C++.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
15 #include "llvm-c/Transforms/PassManagerBuilder.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/BasicAliasAnalysis.h"
19 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
20 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
21 #include "llvm/Analysis/GlobalsModRef.h"
22 #include "llvm/Analysis/InlineCost.h"
23 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Analysis/ScopedNoAliasAA.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/LegacyPassManager.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
33 #include "llvm/Transforms/IPO.h"
34 #include "llvm/Transforms/IPO/Attributor.h"
35 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
36 #include "llvm/Transforms/IPO/FunctionAttrs.h"
37 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
38 #include "llvm/Transforms/InstCombine/InstCombine.h"
39 #include "llvm/Transforms/Instrumentation.h"
40 #include "llvm/Transforms/Scalar.h"
41 #include "llvm/Transforms/Scalar/GVN.h"
42 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
43 #include "llvm/Transforms/Scalar/LICM.h"
44 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
45 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
46 #include "llvm/Transforms/Utils.h"
47 #include "llvm/Transforms/Vectorize.h"
48 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
49 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
50 #include "llvm/Transforms/Vectorize/VectorCombine.h"
51 
52 using namespace llvm;
53 
54 static cl::opt<bool>
55     RunPartialInlining("enable-partial-inlining", cl::init(false), cl::Hidden,
56                        cl::ZeroOrMore, cl::desc("Run Partial inlinining pass"));
57 
58 static cl::opt<bool>
59 UseGVNAfterVectorization("use-gvn-after-vectorization",
60   cl::init(false), cl::Hidden,
61   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
62 
63 static cl::opt<bool> ExtraVectorizerPasses(
64     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
65     cl::desc("Run cleanup optimization passes after vectorization."));
66 
67 static cl::opt<bool>
68 RunLoopRerolling("reroll-loops", cl::Hidden,
69                  cl::desc("Run the loop rerolling pass"));
70 
71 static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
72                                cl::desc("Run the NewGVN pass"));
73 
74 // Experimental option to use CFL-AA
75 enum class CFLAAType { None, Steensgaard, Andersen, Both };
76 static cl::opt<CFLAAType>
77     UseCFLAA("use-cfl-aa", cl::init(CFLAAType::None), cl::Hidden,
78              cl::desc("Enable the new, experimental CFL alias analysis"),
79              cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
80                         clEnumValN(CFLAAType::Steensgaard, "steens",
81                                    "Enable unification-based CFL-AA"),
82                         clEnumValN(CFLAAType::Andersen, "anders",
83                                    "Enable inclusion-based CFL-AA"),
84                         clEnumValN(CFLAAType::Both, "both",
85                                    "Enable both variants of CFL-AA")));
86 
87 static cl::opt<bool> EnableLoopInterchange(
88     "enable-loopinterchange", cl::init(false), cl::Hidden,
89     cl::desc("Enable the new, experimental LoopInterchange Pass"));
90 
91 static cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam",
92                                         cl::init(false), cl::Hidden,
93                                         cl::desc("Enable Unroll And Jam Pass"));
94 
95 static cl::opt<bool>
96     EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden,
97                             cl::desc("Enable preparation for ThinLTO."));
98 
99 static cl::opt<bool>
100     EnablePerformThinLTO("perform-thinlto", cl::init(false), cl::Hidden,
101                          cl::desc("Enable performing ThinLTO."));
102 
103 cl::opt<bool> EnableHotColdSplit("hot-cold-split", cl::init(false),
104     cl::ZeroOrMore, cl::desc("Enable hot-cold splitting pass"));
105 
106 static cl::opt<bool> UseLoopVersioningLICM(
107     "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
108     cl::desc("Enable the experimental Loop Versioning LICM pass"));
109 
110 static cl::opt<bool>
111     DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
112                       cl::desc("Disable pre-instrumentation inliner"));
113 
114 static cl::opt<int> PreInlineThreshold(
115     "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore,
116     cl::desc("Control the amount of inlining in pre-instrumentation inliner "
117              "(default = 75)"));
118 
119 static cl::opt<bool> EnableGVNHoist(
120     "enable-gvn-hoist", cl::init(false), cl::ZeroOrMore,
121     cl::desc("Enable the GVN hoisting pass (default = off)"));
122 
123 static cl::opt<bool>
124     DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false),
125                               cl::Hidden,
126                               cl::desc("Disable shrink-wrap library calls"));
127 
128 static cl::opt<bool> EnableSimpleLoopUnswitch(
129     "enable-simple-loop-unswitch", cl::init(false), cl::Hidden,
130     cl::desc("Enable the simple loop unswitch pass. Also enables independent "
131              "cleanup passes integrated into the loop pass manager pipeline."));
132 
133 static cl::opt<bool> EnableGVNSink(
134     "enable-gvn-sink", cl::init(false), cl::ZeroOrMore,
135     cl::desc("Enable the GVN sinking pass (default = off)"));
136 
137 // This option is used in simplifying testing SampleFDO optimizations for
138 // profile loading.
139 static cl::opt<bool>
140     EnableCHR("enable-chr", cl::init(true), cl::Hidden,
141               cl::desc("Enable control height reduction optimization (CHR)"));
142 
143 cl::opt<bool> FlattenedProfileUsed(
144     "flattened-profile-used", cl::init(false), cl::Hidden,
145     cl::desc("Indicate the sample profile being used is flattened, i.e., "
146              "no inline hierachy exists in the profile. "));
147 
148 cl::opt<bool> EnableOrderFileInstrumentation(
149     "enable-order-file-instrumentation", cl::init(false), cl::Hidden,
150     cl::desc("Enable order file instrumentation (default = off)"));
151 
152 cl::opt<bool> EnableMatrix(
153     "enable-matrix", cl::init(false), cl::Hidden,
154     cl::desc("Enable lowering of the matrix intrinsics"));
155 
156 cl::opt<bool> EnableConstraintElimination(
157     "enable-constraint-elimination", cl::init(false), cl::Hidden,
158     cl::desc(
159         "Enable pass to eliminate conditions based on linear constraints."));
160 
161 cl::opt<AttributorRunOption> AttributorRun(
162     "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
163     cl::desc("Enable the attributor inter-procedural deduction pass."),
164     cl::values(clEnumValN(AttributorRunOption::ALL, "all",
165                           "enable all attributor runs"),
166                clEnumValN(AttributorRunOption::MODULE, "module",
167                           "enable module-wide attributor runs"),
168                clEnumValN(AttributorRunOption::CGSCC, "cgscc",
169                           "enable call graph SCC attributor runs"),
170                clEnumValN(AttributorRunOption::NONE, "none",
171                           "disable attributor runs")));
172 
173 extern cl::opt<bool> EnableKnowledgeRetention;
174 
175 PassManagerBuilder::PassManagerBuilder() {
176     OptLevel = 2;
177     SizeLevel = 0;
178     LibraryInfo = nullptr;
179     Inliner = nullptr;
180     DisableUnrollLoops = false;
181     SLPVectorize = false;
182     LoopVectorize = true;
183     LoopsInterleaved = true;
184     RerollLoops = RunLoopRerolling;
185     NewGVN = RunNewGVN;
186     LicmMssaOptCap = SetLicmMssaOptCap;
187     LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
188     DisableGVNLoadPRE = false;
189     ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
190     VerifyInput = false;
191     VerifyOutput = false;
192     MergeFunctions = false;
193     PrepareForLTO = false;
194     EnablePGOInstrGen = false;
195     EnablePGOCSInstrGen = false;
196     EnablePGOCSInstrUse = false;
197     PGOInstrGen = "";
198     PGOInstrUse = "";
199     PGOSampleUse = "";
200     PrepareForThinLTO = EnablePrepareForThinLTO;
201     PerformThinLTO = EnablePerformThinLTO;
202     DivergentTarget = false;
203     CallGraphProfile = true;
204 }
205 
206 PassManagerBuilder::~PassManagerBuilder() {
207   delete LibraryInfo;
208   delete Inliner;
209 }
210 
211 /// Set of global extensions, automatically added as part of the standard set.
212 static ManagedStatic<
213     SmallVector<std::tuple<PassManagerBuilder::ExtensionPointTy,
214                            PassManagerBuilder::ExtensionFn,
215                            PassManagerBuilder::GlobalExtensionID>,
216                 8>>
217     GlobalExtensions;
218 static PassManagerBuilder::GlobalExtensionID GlobalExtensionsCounter;
219 
220 /// Check if GlobalExtensions is constructed and not empty.
221 /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger
222 /// the construction of the object.
223 static bool GlobalExtensionsNotEmpty() {
224   return GlobalExtensions.isConstructed() && !GlobalExtensions->empty();
225 }
226 
227 PassManagerBuilder::GlobalExtensionID
228 PassManagerBuilder::addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty,
229                                        PassManagerBuilder::ExtensionFn Fn) {
230   auto ExtensionID = GlobalExtensionsCounter++;
231   GlobalExtensions->push_back(std::make_tuple(Ty, std::move(Fn), ExtensionID));
232   return ExtensionID;
233 }
234 
235 void PassManagerBuilder::removeGlobalExtension(
236     PassManagerBuilder::GlobalExtensionID ExtensionID) {
237   // RegisterStandardPasses may try to call this function after GlobalExtensions
238   // has already been destroyed; doing so should not generate an error.
239   if (!GlobalExtensions.isConstructed())
240     return;
241 
242   auto GlobalExtension =
243       llvm::find_if(*GlobalExtensions, [ExtensionID](const auto &elem) {
244         return std::get<2>(elem) == ExtensionID;
245       });
246   assert(GlobalExtension != GlobalExtensions->end() &&
247          "The extension ID to be removed should always be valid.");
248 
249   GlobalExtensions->erase(GlobalExtension);
250 }
251 
252 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
253   Extensions.push_back(std::make_pair(Ty, std::move(Fn)));
254 }
255 
256 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
257                                            legacy::PassManagerBase &PM) const {
258   if (GlobalExtensionsNotEmpty()) {
259     for (auto &Ext : *GlobalExtensions) {
260       if (std::get<0>(Ext) == ETy)
261         std::get<1>(Ext)(*this, PM);
262     }
263   }
264   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
265     if (Extensions[i].first == ETy)
266       Extensions[i].second(*this, PM);
267 }
268 
269 void PassManagerBuilder::addInitialAliasAnalysisPasses(
270     legacy::PassManagerBase &PM) const {
271   switch (UseCFLAA) {
272   case CFLAAType::Steensgaard:
273     PM.add(createCFLSteensAAWrapperPass());
274     break;
275   case CFLAAType::Andersen:
276     PM.add(createCFLAndersAAWrapperPass());
277     break;
278   case CFLAAType::Both:
279     PM.add(createCFLSteensAAWrapperPass());
280     PM.add(createCFLAndersAAWrapperPass());
281     break;
282   default:
283     break;
284   }
285 
286   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
287   // BasicAliasAnalysis wins if they disagree. This is intended to help
288   // support "obvious" type-punning idioms.
289   PM.add(createTypeBasedAAWrapperPass());
290   PM.add(createScopedNoAliasAAWrapperPass());
291 }
292 
293 void PassManagerBuilder::populateFunctionPassManager(
294     legacy::FunctionPassManager &FPM) {
295   addExtensionsToPM(EP_EarlyAsPossible, FPM);
296   FPM.add(createEntryExitInstrumenterPass());
297 
298   // Add LibraryInfo if we have some.
299   if (LibraryInfo)
300     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
301 
302   // The backends do not handle matrix intrinsics currently.
303   // Make sure they are also lowered in O0.
304   // FIXME: A lightweight version of the pass should run in the backend
305   //        pipeline on demand.
306   if (EnableMatrix && OptLevel == 0)
307     FPM.add(createLowerMatrixIntrinsicsMinimalPass());
308 
309   if (OptLevel == 0) return;
310 
311   addInitialAliasAnalysisPasses(FPM);
312 
313   FPM.add(createCFGSimplificationPass());
314   FPM.add(createSROAPass());
315   FPM.add(createEarlyCSEPass());
316   FPM.add(createLowerExpectIntrinsicPass());
317 }
318 
319 // Do PGO instrumentation generation or use pass as the option specified.
320 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM,
321                                            bool IsCS = false) {
322   if (IsCS) {
323     if (!EnablePGOCSInstrGen && !EnablePGOCSInstrUse)
324       return;
325   } else if (!EnablePGOInstrGen && PGOInstrUse.empty() && PGOSampleUse.empty())
326     return;
327 
328   // Perform the preinline and cleanup passes for O1 and above.
329   // And avoid doing them if optimizing for size.
330   // We will not do this inline for context sensitive PGO (when IsCS is true).
331   if (OptLevel > 0 && SizeLevel == 0 && !DisablePreInliner &&
332       PGOSampleUse.empty() && !IsCS) {
333     // Create preinline pass. We construct an InlineParams object and specify
334     // the threshold here to avoid the command line options of the regular
335     // inliner to influence pre-inlining. The only fields of InlineParams we
336     // care about are DefaultThreshold and HintThreshold.
337     InlineParams IP;
338     IP.DefaultThreshold = PreInlineThreshold;
339     // FIXME: The hint threshold has the same value used by the regular inliner.
340     // This should probably be lowered after performance testing.
341     IP.HintThreshold = 325;
342 
343     MPM.add(createFunctionInliningPass(IP));
344     MPM.add(createSROAPass());
345     MPM.add(createEarlyCSEPass());             // Catch trivial redundancies
346     MPM.add(createCFGSimplificationPass());    // Merge & remove BBs
347     MPM.add(createInstructionCombiningPass()); // Combine silly seq's
348     addExtensionsToPM(EP_Peephole, MPM);
349   }
350   if ((EnablePGOInstrGen && !IsCS) || (EnablePGOCSInstrGen && IsCS)) {
351     MPM.add(createPGOInstrumentationGenLegacyPass(IsCS));
352     // Add the profile lowering pass.
353     InstrProfOptions Options;
354     if (!PGOInstrGen.empty())
355       Options.InstrProfileOutput = PGOInstrGen;
356     Options.DoCounterPromotion = true;
357     Options.UseBFIInPromotion = IsCS;
358     MPM.add(createLoopRotatePass());
359     MPM.add(createInstrProfilingLegacyPass(Options, IsCS));
360   }
361   if (!PGOInstrUse.empty())
362     MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse, IsCS));
363   // Indirect call promotion that promotes intra-module targets only.
364   // For ThinLTO this is done earlier due to interactions with globalopt
365   // for imported functions. We don't run this at -O0.
366   if (OptLevel > 0 && !IsCS)
367     MPM.add(
368         createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty()));
369 }
370 void PassManagerBuilder::addFunctionSimplificationPasses(
371     legacy::PassManagerBase &MPM) {
372   // Start of function pass.
373   // Break up aggregate allocas, using SSAUpdater.
374   assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!");
375   MPM.add(createSROAPass());
376   MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies
377   if (EnableKnowledgeRetention)
378     MPM.add(createAssumeSimplifyPass());
379 
380   if (OptLevel > 1) {
381     if (EnableGVNHoist)
382       MPM.add(createGVNHoistPass());
383     if (EnableGVNSink) {
384       MPM.add(createGVNSinkPass());
385       MPM.add(createCFGSimplificationPass());
386     }
387   }
388 
389   if (EnableConstraintElimination)
390     MPM.add(createConstraintEliminationPass());
391 
392   if (OptLevel > 1) {
393     // Speculative execution if the target has divergent branches; otherwise nop.
394     MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass());
395 
396     MPM.add(createJumpThreadingPass());         // Thread jumps.
397     MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
398   }
399   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
400   // Combine silly seq's
401   if (OptLevel > 2)
402     MPM.add(createAggressiveInstCombinerPass());
403   MPM.add(createInstructionCombiningPass());
404   if (SizeLevel == 0 && !DisableLibCallsShrinkWrap)
405     MPM.add(createLibCallsShrinkWrapPass());
406   addExtensionsToPM(EP_Peephole, MPM);
407 
408   // Optimize memory intrinsic calls based on the profiled size information.
409   if (SizeLevel == 0)
410     MPM.add(createPGOMemOPSizeOptLegacyPass());
411 
412   // TODO: Investigate the cost/benefit of tail call elimination on debugging.
413   if (OptLevel > 1)
414     MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
415   MPM.add(createCFGSimplificationPass());      // Merge & remove BBs
416   MPM.add(createReassociatePass());           // Reassociate expressions
417 
418   // Begin the loop pass pipeline.
419   if (EnableSimpleLoopUnswitch) {
420     // The simple loop unswitch pass relies on separate cleanup passes. Schedule
421     // them first so when we re-process a loop they run before other loop
422     // passes.
423     MPM.add(createLoopInstSimplifyPass());
424     MPM.add(createLoopSimplifyCFGPass());
425   }
426   // Rotate Loop - disable header duplication at -Oz
427   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
428   // TODO: Investigate promotion cap for O1.
429   MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
430   if (EnableSimpleLoopUnswitch)
431     MPM.add(createSimpleLoopUnswitchLegacyPass());
432   else
433     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
434   // FIXME: We break the loop pass pipeline here in order to do full
435   // simplify-cfg. Eventually loop-simplifycfg should be enhanced to replace the
436   // need for this.
437   MPM.add(createCFGSimplificationPass());
438   MPM.add(createInstructionCombiningPass());
439   // We resume loop passes creating a second loop pipeline here.
440   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
441   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
442   addExtensionsToPM(EP_LateLoopOptimizations, MPM);
443   MPM.add(createLoopDeletionPass());          // Delete dead loops
444 
445   if (EnableLoopInterchange)
446     MPM.add(createLoopInterchangePass()); // Interchange loops
447 
448   // Unroll small loops
449   MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
450                                      ForgetAllSCEVInLoopUnroll));
451   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
452   // This ends the loop pass pipelines.
453 
454   if (OptLevel > 1) {
455     MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
456     MPM.add(NewGVN ? createNewGVNPass()
457                    : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
458   }
459   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
460   MPM.add(createSCCPPass());                  // Constant prop with SCCP
461 
462   // Delete dead bit computations (instcombine runs after to fold away the dead
463   // computations, and then ADCE will run later to exploit any new DCE
464   // opportunities that creates).
465   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
466 
467   // Run instcombine after redundancy elimination to exploit opportunities
468   // opened up by them.
469   MPM.add(createInstructionCombiningPass());
470   addExtensionsToPM(EP_Peephole, MPM);
471   if (OptLevel > 1) {
472     MPM.add(createJumpThreadingPass());         // Thread jumps
473     MPM.add(createCorrelatedValuePropagationPass());
474     MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
475     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
476   }
477 
478   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
479 
480   if (RerollLoops)
481     MPM.add(createLoopRerollPass());
482 
483   // TODO: Investigate if this is too expensive at O1.
484   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
485   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
486   // Clean up after everything.
487   MPM.add(createInstructionCombiningPass());
488   addExtensionsToPM(EP_Peephole, MPM);
489 
490   if (EnableCHR && OptLevel >= 3 &&
491       (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen))
492     MPM.add(createControlHeightReductionLegacyPass());
493 }
494 
495 void PassManagerBuilder::populateModulePassManager(
496     legacy::PassManagerBase &MPM) {
497   // Whether this is a default or *LTO pre-link pipeline. The FullLTO post-link
498   // is handled separately, so just check this is not the ThinLTO post-link.
499   bool DefaultOrPreLinkPipeline = !PerformThinLTO;
500 
501   if (!PGOSampleUse.empty()) {
502     MPM.add(createPruneEHPass());
503     // In ThinLTO mode, when flattened profile is used, all the available
504     // profile information will be annotated in PreLink phase so there is
505     // no need to load the profile again in PostLink.
506     if (!(FlattenedProfileUsed && PerformThinLTO))
507       MPM.add(createSampleProfileLoaderPass(PGOSampleUse));
508   }
509 
510   // Allow forcing function attributes as a debugging and tuning aid.
511   MPM.add(createForceFunctionAttrsLegacyPass());
512 
513   // If all optimizations are disabled, just run the always-inline pass and,
514   // if enabled, the function merging pass.
515   if (OptLevel == 0) {
516     addPGOInstrPasses(MPM);
517     if (Inliner) {
518       MPM.add(Inliner);
519       Inliner = nullptr;
520     }
521 
522     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
523     // creates a CGSCC pass manager, but we don't want to add extensions into
524     // that pass manager. To prevent this we insert a no-op module pass to reset
525     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
526     // builds. The function merging pass is
527     if (MergeFunctions)
528       MPM.add(createMergeFunctionsPass());
529     else if (GlobalExtensionsNotEmpty() || !Extensions.empty())
530       MPM.add(createBarrierNoopPass());
531 
532     if (PerformThinLTO) {
533       MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
534       // Drop available_externally and unreferenced globals. This is necessary
535       // with ThinLTO in order to avoid leaving undefined references to dead
536       // globals in the object file.
537       MPM.add(createEliminateAvailableExternallyPass());
538       MPM.add(createGlobalDCEPass());
539     }
540 
541     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
542 
543     if (PrepareForLTO || PrepareForThinLTO) {
544       MPM.add(createCanonicalizeAliasesPass());
545       // Rename anon globals to be able to export them in the summary.
546       // This has to be done after we add the extensions to the pass manager
547       // as there could be passes (e.g. Adddress sanitizer) which introduce
548       // new unnamed globals.
549       MPM.add(createNameAnonGlobalPass());
550     }
551     return;
552   }
553 
554   // Add LibraryInfo if we have some.
555   if (LibraryInfo)
556     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
557 
558   addInitialAliasAnalysisPasses(MPM);
559 
560   // For ThinLTO there are two passes of indirect call promotion. The
561   // first is during the compile phase when PerformThinLTO=false and
562   // intra-module indirect call targets are promoted. The second is during
563   // the ThinLTO backend when PerformThinLTO=true, when we promote imported
564   // inter-module indirect calls. For that we perform indirect call promotion
565   // earlier in the pass pipeline, here before globalopt. Otherwise imported
566   // available_externally functions look unreferenced and are removed.
567   if (PerformThinLTO) {
568     MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true,
569                                                      !PGOSampleUse.empty()));
570     MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
571   }
572 
573   // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops
574   // as it will change the CFG too much to make the 2nd profile annotation
575   // in backend more difficult.
576   bool PrepareForThinLTOUsingPGOSampleProfile =
577       PrepareForThinLTO && !PGOSampleUse.empty();
578   if (PrepareForThinLTOUsingPGOSampleProfile)
579     DisableUnrollLoops = true;
580 
581   // Infer attributes about declarations if possible.
582   MPM.add(createInferFunctionAttrsLegacyPass());
583 
584   // Infer attributes on declarations, call sites, arguments, etc.
585   if (AttributorRun & AttributorRunOption::MODULE)
586     MPM.add(createAttributorLegacyPass());
587 
588   addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
589 
590   if (OptLevel > 2)
591     MPM.add(createCallSiteSplittingPass());
592 
593   MPM.add(createIPSCCPPass());          // IP SCCP
594   MPM.add(createCalledValuePropagationPass());
595 
596   MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
597   // Promote any localized global vars.
598   MPM.add(createPromoteMemoryToRegisterPass());
599 
600   MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
601 
602   MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
603   addExtensionsToPM(EP_Peephole, MPM);
604   MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
605 
606   // For SamplePGO in ThinLTO compile phase, we do not want to do indirect
607   // call promotion as it will change the CFG too much to make the 2nd
608   // profile annotation in backend more difficult.
609   // PGO instrumentation is added during the compile phase for ThinLTO, do
610   // not run it a second time
611   if (DefaultOrPreLinkPipeline && !PrepareForThinLTOUsingPGOSampleProfile)
612     addPGOInstrPasses(MPM);
613 
614   // Create profile COMDAT variables. Lld linker wants to see all variables
615   // before the LTO/ThinLTO link since it needs to resolve symbols/comdats.
616   if (!PerformThinLTO && EnablePGOCSInstrGen)
617     MPM.add(createPGOInstrumentationGenCreateVarLegacyPass(PGOInstrGen));
618 
619   // We add a module alias analysis pass here. In part due to bugs in the
620   // analysis infrastructure this "works" in that the analysis stays alive
621   // for the entire SCC pass run below.
622   MPM.add(createGlobalsAAWrapperPass());
623 
624   // Start of CallGraph SCC passes.
625   MPM.add(createPruneEHPass()); // Remove dead EH info
626   bool RunInliner = false;
627   if (Inliner) {
628     MPM.add(Inliner);
629     Inliner = nullptr;
630     RunInliner = true;
631   }
632 
633   // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
634   if (AttributorRun & AttributorRunOption::CGSCC)
635     MPM.add(createAttributorCGSCCLegacyPass());
636 
637   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
638   // there are no OpenMP runtime calls present in the module.
639   if (OptLevel > 1)
640     MPM.add(createOpenMPOptLegacyPass());
641 
642   MPM.add(createPostOrderFunctionAttrsLegacyPass());
643   if (OptLevel > 2)
644     MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
645 
646   addExtensionsToPM(EP_CGSCCOptimizerLate, MPM);
647   addFunctionSimplificationPasses(MPM);
648 
649   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
650   // pass manager that we are specifically trying to avoid. To prevent this
651   // we must insert a no-op module pass to reset the pass manager.
652   MPM.add(createBarrierNoopPass());
653 
654   if (RunPartialInlining)
655     MPM.add(createPartialInliningPass());
656 
657   if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO)
658     // Remove avail extern fns and globals definitions if we aren't
659     // compiling an object file for later LTO. For LTO we want to preserve
660     // these so they are eligible for inlining at link-time. Note if they
661     // are unreferenced they will be removed by GlobalDCE later, so
662     // this only impacts referenced available externally globals.
663     // Eventually they will be suppressed during codegen, but eliminating
664     // here enables more opportunity for GlobalDCE as it may make
665     // globals referenced by available external functions dead
666     // and saves running remaining passes on the eliminated functions.
667     MPM.add(createEliminateAvailableExternallyPass());
668 
669   // CSFDO instrumentation and use pass. Don't invoke this for Prepare pass
670   // for LTO and ThinLTO -- The actual pass will be called after all inlines
671   // are performed.
672   // Need to do this after COMDAT variables have been eliminated,
673   // (i.e. after EliminateAvailableExternallyPass).
674   if (!(PrepareForLTO || PrepareForThinLTO))
675     addPGOInstrPasses(MPM, /* IsCS */ true);
676 
677   if (EnableOrderFileInstrumentation)
678     MPM.add(createInstrOrderFilePass());
679 
680   MPM.add(createReversePostOrderFunctionAttrsPass());
681 
682   // The inliner performs some kind of dead code elimination as it goes,
683   // but there are cases that are not really caught by it. We might
684   // at some point consider teaching the inliner about them, but it
685   // is OK for now to run GlobalOpt + GlobalDCE in tandem as their
686   // benefits generally outweight the cost, making the whole pipeline
687   // faster.
688   if (RunInliner) {
689     MPM.add(createGlobalOptimizerPass());
690     MPM.add(createGlobalDCEPass());
691   }
692 
693   // If we are planning to perform ThinLTO later, let's not bloat the code with
694   // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes
695   // during ThinLTO and perform the rest of the optimizations afterward.
696   if (PrepareForThinLTO) {
697     // Ensure we perform any last passes, but do so before renaming anonymous
698     // globals in case the passes add any.
699     addExtensionsToPM(EP_OptimizerLast, MPM);
700     MPM.add(createCanonicalizeAliasesPass());
701     // Rename anon globals to be able to export them in the summary.
702     MPM.add(createNameAnonGlobalPass());
703     return;
704   }
705 
706   if (PerformThinLTO)
707     // Optimize globals now when performing ThinLTO, this enables more
708     // optimizations later.
709     MPM.add(createGlobalOptimizerPass());
710 
711   // Scheduling LoopVersioningLICM when inlining is over, because after that
712   // we may see more accurate aliasing. Reason to run this late is that too
713   // early versioning may prevent further inlining due to increase of code
714   // size. By placing it just after inlining other optimizations which runs
715   // later might get benefit of no-alias assumption in clone loop.
716   if (UseLoopVersioningLICM) {
717     MPM.add(createLoopVersioningLICMPass());    // Do LoopVersioningLICM
718     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
719   }
720 
721   // We add a fresh GlobalsModRef run at this point. This is particularly
722   // useful as the above will have inlined, DCE'ed, and function-attr
723   // propagated everything. We should at this point have a reasonably minimal
724   // and richly annotated call graph. By computing aliasing and mod/ref
725   // information for all local globals here, the late loop passes and notably
726   // the vectorizer will be able to use them to help recognize vectorizable
727   // memory operations.
728   //
729   // Note that this relies on a bug in the pass manager which preserves
730   // a module analysis into a function pass pipeline (and throughout it) so
731   // long as the first function pass doesn't invalidate the module analysis.
732   // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
733   // this to work. Fortunately, it is trivial to preserve AliasAnalysis
734   // (doing nothing preserves it as it is required to be conservatively
735   // correct in the face of IR changes).
736   MPM.add(createGlobalsAAWrapperPass());
737 
738   MPM.add(createFloat2IntPass());
739   MPM.add(createLowerConstantIntrinsicsPass());
740 
741   if (EnableMatrix) {
742     MPM.add(createLowerMatrixIntrinsicsPass());
743     // CSE the pointer arithmetic of the column vectors.  This allows alias
744     // analysis to establish no-aliasing between loads and stores of different
745     // columns of the same matrix.
746     MPM.add(createEarlyCSEPass(false));
747   }
748 
749   addExtensionsToPM(EP_VectorizerStart, MPM);
750 
751   // Re-rotate loops in all our loop nests. These may have fallout out of
752   // rotated form due to GVN or other transformations, and the vectorizer relies
753   // on the rotated form. Disable header duplication at -Oz.
754   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
755 
756   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
757   // into separate loop that would otherwise inhibit vectorization.  This is
758   // currently only performed for loops marked with the metadata
759   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
760   MPM.add(createLoopDistributePass());
761 
762   MPM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize));
763 
764   // Eliminate loads by forwarding stores from the previous iteration to loads
765   // of the current iteration.
766   MPM.add(createLoopLoadEliminationPass());
767 
768   // FIXME: Because of #pragma vectorize enable, the passes below are always
769   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
770   // on -O1 and no #pragma is found). Would be good to have these two passes
771   // as function calls, so that we can only pass them when the vectorizer
772   // changed the code.
773   MPM.add(createInstructionCombiningPass());
774   if (OptLevel > 1 && ExtraVectorizerPasses) {
775     // At higher optimization levels, try to clean up any runtime overlap and
776     // alignment checks inserted by the vectorizer. We want to track correllated
777     // runtime checks for two inner loops in the same outer loop, fold any
778     // common computations, hoist loop-invariant aspects out of any outer loop,
779     // and unswitch the runtime checks if possible. Once hoisted, we may have
780     // dead (or speculatable) control flows or more combining opportunities.
781     MPM.add(createEarlyCSEPass());
782     MPM.add(createCorrelatedValuePropagationPass());
783     MPM.add(createInstructionCombiningPass());
784     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
785     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
786     MPM.add(createCFGSimplificationPass());
787     MPM.add(createInstructionCombiningPass());
788   }
789 
790   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
791   // GVN, loop transforms, and others have already run, so it's now better to
792   // convert to more optimized IR using more aggressive simplify CFG options.
793   // The extra sinking transform can create larger basic blocks, so do this
794   // before SLP vectorization.
795   // FIXME: study whether hoisting and/or sinking of common instructions should
796   //        be delayed until after SLP vectorizer.
797   MPM.add(createCFGSimplificationPass(SimplifyCFGOptions()
798                                           .forwardSwitchCondToPhi(true)
799                                           .convertSwitchToLookupTable(true)
800                                           .needCanonicalLoops(false)
801                                           .hoistCommonInsts(true)
802                                           .sinkCommonInsts(true)));
803 
804   if (SLPVectorize) {
805     MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
806     if (OptLevel > 1 && ExtraVectorizerPasses) {
807       MPM.add(createEarlyCSEPass());
808     }
809   }
810 
811   // Enhance/cleanup vector code.
812   MPM.add(createVectorCombinePass());
813 
814   addExtensionsToPM(EP_Peephole, MPM);
815   MPM.add(createInstructionCombiningPass());
816 
817   if (EnableUnrollAndJam && !DisableUnrollLoops) {
818     // Unroll and Jam. We do this before unroll but need to be in a separate
819     // loop pass manager in order for the outer loop to be processed by
820     // unroll and jam before the inner loop is unrolled.
821     MPM.add(createLoopUnrollAndJamPass(OptLevel));
822   }
823 
824   // Unroll small loops
825   MPM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
826                                ForgetAllSCEVInLoopUnroll));
827 
828   if (!DisableUnrollLoops) {
829     // LoopUnroll may generate some redundency to cleanup.
830     MPM.add(createInstructionCombiningPass());
831 
832     // Runtime unrolling will introduce runtime check in loop prologue. If the
833     // unrolled loop is a inner loop, then the prologue will be inside the
834     // outer loop. LICM pass can help to promote the runtime check out if the
835     // checked value is loop invariant.
836     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
837   }
838 
839   MPM.add(createWarnMissedTransformationsPass());
840 
841   // After vectorization and unrolling, assume intrinsics may tell us more
842   // about pointer alignments.
843   MPM.add(createAlignmentFromAssumptionsPass());
844 
845   // FIXME: We shouldn't bother with this anymore.
846   MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
847 
848   // GlobalOpt already deletes dead functions and globals, at -O2 try a
849   // late pass of GlobalDCE.  It is capable of deleting dead cycles.
850   if (OptLevel > 1) {
851     MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
852     MPM.add(createConstantMergePass());     // Merge dup global constants
853   }
854 
855   // See comment in the new PM for justification of scheduling splitting at
856   // this stage (\ref buildModuleSimplificationPipeline).
857   if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO))
858     MPM.add(createHotColdSplittingPass());
859 
860   if (MergeFunctions)
861     MPM.add(createMergeFunctionsPass());
862 
863   // Add Module flag "CG Profile" based on Branch Frequency Information.
864   if (CallGraphProfile)
865     MPM.add(createCGProfileLegacyPass());
866 
867   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
868   // canonicalization pass that enables other optimizations. As a result,
869   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
870   // result too early.
871   MPM.add(createLoopSinkPass());
872   // Get rid of LCSSA nodes.
873   MPM.add(createInstSimplifyLegacyPass());
874 
875   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
876   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
877   // flattening of blocks.
878   MPM.add(createDivRemPairsPass());
879 
880   // LoopSink (and other loop passes since the last simplifyCFG) might have
881   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
882   MPM.add(createCFGSimplificationPass());
883 
884   addExtensionsToPM(EP_OptimizerLast, MPM);
885 
886   if (PrepareForLTO) {
887     MPM.add(createCanonicalizeAliasesPass());
888     // Rename anon globals to be able to handle them in the summary
889     MPM.add(createNameAnonGlobalPass());
890   }
891 }
892 
893 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
894   // Load sample profile before running the LTO optimization pipeline.
895   if (!PGOSampleUse.empty()) {
896     PM.add(createPruneEHPass());
897     PM.add(createSampleProfileLoaderPass(PGOSampleUse));
898   }
899 
900   // Remove unused virtual tables to improve the quality of code generated by
901   // whole-program devirtualization and bitset lowering.
902   PM.add(createGlobalDCEPass());
903 
904   // Provide AliasAnalysis services for optimizations.
905   addInitialAliasAnalysisPasses(PM);
906 
907   // Allow forcing function attributes as a debugging and tuning aid.
908   PM.add(createForceFunctionAttrsLegacyPass());
909 
910   // Infer attributes about declarations if possible.
911   PM.add(createInferFunctionAttrsLegacyPass());
912 
913   if (OptLevel > 1) {
914     // Split call-site with more constrained arguments.
915     PM.add(createCallSiteSplittingPass());
916 
917     // Indirect call promotion. This should promote all the targets that are
918     // left by the earlier promotion pass that promotes intra-module targets.
919     // This two-step promotion is to save the compile time. For LTO, it should
920     // produce the same result as if we only do promotion here.
921     PM.add(
922         createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty()));
923 
924     // Propagate constants at call sites into the functions they call.  This
925     // opens opportunities for globalopt (and inlining) by substituting function
926     // pointers passed as arguments to direct uses of functions.
927     PM.add(createIPSCCPPass());
928 
929     // Attach metadata to indirect call sites indicating the set of functions
930     // they may target at run-time. This should follow IPSCCP.
931     PM.add(createCalledValuePropagationPass());
932 
933     // Infer attributes on declarations, call sites, arguments, etc.
934     if (AttributorRun & AttributorRunOption::MODULE)
935       PM.add(createAttributorLegacyPass());
936   }
937 
938   // Infer attributes about definitions. The readnone attribute in particular is
939   // required for virtual constant propagation.
940   PM.add(createPostOrderFunctionAttrsLegacyPass());
941   PM.add(createReversePostOrderFunctionAttrsPass());
942 
943   // Split globals using inrange annotations on GEP indices. This can help
944   // improve the quality of generated code when virtual constant propagation or
945   // control flow integrity are enabled.
946   PM.add(createGlobalSplitPass());
947 
948   // Apply whole-program devirtualization and virtual constant propagation.
949   PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
950 
951   // That's all we need at opt level 1.
952   if (OptLevel == 1)
953     return;
954 
955   // Now that we internalized some globals, see if we can hack on them!
956   PM.add(createGlobalOptimizerPass());
957   // Promote any localized global vars.
958   PM.add(createPromoteMemoryToRegisterPass());
959 
960   // Linking modules together can lead to duplicated global constants, only
961   // keep one copy of each constant.
962   PM.add(createConstantMergePass());
963 
964   // Remove unused arguments from functions.
965   PM.add(createDeadArgEliminationPass());
966 
967   // Reduce the code after globalopt and ipsccp.  Both can open up significant
968   // simplification opportunities, and both can propagate functions through
969   // function pointers.  When this happens, we often have to resolve varargs
970   // calls, etc, so let instcombine do this.
971   if (OptLevel > 2)
972     PM.add(createAggressiveInstCombinerPass());
973   PM.add(createInstructionCombiningPass());
974   addExtensionsToPM(EP_Peephole, PM);
975 
976   // Inline small functions
977   bool RunInliner = Inliner;
978   if (RunInliner) {
979     PM.add(Inliner);
980     Inliner = nullptr;
981   }
982 
983   PM.add(createPruneEHPass());   // Remove dead EH info.
984 
985   // CSFDO instrumentation and use pass.
986   addPGOInstrPasses(PM, /* IsCS */ true);
987 
988   // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
989   if (AttributorRun & AttributorRunOption::CGSCC)
990     PM.add(createAttributorCGSCCLegacyPass());
991 
992   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
993   // there are no OpenMP runtime calls present in the module.
994   if (OptLevel > 1)
995     PM.add(createOpenMPOptLegacyPass());
996 
997   // Optimize globals again if we ran the inliner.
998   if (RunInliner)
999     PM.add(createGlobalOptimizerPass());
1000   PM.add(createGlobalDCEPass()); // Remove dead functions.
1001 
1002   // If we didn't decide to inline a function, check to see if we can
1003   // transform it to pass arguments by value instead of by reference.
1004   PM.add(createArgumentPromotionPass());
1005 
1006   // The IPO passes may leave cruft around.  Clean up after them.
1007   PM.add(createInstructionCombiningPass());
1008   addExtensionsToPM(EP_Peephole, PM);
1009   PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true));
1010 
1011   // Break up allocas
1012   PM.add(createSROAPass());
1013 
1014   // LTO provides additional opportunities for tailcall elimination due to
1015   // link-time inlining, and visibility of nocapture attribute.
1016   if (OptLevel > 1)
1017     PM.add(createTailCallEliminationPass());
1018 
1019   // Infer attributes on declarations, call sites, arguments, etc.
1020   PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture.
1021   // Run a few AA driven optimizations here and now, to cleanup the code.
1022   PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
1023 
1024   PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
1025   PM.add(NewGVN ? createNewGVNPass()
1026                 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
1027   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
1028 
1029   // Nuke dead stores.
1030   PM.add(createDeadStoreEliminationPass());
1031   PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
1032 
1033   // More loops are countable; try to optimize them.
1034   PM.add(createIndVarSimplifyPass());
1035   PM.add(createLoopDeletionPass());
1036   if (EnableLoopInterchange)
1037     PM.add(createLoopInterchangePass());
1038 
1039   // Unroll small loops
1040   PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
1041                                     ForgetAllSCEVInLoopUnroll));
1042   PM.add(createLoopVectorizePass(true, !LoopVectorize));
1043   // The vectorizer may have significantly shortened a loop body; unroll again.
1044   PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
1045                               ForgetAllSCEVInLoopUnroll));
1046 
1047   PM.add(createWarnMissedTransformationsPass());
1048 
1049   // Now that we've optimized loops (in particular loop induction variables),
1050   // we may have exposed more scalar opportunities. Run parts of the scalar
1051   // optimizer again at this point.
1052   PM.add(createInstructionCombiningPass()); // Initial cleanup
1053   PM.add(createCFGSimplificationPass()); // if-convert
1054   PM.add(createSCCPPass()); // Propagate exposed constants
1055   PM.add(createInstructionCombiningPass()); // Clean up again
1056   PM.add(createBitTrackingDCEPass());
1057 
1058   // More scalar chains could be vectorized due to more alias information
1059   if (SLPVectorize)
1060     PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
1061 
1062   PM.add(createVectorCombinePass()); // Clean up partial vectorization.
1063 
1064   // After vectorization, assume intrinsics may tell us more about pointer
1065   // alignments.
1066   PM.add(createAlignmentFromAssumptionsPass());
1067 
1068   // Cleanup and simplify the code after the scalar optimizations.
1069   PM.add(createInstructionCombiningPass());
1070   addExtensionsToPM(EP_Peephole, PM);
1071 
1072   PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true));
1073 }
1074 
1075 void PassManagerBuilder::addLateLTOOptimizationPasses(
1076     legacy::PassManagerBase &PM) {
1077   // See comment in the new PM for justification of scheduling splitting at
1078   // this stage (\ref buildLTODefaultPipeline).
1079   if (EnableHotColdSplit)
1080     PM.add(createHotColdSplittingPass());
1081 
1082   // Delete basic blocks, which optimization passes may have killed.
1083   PM.add(createCFGSimplificationPass());
1084 
1085   // Drop bodies of available externally objects to improve GlobalDCE.
1086   PM.add(createEliminateAvailableExternallyPass());
1087 
1088   // Now that we have optimized the program, discard unreachable functions.
1089   PM.add(createGlobalDCEPass());
1090 
1091   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
1092   // currently it damages debug info.
1093   if (MergeFunctions)
1094     PM.add(createMergeFunctionsPass());
1095 }
1096 
1097 void PassManagerBuilder::populateThinLTOPassManager(
1098     legacy::PassManagerBase &PM) {
1099   PerformThinLTO = true;
1100   if (LibraryInfo)
1101     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
1102 
1103   if (VerifyInput)
1104     PM.add(createVerifierPass());
1105 
1106   if (ImportSummary) {
1107     // This pass imports type identifier resolutions for whole-program
1108     // devirtualization and CFI. It must run early because other passes may
1109     // disturb the specific instruction patterns that these passes look for,
1110     // creating dependencies on resolutions that may not appear in the summary.
1111     //
1112     // For example, GVN may transform the pattern assume(type.test) appearing in
1113     // two basic blocks into assume(phi(type.test, type.test)), which would
1114     // transform a dependency on a WPD resolution into a dependency on a type
1115     // identifier resolution for CFI.
1116     //
1117     // Also, WPD has access to more precise information than ICP and can
1118     // devirtualize more effectively, so it should operate on the IR first.
1119     PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary));
1120     PM.add(createLowerTypeTestsPass(nullptr, ImportSummary));
1121   }
1122 
1123   populateModulePassManager(PM);
1124 
1125   if (VerifyOutput)
1126     PM.add(createVerifierPass());
1127   PerformThinLTO = false;
1128 }
1129 
1130 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
1131   if (LibraryInfo)
1132     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
1133 
1134   if (VerifyInput)
1135     PM.add(createVerifierPass());
1136 
1137   addExtensionsToPM(EP_FullLinkTimeOptimizationEarly, PM);
1138 
1139   if (OptLevel != 0)
1140     addLTOOptimizationPasses(PM);
1141   else {
1142     // The whole-program-devirt pass needs to run at -O0 because only it knows
1143     // about the llvm.type.checked.load intrinsic: it needs to both lower the
1144     // intrinsic itself and handle it in the summary.
1145     PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
1146   }
1147 
1148   // Create a function that performs CFI checks for cross-DSO calls with targets
1149   // in the current module.
1150   PM.add(createCrossDSOCFIPass());
1151 
1152   // Lower type metadata and the type.test intrinsic. This pass supports Clang's
1153   // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at
1154   // link time if CFI is enabled. The pass does nothing if CFI is disabled.
1155   PM.add(createLowerTypeTestsPass(ExportSummary, nullptr));
1156   // Run a second time to clean up any type tests left behind by WPD for use
1157   // in ICP (which is performed earlier than this in the regular LTO pipeline).
1158   PM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
1159 
1160   if (OptLevel != 0)
1161     addLateLTOOptimizationPasses(PM);
1162 
1163   addExtensionsToPM(EP_FullLinkTimeOptimizationLast, PM);
1164 
1165   if (VerifyOutput)
1166     PM.add(createVerifierPass());
1167 }
1168 
1169 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
1170   PassManagerBuilder *PMB = new PassManagerBuilder();
1171   return wrap(PMB);
1172 }
1173 
1174 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
1175   PassManagerBuilder *Builder = unwrap(PMB);
1176   delete Builder;
1177 }
1178 
1179 void
1180 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
1181                                   unsigned OptLevel) {
1182   PassManagerBuilder *Builder = unwrap(PMB);
1183   Builder->OptLevel = OptLevel;
1184 }
1185 
1186 void
1187 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
1188                                    unsigned SizeLevel) {
1189   PassManagerBuilder *Builder = unwrap(PMB);
1190   Builder->SizeLevel = SizeLevel;
1191 }
1192 
1193 void
1194 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
1195                                             LLVMBool Value) {
1196   // NOTE: The DisableUnitAtATime switch has been removed.
1197 }
1198 
1199 void
1200 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
1201                                             LLVMBool Value) {
1202   PassManagerBuilder *Builder = unwrap(PMB);
1203   Builder->DisableUnrollLoops = Value;
1204 }
1205 
1206 void
1207 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
1208                                                  LLVMBool Value) {
1209   // NOTE: The simplify-libcalls pass has been removed.
1210 }
1211 
1212 void
1213 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
1214                                               unsigned Threshold) {
1215   PassManagerBuilder *Builder = unwrap(PMB);
1216   Builder->Inliner = createFunctionInliningPass(Threshold);
1217 }
1218 
1219 void
1220 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
1221                                                   LLVMPassManagerRef PM) {
1222   PassManagerBuilder *Builder = unwrap(PMB);
1223   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
1224   Builder->populateFunctionPassManager(*FPM);
1225 }
1226 
1227 void
1228 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
1229                                                 LLVMPassManagerRef PM) {
1230   PassManagerBuilder *Builder = unwrap(PMB);
1231   legacy::PassManagerBase *MPM = unwrap(PM);
1232   Builder->populateModulePassManager(*MPM);
1233 }
1234 
1235 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
1236                                                   LLVMPassManagerRef PM,
1237                                                   LLVMBool Internalize,
1238                                                   LLVMBool RunInliner) {
1239   PassManagerBuilder *Builder = unwrap(PMB);
1240   legacy::PassManagerBase *LPM = unwrap(PM);
1241 
1242   // A small backwards compatibility hack. populateLTOPassManager used to take
1243   // an RunInliner option.
1244   if (RunInliner && !Builder->Inliner)
1245     Builder->Inliner = createFunctionInliningPass();
1246 
1247   Builder->populateLTOPassManager(*LPM);
1248 }
1249