1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the PassManagerBuilder class, which is used to set up a
11 // "standard" optimization sequence suitable for languages like C and C++.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
17 #include "llvm-c/Transforms/PassManagerBuilder.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Target/TargetLibraryInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include "llvm/Transforms/IPO.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Vectorize.h"
35 RunLoopVectorization("vectorize-loops", cl::Hidden,
36 cl::desc("Run the Loop vectorization passes"));
39 RunSLPVectorization("vectorize-slp", cl::Hidden,
40 cl::desc("Run the SLP vectorization passes"));
43 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
44 cl::desc("Run the BB vectorization passes"));
47 UseGVNAfterVectorization("use-gvn-after-vectorization",
48 cl::init(false), cl::Hidden,
49 cl::desc("Run GVN instead of Early CSE after vectorization passes"));
51 static cl::opt<bool> UseNewSROA("use-new-sroa",
52 cl::init(true), cl::Hidden,
53 cl::desc("Enable the new, experimental SROA pass"));
56 RunLoopRerolling("reroll-loops", cl::Hidden,
57 cl::desc("Run the loop rerolling pass"));
59 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
61 cl::desc("Run the load combining pass"));
64 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
65 cl::init(false), cl::Hidden,
66 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
67 "vectorizer instead of before"));
69 static cl::opt<bool> UseCFLAA("use-cfl-aa",
70 cl::init(false), cl::Hidden,
71 cl::desc("Enable the new, experimental CFL alias analysis"));
73 PassManagerBuilder::PassManagerBuilder() {
76 LibraryInfo = nullptr;
78 DisableTailCalls = false;
79 DisableUnitAtATime = false;
80 DisableUnrollLoops = false;
81 BBVectorize = RunBBVectorization;
82 SLPVectorize = RunSLPVectorization;
83 LoopVectorize = RunLoopVectorization;
84 RerollLoops = RunLoopRerolling;
85 LoadCombine = RunLoadCombine;
86 DisableGVNLoadPRE = false;
92 PassManagerBuilder::~PassManagerBuilder() {
97 /// Set of global extensions, automatically added as part of the standard set.
98 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
99 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
101 void PassManagerBuilder::addGlobalExtension(
102 PassManagerBuilder::ExtensionPointTy Ty,
103 PassManagerBuilder::ExtensionFn Fn) {
104 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
107 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
108 Extensions.push_back(std::make_pair(Ty, Fn));
111 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
112 PassManagerBase &PM) const {
113 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
114 if ((*GlobalExtensions)[i].first == ETy)
115 (*GlobalExtensions)[i].second(*this, PM);
116 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
117 if (Extensions[i].first == ETy)
118 Extensions[i].second(*this, PM);
122 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
123 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
124 // BasicAliasAnalysis wins if they disagree. This is intended to help
125 // support "obvious" type-punning idioms.
127 PM.add(createCFLAliasAnalysisPass());
128 PM.add(createTypeBasedAliasAnalysisPass());
129 PM.add(createScopedNoAliasAAPass());
130 PM.add(createBasicAliasAnalysisPass());
133 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
134 addExtensionsToPM(EP_EarlyAsPossible, FPM);
136 // Add LibraryInfo if we have some.
137 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
139 if (OptLevel == 0) return;
141 addInitialAliasAnalysisPasses(FPM);
143 FPM.add(createCFGSimplificationPass());
145 FPM.add(createSROAPass());
147 FPM.add(createScalarReplAggregatesPass());
148 FPM.add(createEarlyCSEPass());
149 FPM.add(createLowerExpectIntrinsicPass());
152 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
153 // If all optimizations are disabled, just run the always-inline pass.
160 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
161 // pass manager, but we don't want to add extensions into that pass manager.
162 // To prevent this we must insert a no-op module pass to reset the pass
163 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
164 if (!GlobalExtensions->empty() || !Extensions.empty())
165 MPM.add(createBarrierNoopPass());
167 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
171 // Add LibraryInfo if we have some.
172 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
174 addInitialAliasAnalysisPasses(MPM);
176 if (!DisableUnitAtATime) {
177 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
179 MPM.add(createIPSCCPPass()); // IP SCCP
180 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
182 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
184 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
185 addExtensionsToPM(EP_Peephole, MPM);
186 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
189 // Start of CallGraph SCC passes.
190 if (!DisableUnitAtATime)
191 MPM.add(createPruneEHPass()); // Remove dead EH info
196 if (!DisableUnitAtATime)
197 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
199 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
201 // Start of function pass.
202 // Break up aggregate allocas, using SSAUpdater.
204 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
206 MPM.add(createScalarReplAggregatesPass(-1, false));
207 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
208 MPM.add(createJumpThreadingPass()); // Thread jumps.
209 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
210 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
211 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
212 addExtensionsToPM(EP_Peephole, MPM);
214 if (!DisableTailCalls)
215 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
216 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
217 MPM.add(createReassociatePass()); // Reassociate expressions
218 MPM.add(createLoopRotatePass()); // Rotate Loop
219 MPM.add(createLICMPass()); // Hoist loop invariants
220 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
221 MPM.add(createInstructionCombiningPass());
222 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
223 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
224 MPM.add(createLoopDeletionPass()); // Delete dead loops
226 if (!DisableUnrollLoops)
227 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
228 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
231 MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
232 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
234 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
235 MPM.add(createSCCPPass()); // Constant prop with SCCP
237 // Run instcombine after redundancy elimination to exploit opportunities
238 // opened up by them.
239 MPM.add(createInstructionCombiningPass());
240 addExtensionsToPM(EP_Peephole, MPM);
241 MPM.add(createJumpThreadingPass()); // Thread jumps
242 MPM.add(createCorrelatedValuePropagationPass());
243 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
245 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
248 MPM.add(createLoopRerollPass());
249 if (!RunSLPAfterLoopVectorization) {
251 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
254 MPM.add(createBBVectorizePass());
255 MPM.add(createInstructionCombiningPass());
256 addExtensionsToPM(EP_Peephole, MPM);
257 if (OptLevel > 1 && UseGVNAfterVectorization)
258 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
260 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
262 // BBVectorize may have significantly shortened a loop body; unroll again.
263 if (!DisableUnrollLoops)
264 MPM.add(createLoopUnrollPass());
269 MPM.add(createLoadCombinePass());
271 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
272 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
273 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
274 addExtensionsToPM(EP_Peephole, MPM);
276 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
277 // pass manager that we are specifically trying to avoid. To prevent this
278 // we must insert a no-op module pass to reset the pass manager.
279 MPM.add(createBarrierNoopPass());
280 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
281 // FIXME: Because of #pragma vectorize enable, the passes below are always
282 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
283 // on -O1 and no #pragma is found). Would be good to have these two passes
284 // as function calls, so that we can only pass them when the vectorizer
286 MPM.add(createInstructionCombiningPass());
288 if (RunSLPAfterLoopVectorization) {
290 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
293 MPM.add(createBBVectorizePass());
294 MPM.add(createInstructionCombiningPass());
295 addExtensionsToPM(EP_Peephole, MPM);
296 if (OptLevel > 1 && UseGVNAfterVectorization)
297 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
299 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
301 // BBVectorize may have significantly shortened a loop body; unroll again.
302 if (!DisableUnrollLoops)
303 MPM.add(createLoopUnrollPass());
307 addExtensionsToPM(EP_Peephole, MPM);
308 MPM.add(createCFGSimplificationPass());
310 if (!DisableUnrollLoops)
311 MPM.add(createLoopUnrollPass()); // Unroll small loops
313 if (!DisableUnitAtATime) {
314 // FIXME: We shouldn't bother with this anymore.
315 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
317 // GlobalOpt already deletes dead functions and globals, at -O2 try a
318 // late pass of GlobalDCE. It is capable of deleting dead cycles.
320 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
321 MPM.add(createConstantMergePass()); // Merge dup global constants
324 addExtensionsToPM(EP_OptimizerLast, MPM);
327 void PassManagerBuilder::addLTOOptimizationPasses(PassManagerBase &PM) {
328 // Provide AliasAnalysis services for optimizations.
329 addInitialAliasAnalysisPasses(PM);
331 // Propagate constants at call sites into the functions they call. This
332 // opens opportunities for globalopt (and inlining) by substituting function
333 // pointers passed as arguments to direct uses of functions.
334 PM.add(createIPSCCPPass());
336 // Now that we internalized some globals, see if we can hack on them!
337 PM.add(createGlobalOptimizerPass());
339 // Linking modules together can lead to duplicated global constants, only
340 // keep one copy of each constant.
341 PM.add(createConstantMergePass());
343 // Remove unused arguments from functions.
344 PM.add(createDeadArgEliminationPass());
346 // Reduce the code after globalopt and ipsccp. Both can open up significant
347 // simplification opportunities, and both can propagate functions through
348 // function pointers. When this happens, we often have to resolve varargs
349 // calls, etc, so let instcombine do this.
350 PM.add(createInstructionCombiningPass());
351 addExtensionsToPM(EP_Peephole, PM);
353 // Inline small functions
354 bool RunInliner = Inliner;
360 PM.add(createPruneEHPass()); // Remove dead EH info.
362 // Optimize globals again if we ran the inliner.
364 PM.add(createGlobalOptimizerPass());
365 PM.add(createGlobalDCEPass()); // Remove dead functions.
367 // If we didn't decide to inline a function, check to see if we can
368 // transform it to pass arguments by value instead of by reference.
369 PM.add(createArgumentPromotionPass());
371 // The IPO passes may leave cruft around. Clean up after them.
372 PM.add(createInstructionCombiningPass());
373 addExtensionsToPM(EP_Peephole, PM);
374 PM.add(createJumpThreadingPass());
378 PM.add(createSROAPass());
380 PM.add(createScalarReplAggregatesPass());
382 // Run a few AA driven optimizations here and now, to cleanup the code.
383 PM.add(createFunctionAttrsPass()); // Add nocapture.
384 PM.add(createGlobalsModRefPass()); // IP alias analysis.
386 PM.add(createLICMPass()); // Hoist loop invariants.
387 PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
388 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
389 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
392 PM.add(createDeadStoreEliminationPass());
394 // More loops are countable; try to optimize them.
395 PM.add(createIndVarSimplifyPass());
396 PM.add(createLoopDeletionPass());
397 PM.add(createLoopVectorizePass(true, true));
399 // More scalar chains could be vectorized due to more alias information
400 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
403 PM.add(createLoadCombinePass());
405 // Cleanup and simplify the code after the scalar optimizations.
406 PM.add(createInstructionCombiningPass());
407 addExtensionsToPM(EP_Peephole, PM);
409 PM.add(createJumpThreadingPass());
411 // Delete basic blocks, which optimization passes may have killed.
412 PM.add(createCFGSimplificationPass());
414 // Now that we have optimized the program, discard unreachable functions.
415 PM.add(createGlobalDCEPass());
418 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
421 const DataLayout *DL = TM->getSubtargetImpl()->getDataLayout();
422 PM.add(new DataLayoutPass(*DL));
423 TM->addAnalysisPasses(PM);
427 PM.add(new TargetLibraryInfo(*LibraryInfo));
430 PM.add(createVerifierPass());
433 PM.add(createStripSymbolsPass(true));
436 PM.add(createDebugInfoVerifierPass());
439 addLTOOptimizationPasses(PM);
442 PM.add(createVerifierPass());
443 PM.add(createDebugInfoVerifierPass());
447 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
448 return reinterpret_cast<PassManagerBuilder*>(P);
451 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
452 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
455 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
456 PassManagerBuilder *PMB = new PassManagerBuilder();
460 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
461 PassManagerBuilder *Builder = unwrap(PMB);
466 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
468 PassManagerBuilder *Builder = unwrap(PMB);
469 Builder->OptLevel = OptLevel;
473 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
474 unsigned SizeLevel) {
475 PassManagerBuilder *Builder = unwrap(PMB);
476 Builder->SizeLevel = SizeLevel;
480 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
482 PassManagerBuilder *Builder = unwrap(PMB);
483 Builder->DisableUnitAtATime = Value;
487 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
489 PassManagerBuilder *Builder = unwrap(PMB);
490 Builder->DisableUnrollLoops = Value;
494 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
496 // NOTE: The simplify-libcalls pass has been removed.
500 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
501 unsigned Threshold) {
502 PassManagerBuilder *Builder = unwrap(PMB);
503 Builder->Inliner = createFunctionInliningPass(Threshold);
507 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
508 LLVMPassManagerRef PM) {
509 PassManagerBuilder *Builder = unwrap(PMB);
510 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
511 Builder->populateFunctionPassManager(*FPM);
515 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
516 LLVMPassManagerRef PM) {
517 PassManagerBuilder *Builder = unwrap(PMB);
518 PassManagerBase *MPM = unwrap(PM);
519 Builder->populateModulePassManager(*MPM);
522 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
523 LLVMPassManagerRef PM,
524 LLVMBool Internalize,
525 LLVMBool RunInliner) {
526 PassManagerBuilder *Builder = unwrap(PMB);
527 PassManagerBase *LPM = unwrap(PM);
529 // A small backwards compatibility hack. populateLTOPassManager used to take
530 // an RunInliner option.
531 if (RunInliner && !Builder->Inliner)
532 Builder->Inliner = createFunctionInliningPass();
534 Builder->populateLTOPassManager(*LPM);