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