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