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