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