[attrs] Split off the forced attributes utility into its own pass that
[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/FunctionInfo.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/ManagedStatic.h"
26 #include "llvm/Analysis/BasicAliasAnalysis.h"
27 #include "llvm/Analysis/CFLAliasAnalysis.h"
28 #include "llvm/Analysis/GlobalsModRef.h"
29 #include "llvm/Analysis/ScopedNoAliasAA.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Transforms/IPO.h"
34 #include "llvm/Transforms/IPO/ForceFunctionAttrs.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     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
224
225     MPM.add(createIPSCCPPass());              // IP SCCP
226     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
227     // Promote any localized global vars
228     MPM.add(createPromoteMemoryToRegisterPass());
229
230     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
231
232     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
233     addExtensionsToPM(EP_Peephole, MPM);
234     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
235   }
236
237   if (EnableNonLTOGlobalsModRef)
238     // We add a module alias analysis pass here. In part due to bugs in the
239     // analysis infrastructure this "works" in that the analysis stays alive
240     // for the entire SCC pass run below.
241     MPM.add(createGlobalsAAWrapperPass());
242
243   // Start of CallGraph SCC passes.
244   if (!DisableUnitAtATime)
245     MPM.add(createPruneEHPass());             // Remove dead EH info
246   if (Inliner) {
247     MPM.add(Inliner);
248     Inliner = nullptr;
249   }
250   if (!DisableUnitAtATime)
251     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
252   if (OptLevel > 2)
253     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
254
255   // Start of function pass.
256   // Break up aggregate allocas, using SSAUpdater.
257   if (UseNewSROA)
258     MPM.add(createSROAPass());
259   else
260     MPM.add(createScalarReplAggregatesPass(-1, false));
261   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
262   MPM.add(createJumpThreadingPass());         // Thread jumps.
263   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
264   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
265   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
266   addExtensionsToPM(EP_Peephole, MPM);
267
268   MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
269   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
270   MPM.add(createReassociatePass());           // Reassociate expressions
271   // Rotate Loop - disable header duplication at -Oz
272   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
273   MPM.add(createLICMPass());                  // Hoist loop invariants
274   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
275   MPM.add(createCFGSimplificationPass());
276   MPM.add(createInstructionCombiningPass());
277   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
278   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
279   MPM.add(createLoopDeletionPass());          // Delete dead loops
280   if (EnableLoopInterchange) {
281     MPM.add(createLoopInterchangePass()); // Interchange loops
282     MPM.add(createCFGSimplificationPass());
283   }
284   if (!DisableUnrollLoops)
285     MPM.add(createSimpleLoopUnrollPass());    // Unroll small loops
286   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
287
288   if (OptLevel > 1) {
289     if (EnableMLSM)
290       MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
291     MPM.add(createGVNPass(DisableGVNLoadPRE));  // Remove redundancies
292   }
293   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
294   MPM.add(createSCCPPass());                  // Constant prop with SCCP
295
296   // Delete dead bit computations (instcombine runs after to fold away the dead
297   // computations, and then ADCE will run later to exploit any new DCE
298   // opportunities that creates).
299   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
300
301   // Run instcombine after redundancy elimination to exploit opportunities
302   // opened up by them.
303   MPM.add(createInstructionCombiningPass());
304   addExtensionsToPM(EP_Peephole, MPM);
305   MPM.add(createJumpThreadingPass());         // Thread jumps
306   MPM.add(createCorrelatedValuePropagationPass());
307   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
308   MPM.add(createLICMPass());
309
310   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
311
312   if (RerollLoops)
313     MPM.add(createLoopRerollPass());
314   if (!RunSLPAfterLoopVectorization) {
315     if (SLPVectorize)
316       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
317
318     if (BBVectorize) {
319       MPM.add(createBBVectorizePass());
320       MPM.add(createInstructionCombiningPass());
321       addExtensionsToPM(EP_Peephole, MPM);
322       if (OptLevel > 1 && UseGVNAfterVectorization)
323         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
324       else
325         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
326
327       // BBVectorize may have significantly shortened a loop body; unroll again.
328       if (!DisableUnrollLoops)
329         MPM.add(createLoopUnrollPass());
330     }
331   }
332
333   if (LoadCombine)
334     MPM.add(createLoadCombinePass());
335
336   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
337   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
338   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
339   addExtensionsToPM(EP_Peephole, MPM);
340
341   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
342   // pass manager that we are specifically trying to avoid. To prevent this
343   // we must insert a no-op module pass to reset the pass manager.
344   MPM.add(createBarrierNoopPass());
345
346   if (!DisableUnitAtATime && OptLevel > 1 && !PrepareForLTO) {
347     // Remove avail extern fns and globals definitions if we aren't
348     // compiling an object file for later LTO. For LTO we want to preserve
349     // these so they are eligible for inlining at link-time. Note if they
350     // are unreferenced they will be removed by GlobalDCE later, so
351     // this only impacts referenced available externally globals.
352     // Eventually they will be suppressed during codegen, but eliminating
353     // here enables more opportunity for GlobalDCE as it may make
354     // globals referenced by available external functions dead
355     // and saves running remaining passes on the eliminated functions.
356     MPM.add(createEliminateAvailableExternallyPass());
357   }
358
359   if (EnableNonLTOGlobalsModRef)
360     // We add a fresh GlobalsModRef run at this point. This is particularly
361     // useful as the above will have inlined, DCE'ed, and function-attr
362     // propagated everything. We should at this point have a reasonably minimal
363     // and richly annotated call graph. By computing aliasing and mod/ref
364     // information for all local globals here, the late loop passes and notably
365     // the vectorizer will be able to use them to help recognize vectorizable
366     // memory operations.
367     //
368     // Note that this relies on a bug in the pass manager which preserves
369     // a module analysis into a function pass pipeline (and throughout it) so
370     // long as the first function pass doesn't invalidate the module analysis.
371     // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
372     // this to work. Fortunately, it is trivial to preserve AliasAnalysis
373     // (doing nothing preserves it as it is required to be conservatively
374     // correct in the face of IR changes).
375     MPM.add(createGlobalsAAWrapperPass());
376
377   if (RunFloat2Int)
378     MPM.add(createFloat2IntPass());
379
380   addExtensionsToPM(EP_VectorizerStart, MPM);
381
382   // Re-rotate loops in all our loop nests. These may have fallout out of
383   // rotated form due to GVN or other transformations, and the vectorizer relies
384   // on the rotated form. Disable header duplication at -Oz.
385   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
386
387   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
388   // into separate loop that would otherwise inhibit vectorization.
389   if (EnableLoopDistribute)
390     MPM.add(createLoopDistributePass());
391
392   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
393
394   // Eliminate loads by forwarding stores from the previous iteration to loads
395   // of the current iteration.
396   if (EnableLoopLoadElim)
397     MPM.add(createLoopLoadEliminationPass());
398
399   // FIXME: Because of #pragma vectorize enable, the passes below are always
400   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
401   // on -O1 and no #pragma is found). Would be good to have these two passes
402   // as function calls, so that we can only pass them when the vectorizer
403   // changed the code.
404   MPM.add(createInstructionCombiningPass());
405   if (OptLevel > 1 && ExtraVectorizerPasses) {
406     // At higher optimization levels, try to clean up any runtime overlap and
407     // alignment checks inserted by the vectorizer. We want to track correllated
408     // runtime checks for two inner loops in the same outer loop, fold any
409     // common computations, hoist loop-invariant aspects out of any outer loop,
410     // and unswitch the runtime checks if possible. Once hoisted, we may have
411     // dead (or speculatable) control flows or more combining opportunities.
412     MPM.add(createEarlyCSEPass());
413     MPM.add(createCorrelatedValuePropagationPass());
414     MPM.add(createInstructionCombiningPass());
415     MPM.add(createLICMPass());
416     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
417     MPM.add(createCFGSimplificationPass());
418     MPM.add(createInstructionCombiningPass());
419   }
420
421   if (RunSLPAfterLoopVectorization) {
422     if (SLPVectorize) {
423       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
424       if (OptLevel > 1 && ExtraVectorizerPasses) {
425         MPM.add(createEarlyCSEPass());
426       }
427     }
428
429     if (BBVectorize) {
430       MPM.add(createBBVectorizePass());
431       MPM.add(createInstructionCombiningPass());
432       addExtensionsToPM(EP_Peephole, MPM);
433       if (OptLevel > 1 && UseGVNAfterVectorization)
434         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
435       else
436         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
437
438       // BBVectorize may have significantly shortened a loop body; unroll again.
439       if (!DisableUnrollLoops)
440         MPM.add(createLoopUnrollPass());
441     }
442   }
443
444   addExtensionsToPM(EP_Peephole, MPM);
445   MPM.add(createCFGSimplificationPass());
446   MPM.add(createInstructionCombiningPass());
447
448   if (!DisableUnrollLoops) {
449     MPM.add(createLoopUnrollPass());    // Unroll small loops
450
451     // LoopUnroll may generate some redundency to cleanup.
452     MPM.add(createInstructionCombiningPass());
453
454     // Runtime unrolling will introduce runtime check in loop prologue. If the
455     // unrolled loop is a inner loop, then the prologue will be inside the
456     // outer loop. LICM pass can help to promote the runtime check out if the
457     // checked value is loop invariant.
458     MPM.add(createLICMPass());
459   }
460
461   // After vectorization and unrolling, assume intrinsics may tell us more
462   // about pointer alignments.
463   MPM.add(createAlignmentFromAssumptionsPass());
464
465   if (!DisableUnitAtATime) {
466     // FIXME: We shouldn't bother with this anymore.
467     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
468
469     // GlobalOpt already deletes dead functions and globals, at -O2 try a
470     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
471     if (OptLevel > 1) {
472       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
473       MPM.add(createConstantMergePass());     // Merge dup global constants
474     }
475   }
476
477   if (MergeFunctions)
478     MPM.add(createMergeFunctionsPass());
479
480   addExtensionsToPM(EP_OptimizerLast, MPM);
481 }
482
483 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
484   // Provide AliasAnalysis services for optimizations.
485   addInitialAliasAnalysisPasses(PM);
486
487   if (FunctionIndex)
488     PM.add(createFunctionImportPass(FunctionIndex));
489
490   // Allow forcing function attributes as a debugging and tuning aid.
491   PM.add(createForceFunctionAttrsLegacyPass());
492
493   // Propagate constants at call sites into the functions they call.  This
494   // opens opportunities for globalopt (and inlining) by substituting function
495   // pointers passed as arguments to direct uses of functions.
496   PM.add(createIPSCCPPass());
497
498   // Now that we internalized some globals, see if we can hack on them!
499   PM.add(createFunctionAttrsPass()); // Add norecurse if possible.
500   PM.add(createGlobalOptimizerPass());
501   // Promote any localized global vars.
502   PM.add(createPromoteMemoryToRegisterPass());
503
504   // Linking modules together can lead to duplicated global constants, only
505   // keep one copy of each constant.
506   PM.add(createConstantMergePass());
507
508   // Remove unused arguments from functions.
509   PM.add(createDeadArgEliminationPass());
510
511   // Reduce the code after globalopt and ipsccp.  Both can open up significant
512   // simplification opportunities, and both can propagate functions through
513   // function pointers.  When this happens, we often have to resolve varargs
514   // calls, etc, so let instcombine do this.
515   PM.add(createInstructionCombiningPass());
516   addExtensionsToPM(EP_Peephole, PM);
517
518   // Inline small functions
519   bool RunInliner = Inliner;
520   if (RunInliner) {
521     PM.add(Inliner);
522     Inliner = nullptr;
523   }
524
525   PM.add(createPruneEHPass());   // Remove dead EH info.
526
527   // Optimize globals again if we ran the inliner.
528   if (RunInliner)
529     PM.add(createGlobalOptimizerPass());
530   PM.add(createGlobalDCEPass()); // Remove dead functions.
531
532   // If we didn't decide to inline a function, check to see if we can
533   // transform it to pass arguments by value instead of by reference.
534   PM.add(createArgumentPromotionPass());
535
536   // The IPO passes may leave cruft around.  Clean up after them.
537   PM.add(createInstructionCombiningPass());
538   addExtensionsToPM(EP_Peephole, PM);
539   PM.add(createJumpThreadingPass());
540
541   // Break up allocas
542   if (UseNewSROA)
543     PM.add(createSROAPass());
544   else
545     PM.add(createScalarReplAggregatesPass());
546
547   // Run a few AA driven optimizations here and now, to cleanup the code.
548   PM.add(createFunctionAttrsPass()); // Add nocapture.
549   PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
550
551   PM.add(createLICMPass());                 // Hoist loop invariants.
552   if (EnableMLSM)
553     PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
554   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
555   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
556
557   // Nuke dead stores.
558   PM.add(createDeadStoreEliminationPass());
559
560   // More loops are countable; try to optimize them.
561   PM.add(createIndVarSimplifyPass());
562   PM.add(createLoopDeletionPass());
563   if (EnableLoopInterchange)
564     PM.add(createLoopInterchangePass());
565
566   PM.add(createLoopVectorizePass(true, LoopVectorize));
567
568   // Now that we've optimized loops (in particular loop induction variables),
569   // we may have exposed more scalar opportunities. Run parts of the scalar
570   // optimizer again at this point.
571   PM.add(createInstructionCombiningPass()); // Initial cleanup
572   PM.add(createCFGSimplificationPass()); // if-convert
573   PM.add(createSCCPPass()); // Propagate exposed constants
574   PM.add(createInstructionCombiningPass()); // Clean up again
575   PM.add(createBitTrackingDCEPass());
576
577   // More scalar chains could be vectorized due to more alias information
578   if (RunSLPAfterLoopVectorization)
579     if (SLPVectorize)
580       PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
581
582   // After vectorization, assume intrinsics may tell us more about pointer
583   // alignments.
584   PM.add(createAlignmentFromAssumptionsPass());
585
586   if (LoadCombine)
587     PM.add(createLoadCombinePass());
588
589   // Cleanup and simplify the code after the scalar optimizations.
590   PM.add(createInstructionCombiningPass());
591   addExtensionsToPM(EP_Peephole, PM);
592
593   PM.add(createJumpThreadingPass());
594 }
595
596 void PassManagerBuilder::addLateLTOOptimizationPasses(
597     legacy::PassManagerBase &PM) {
598   // Delete basic blocks, which optimization passes may have killed.
599   PM.add(createCFGSimplificationPass());
600
601   // Drop bodies of available externally objects to improve GlobalDCE.
602   PM.add(createEliminateAvailableExternallyPass());
603
604   // Now that we have optimized the program, discard unreachable functions.
605   PM.add(createGlobalDCEPass());
606
607   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
608   // currently it damages debug info.
609   if (MergeFunctions)
610     PM.add(createMergeFunctionsPass());
611 }
612
613 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
614   if (LibraryInfo)
615     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
616
617   if (VerifyInput)
618     PM.add(createVerifierPass());
619
620   if (OptLevel > 1)
621     addLTOOptimizationPasses(PM);
622
623   // Create a function that performs CFI checks for cross-DSO calls with targets
624   // in the current module.
625   PM.add(createCrossDSOCFIPass());
626
627   // Lower bit sets to globals. This pass supports Clang's control flow
628   // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
629   // is enabled. The pass does nothing if CFI is disabled.
630   PM.add(createLowerBitSetsPass());
631
632   if (OptLevel != 0)
633     addLateLTOOptimizationPasses(PM);
634
635   if (VerifyOutput)
636     PM.add(createVerifierPass());
637 }
638
639 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
640     return reinterpret_cast<PassManagerBuilder*>(P);
641 }
642
643 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
644   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
645 }
646
647 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
648   PassManagerBuilder *PMB = new PassManagerBuilder();
649   return wrap(PMB);
650 }
651
652 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
653   PassManagerBuilder *Builder = unwrap(PMB);
654   delete Builder;
655 }
656
657 void
658 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
659                                   unsigned OptLevel) {
660   PassManagerBuilder *Builder = unwrap(PMB);
661   Builder->OptLevel = OptLevel;
662 }
663
664 void
665 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
666                                    unsigned SizeLevel) {
667   PassManagerBuilder *Builder = unwrap(PMB);
668   Builder->SizeLevel = SizeLevel;
669 }
670
671 void
672 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
673                                             LLVMBool Value) {
674   PassManagerBuilder *Builder = unwrap(PMB);
675   Builder->DisableUnitAtATime = Value;
676 }
677
678 void
679 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
680                                             LLVMBool Value) {
681   PassManagerBuilder *Builder = unwrap(PMB);
682   Builder->DisableUnrollLoops = Value;
683 }
684
685 void
686 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
687                                                  LLVMBool Value) {
688   // NOTE: The simplify-libcalls pass has been removed.
689 }
690
691 void
692 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
693                                               unsigned Threshold) {
694   PassManagerBuilder *Builder = unwrap(PMB);
695   Builder->Inliner = createFunctionInliningPass(Threshold);
696 }
697
698 void
699 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
700                                                   LLVMPassManagerRef PM) {
701   PassManagerBuilder *Builder = unwrap(PMB);
702   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
703   Builder->populateFunctionPassManager(*FPM);
704 }
705
706 void
707 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
708                                                 LLVMPassManagerRef PM) {
709   PassManagerBuilder *Builder = unwrap(PMB);
710   legacy::PassManagerBase *MPM = unwrap(PM);
711   Builder->populateModulePassManager(*MPM);
712 }
713
714 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
715                                                   LLVMPassManagerRef PM,
716                                                   LLVMBool Internalize,
717                                                   LLVMBool RunInliner) {
718   PassManagerBuilder *Builder = unwrap(PMB);
719   legacy::PassManagerBase *LPM = unwrap(PM);
720
721   // A small backwards compatibility hack. populateLTOPassManager used to take
722   // an RunInliner option.
723   if (RunInliner && !Builder->Inliner)
724     Builder->Inliner = createFunctionInliningPass();
725
726   Builder->populateLTOPassManager(*LPM);
727 }