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