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