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