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