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