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