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