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