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