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