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/CFLAndersAliasAnalysis.h"
19 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/ScopedNoAliasAA.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
24 #include "llvm/IR/LegacyPassManager.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Target/CGPassBuilderOption.h"
28 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/IPO/Attributor.h"
31 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
32 #include "llvm/Transforms/IPO/FunctionAttrs.h"
33 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
34 #include "llvm/Transforms/InstCombine/InstCombine.h"
35 #include "llvm/Transforms/Instrumentation.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Scalar/GVN.h"
38 #include "llvm/Transforms/Scalar/LICM.h"
39 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
40 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
41 #include "llvm/Transforms/Utils.h"
42 #include "llvm/Transforms/Vectorize.h"
43 
44 using namespace llvm;
45 
46 namespace llvm {
47 cl::opt<bool> RunPartialInlining("enable-partial-inlining", cl::Hidden,
48                                  cl::desc("Run Partial inlinining pass"));
49 
50 static cl::opt<bool>
51 UseGVNAfterVectorization("use-gvn-after-vectorization",
52   cl::init(false), cl::Hidden,
53   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
54 
55 cl::opt<bool> ExtraVectorizerPasses(
56     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
57     cl::desc("Run cleanup optimization passes after vectorization."));
58 
59 static cl::opt<bool>
60 RunLoopRerolling("reroll-loops", cl::Hidden,
61                  cl::desc("Run the loop rerolling pass"));
62 
63 cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
64                         cl::desc("Run the NewGVN pass"));
65 
66 // Experimental option to use CFL-AA
67 static cl::opt<::CFLAAType>
68     UseCFLAA("use-cfl-aa", cl::init(::CFLAAType::None), cl::Hidden,
69              cl::desc("Enable the new, experimental CFL alias analysis"),
70              cl::values(clEnumValN(::CFLAAType::None, "none", "Disable CFL-AA"),
71                         clEnumValN(::CFLAAType::Steensgaard, "steens",
72                                    "Enable unification-based CFL-AA"),
73                         clEnumValN(::CFLAAType::Andersen, "anders",
74                                    "Enable inclusion-based CFL-AA"),
75                         clEnumValN(::CFLAAType::Both, "both",
76                                    "Enable both variants of CFL-AA")));
77 
78 cl::opt<bool> EnableLoopInterchange(
79     "enable-loopinterchange", cl::init(false), cl::Hidden,
80     cl::desc("Enable the experimental LoopInterchange Pass"));
81 
82 cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false),
83                                  cl::Hidden,
84                                  cl::desc("Enable Unroll And Jam Pass"));
85 
86 cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
87                                 cl::Hidden,
88                                 cl::desc("Enable the LoopFlatten Pass"));
89 
90 cl::opt<bool> EnableDFAJumpThreading("enable-dfa-jump-thread",
91                                      cl::desc("Enable DFA jump threading."),
92                                      cl::init(false), cl::Hidden);
93 
94 cl::opt<bool> EnableHotColdSplit("hot-cold-split",
95                                  cl::desc("Enable hot-cold splitting pass"));
96 
97 cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden,
98     cl::desc("Enable ir outliner pass"));
99 
100 static cl::opt<bool> UseLoopVersioningLICM(
101     "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
102     cl::desc("Enable the experimental Loop Versioning LICM pass"));
103 
104 cl::opt<bool>
105     DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
106                       cl::desc("Disable pre-instrumentation inliner"));
107 
108 cl::opt<int> PreInlineThreshold(
109     "preinline-threshold", cl::Hidden, cl::init(75),
110     cl::desc("Control the amount of inlining in pre-instrumentation inliner "
111              "(default = 75)"));
112 
113 cl::opt<bool>
114     EnableGVNHoist("enable-gvn-hoist",
115                    cl::desc("Enable the GVN hoisting pass (default = off)"));
116 
117 static cl::opt<bool>
118     DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false),
119                               cl::Hidden,
120                               cl::desc("Disable shrink-wrap library calls"));
121 
122 cl::opt<bool>
123     EnableGVNSink("enable-gvn-sink",
124                   cl::desc("Enable the GVN sinking pass (default = off)"));
125 
126 // This option is used in simplifying testing SampleFDO optimizations for
127 // profile loading.
128 cl::opt<bool>
129     EnableCHR("enable-chr", cl::init(true), cl::Hidden,
130               cl::desc("Enable control height reduction optimization (CHR)"));
131 
132 cl::opt<bool> FlattenedProfileUsed(
133     "flattened-profile-used", cl::init(false), cl::Hidden,
134     cl::desc("Indicate the sample profile being used is flattened, i.e., "
135              "no inline hierachy exists in the profile. "));
136 
137 cl::opt<bool> EnableOrderFileInstrumentation(
138     "enable-order-file-instrumentation", cl::init(false), cl::Hidden,
139     cl::desc("Enable order file instrumentation (default = off)"));
140 
141 cl::opt<bool> EnableMatrix(
142     "enable-matrix", cl::init(false), cl::Hidden,
143     cl::desc("Enable lowering of the matrix intrinsics"));
144 
145 cl::opt<bool> EnableConstraintElimination(
146     "enable-constraint-elimination", cl::init(false), cl::Hidden,
147     cl::desc(
148         "Enable pass to eliminate conditions based on linear constraints."));
149 
150 cl::opt<bool> EnableFunctionSpecialization(
151     "enable-function-specialization", cl::init(false), cl::Hidden,
152     cl::desc("Enable Function Specialization pass"));
153 
154 cl::opt<AttributorRunOption> AttributorRun(
155     "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
156     cl::desc("Enable the attributor inter-procedural deduction pass."),
157     cl::values(clEnumValN(AttributorRunOption::ALL, "all",
158                           "enable all attributor runs"),
159                clEnumValN(AttributorRunOption::MODULE, "module",
160                           "enable module-wide attributor runs"),
161                clEnumValN(AttributorRunOption::CGSCC, "cgscc",
162                           "enable call graph SCC attributor runs"),
163                clEnumValN(AttributorRunOption::NONE, "none",
164                           "disable attributor runs")));
165 
166 extern cl::opt<bool> EnableKnowledgeRetention;
167 } // namespace llvm
168 
PassManagerBuilder()169 PassManagerBuilder::PassManagerBuilder() {
170     OptLevel = 2;
171     SizeLevel = 0;
172     LibraryInfo = nullptr;
173     Inliner = nullptr;
174     DisableUnrollLoops = false;
175     SLPVectorize = false;
176     LoopVectorize = true;
177     LoopsInterleaved = true;
178     RerollLoops = RunLoopRerolling;
179     NewGVN = RunNewGVN;
180     LicmMssaOptCap = SetLicmMssaOptCap;
181     LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
182     DisableGVNLoadPRE = false;
183     ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
184     VerifyInput = false;
185     VerifyOutput = false;
186     MergeFunctions = false;
187     DivergentTarget = false;
188     CallGraphProfile = true;
189 }
190 
~PassManagerBuilder()191 PassManagerBuilder::~PassManagerBuilder() {
192   delete LibraryInfo;
193   delete Inliner;
194 }
195 
196 /// Set of global extensions, automatically added as part of the standard set.
197 static ManagedStatic<
198     SmallVector<std::tuple<PassManagerBuilder::ExtensionPointTy,
199                            PassManagerBuilder::ExtensionFn,
200                            PassManagerBuilder::GlobalExtensionID>,
201                 8>>
202     GlobalExtensions;
203 static PassManagerBuilder::GlobalExtensionID GlobalExtensionsCounter;
204 
205 /// Check if GlobalExtensions is constructed and not empty.
206 /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger
207 /// the construction of the object.
GlobalExtensionsNotEmpty()208 static bool GlobalExtensionsNotEmpty() {
209   return GlobalExtensions.isConstructed() && !GlobalExtensions->empty();
210 }
211 
212 PassManagerBuilder::GlobalExtensionID
addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty,PassManagerBuilder::ExtensionFn Fn)213 PassManagerBuilder::addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty,
214                                        PassManagerBuilder::ExtensionFn Fn) {
215   auto ExtensionID = GlobalExtensionsCounter++;
216   GlobalExtensions->push_back(std::make_tuple(Ty, std::move(Fn), ExtensionID));
217   return ExtensionID;
218 }
219 
removeGlobalExtension(PassManagerBuilder::GlobalExtensionID ExtensionID)220 void PassManagerBuilder::removeGlobalExtension(
221     PassManagerBuilder::GlobalExtensionID ExtensionID) {
222   // RegisterStandardPasses may try to call this function after GlobalExtensions
223   // has already been destroyed; doing so should not generate an error.
224   if (!GlobalExtensions.isConstructed())
225     return;
226 
227   auto GlobalExtension =
228       llvm::find_if(*GlobalExtensions, [ExtensionID](const auto &elem) {
229         return std::get<2>(elem) == ExtensionID;
230       });
231   assert(GlobalExtension != GlobalExtensions->end() &&
232          "The extension ID to be removed should always be valid.");
233 
234   GlobalExtensions->erase(GlobalExtension);
235 }
236 
addExtension(ExtensionPointTy Ty,ExtensionFn Fn)237 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
238   Extensions.push_back(std::make_pair(Ty, std::move(Fn)));
239 }
240 
addExtensionsToPM(ExtensionPointTy ETy,legacy::PassManagerBase & PM) const241 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
242                                            legacy::PassManagerBase &PM) const {
243   if (GlobalExtensionsNotEmpty()) {
244     for (auto &Ext : *GlobalExtensions) {
245       if (std::get<0>(Ext) == ETy)
246         std::get<1>(Ext)(*this, PM);
247     }
248   }
249   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
250     if (Extensions[i].first == ETy)
251       Extensions[i].second(*this, PM);
252 }
253 
addInitialAliasAnalysisPasses(legacy::PassManagerBase & PM) const254 void PassManagerBuilder::addInitialAliasAnalysisPasses(
255     legacy::PassManagerBase &PM) const {
256   switch (UseCFLAA) {
257   case ::CFLAAType::Steensgaard:
258     PM.add(createCFLSteensAAWrapperPass());
259     break;
260   case ::CFLAAType::Andersen:
261     PM.add(createCFLAndersAAWrapperPass());
262     break;
263   case ::CFLAAType::Both:
264     PM.add(createCFLSteensAAWrapperPass());
265     PM.add(createCFLAndersAAWrapperPass());
266     break;
267   default:
268     break;
269   }
270 
271   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
272   // BasicAliasAnalysis wins if they disagree. This is intended to help
273   // support "obvious" type-punning idioms.
274   PM.add(createTypeBasedAAWrapperPass());
275   PM.add(createScopedNoAliasAAWrapperPass());
276 }
277 
populateFunctionPassManager(legacy::FunctionPassManager & FPM)278 void PassManagerBuilder::populateFunctionPassManager(
279     legacy::FunctionPassManager &FPM) {
280   addExtensionsToPM(EP_EarlyAsPossible, FPM);
281 
282   // Add LibraryInfo if we have some.
283   if (LibraryInfo)
284     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
285 
286   // The backends do not handle matrix intrinsics currently.
287   // Make sure they are also lowered in O0.
288   // FIXME: A lightweight version of the pass should run in the backend
289   //        pipeline on demand.
290   if (EnableMatrix && OptLevel == 0)
291     FPM.add(createLowerMatrixIntrinsicsMinimalPass());
292 
293   if (OptLevel == 0) return;
294 
295   addInitialAliasAnalysisPasses(FPM);
296 
297   // Lower llvm.expect to metadata before attempting transforms.
298   // Compare/branch metadata may alter the behavior of passes like SimplifyCFG.
299   FPM.add(createLowerExpectIntrinsicPass());
300   FPM.add(createCFGSimplificationPass());
301   FPM.add(createSROAPass());
302   FPM.add(createEarlyCSEPass());
303 }
304 
addFunctionSimplificationPasses(legacy::PassManagerBase & MPM)305 void PassManagerBuilder::addFunctionSimplificationPasses(
306     legacy::PassManagerBase &MPM) {
307   // Start of function pass.
308   // Break up aggregate allocas, using SSAUpdater.
309   assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!");
310   MPM.add(createSROAPass());
311   MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies
312   if (EnableKnowledgeRetention)
313     MPM.add(createAssumeSimplifyPass());
314 
315   if (OptLevel > 1) {
316     if (EnableGVNHoist)
317       MPM.add(createGVNHoistPass());
318     if (EnableGVNSink) {
319       MPM.add(createGVNSinkPass());
320       MPM.add(createCFGSimplificationPass(
321           SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
322     }
323   }
324 
325   if (EnableConstraintElimination)
326     MPM.add(createConstraintEliminationPass());
327 
328   if (OptLevel > 1) {
329     // Speculative execution if the target has divergent branches; otherwise nop.
330     MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass());
331 
332     MPM.add(createJumpThreadingPass());         // Thread jumps.
333     MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
334   }
335   MPM.add(
336       createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
337           true))); // Merge & remove BBs
338   // Combine silly seq's
339   if (OptLevel > 2)
340     MPM.add(createAggressiveInstCombinerPass());
341   MPM.add(createInstructionCombiningPass());
342   if (SizeLevel == 0 && !DisableLibCallsShrinkWrap)
343     MPM.add(createLibCallsShrinkWrapPass());
344   addExtensionsToPM(EP_Peephole, MPM);
345 
346   // TODO: Investigate the cost/benefit of tail call elimination on debugging.
347   if (OptLevel > 1)
348     MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
349   MPM.add(
350       createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
351           true)));                            // Merge & remove BBs
352   MPM.add(createReassociatePass());           // Reassociate expressions
353 
354   // The matrix extension can introduce large vector operations early, which can
355   // benefit from running vector-combine early on.
356   if (EnableMatrix)
357     MPM.add(createVectorCombinePass());
358 
359   // Begin the loop pass pipeline.
360 
361   // The simple loop unswitch pass relies on separate cleanup passes. Schedule
362   // them first so when we re-process a loop they run before other loop
363   // passes.
364   MPM.add(createLoopInstSimplifyPass());
365   MPM.add(createLoopSimplifyCFGPass());
366 
367   // Try to remove as much code from the loop header as possible,
368   // to reduce amount of IR that will have to be duplicated. However,
369   // do not perform speculative hoisting the first time as LICM
370   // will destroy metadata that may not need to be destroyed if run
371   // after loop rotation.
372   // TODO: Investigate promotion cap for O1.
373   MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
374                          /*AllowSpeculation=*/false));
375   // Rotate Loop - disable header duplication at -Oz
376   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, false));
377   // TODO: Investigate promotion cap for O1.
378   MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
379                          /*AllowSpeculation=*/true));
380   MPM.add(createSimpleLoopUnswitchLegacyPass(OptLevel == 3));
381   // FIXME: We break the loop pass pipeline here in order to do full
382   // simplifycfg. Eventually loop-simplifycfg should be enhanced to replace the
383   // need for this.
384   MPM.add(createCFGSimplificationPass(
385       SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
386   MPM.add(createInstructionCombiningPass());
387   // We resume loop passes creating a second loop pipeline here.
388   if (EnableLoopFlatten) {
389     MPM.add(createLoopFlattenPass()); // Flatten loops
390     MPM.add(createLoopSimplifyCFGPass());
391   }
392   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
393   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
394   addExtensionsToPM(EP_LateLoopOptimizations, MPM);
395   MPM.add(createLoopDeletionPass());          // Delete dead loops
396 
397   if (EnableLoopInterchange)
398     MPM.add(createLoopInterchangePass()); // Interchange loops
399 
400   // Unroll small loops and perform peeling.
401   MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
402                                      ForgetAllSCEVInLoopUnroll));
403   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
404   // This ends the loop pass pipelines.
405 
406   // Break up allocas that may now be splittable after loop unrolling.
407   MPM.add(createSROAPass());
408 
409   if (OptLevel > 1) {
410     MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
411     MPM.add(NewGVN ? createNewGVNPass()
412                    : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
413   }
414   MPM.add(createSCCPPass());                  // Constant prop with SCCP
415 
416   if (EnableConstraintElimination)
417     MPM.add(createConstraintEliminationPass());
418 
419   // Delete dead bit computations (instcombine runs after to fold away the dead
420   // computations, and then ADCE will run later to exploit any new DCE
421   // opportunities that creates).
422   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
423 
424   // Run instcombine after redundancy elimination to exploit opportunities
425   // opened up by them.
426   MPM.add(createInstructionCombiningPass());
427   addExtensionsToPM(EP_Peephole, MPM);
428   if (OptLevel > 1) {
429     if (EnableDFAJumpThreading && SizeLevel == 0)
430       MPM.add(createDFAJumpThreadingPass());
431 
432     MPM.add(createJumpThreadingPass());         // Thread jumps
433     MPM.add(createCorrelatedValuePropagationPass());
434   }
435   MPM.add(createAggressiveDCEPass()); // Delete dead instructions
436 
437   MPM.add(createMemCpyOptPass());               // Remove memcpy / form memset
438   // TODO: Investigate if this is too expensive at O1.
439   if (OptLevel > 1) {
440     MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
441     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
442                            /*AllowSpeculation=*/true));
443   }
444 
445   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
446 
447   if (RerollLoops)
448     MPM.add(createLoopRerollPass());
449 
450   // Merge & remove BBs and sink & hoist common instructions.
451   MPM.add(createCFGSimplificationPass(
452       SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true)));
453   // Clean up after everything.
454   MPM.add(createInstructionCombiningPass());
455   addExtensionsToPM(EP_Peephole, MPM);
456 }
457 
458 /// FIXME: Should LTO cause any differences to this set of passes?
addVectorPasses(legacy::PassManagerBase & PM,bool IsFullLTO)459 void PassManagerBuilder::addVectorPasses(legacy::PassManagerBase &PM,
460                                          bool IsFullLTO) {
461   PM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize));
462 
463   if (IsFullLTO) {
464     // The vectorizer may have significantly shortened a loop body; unroll
465     // again. Unroll small loops to hide loop backedge latency and saturate any
466     // parallel execution resources of an out-of-order processor. We also then
467     // need to clean up redundancies and loop invariant code.
468     // FIXME: It would be really good to use a loop-integrated instruction
469     // combiner for cleanup here so that the unrolling and LICM can be pipelined
470     // across the loop nests.
471     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
472     if (EnableUnrollAndJam && !DisableUnrollLoops)
473       PM.add(createLoopUnrollAndJamPass(OptLevel));
474     PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
475                                 ForgetAllSCEVInLoopUnroll));
476     PM.add(createWarnMissedTransformationsPass());
477   }
478 
479   if (!IsFullLTO) {
480     // Eliminate loads by forwarding stores from the previous iteration to loads
481     // of the current iteration.
482     PM.add(createLoopLoadEliminationPass());
483   }
484   // Cleanup after the loop optimization passes.
485   PM.add(createInstructionCombiningPass());
486 
487   if (OptLevel > 1 && ExtraVectorizerPasses) {
488     // At higher optimization levels, try to clean up any runtime overlap and
489     // alignment checks inserted by the vectorizer. We want to track correlated
490     // runtime checks for two inner loops in the same outer loop, fold any
491     // common computations, hoist loop-invariant aspects out of any outer loop,
492     // and unswitch the runtime checks if possible. Once hoisted, we may have
493     // dead (or speculatable) control flows or more combining opportunities.
494     PM.add(createEarlyCSEPass());
495     PM.add(createCorrelatedValuePropagationPass());
496     PM.add(createInstructionCombiningPass());
497     PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
498                           /*AllowSpeculation=*/true));
499     PM.add(createSimpleLoopUnswitchLegacyPass());
500     PM.add(createCFGSimplificationPass(
501         SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
502     PM.add(createInstructionCombiningPass());
503   }
504 
505   // Now that we've formed fast to execute loop structures, we do further
506   // optimizations. These are run afterward as they might block doing complex
507   // analyses and transforms such as what are needed for loop vectorization.
508 
509   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
510   // GVN, loop transforms, and others have already run, so it's now better to
511   // convert to more optimized IR using more aggressive simplify CFG options.
512   // The extra sinking transform can create larger basic blocks, so do this
513   // before SLP vectorization.
514   PM.add(createCFGSimplificationPass(SimplifyCFGOptions()
515                                          .forwardSwitchCondToPhi(true)
516                                          .convertSwitchRangeToICmp(true)
517                                          .convertSwitchToLookupTable(true)
518                                          .needCanonicalLoops(false)
519                                          .hoistCommonInsts(true)
520                                          .sinkCommonInsts(true)));
521 
522   if (IsFullLTO) {
523     PM.add(createSCCPPass());                 // Propagate exposed constants
524     PM.add(createInstructionCombiningPass()); // Clean up again
525     PM.add(createBitTrackingDCEPass());
526   }
527 
528   // Optimize parallel scalar instruction chains into SIMD instructions.
529   if (SLPVectorize) {
530     PM.add(createSLPVectorizerPass());
531     if (OptLevel > 1 && ExtraVectorizerPasses)
532       PM.add(createEarlyCSEPass());
533   }
534 
535   // Enhance/cleanup vector code.
536   PM.add(createVectorCombinePass());
537 
538   if (!IsFullLTO) {
539     addExtensionsToPM(EP_Peephole, PM);
540     PM.add(createInstructionCombiningPass());
541 
542     if (EnableUnrollAndJam && !DisableUnrollLoops) {
543       // Unroll and Jam. We do this before unroll but need to be in a separate
544       // loop pass manager in order for the outer loop to be processed by
545       // unroll and jam before the inner loop is unrolled.
546       PM.add(createLoopUnrollAndJamPass(OptLevel));
547     }
548 
549     // Unroll small loops
550     PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
551                                 ForgetAllSCEVInLoopUnroll));
552 
553     if (!DisableUnrollLoops) {
554       // LoopUnroll may generate some redundency to cleanup.
555       PM.add(createInstructionCombiningPass());
556 
557       // Runtime unrolling will introduce runtime check in loop prologue. If the
558       // unrolled loop is a inner loop, then the prologue will be inside the
559       // outer loop. LICM pass can help to promote the runtime check out if the
560       // checked value is loop invariant.
561       PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
562                             /*AllowSpeculation=*/true));
563     }
564 
565     PM.add(createWarnMissedTransformationsPass());
566   }
567 
568   // After vectorization and unrolling, assume intrinsics may tell us more
569   // about pointer alignments.
570   PM.add(createAlignmentFromAssumptionsPass());
571 
572   if (IsFullLTO)
573     PM.add(createInstructionCombiningPass());
574 }
575 
populateModulePassManager(legacy::PassManagerBase & MPM)576 void PassManagerBuilder::populateModulePassManager(
577     legacy::PassManagerBase &MPM) {
578   MPM.add(createAnnotation2MetadataLegacyPass());
579 
580   // Allow forcing function attributes as a debugging and tuning aid.
581   MPM.add(createForceFunctionAttrsLegacyPass());
582 
583   // If all optimizations are disabled, just run the always-inline pass and,
584   // if enabled, the function merging pass.
585   if (OptLevel == 0) {
586     if (Inliner) {
587       MPM.add(Inliner);
588       Inliner = nullptr;
589     }
590 
591     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
592     // creates a CGSCC pass manager, but we don't want to add extensions into
593     // that pass manager. To prevent this we insert a no-op module pass to reset
594     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
595     // builds. The function merging pass is
596     if (MergeFunctions)
597       MPM.add(createMergeFunctionsPass());
598     else if (GlobalExtensionsNotEmpty() || !Extensions.empty())
599       MPM.add(createBarrierNoopPass());
600 
601     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
602 
603     MPM.add(createAnnotationRemarksLegacyPass());
604     return;
605   }
606 
607   // Add LibraryInfo if we have some.
608   if (LibraryInfo)
609     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
610 
611   addInitialAliasAnalysisPasses(MPM);
612 
613   // Infer attributes about declarations if possible.
614   MPM.add(createInferFunctionAttrsLegacyPass());
615 
616   // Infer attributes on declarations, call sites, arguments, etc.
617   if (AttributorRun & AttributorRunOption::MODULE)
618     MPM.add(createAttributorLegacyPass());
619 
620   addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
621 
622   if (OptLevel > 2)
623     MPM.add(createCallSiteSplittingPass());
624 
625   // Propage constant function arguments by specializing the functions.
626   if (OptLevel > 2 && EnableFunctionSpecialization)
627     MPM.add(createFunctionSpecializationPass());
628 
629   MPM.add(createIPSCCPPass());          // IP SCCP
630   MPM.add(createCalledValuePropagationPass());
631 
632   MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
633   // Promote any localized global vars.
634   MPM.add(createPromoteMemoryToRegisterPass());
635 
636   MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
637 
638   MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
639   addExtensionsToPM(EP_Peephole, MPM);
640   MPM.add(
641       createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
642           true))); // Clean up after IPCP & DAE
643 
644   // We add a module alias analysis pass here. In part due to bugs in the
645   // analysis infrastructure this "works" in that the analysis stays alive
646   // for the entire SCC pass run below.
647   MPM.add(createGlobalsAAWrapperPass());
648 
649   // Start of CallGraph SCC passes.
650   MPM.add(createPruneEHPass()); // Remove dead EH info
651   bool RunInliner = false;
652   if (Inliner) {
653     MPM.add(Inliner);
654     Inliner = nullptr;
655     RunInliner = true;
656   }
657 
658   // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
659   if (AttributorRun & AttributorRunOption::CGSCC)
660     MPM.add(createAttributorCGSCCLegacyPass());
661 
662   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
663   // there are no OpenMP runtime calls present in the module.
664   if (OptLevel > 1)
665     MPM.add(createOpenMPOptCGSCCLegacyPass());
666 
667   MPM.add(createPostOrderFunctionAttrsLegacyPass());
668 
669   addExtensionsToPM(EP_CGSCCOptimizerLate, MPM);
670   addFunctionSimplificationPasses(MPM);
671 
672   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
673   // pass manager that we are specifically trying to avoid. To prevent this
674   // we must insert a no-op module pass to reset the pass manager.
675   MPM.add(createBarrierNoopPass());
676 
677   if (RunPartialInlining)
678     MPM.add(createPartialInliningPass());
679 
680   if (OptLevel > 1)
681     // Remove avail extern fns and globals definitions if we aren't
682     // compiling an object file for later LTO. For LTO we want to preserve
683     // these so they are eligible for inlining at link-time. Note if they
684     // are unreferenced they will be removed by GlobalDCE later, so
685     // this only impacts referenced available externally globals.
686     // Eventually they will be suppressed during codegen, but eliminating
687     // here enables more opportunity for GlobalDCE as it may make
688     // globals referenced by available external functions dead
689     // and saves running remaining passes on the eliminated functions.
690     MPM.add(createEliminateAvailableExternallyPass());
691 
692   MPM.add(createReversePostOrderFunctionAttrsPass());
693 
694   // The inliner performs some kind of dead code elimination as it goes,
695   // but there are cases that are not really caught by it. We might
696   // at some point consider teaching the inliner about them, but it
697   // is OK for now to run GlobalOpt + GlobalDCE in tandem as their
698   // benefits generally outweight the cost, making the whole pipeline
699   // faster.
700   if (RunInliner) {
701     MPM.add(createGlobalOptimizerPass());
702     MPM.add(createGlobalDCEPass());
703   }
704 
705   // Scheduling LoopVersioningLICM when inlining is over, because after that
706   // we may see more accurate aliasing. Reason to run this late is that too
707   // early versioning may prevent further inlining due to increase of code
708   // size. By placing it just after inlining other optimizations which runs
709   // later might get benefit of no-alias assumption in clone loop.
710   if (UseLoopVersioningLICM) {
711     MPM.add(createLoopVersioningLICMPass());    // Do LoopVersioningLICM
712     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
713                            /*AllowSpeculation=*/true));
714   }
715 
716   // We add a fresh GlobalsModRef run at this point. This is particularly
717   // useful as the above will have inlined, DCE'ed, and function-attr
718   // propagated everything. We should at this point have a reasonably minimal
719   // and richly annotated call graph. By computing aliasing and mod/ref
720   // information for all local globals here, the late loop passes and notably
721   // the vectorizer will be able to use them to help recognize vectorizable
722   // memory operations.
723   //
724   // Note that this relies on a bug in the pass manager which preserves
725   // a module analysis into a function pass pipeline (and throughout it) so
726   // long as the first function pass doesn't invalidate the module analysis.
727   // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
728   // this to work. Fortunately, it is trivial to preserve AliasAnalysis
729   // (doing nothing preserves it as it is required to be conservatively
730   // correct in the face of IR changes).
731   MPM.add(createGlobalsAAWrapperPass());
732 
733   MPM.add(createFloat2IntPass());
734   MPM.add(createLowerConstantIntrinsicsPass());
735 
736   if (EnableMatrix) {
737     MPM.add(createLowerMatrixIntrinsicsPass());
738     // CSE the pointer arithmetic of the column vectors.  This allows alias
739     // analysis to establish no-aliasing between loads and stores of different
740     // columns of the same matrix.
741     MPM.add(createEarlyCSEPass(false));
742   }
743 
744   addExtensionsToPM(EP_VectorizerStart, MPM);
745 
746   // Re-rotate loops in all our loop nests. These may have fallout out of
747   // rotated form due to GVN or other transformations, and the vectorizer relies
748   // on the rotated form. Disable header duplication at -Oz.
749   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, false));
750 
751   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
752   // into separate loop that would otherwise inhibit vectorization.  This is
753   // currently only performed for loops marked with the metadata
754   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
755   MPM.add(createLoopDistributePass());
756 
757   addVectorPasses(MPM, /* IsFullLTO */ false);
758 
759   // FIXME: We shouldn't bother with this anymore.
760   MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
761 
762   // GlobalOpt already deletes dead functions and globals, at -O2 try a
763   // late pass of GlobalDCE.  It is capable of deleting dead cycles.
764   if (OptLevel > 1) {
765     MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
766     MPM.add(createConstantMergePass());     // Merge dup global constants
767   }
768 
769   // See comment in the new PM for justification of scheduling splitting at
770   // this stage (\ref buildModuleSimplificationPipeline).
771   if (EnableHotColdSplit)
772     MPM.add(createHotColdSplittingPass());
773 
774   if (EnableIROutliner)
775     MPM.add(createIROutlinerPass());
776 
777   if (MergeFunctions)
778     MPM.add(createMergeFunctionsPass());
779 
780   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
781   // canonicalization pass that enables other optimizations. As a result,
782   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
783   // result too early.
784   MPM.add(createLoopSinkPass());
785   // Get rid of LCSSA nodes.
786   MPM.add(createInstSimplifyLegacyPass());
787 
788   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
789   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
790   // flattening of blocks.
791   MPM.add(createDivRemPairsPass());
792 
793   // LoopSink (and other loop passes since the last simplifyCFG) might have
794   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
795   MPM.add(createCFGSimplificationPass(
796       SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
797 
798   addExtensionsToPM(EP_OptimizerLast, MPM);
799 
800   MPM.add(createAnnotationRemarksLegacyPass());
801 }
802 
LLVMPassManagerBuilderCreate()803 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
804   PassManagerBuilder *PMB = new PassManagerBuilder();
805   return wrap(PMB);
806 }
807 
LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB)808 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
809   PassManagerBuilder *Builder = unwrap(PMB);
810   delete Builder;
811 }
812 
813 void
LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,unsigned OptLevel)814 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
815                                   unsigned OptLevel) {
816   PassManagerBuilder *Builder = unwrap(PMB);
817   Builder->OptLevel = OptLevel;
818 }
819 
820 void
LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,unsigned SizeLevel)821 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
822                                    unsigned SizeLevel) {
823   PassManagerBuilder *Builder = unwrap(PMB);
824   Builder->SizeLevel = SizeLevel;
825 }
826 
827 void
LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,LLVMBool Value)828 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
829                                             LLVMBool Value) {
830   // NOTE: The DisableUnitAtATime switch has been removed.
831 }
832 
833 void
LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,LLVMBool Value)834 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
835                                             LLVMBool Value) {
836   PassManagerBuilder *Builder = unwrap(PMB);
837   Builder->DisableUnrollLoops = Value;
838 }
839 
840 void
LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,LLVMBool Value)841 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
842                                                  LLVMBool Value) {
843   // NOTE: The simplify-libcalls pass has been removed.
844 }
845 
846 void
LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,unsigned Threshold)847 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
848                                               unsigned Threshold) {
849   PassManagerBuilder *Builder = unwrap(PMB);
850   Builder->Inliner = createFunctionInliningPass(Threshold);
851 }
852 
853 void
LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,LLVMPassManagerRef PM)854 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
855                                                   LLVMPassManagerRef PM) {
856   PassManagerBuilder *Builder = unwrap(PMB);
857   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
858   Builder->populateFunctionPassManager(*FPM);
859 }
860 
861 void
LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,LLVMPassManagerRef PM)862 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
863                                                 LLVMPassManagerRef PM) {
864   PassManagerBuilder *Builder = unwrap(PMB);
865   legacy::PassManagerBase *MPM = unwrap(PM);
866   Builder->populateModulePassManager(*MPM);
867 }
868