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