cf16aaacb0dd82586d808417a0cb81a6064835d3
[oota-llvm.git] / lib / Transforms / IPO / PassManagerBuilder.cpp
1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the PassManagerBuilder class, which is used to set up a
11 // "standard" optimization sequence suitable for languages like C and C++.
12 //
13 //===----------------------------------------------------------------------===//
14
15
16 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
17 #include "llvm-c/Transforms/PassManagerBuilder.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Transforms/IPO.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Transforms/Vectorize.h"
30
31 using namespace llvm;
32
33 static cl::opt<bool>
34 RunLoopVectorization("vectorize-loops", cl::Hidden,
35                      cl::desc("Run the Loop vectorization passes"));
36
37 static cl::opt<bool>
38 RunSLPVectorization("vectorize-slp", cl::Hidden,
39                     cl::desc("Run the SLP vectorization passes"));
40
41 static cl::opt<bool>
42 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
43                     cl::desc("Run the BB vectorization passes"));
44
45 static cl::opt<bool>
46 UseGVNAfterVectorization("use-gvn-after-vectorization",
47   cl::init(false), cl::Hidden,
48   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
49
50 static cl::opt<bool> ExtraVectorizerPasses(
51     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
52     cl::desc("Run cleanup optimization passes after vectorization."));
53
54 static cl::opt<bool> UseNewSROA("use-new-sroa",
55   cl::init(true), cl::Hidden,
56   cl::desc("Enable the new, experimental SROA pass"));
57
58 static cl::opt<bool>
59 RunLoopRerolling("reroll-loops", cl::Hidden,
60                  cl::desc("Run the loop rerolling pass"));
61
62 static cl::opt<bool>
63 RunFloat2Int("float-to-int", cl::Hidden, cl::init(true),
64              cl::desc("Run the float2int (float demotion) pass"));
65
66 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
67                                     cl::Hidden,
68                                     cl::desc("Run the load combining pass"));
69
70 static cl::opt<bool>
71 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
72   cl::init(true), cl::Hidden,
73   cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
74            "vectorizer instead of before"));
75
76 static cl::opt<bool> UseCFLAA("use-cfl-aa",
77   cl::init(false), cl::Hidden,
78   cl::desc("Enable the new, experimental CFL alias analysis"));
79
80 static cl::opt<bool>
81 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
82            cl::desc("Enable motion of merged load and store"));
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> EnableLoopDistribute(
89     "enable-loop-distribute", cl::init(false), cl::Hidden,
90     cl::desc("Enable the new, experimental LoopDistribution Pass"));
91
92 static cl::opt<bool> EnableNonLTOGlobalsModRef(
93     "enable-non-lto-gmr", cl::init(false), cl::Hidden,
94     cl::desc(
95         "Enable the GlobalsModRef AliasAnalysis outside of the LTO pipeline."));
96
97 PassManagerBuilder::PassManagerBuilder() {
98     OptLevel = 2;
99     SizeLevel = 0;
100     LibraryInfo = nullptr;
101     Inliner = nullptr;
102     DisableUnitAtATime = false;
103     DisableUnrollLoops = false;
104     BBVectorize = RunBBVectorization;
105     SLPVectorize = RunSLPVectorization;
106     LoopVectorize = RunLoopVectorization;
107     RerollLoops = RunLoopRerolling;
108     LoadCombine = RunLoadCombine;
109     DisableGVNLoadPRE = false;
110     VerifyInput = false;
111     VerifyOutput = false;
112     MergeFunctions = false;
113     PrepareForLTO = false;
114 }
115
116 PassManagerBuilder::~PassManagerBuilder() {
117   delete LibraryInfo;
118   delete Inliner;
119 }
120
121 /// Set of global extensions, automatically added as part of the standard set.
122 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
123    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
124
125 void PassManagerBuilder::addGlobalExtension(
126     PassManagerBuilder::ExtensionPointTy Ty,
127     PassManagerBuilder::ExtensionFn Fn) {
128   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
129 }
130
131 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
132   Extensions.push_back(std::make_pair(Ty, Fn));
133 }
134
135 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
136                                            legacy::PassManagerBase &PM) const {
137   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
138     if ((*GlobalExtensions)[i].first == ETy)
139       (*GlobalExtensions)[i].second(*this, PM);
140   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
141     if (Extensions[i].first == ETy)
142       Extensions[i].second(*this, PM);
143 }
144
145 void PassManagerBuilder::addInitialAliasAnalysisPasses(
146     legacy::PassManagerBase &PM) const {
147   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
148   // BasicAliasAnalysis wins if they disagree. This is intended to help
149   // support "obvious" type-punning idioms.
150   if (UseCFLAA)
151     PM.add(createCFLAliasAnalysisPass());
152   PM.add(createTypeBasedAliasAnalysisPass());
153   PM.add(createScopedNoAliasAAPass());
154   PM.add(createBasicAliasAnalysisPass());
155 }
156
157 void PassManagerBuilder::populateFunctionPassManager(
158     legacy::FunctionPassManager &FPM) {
159   addExtensionsToPM(EP_EarlyAsPossible, FPM);
160
161   // Add LibraryInfo if we have some.
162   if (LibraryInfo)
163     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
164
165   if (OptLevel == 0) return;
166
167   addInitialAliasAnalysisPasses(FPM);
168
169   FPM.add(createCFGSimplificationPass());
170   if (UseNewSROA)
171     FPM.add(createSROAPass());
172   else
173     FPM.add(createScalarReplAggregatesPass());
174   FPM.add(createEarlyCSEPass());
175   FPM.add(createLowerExpectIntrinsicPass());
176 }
177
178 void PassManagerBuilder::populateModulePassManager(
179     legacy::PassManagerBase &MPM) {
180   // If all optimizations are disabled, just run the always-inline pass and,
181   // if enabled, the function merging pass.
182   if (OptLevel == 0) {
183     if (Inliner) {
184       MPM.add(Inliner);
185       Inliner = nullptr;
186     }
187
188     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
189     // creates a CGSCC pass manager, but we don't want to add extensions into
190     // that pass manager. To prevent this we insert a no-op module pass to reset
191     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
192     // builds. The function merging pass is 
193     if (MergeFunctions)
194       MPM.add(createMergeFunctionsPass());
195     else if (!GlobalExtensions->empty() || !Extensions.empty())
196       MPM.add(createBarrierNoopPass());
197
198     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
199     return;
200   }
201
202   // Add LibraryInfo if we have some.
203   if (LibraryInfo)
204     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
205
206   addInitialAliasAnalysisPasses(MPM);
207
208   if (!DisableUnitAtATime) {
209     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
210
211     MPM.add(createIPSCCPPass());              // IP SCCP
212     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
213
214     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
215
216     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
217     addExtensionsToPM(EP_Peephole, MPM);
218     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
219   }
220
221   if (EnableNonLTOGlobalsModRef)
222     // We add a module alias analysis pass here. In part due to bugs in the
223     // analysis infrastructure this "works" in that the analysis stays alive
224     // for the entire SCC pass run below.
225     MPM.add(createGlobalsModRefPass());
226
227   // Start of CallGraph SCC passes.
228   if (!DisableUnitAtATime)
229     MPM.add(createPruneEHPass());             // Remove dead EH info
230   if (Inliner) {
231     MPM.add(Inliner);
232     Inliner = nullptr;
233   }
234   if (!DisableUnitAtATime)
235     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
236   if (OptLevel > 2)
237     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
238
239   // Start of function pass.
240   // Break up aggregate allocas, using SSAUpdater.
241   if (UseNewSROA)
242     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
243   else
244     MPM.add(createScalarReplAggregatesPass(-1, false));
245   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
246   MPM.add(createJumpThreadingPass());         // Thread jumps.
247   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
248   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
249   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
250   addExtensionsToPM(EP_Peephole, MPM);
251
252   MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
253   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
254   MPM.add(createReassociatePass());           // Reassociate expressions
255   // Rotate Loop - disable header duplication at -Oz
256   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
257   MPM.add(createLICMPass());                  // Hoist loop invariants
258   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
259   MPM.add(createInstructionCombiningPass());
260   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
261   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
262   MPM.add(createLoopDeletionPass());          // Delete dead loops
263   if (EnableLoopInterchange) {
264     MPM.add(createLoopInterchangePass()); // Interchange loops
265     MPM.add(createCFGSimplificationPass());
266   }
267   if (!DisableUnrollLoops)
268     MPM.add(createSimpleLoopUnrollPass());    // Unroll small loops
269   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
270
271   if (OptLevel > 1) {
272     if (EnableMLSM)
273       MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
274     MPM.add(createGVNPass(DisableGVNLoadPRE));  // Remove redundancies
275   }
276   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
277   MPM.add(createSCCPPass());                  // Constant prop with SCCP
278
279   // Delete dead bit computations (instcombine runs after to fold away the dead
280   // computations, and then ADCE will run later to exploit any new DCE
281   // opportunities that creates).
282   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
283
284   // Run instcombine after redundancy elimination to exploit opportunities
285   // opened up by them.
286   MPM.add(createInstructionCombiningPass());
287   addExtensionsToPM(EP_Peephole, MPM);
288   MPM.add(createJumpThreadingPass());         // Thread jumps
289   MPM.add(createCorrelatedValuePropagationPass());
290   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
291   MPM.add(createLICMPass());
292
293   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
294
295   if (RerollLoops)
296     MPM.add(createLoopRerollPass());
297   if (!RunSLPAfterLoopVectorization) {
298     if (SLPVectorize)
299       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
300
301     if (BBVectorize) {
302       MPM.add(createBBVectorizePass());
303       MPM.add(createInstructionCombiningPass());
304       addExtensionsToPM(EP_Peephole, MPM);
305       if (OptLevel > 1 && UseGVNAfterVectorization)
306         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
307       else
308         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
309
310       // BBVectorize may have significantly shortened a loop body; unroll again.
311       if (!DisableUnrollLoops)
312         MPM.add(createLoopUnrollPass());
313     }
314   }
315
316   if (LoadCombine)
317     MPM.add(createLoadCombinePass());
318
319   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
320   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
321   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
322   addExtensionsToPM(EP_Peephole, MPM);
323
324   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
325   // pass manager that we are specifically trying to avoid. To prevent this
326   // we must insert a no-op module pass to reset the pass manager.
327   MPM.add(createBarrierNoopPass());
328
329   if (RunFloat2Int)
330     MPM.add(createFloat2IntPass());
331
332   addExtensionsToPM(EP_VectorizerStart, MPM);
333
334   // Re-rotate loops in all our loop nests. These may have fallout out of
335   // rotated form due to GVN or other transformations, and the vectorizer relies
336   // on the rotated form. Disable header duplication at -Oz.
337   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
338
339   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
340   // into separate loop that would otherwise inhibit vectorization.
341   if (EnableLoopDistribute)
342     MPM.add(createLoopDistributePass());
343
344   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
345   // FIXME: Because of #pragma vectorize enable, the passes below are always
346   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
347   // on -O1 and no #pragma is found). Would be good to have these two passes
348   // as function calls, so that we can only pass them when the vectorizer
349   // changed the code.
350   MPM.add(createInstructionCombiningPass());
351   if (OptLevel > 1 && ExtraVectorizerPasses) {
352     // At higher optimization levels, try to clean up any runtime overlap and
353     // alignment checks inserted by the vectorizer. We want to track correllated
354     // runtime checks for two inner loops in the same outer loop, fold any
355     // common computations, hoist loop-invariant aspects out of any outer loop,
356     // and unswitch the runtime checks if possible. Once hoisted, we may have
357     // dead (or speculatable) control flows or more combining opportunities.
358     MPM.add(createEarlyCSEPass());
359     MPM.add(createCorrelatedValuePropagationPass());
360     MPM.add(createInstructionCombiningPass());
361     MPM.add(createLICMPass());
362     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
363     MPM.add(createCFGSimplificationPass());
364     MPM.add(createInstructionCombiningPass());
365   }
366
367   if (RunSLPAfterLoopVectorization) {
368     if (SLPVectorize) {
369       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
370       if (OptLevel > 1 && ExtraVectorizerPasses) {
371         MPM.add(createEarlyCSEPass());
372       }
373     }
374
375     if (BBVectorize) {
376       MPM.add(createBBVectorizePass());
377       MPM.add(createInstructionCombiningPass());
378       addExtensionsToPM(EP_Peephole, MPM);
379       if (OptLevel > 1 && UseGVNAfterVectorization)
380         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
381       else
382         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
383
384       // BBVectorize may have significantly shortened a loop body; unroll again.
385       if (!DisableUnrollLoops)
386         MPM.add(createLoopUnrollPass());
387     }
388   }
389
390   addExtensionsToPM(EP_Peephole, MPM);
391   MPM.add(createCFGSimplificationPass());
392   MPM.add(createInstructionCombiningPass());
393
394   if (!DisableUnrollLoops) {
395     MPM.add(createLoopUnrollPass());    // Unroll small loops
396
397     // LoopUnroll may generate some redundency to cleanup.
398     MPM.add(createInstructionCombiningPass());
399
400     // Runtime unrolling will introduce runtime check in loop prologue. If the
401     // unrolled loop is a inner loop, then the prologue will be inside the
402     // outer loop. LICM pass can help to promote the runtime check out if the
403     // checked value is loop invariant.
404     MPM.add(createLICMPass());
405   }
406
407   // After vectorization and unrolling, assume intrinsics may tell us more
408   // about pointer alignments.
409   MPM.add(createAlignmentFromAssumptionsPass());
410
411   if (!DisableUnitAtATime) {
412     // FIXME: We shouldn't bother with this anymore.
413     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
414
415     // GlobalOpt already deletes dead functions and globals, at -O2 try a
416     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
417     if (OptLevel > 1) {
418       if (!PrepareForLTO) {
419         // Remove avail extern fns and globals definitions if we aren't
420         // compiling an object file for later LTO. For LTO we want to preserve
421         // these so they are eligible for inlining at link-time. Note if they
422         // are unreferenced they will be removed by GlobalDCE below, so
423         // this only impacts referenced available externally globals.
424         // Eventually they will be suppressed during codegen, but eliminating
425         // here enables more opportunity for GlobalDCE as it may make
426         // globals referenced by available external functions dead.
427         MPM.add(createEliminateAvailableExternallyPass());
428       }
429       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
430       MPM.add(createConstantMergePass());     // Merge dup global constants
431     }
432   }
433
434   if (MergeFunctions)
435     MPM.add(createMergeFunctionsPass());
436
437   addExtensionsToPM(EP_OptimizerLast, MPM);
438 }
439
440 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
441   // Provide AliasAnalysis services for optimizations.
442   addInitialAliasAnalysisPasses(PM);
443
444   // Propagate constants at call sites into the functions they call.  This
445   // opens opportunities for globalopt (and inlining) by substituting function
446   // pointers passed as arguments to direct uses of functions.
447   PM.add(createIPSCCPPass());
448
449   // Now that we internalized some globals, see if we can hack on them!
450   PM.add(createGlobalOptimizerPass());
451
452   // Linking modules together can lead to duplicated global constants, only
453   // keep one copy of each constant.
454   PM.add(createConstantMergePass());
455
456   // Remove unused arguments from functions.
457   PM.add(createDeadArgEliminationPass());
458
459   // Reduce the code after globalopt and ipsccp.  Both can open up significant
460   // simplification opportunities, and both can propagate functions through
461   // function pointers.  When this happens, we often have to resolve varargs
462   // calls, etc, so let instcombine do this.
463   PM.add(createInstructionCombiningPass());
464   addExtensionsToPM(EP_Peephole, PM);
465
466   // Inline small functions
467   bool RunInliner = Inliner;
468   if (RunInliner) {
469     PM.add(Inliner);
470     Inliner = nullptr;
471   }
472
473   PM.add(createPruneEHPass());   // Remove dead EH info.
474
475   // Optimize globals again if we ran the inliner.
476   if (RunInliner)
477     PM.add(createGlobalOptimizerPass());
478   PM.add(createGlobalDCEPass()); // Remove dead functions.
479
480   // If we didn't decide to inline a function, check to see if we can
481   // transform it to pass arguments by value instead of by reference.
482   PM.add(createArgumentPromotionPass());
483
484   // The IPO passes may leave cruft around.  Clean up after them.
485   PM.add(createInstructionCombiningPass());
486   addExtensionsToPM(EP_Peephole, PM);
487   PM.add(createJumpThreadingPass());
488
489   // Break up allocas
490   if (UseNewSROA)
491     PM.add(createSROAPass());
492   else
493     PM.add(createScalarReplAggregatesPass());
494
495   // Run a few AA driven optimizations here and now, to cleanup the code.
496   PM.add(createFunctionAttrsPass()); // Add nocapture.
497   PM.add(createGlobalsModRefPass()); // IP alias analysis.
498
499   PM.add(createLICMPass());                 // Hoist loop invariants.
500   if (EnableMLSM)
501     PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
502   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
503   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
504
505   // Nuke dead stores.
506   PM.add(createDeadStoreEliminationPass());
507
508   // More loops are countable; try to optimize them.
509   PM.add(createIndVarSimplifyPass());
510   PM.add(createLoopDeletionPass());
511   if (EnableLoopInterchange)
512     PM.add(createLoopInterchangePass());
513
514   PM.add(createLoopVectorizePass(true, LoopVectorize));
515
516   // More scalar chains could be vectorized due to more alias information
517   if (RunSLPAfterLoopVectorization)
518     if (SLPVectorize)
519       PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
520
521   // After vectorization, assume intrinsics may tell us more about pointer
522   // alignments.
523   PM.add(createAlignmentFromAssumptionsPass());
524
525   if (LoadCombine)
526     PM.add(createLoadCombinePass());
527
528   // Cleanup and simplify the code after the scalar optimizations.
529   PM.add(createInstructionCombiningPass());
530   addExtensionsToPM(EP_Peephole, PM);
531
532   PM.add(createJumpThreadingPass());
533 }
534
535 void PassManagerBuilder::addLateLTOOptimizationPasses(
536     legacy::PassManagerBase &PM) {
537   // Delete basic blocks, which optimization passes may have killed.
538   PM.add(createCFGSimplificationPass());
539
540   // Now that we have optimized the program, discard unreachable functions.
541   PM.add(createGlobalDCEPass());
542
543   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
544   // currently it damages debug info.
545   if (MergeFunctions)
546     PM.add(createMergeFunctionsPass());
547 }
548
549 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
550   if (LibraryInfo)
551     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
552
553   if (VerifyInput)
554     PM.add(createVerifierPass());
555
556   if (OptLevel > 1)
557     addLTOOptimizationPasses(PM);
558
559   // Lower bit sets to globals. This pass supports Clang's control flow
560   // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
561   // is enabled. The pass does nothing if CFI is disabled.
562   PM.add(createLowerBitSetsPass());
563
564   if (OptLevel != 0)
565     addLateLTOOptimizationPasses(PM);
566
567   if (VerifyOutput)
568     PM.add(createVerifierPass());
569 }
570
571 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
572     return reinterpret_cast<PassManagerBuilder*>(P);
573 }
574
575 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
576   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
577 }
578
579 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
580   PassManagerBuilder *PMB = new PassManagerBuilder();
581   return wrap(PMB);
582 }
583
584 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
585   PassManagerBuilder *Builder = unwrap(PMB);
586   delete Builder;
587 }
588
589 void
590 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
591                                   unsigned OptLevel) {
592   PassManagerBuilder *Builder = unwrap(PMB);
593   Builder->OptLevel = OptLevel;
594 }
595
596 void
597 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
598                                    unsigned SizeLevel) {
599   PassManagerBuilder *Builder = unwrap(PMB);
600   Builder->SizeLevel = SizeLevel;
601 }
602
603 void
604 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
605                                             LLVMBool Value) {
606   PassManagerBuilder *Builder = unwrap(PMB);
607   Builder->DisableUnitAtATime = Value;
608 }
609
610 void
611 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
612                                             LLVMBool Value) {
613   PassManagerBuilder *Builder = unwrap(PMB);
614   Builder->DisableUnrollLoops = Value;
615 }
616
617 void
618 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
619                                                  LLVMBool Value) {
620   // NOTE: The simplify-libcalls pass has been removed.
621 }
622
623 void
624 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
625                                               unsigned Threshold) {
626   PassManagerBuilder *Builder = unwrap(PMB);
627   Builder->Inliner = createFunctionInliningPass(Threshold);
628 }
629
630 void
631 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
632                                                   LLVMPassManagerRef PM) {
633   PassManagerBuilder *Builder = unwrap(PMB);
634   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
635   Builder->populateFunctionPassManager(*FPM);
636 }
637
638 void
639 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
640                                                 LLVMPassManagerRef PM) {
641   PassManagerBuilder *Builder = unwrap(PMB);
642   legacy::PassManagerBase *MPM = unwrap(PM);
643   Builder->populateModulePassManager(*MPM);
644 }
645
646 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
647                                                   LLVMPassManagerRef PM,
648                                                   LLVMBool Internalize,
649                                                   LLVMBool RunInliner) {
650   PassManagerBuilder *Builder = unwrap(PMB);
651   legacy::PassManagerBase *LPM = unwrap(PM);
652
653   // A small backwards compatibility hack. populateLTOPassManager used to take
654   // an RunInliner option.
655   if (RunInliner && !Builder->Inliner)
656     Builder->Inliner = createFunctionInliningPass();
657
658   Builder->populateLTOPassManager(*LPM);
659 }