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