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