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