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