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   // And avoid doing them if optimizing for size.
334   // We will not do this inline for context sensitive PGO (when IsCS is true).
335   if (OptLevel > 0 && SizeLevel == 0 && !DisablePreInliner &&
336       PGOSampleUse.empty() && !IsCS) {
337     // Create preinline pass. We construct an InlineParams object and specify
338     // the threshold here to avoid the command line options of the regular
339     // inliner to influence pre-inlining. The only fields of InlineParams we
340     // care about are DefaultThreshold and HintThreshold.
341     InlineParams IP;
342     IP.DefaultThreshold = PreInlineThreshold;
343     // FIXME: The hint threshold has the same value used by the regular inliner.
344     // This should probably be lowered after performance testing.
345     IP.HintThreshold = 325;
346 
347     MPM.add(createFunctionInliningPass(IP));
348     MPM.add(createSROAPass());
349     MPM.add(createEarlyCSEPass());             // Catch trivial redundancies
350     MPM.add(createCFGSimplificationPass());    // Merge & remove BBs
351     MPM.add(createInstructionCombiningPass()); // Combine silly seq's
352     addExtensionsToPM(EP_Peephole, MPM);
353   }
354   if ((EnablePGOInstrGen && !IsCS) || (EnablePGOCSInstrGen && IsCS)) {
355     MPM.add(createPGOInstrumentationGenLegacyPass(IsCS));
356     // Add the profile lowering pass.
357     InstrProfOptions Options;
358     if (!PGOInstrGen.empty())
359       Options.InstrProfileOutput = PGOInstrGen;
360     Options.DoCounterPromotion = true;
361     Options.UseBFIInPromotion = IsCS;
362     MPM.add(createLoopRotatePass());
363     MPM.add(createInstrProfilingLegacyPass(Options, IsCS));
364   }
365   if (!PGOInstrUse.empty())
366     MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse, IsCS));
367   // Indirect call promotion that promotes intra-module targets only.
368   // For ThinLTO this is done earlier due to interactions with globalopt
369   // for imported functions. We don't run this at -O0.
370   if (OptLevel > 0 && !IsCS)
371     MPM.add(
372         createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty()));
373 }
374 void PassManagerBuilder::addFunctionSimplificationPasses(
375     legacy::PassManagerBase &MPM) {
376   // Start of function pass.
377   // Break up aggregate allocas, using SSAUpdater.
378   assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!");
379   MPM.add(createSROAPass());
380   MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies
381   if (EnableKnowledgeRetention)
382     MPM.add(createAssumeSimplifyPass());
383 
384   if (OptLevel > 1) {
385     if (EnableGVNHoist)
386       MPM.add(createGVNHoistPass());
387     if (EnableGVNSink) {
388       MPM.add(createGVNSinkPass());
389       MPM.add(createCFGSimplificationPass());
390     }
391   }
392 
393   if (EnableConstraintElimination)
394     MPM.add(createConstraintEliminationPass());
395 
396   if (OptLevel > 1) {
397     // Speculative execution if the target has divergent branches; otherwise nop.
398     MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass());
399 
400     MPM.add(createJumpThreadingPass());         // Thread jumps.
401     MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
402   }
403   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
404   // Combine silly seq's
405   if (OptLevel > 2)
406     MPM.add(createAggressiveInstCombinerPass());
407   MPM.add(createInstructionCombiningPass());
408   if (SizeLevel == 0 && !DisableLibCallsShrinkWrap)
409     MPM.add(createLibCallsShrinkWrapPass());
410   addExtensionsToPM(EP_Peephole, MPM);
411 
412   // Optimize memory intrinsic calls based on the profiled size information.
413   if (SizeLevel == 0)
414     MPM.add(createPGOMemOPSizeOptLegacyPass());
415 
416   // TODO: Investigate the cost/benefit of tail call elimination on debugging.
417   if (OptLevel > 1)
418     MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
419   MPM.add(createCFGSimplificationPass());      // Merge & remove BBs
420   MPM.add(createReassociatePass());           // Reassociate expressions
421 
422   // Begin the loop pass pipeline.
423   if (EnableSimpleLoopUnswitch) {
424     // The simple loop unswitch pass relies on separate cleanup passes. Schedule
425     // them first so when we re-process a loop they run before other loop
426     // passes.
427     MPM.add(createLoopInstSimplifyPass());
428     MPM.add(createLoopSimplifyCFGPass());
429   }
430   // Rotate Loop - disable header duplication at -Oz
431   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
432   // TODO: Investigate promotion cap for O1.
433   MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
434   if (EnableSimpleLoopUnswitch)
435     MPM.add(createSimpleLoopUnswitchLegacyPass());
436   else
437     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
438   // FIXME: We break the loop pass pipeline here in order to do full
439   // simplify-cfg. Eventually loop-simplifycfg should be enhanced to replace the
440   // need for this.
441   MPM.add(createCFGSimplificationPass());
442   MPM.add(createInstructionCombiningPass());
443   // We resume loop passes creating a second loop pipeline here.
444   if (EnableLoopFlatten) {
445     MPM.add(createLoopFlattenPass()); // Flatten loops
446     MPM.add(createLoopSimplifyCFGPass());
447   }
448   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
449   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
450   addExtensionsToPM(EP_LateLoopOptimizations, MPM);
451   MPM.add(createLoopDeletionPass());          // Delete dead loops
452 
453   if (EnableLoopInterchange)
454     MPM.add(createLoopInterchangePass()); // Interchange loops
455 
456   // Unroll small loops
457   MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
458                                      ForgetAllSCEVInLoopUnroll));
459   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
460   // This ends the loop pass pipelines.
461 
462   // Break up allocas that may now be splittable after loop unrolling.
463   MPM.add(createSROAPass());
464 
465   if (OptLevel > 1) {
466     MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
467     MPM.add(NewGVN ? createNewGVNPass()
468                    : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
469   }
470   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
471   MPM.add(createSCCPPass());                  // Constant prop with SCCP
472 
473   if (EnableConstraintElimination)
474     MPM.add(createConstraintEliminationPass());
475 
476   // Delete dead bit computations (instcombine runs after to fold away the dead
477   // computations, and then ADCE will run later to exploit any new DCE
478   // opportunities that creates).
479   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
480 
481   // Run instcombine after redundancy elimination to exploit opportunities
482   // opened up by them.
483   MPM.add(createInstructionCombiningPass());
484   addExtensionsToPM(EP_Peephole, MPM);
485   if (OptLevel > 1) {
486     MPM.add(createJumpThreadingPass());         // Thread jumps
487     MPM.add(createCorrelatedValuePropagationPass());
488   }
489   MPM.add(createAggressiveDCEPass()); // Delete dead instructions
490 
491   // TODO: Investigate if this is too expensive at O1.
492   if (OptLevel > 1) {
493     MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
494     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
495   }
496 
497   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
498 
499   if (RerollLoops)
500     MPM.add(createLoopRerollPass());
501 
502   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
503   // Clean up after everything.
504   MPM.add(createInstructionCombiningPass());
505   addExtensionsToPM(EP_Peephole, MPM);
506 
507   if (EnableCHR && OptLevel >= 3 &&
508       (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen))
509     MPM.add(createControlHeightReductionLegacyPass());
510 }
511 
512 void PassManagerBuilder::populateModulePassManager(
513     legacy::PassManagerBase &MPM) {
514   // Whether this is a default or *LTO pre-link pipeline. The FullLTO post-link
515   // is handled separately, so just check this is not the ThinLTO post-link.
516   bool DefaultOrPreLinkPipeline = !PerformThinLTO;
517 
518   MPM.add(createAnnotation2MetadataLegacyPass());
519 
520   if (!PGOSampleUse.empty()) {
521     MPM.add(createPruneEHPass());
522     // In ThinLTO mode, when flattened profile is used, all the available
523     // profile information will be annotated in PreLink phase so there is
524     // no need to load the profile again in PostLink.
525     if (!(FlattenedProfileUsed && PerformThinLTO))
526       MPM.add(createSampleProfileLoaderPass(PGOSampleUse));
527   }
528 
529   // Allow forcing function attributes as a debugging and tuning aid.
530   MPM.add(createForceFunctionAttrsLegacyPass());
531 
532   // If all optimizations are disabled, just run the always-inline pass and,
533   // if enabled, the function merging pass.
534   if (OptLevel == 0) {
535     addPGOInstrPasses(MPM);
536     if (Inliner) {
537       MPM.add(Inliner);
538       Inliner = nullptr;
539     }
540 
541     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
542     // creates a CGSCC pass manager, but we don't want to add extensions into
543     // that pass manager. To prevent this we insert a no-op module pass to reset
544     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
545     // builds. The function merging pass is
546     if (MergeFunctions)
547       MPM.add(createMergeFunctionsPass());
548     else if (GlobalExtensionsNotEmpty() || !Extensions.empty())
549       MPM.add(createBarrierNoopPass());
550 
551     if (PerformThinLTO) {
552       MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
553       // Drop available_externally and unreferenced globals. This is necessary
554       // with ThinLTO in order to avoid leaving undefined references to dead
555       // globals in the object file.
556       MPM.add(createEliminateAvailableExternallyPass());
557       MPM.add(createGlobalDCEPass());
558     }
559 
560     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
561 
562     if (PrepareForLTO || PrepareForThinLTO) {
563       MPM.add(createCanonicalizeAliasesPass());
564       // Rename anon globals to be able to export them in the summary.
565       // This has to be done after we add the extensions to the pass manager
566       // as there could be passes (e.g. Adddress sanitizer) which introduce
567       // new unnamed globals.
568       MPM.add(createNameAnonGlobalPass());
569     }
570     return;
571   }
572 
573   // Add LibraryInfo if we have some.
574   if (LibraryInfo)
575     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
576 
577   addInitialAliasAnalysisPasses(MPM);
578 
579   // For ThinLTO there are two passes of indirect call promotion. The
580   // first is during the compile phase when PerformThinLTO=false and
581   // intra-module indirect call targets are promoted. The second is during
582   // the ThinLTO backend when PerformThinLTO=true, when we promote imported
583   // inter-module indirect calls. For that we perform indirect call promotion
584   // earlier in the pass pipeline, here before globalopt. Otherwise imported
585   // available_externally functions look unreferenced and are removed.
586   if (PerformThinLTO) {
587     MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true,
588                                                      !PGOSampleUse.empty()));
589     MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
590   }
591 
592   // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops
593   // as it will change the CFG too much to make the 2nd profile annotation
594   // in backend more difficult.
595   bool PrepareForThinLTOUsingPGOSampleProfile =
596       PrepareForThinLTO && !PGOSampleUse.empty();
597   if (PrepareForThinLTOUsingPGOSampleProfile)
598     DisableUnrollLoops = true;
599 
600   // Infer attributes about declarations if possible.
601   MPM.add(createInferFunctionAttrsLegacyPass());
602 
603   // Infer attributes on declarations, call sites, arguments, etc.
604   if (AttributorRun & AttributorRunOption::MODULE)
605     MPM.add(createAttributorLegacyPass());
606 
607   addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
608 
609   if (OptLevel > 2)
610     MPM.add(createCallSiteSplittingPass());
611 
612   MPM.add(createIPSCCPPass());          // IP SCCP
613   MPM.add(createCalledValuePropagationPass());
614 
615   MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
616   // Promote any localized global vars.
617   MPM.add(createPromoteMemoryToRegisterPass());
618 
619   MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
620 
621   MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
622   addExtensionsToPM(EP_Peephole, MPM);
623   MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
624 
625   // For SamplePGO in ThinLTO compile phase, we do not want to do indirect
626   // call promotion as it will change the CFG too much to make the 2nd
627   // profile annotation in backend more difficult.
628   // PGO instrumentation is added during the compile phase for ThinLTO, do
629   // not run it a second time
630   if (DefaultOrPreLinkPipeline && !PrepareForThinLTOUsingPGOSampleProfile)
631     addPGOInstrPasses(MPM);
632 
633   // Create profile COMDAT variables. Lld linker wants to see all variables
634   // before the LTO/ThinLTO link since it needs to resolve symbols/comdats.
635   if (!PerformThinLTO && EnablePGOCSInstrGen)
636     MPM.add(createPGOInstrumentationGenCreateVarLegacyPass(PGOInstrGen));
637 
638   // We add a module alias analysis pass here. In part due to bugs in the
639   // analysis infrastructure this "works" in that the analysis stays alive
640   // for the entire SCC pass run below.
641   MPM.add(createGlobalsAAWrapperPass());
642 
643   // Start of CallGraph SCC passes.
644   MPM.add(createPruneEHPass()); // Remove dead EH info
645   bool RunInliner = false;
646   if (Inliner) {
647     MPM.add(Inliner);
648     Inliner = nullptr;
649     RunInliner = true;
650   }
651 
652   // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
653   if (AttributorRun & AttributorRunOption::CGSCC)
654     MPM.add(createAttributorCGSCCLegacyPass());
655 
656   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
657   // there are no OpenMP runtime calls present in the module.
658   if (OptLevel > 1)
659     MPM.add(createOpenMPOptLegacyPass());
660 
661   MPM.add(createPostOrderFunctionAttrsLegacyPass());
662   if (OptLevel > 2)
663     MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
664 
665   addExtensionsToPM(EP_CGSCCOptimizerLate, MPM);
666   addFunctionSimplificationPasses(MPM);
667 
668   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
669   // pass manager that we are specifically trying to avoid. To prevent this
670   // we must insert a no-op module pass to reset the pass manager.
671   MPM.add(createBarrierNoopPass());
672 
673   if (RunPartialInlining)
674     MPM.add(createPartialInliningPass());
675 
676   if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO)
677     // Remove avail extern fns and globals definitions if we aren't
678     // compiling an object file for later LTO. For LTO we want to preserve
679     // these so they are eligible for inlining at link-time. Note if they
680     // are unreferenced they will be removed by GlobalDCE later, so
681     // this only impacts referenced available externally globals.
682     // Eventually they will be suppressed during codegen, but eliminating
683     // here enables more opportunity for GlobalDCE as it may make
684     // globals referenced by available external functions dead
685     // and saves running remaining passes on the eliminated functions.
686     MPM.add(createEliminateAvailableExternallyPass());
687 
688   // CSFDO instrumentation and use pass. Don't invoke this for Prepare pass
689   // for LTO and ThinLTO -- The actual pass will be called after all inlines
690   // are performed.
691   // Need to do this after COMDAT variables have been eliminated,
692   // (i.e. after EliminateAvailableExternallyPass).
693   if (!(PrepareForLTO || PrepareForThinLTO))
694     addPGOInstrPasses(MPM, /* IsCS */ true);
695 
696   if (EnableOrderFileInstrumentation)
697     MPM.add(createInstrOrderFilePass());
698 
699   MPM.add(createReversePostOrderFunctionAttrsPass());
700 
701   // The inliner performs some kind of dead code elimination as it goes,
702   // but there are cases that are not really caught by it. We might
703   // at some point consider teaching the inliner about them, but it
704   // is OK for now to run GlobalOpt + GlobalDCE in tandem as their
705   // benefits generally outweight the cost, making the whole pipeline
706   // faster.
707   if (RunInliner) {
708     MPM.add(createGlobalOptimizerPass());
709     MPM.add(createGlobalDCEPass());
710   }
711 
712   // If we are planning to perform ThinLTO later, let's not bloat the code with
713   // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes
714   // during ThinLTO and perform the rest of the optimizations afterward.
715   if (PrepareForThinLTO) {
716     // Ensure we perform any last passes, but do so before renaming anonymous
717     // globals in case the passes add any.
718     addExtensionsToPM(EP_OptimizerLast, MPM);
719     MPM.add(createCanonicalizeAliasesPass());
720     // Rename anon globals to be able to export them in the summary.
721     MPM.add(createNameAnonGlobalPass());
722     return;
723   }
724 
725   if (PerformThinLTO)
726     // Optimize globals now when performing ThinLTO, this enables more
727     // optimizations later.
728     MPM.add(createGlobalOptimizerPass());
729 
730   // Scheduling LoopVersioningLICM when inlining is over, because after that
731   // we may see more accurate aliasing. Reason to run this late is that too
732   // early versioning may prevent further inlining due to increase of code
733   // size. By placing it just after inlining other optimizations which runs
734   // later might get benefit of no-alias assumption in clone loop.
735   if (UseLoopVersioningLICM) {
736     MPM.add(createLoopVersioningLICMPass());    // Do LoopVersioningLICM
737     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
738   }
739 
740   // We add a fresh GlobalsModRef run at this point. This is particularly
741   // useful as the above will have inlined, DCE'ed, and function-attr
742   // propagated everything. We should at this point have a reasonably minimal
743   // and richly annotated call graph. By computing aliasing and mod/ref
744   // information for all local globals here, the late loop passes and notably
745   // the vectorizer will be able to use them to help recognize vectorizable
746   // memory operations.
747   //
748   // Note that this relies on a bug in the pass manager which preserves
749   // a module analysis into a function pass pipeline (and throughout it) so
750   // long as the first function pass doesn't invalidate the module analysis.
751   // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
752   // this to work. Fortunately, it is trivial to preserve AliasAnalysis
753   // (doing nothing preserves it as it is required to be conservatively
754   // correct in the face of IR changes).
755   MPM.add(createGlobalsAAWrapperPass());
756 
757   MPM.add(createFloat2IntPass());
758   MPM.add(createLowerConstantIntrinsicsPass());
759 
760   if (EnableMatrix) {
761     MPM.add(createLowerMatrixIntrinsicsPass());
762     // CSE the pointer arithmetic of the column vectors.  This allows alias
763     // analysis to establish no-aliasing between loads and stores of different
764     // columns of the same matrix.
765     MPM.add(createEarlyCSEPass(false));
766   }
767 
768   addExtensionsToPM(EP_VectorizerStart, MPM);
769 
770   // Re-rotate loops in all our loop nests. These may have fallout out of
771   // rotated form due to GVN or other transformations, and the vectorizer relies
772   // on the rotated form. Disable header duplication at -Oz.
773   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
774 
775   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
776   // into separate loop that would otherwise inhibit vectorization.  This is
777   // currently only performed for loops marked with the metadata
778   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
779   MPM.add(createLoopDistributePass());
780 
781   MPM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize));
782 
783   // Eliminate loads by forwarding stores from the previous iteration to loads
784   // of the current iteration.
785   MPM.add(createLoopLoadEliminationPass());
786 
787   // FIXME: Because of #pragma vectorize enable, the passes below are always
788   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
789   // on -O1 and no #pragma is found). Would be good to have these two passes
790   // as function calls, so that we can only pass them when the vectorizer
791   // changed the code.
792   MPM.add(createInstructionCombiningPass());
793   if (OptLevel > 1 && ExtraVectorizerPasses) {
794     // At higher optimization levels, try to clean up any runtime overlap and
795     // alignment checks inserted by the vectorizer. We want to track correllated
796     // runtime checks for two inner loops in the same outer loop, fold any
797     // common computations, hoist loop-invariant aspects out of any outer loop,
798     // and unswitch the runtime checks if possible. Once hoisted, we may have
799     // dead (or speculatable) control flows or more combining opportunities.
800     MPM.add(createEarlyCSEPass());
801     MPM.add(createCorrelatedValuePropagationPass());
802     MPM.add(createInstructionCombiningPass());
803     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
804     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
805     MPM.add(createCFGSimplificationPass());
806     MPM.add(createInstructionCombiningPass());
807   }
808 
809   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
810   // GVN, loop transforms, and others have already run, so it's now better to
811   // convert to more optimized IR using more aggressive simplify CFG options.
812   // The extra sinking transform can create larger basic blocks, so do this
813   // before SLP vectorization.
814   // FIXME: study whether hoisting and/or sinking of common instructions should
815   //        be delayed until after SLP vectorizer.
816   MPM.add(createCFGSimplificationPass(SimplifyCFGOptions()
817                                           .forwardSwitchCondToPhi(true)
818                                           .convertSwitchToLookupTable(true)
819                                           .needCanonicalLoops(false)
820                                           .hoistCommonInsts(true)
821                                           .sinkCommonInsts(true)));
822 
823   if (SLPVectorize) {
824     MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
825     if (OptLevel > 1 && ExtraVectorizerPasses) {
826       MPM.add(createEarlyCSEPass());
827     }
828   }
829 
830   // Enhance/cleanup vector code.
831   MPM.add(createVectorCombinePass());
832 
833   addExtensionsToPM(EP_Peephole, MPM);
834   MPM.add(createInstructionCombiningPass());
835 
836   if (EnableUnrollAndJam && !DisableUnrollLoops) {
837     // Unroll and Jam. We do this before unroll but need to be in a separate
838     // loop pass manager in order for the outer loop to be processed by
839     // unroll and jam before the inner loop is unrolled.
840     MPM.add(createLoopUnrollAndJamPass(OptLevel));
841   }
842 
843   // Unroll small loops
844   MPM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
845                                ForgetAllSCEVInLoopUnroll));
846 
847   if (!DisableUnrollLoops) {
848     // LoopUnroll may generate some redundency to cleanup.
849     MPM.add(createInstructionCombiningPass());
850 
851     // Runtime unrolling will introduce runtime check in loop prologue. If the
852     // unrolled loop is a inner loop, then the prologue will be inside the
853     // outer loop. LICM pass can help to promote the runtime check out if the
854     // checked value is loop invariant.
855     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
856   }
857 
858   MPM.add(createWarnMissedTransformationsPass());
859 
860   // After vectorization and unrolling, assume intrinsics may tell us more
861   // about pointer alignments.
862   MPM.add(createAlignmentFromAssumptionsPass());
863 
864   // FIXME: We shouldn't bother with this anymore.
865   MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
866 
867   // GlobalOpt already deletes dead functions and globals, at -O2 try a
868   // late pass of GlobalDCE.  It is capable of deleting dead cycles.
869   if (OptLevel > 1) {
870     MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
871     MPM.add(createConstantMergePass());     // Merge dup global constants
872   }
873 
874   // See comment in the new PM for justification of scheduling splitting at
875   // this stage (\ref buildModuleSimplificationPipeline).
876   if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO))
877     MPM.add(createHotColdSplittingPass());
878 
879   if (MergeFunctions)
880     MPM.add(createMergeFunctionsPass());
881 
882   // Add Module flag "CG Profile" based on Branch Frequency Information.
883   if (CallGraphProfile)
884     MPM.add(createCGProfileLegacyPass());
885 
886   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
887   // canonicalization pass that enables other optimizations. As a result,
888   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
889   // result too early.
890   MPM.add(createLoopSinkPass());
891   // Get rid of LCSSA nodes.
892   MPM.add(createInstSimplifyLegacyPass());
893 
894   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
895   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
896   // flattening of blocks.
897   MPM.add(createDivRemPairsPass());
898 
899   // LoopSink (and other loop passes since the last simplifyCFG) might have
900   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
901   MPM.add(createCFGSimplificationPass());
902 
903   addExtensionsToPM(EP_OptimizerLast, MPM);
904 
905   if (PrepareForLTO) {
906     MPM.add(createCanonicalizeAliasesPass());
907     // Rename anon globals to be able to handle them in the summary
908     MPM.add(createNameAnonGlobalPass());
909   }
910 
911   MPM.add(createAnnotationRemarksLegacyPass());
912 }
913 
914 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
915   // Load sample profile before running the LTO optimization pipeline.
916   if (!PGOSampleUse.empty()) {
917     PM.add(createPruneEHPass());
918     PM.add(createSampleProfileLoaderPass(PGOSampleUse));
919   }
920 
921   // Remove unused virtual tables to improve the quality of code generated by
922   // whole-program devirtualization and bitset lowering.
923   PM.add(createGlobalDCEPass());
924 
925   // Provide AliasAnalysis services for optimizations.
926   addInitialAliasAnalysisPasses(PM);
927 
928   // Allow forcing function attributes as a debugging and tuning aid.
929   PM.add(createForceFunctionAttrsLegacyPass());
930 
931   // Infer attributes about declarations if possible.
932   PM.add(createInferFunctionAttrsLegacyPass());
933 
934   if (OptLevel > 1) {
935     // Split call-site with more constrained arguments.
936     PM.add(createCallSiteSplittingPass());
937 
938     // Indirect call promotion. This should promote all the targets that are
939     // left by the earlier promotion pass that promotes intra-module targets.
940     // This two-step promotion is to save the compile time. For LTO, it should
941     // produce the same result as if we only do promotion here.
942     PM.add(
943         createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty()));
944 
945     // Propagate constants at call sites into the functions they call.  This
946     // opens opportunities for globalopt (and inlining) by substituting function
947     // pointers passed as arguments to direct uses of functions.
948     PM.add(createIPSCCPPass());
949 
950     // Attach metadata to indirect call sites indicating the set of functions
951     // they may target at run-time. This should follow IPSCCP.
952     PM.add(createCalledValuePropagationPass());
953 
954     // Infer attributes on declarations, call sites, arguments, etc.
955     if (AttributorRun & AttributorRunOption::MODULE)
956       PM.add(createAttributorLegacyPass());
957   }
958 
959   // Infer attributes about definitions. The readnone attribute in particular is
960   // required for virtual constant propagation.
961   PM.add(createPostOrderFunctionAttrsLegacyPass());
962   PM.add(createReversePostOrderFunctionAttrsPass());
963 
964   // Split globals using inrange annotations on GEP indices. This can help
965   // improve the quality of generated code when virtual constant propagation or
966   // control flow integrity are enabled.
967   PM.add(createGlobalSplitPass());
968 
969   // Apply whole-program devirtualization and virtual constant propagation.
970   PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
971 
972   // That's all we need at opt level 1.
973   if (OptLevel == 1)
974     return;
975 
976   // Now that we internalized some globals, see if we can hack on them!
977   PM.add(createGlobalOptimizerPass());
978   // Promote any localized global vars.
979   PM.add(createPromoteMemoryToRegisterPass());
980 
981   // Linking modules together can lead to duplicated global constants, only
982   // keep one copy of each constant.
983   PM.add(createConstantMergePass());
984 
985   // Remove unused arguments from functions.
986   PM.add(createDeadArgEliminationPass());
987 
988   // Reduce the code after globalopt and ipsccp.  Both can open up significant
989   // simplification opportunities, and both can propagate functions through
990   // function pointers.  When this happens, we often have to resolve varargs
991   // calls, etc, so let instcombine do this.
992   if (OptLevel > 2)
993     PM.add(createAggressiveInstCombinerPass());
994   PM.add(createInstructionCombiningPass());
995   addExtensionsToPM(EP_Peephole, PM);
996 
997   // Inline small functions
998   bool RunInliner = Inliner;
999   if (RunInliner) {
1000     PM.add(Inliner);
1001     Inliner = nullptr;
1002   }
1003 
1004   PM.add(createPruneEHPass());   // Remove dead EH info.
1005 
1006   // CSFDO instrumentation and use pass.
1007   addPGOInstrPasses(PM, /* IsCS */ true);
1008 
1009   // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
1010   if (AttributorRun & AttributorRunOption::CGSCC)
1011     PM.add(createAttributorCGSCCLegacyPass());
1012 
1013   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
1014   // there are no OpenMP runtime calls present in the module.
1015   if (OptLevel > 1)
1016     PM.add(createOpenMPOptLegacyPass());
1017 
1018   // Optimize globals again if we ran the inliner.
1019   if (RunInliner)
1020     PM.add(createGlobalOptimizerPass());
1021   PM.add(createGlobalDCEPass()); // Remove dead functions.
1022 
1023   // If we didn't decide to inline a function, check to see if we can
1024   // transform it to pass arguments by value instead of by reference.
1025   PM.add(createArgumentPromotionPass());
1026 
1027   // The IPO passes may leave cruft around.  Clean up after them.
1028   PM.add(createInstructionCombiningPass());
1029   addExtensionsToPM(EP_Peephole, PM);
1030   PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true));
1031 
1032   // Break up allocas
1033   PM.add(createSROAPass());
1034 
1035   // LTO provides additional opportunities for tailcall elimination due to
1036   // link-time inlining, and visibility of nocapture attribute.
1037   if (OptLevel > 1)
1038     PM.add(createTailCallEliminationPass());
1039 
1040   // Infer attributes on declarations, call sites, arguments, etc.
1041   PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture.
1042   // Run a few AA driven optimizations here and now, to cleanup the code.
1043   PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
1044 
1045   PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
1046   PM.add(NewGVN ? createNewGVNPass()
1047                 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
1048   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
1049 
1050   // Nuke dead stores.
1051   PM.add(createDeadStoreEliminationPass());
1052   PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
1053 
1054   // More loops are countable; try to optimize them.
1055   if (EnableLoopFlatten)
1056     PM.add(createLoopFlattenPass());
1057   PM.add(createIndVarSimplifyPass());
1058   PM.add(createLoopDeletionPass());
1059   if (EnableLoopInterchange)
1060     PM.add(createLoopInterchangePass());
1061 
1062   if (EnableConstraintElimination)
1063     PM.add(createConstraintEliminationPass());
1064 
1065   // Unroll small loops
1066   PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
1067                                     ForgetAllSCEVInLoopUnroll));
1068   PM.add(createLoopDistributePass());
1069   PM.add(createLoopVectorizePass(true, !LoopVectorize));
1070   // The vectorizer may have significantly shortened a loop body; unroll again.
1071   PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
1072                               ForgetAllSCEVInLoopUnroll));
1073 
1074   PM.add(createWarnMissedTransformationsPass());
1075 
1076   // Now that we've optimized loops (in particular loop induction variables),
1077   // we may have exposed more scalar opportunities. Run parts of the scalar
1078   // optimizer again at this point.
1079   PM.add(createInstructionCombiningPass()); // Initial cleanup
1080   PM.add(createCFGSimplificationPass()); // if-convert
1081   PM.add(createSCCPPass()); // Propagate exposed constants
1082   PM.add(createInstructionCombiningPass()); // Clean up again
1083   PM.add(createBitTrackingDCEPass());
1084 
1085   // More scalar chains could be vectorized due to more alias information
1086   if (SLPVectorize)
1087     PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
1088 
1089   PM.add(createVectorCombinePass()); // Clean up partial vectorization.
1090 
1091   // After vectorization, assume intrinsics may tell us more about pointer
1092   // alignments.
1093   PM.add(createAlignmentFromAssumptionsPass());
1094 
1095   // Cleanup and simplify the code after the scalar optimizations.
1096   PM.add(createInstructionCombiningPass());
1097   addExtensionsToPM(EP_Peephole, PM);
1098 
1099   PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true));
1100 }
1101 
1102 void PassManagerBuilder::addLateLTOOptimizationPasses(
1103     legacy::PassManagerBase &PM) {
1104   // See comment in the new PM for justification of scheduling splitting at
1105   // this stage (\ref buildLTODefaultPipeline).
1106   if (EnableHotColdSplit)
1107     PM.add(createHotColdSplittingPass());
1108 
1109   // Delete basic blocks, which optimization passes may have killed.
1110   PM.add(createCFGSimplificationPass());
1111 
1112   // Drop bodies of available externally objects to improve GlobalDCE.
1113   PM.add(createEliminateAvailableExternallyPass());
1114 
1115   // Now that we have optimized the program, discard unreachable functions.
1116   PM.add(createGlobalDCEPass());
1117 
1118   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
1119   // currently it damages debug info.
1120   if (MergeFunctions)
1121     PM.add(createMergeFunctionsPass());
1122 }
1123 
1124 void PassManagerBuilder::populateThinLTOPassManager(
1125     legacy::PassManagerBase &PM) {
1126   PerformThinLTO = true;
1127   if (LibraryInfo)
1128     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
1129 
1130   if (VerifyInput)
1131     PM.add(createVerifierPass());
1132 
1133   if (ImportSummary) {
1134     // This pass imports type identifier resolutions for whole-program
1135     // devirtualization and CFI. It must run early because other passes may
1136     // disturb the specific instruction patterns that these passes look for,
1137     // creating dependencies on resolutions that may not appear in the summary.
1138     //
1139     // For example, GVN may transform the pattern assume(type.test) appearing in
1140     // two basic blocks into assume(phi(type.test, type.test)), which would
1141     // transform a dependency on a WPD resolution into a dependency on a type
1142     // identifier resolution for CFI.
1143     //
1144     // Also, WPD has access to more precise information than ICP and can
1145     // devirtualize more effectively, so it should operate on the IR first.
1146     PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary));
1147     PM.add(createLowerTypeTestsPass(nullptr, ImportSummary));
1148   }
1149 
1150   populateModulePassManager(PM);
1151 
1152   if (VerifyOutput)
1153     PM.add(createVerifierPass());
1154   PerformThinLTO = false;
1155 }
1156 
1157 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
1158   if (LibraryInfo)
1159     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
1160 
1161   if (VerifyInput)
1162     PM.add(createVerifierPass());
1163 
1164   addExtensionsToPM(EP_FullLinkTimeOptimizationEarly, PM);
1165 
1166   if (OptLevel != 0)
1167     addLTOOptimizationPasses(PM);
1168   else {
1169     // The whole-program-devirt pass needs to run at -O0 because only it knows
1170     // about the llvm.type.checked.load intrinsic: it needs to both lower the
1171     // intrinsic itself and handle it in the summary.
1172     PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
1173   }
1174 
1175   // Create a function that performs CFI checks for cross-DSO calls with targets
1176   // in the current module.
1177   PM.add(createCrossDSOCFIPass());
1178 
1179   // Lower type metadata and the type.test intrinsic. This pass supports Clang's
1180   // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at
1181   // link time if CFI is enabled. The pass does nothing if CFI is disabled.
1182   PM.add(createLowerTypeTestsPass(ExportSummary, nullptr));
1183   // Run a second time to clean up any type tests left behind by WPD for use
1184   // in ICP (which is performed earlier than this in the regular LTO pipeline).
1185   PM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
1186 
1187   if (OptLevel != 0)
1188     addLateLTOOptimizationPasses(PM);
1189 
1190   addExtensionsToPM(EP_FullLinkTimeOptimizationLast, PM);
1191 
1192   PM.add(createAnnotationRemarksLegacyPass());
1193 
1194   if (VerifyOutput)
1195     PM.add(createVerifierPass());
1196 }
1197 
1198 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
1199   PassManagerBuilder *PMB = new PassManagerBuilder();
1200   return wrap(PMB);
1201 }
1202 
1203 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
1204   PassManagerBuilder *Builder = unwrap(PMB);
1205   delete Builder;
1206 }
1207 
1208 void
1209 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
1210                                   unsigned OptLevel) {
1211   PassManagerBuilder *Builder = unwrap(PMB);
1212   Builder->OptLevel = OptLevel;
1213 }
1214 
1215 void
1216 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
1217                                    unsigned SizeLevel) {
1218   PassManagerBuilder *Builder = unwrap(PMB);
1219   Builder->SizeLevel = SizeLevel;
1220 }
1221 
1222 void
1223 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
1224                                             LLVMBool Value) {
1225   // NOTE: The DisableUnitAtATime switch has been removed.
1226 }
1227 
1228 void
1229 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
1230                                             LLVMBool Value) {
1231   PassManagerBuilder *Builder = unwrap(PMB);
1232   Builder->DisableUnrollLoops = Value;
1233 }
1234 
1235 void
1236 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
1237                                                  LLVMBool Value) {
1238   // NOTE: The simplify-libcalls pass has been removed.
1239 }
1240 
1241 void
1242 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
1243                                               unsigned Threshold) {
1244   PassManagerBuilder *Builder = unwrap(PMB);
1245   Builder->Inliner = createFunctionInliningPass(Threshold);
1246 }
1247 
1248 void
1249 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
1250                                                   LLVMPassManagerRef PM) {
1251   PassManagerBuilder *Builder = unwrap(PMB);
1252   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
1253   Builder->populateFunctionPassManager(*FPM);
1254 }
1255 
1256 void
1257 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
1258                                                 LLVMPassManagerRef PM) {
1259   PassManagerBuilder *Builder = unwrap(PMB);
1260   legacy::PassManagerBase *MPM = unwrap(PM);
1261   Builder->populateModulePassManager(*MPM);
1262 }
1263 
1264 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
1265                                                   LLVMPassManagerRef PM,
1266                                                   LLVMBool Internalize,
1267                                                   LLVMBool RunInliner) {
1268   PassManagerBuilder *Builder = unwrap(PMB);
1269   legacy::PassManagerBase *LPM = unwrap(PM);
1270 
1271   // A small backwards compatibility hack. populateLTOPassManager used to take
1272   // an RunInliner option.
1273   if (RunInliner && !Builder->Inliner)
1274     Builder->Inliner = createFunctionInliningPass();
1275 
1276   Builder->populateLTOPassManager(*LPM);
1277 }
1278