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