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/Verifier.h"
21 #include "llvm/PassManager.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Target/TargetLibraryInfo.h"
25 #include "llvm/Transforms/IPO.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Transforms/Vectorize.h"
32 RunLoopVectorization("vectorize-loops", cl::Hidden,
33 cl::desc("Run the Loop vectorization passes"));
36 RunSLPVectorization("vectorize-slp", cl::Hidden,
37 cl::desc("Run the SLP vectorization passes"));
40 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
41 cl::desc("Run the BB vectorization passes"));
44 UseGVNAfterVectorization("use-gvn-after-vectorization",
45 cl::init(false), cl::Hidden,
46 cl::desc("Run GVN instead of Early CSE after vectorization passes"));
48 static cl::opt<bool> UseNewSROA("use-new-sroa",
49 cl::init(true), cl::Hidden,
50 cl::desc("Enable the new, experimental SROA pass"));
53 RunLoopRerolling("reroll-loops", cl::Hidden,
54 cl::desc("Run the loop rerolling pass"));
56 PassManagerBuilder::PassManagerBuilder() {
61 DisableUnitAtATime = false;
62 DisableUnrollLoops = false;
63 BBVectorize = RunBBVectorization;
64 SLPVectorize = RunSLPVectorization;
65 LoopVectorize = RunLoopVectorization;
66 RerollLoops = RunLoopRerolling;
69 PassManagerBuilder::~PassManagerBuilder() {
74 /// Set of global extensions, automatically added as part of the standard set.
75 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
76 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
78 void PassManagerBuilder::addGlobalExtension(
79 PassManagerBuilder::ExtensionPointTy Ty,
80 PassManagerBuilder::ExtensionFn Fn) {
81 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
84 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
85 Extensions.push_back(std::make_pair(Ty, Fn));
88 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
89 PassManagerBase &PM) const {
90 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
91 if ((*GlobalExtensions)[i].first == ETy)
92 (*GlobalExtensions)[i].second(*this, PM);
93 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
94 if (Extensions[i].first == ETy)
95 Extensions[i].second(*this, PM);
99 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
100 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
101 // BasicAliasAnalysis wins if they disagree. This is intended to help
102 // support "obvious" type-punning idioms.
103 PM.add(createTypeBasedAliasAnalysisPass());
104 PM.add(createBasicAliasAnalysisPass());
107 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
108 addExtensionsToPM(EP_EarlyAsPossible, FPM);
110 // Add LibraryInfo if we have some.
111 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
113 if (OptLevel == 0) return;
115 addInitialAliasAnalysisPasses(FPM);
117 FPM.add(createCFGSimplificationPass());
119 FPM.add(createSROAPass());
121 FPM.add(createScalarReplAggregatesPass());
122 FPM.add(createEarlyCSEPass());
123 FPM.add(createLowerExpectIntrinsicPass());
126 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
127 // If all optimizations are disabled, just run the always-inline pass.
134 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
135 // pass manager, but we don't want to add extensions into that pass manager.
136 // To prevent this we must insert a no-op module pass to reset the pass
137 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
138 if (!GlobalExtensions->empty() || !Extensions.empty())
139 MPM.add(createBarrierNoopPass());
141 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
145 // Add LibraryInfo if we have some.
146 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
148 addInitialAliasAnalysisPasses(MPM);
150 if (!DisableUnitAtATime) {
151 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
153 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
155 MPM.add(createIPSCCPPass()); // IP SCCP
156 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
158 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
159 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
162 // Start of CallGraph SCC passes.
163 if (!DisableUnitAtATime)
164 MPM.add(createPruneEHPass()); // Remove dead EH info
169 if (!DisableUnitAtATime)
170 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
172 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
174 // Start of function pass.
175 // Break up aggregate allocas, using SSAUpdater.
177 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
179 MPM.add(createScalarReplAggregatesPass(-1, false));
180 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
181 MPM.add(createJumpThreadingPass()); // Thread jumps.
182 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
183 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
184 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
186 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
187 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
188 MPM.add(createReassociatePass()); // Reassociate expressions
189 MPM.add(createLoopRotatePass()); // Rotate Loop
190 MPM.add(createLICMPass()); // Hoist loop invariants
191 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
192 MPM.add(createInstructionCombiningPass());
193 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
194 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
195 MPM.add(createLoopDeletionPass()); // Delete dead loops
197 if (!DisableUnrollLoops)
198 MPM.add(createLoopUnrollPass()); // Unroll small loops
199 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
202 MPM.add(createGVNPass()); // Remove redundancies
203 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
204 MPM.add(createSCCPPass()); // Constant prop with SCCP
206 // Run instcombine after redundancy elimination to exploit opportunities
207 // opened up by them.
208 MPM.add(createInstructionCombiningPass());
209 MPM.add(createJumpThreadingPass()); // Thread jumps
210 MPM.add(createCorrelatedValuePropagationPass());
211 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
213 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
216 MPM.add(createLoopRerollPass());
218 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
221 MPM.add(createBBVectorizePass());
222 MPM.add(createInstructionCombiningPass());
223 if (OptLevel > 1 && UseGVNAfterVectorization)
224 MPM.add(createGVNPass()); // Remove redundancies
226 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
228 // BBVectorize may have significantly shortened a loop body; unroll again.
229 if (!DisableUnrollLoops)
230 MPM.add(createLoopUnrollPass());
233 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
234 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
235 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
237 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
238 // pass manager that we are specifically trying to avoid. To prevent this
239 // we must insert a no-op module pass to reset the pass manager.
240 MPM.add(createBarrierNoopPass());
241 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
242 // FIXME: Because of #pragma vectorize enable, the passes below are always
243 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
244 // on -O1 and no #pragma is found). Would be good to have these two passes
245 // as function calls, so that we can only pass them when the vectorizer
247 MPM.add(createInstructionCombiningPass());
248 MPM.add(createCFGSimplificationPass());
250 if (!DisableUnitAtATime) {
251 // FIXME: We shouldn't bother with this anymore.
252 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
254 // GlobalOpt already deletes dead functions and globals, at -O2 try a
255 // late pass of GlobalDCE. It is capable of deleting dead cycles.
257 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
258 MPM.add(createConstantMergePass()); // Merge dup global constants
261 addExtensionsToPM(EP_OptimizerLast, MPM);
264 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
267 bool DisableGVNLoadPRE) {
268 // Provide AliasAnalysis services for optimizations.
269 addInitialAliasAnalysisPasses(PM);
271 // Now that composite has been compiled, scan through the module, looking
272 // for a main function. If main is defined, mark all other functions
275 PM.add(createInternalizePass("main"));
277 // Propagate constants at call sites into the functions they call. This
278 // opens opportunities for globalopt (and inlining) by substituting function
279 // pointers passed as arguments to direct uses of functions.
280 PM.add(createIPSCCPPass());
282 // Now that we internalized some globals, see if we can hack on them!
283 PM.add(createGlobalOptimizerPass());
285 // Linking modules together can lead to duplicated global constants, only
286 // keep one copy of each constant.
287 PM.add(createConstantMergePass());
289 // Remove unused arguments from functions.
290 PM.add(createDeadArgEliminationPass());
292 // Reduce the code after globalopt and ipsccp. Both can open up significant
293 // simplification opportunities, and both can propagate functions through
294 // function pointers. When this happens, we often have to resolve varargs
295 // calls, etc, so let instcombine do this.
296 PM.add(createInstructionCombiningPass());
298 // Inline small functions
300 PM.add(createFunctionInliningPass());
302 PM.add(createPruneEHPass()); // Remove dead EH info.
304 // Optimize globals again if we ran the inliner.
306 PM.add(createGlobalOptimizerPass());
307 PM.add(createGlobalDCEPass()); // Remove dead functions.
309 // If we didn't decide to inline a function, check to see if we can
310 // transform it to pass arguments by value instead of by reference.
311 PM.add(createArgumentPromotionPass());
313 // The IPO passes may leave cruft around. Clean up after them.
314 PM.add(createInstructionCombiningPass());
315 PM.add(createJumpThreadingPass());
319 PM.add(createSROAPass());
321 PM.add(createScalarReplAggregatesPass());
323 // Run a few AA driven optimizations here and now, to cleanup the code.
324 PM.add(createFunctionAttrsPass()); // Add nocapture.
325 PM.add(createGlobalsModRefPass()); // IP alias analysis.
327 PM.add(createLICMPass()); // Hoist loop invariants.
328 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
329 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
332 PM.add(createDeadStoreEliminationPass());
334 // Cleanup and simplify the code after the scalar optimizations.
335 PM.add(createInstructionCombiningPass());
337 PM.add(createJumpThreadingPass());
339 // Delete basic blocks, which optimization passes may have killed.
340 PM.add(createCFGSimplificationPass());
342 // Now that we have optimized the program, discard unreachable functions.
343 PM.add(createGlobalDCEPass());
346 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
347 return reinterpret_cast<PassManagerBuilder*>(P);
350 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
351 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
354 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
355 PassManagerBuilder *PMB = new PassManagerBuilder();
359 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
360 PassManagerBuilder *Builder = unwrap(PMB);
365 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
367 PassManagerBuilder *Builder = unwrap(PMB);
368 Builder->OptLevel = OptLevel;
372 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
373 unsigned SizeLevel) {
374 PassManagerBuilder *Builder = unwrap(PMB);
375 Builder->SizeLevel = SizeLevel;
379 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
381 PassManagerBuilder *Builder = unwrap(PMB);
382 Builder->DisableUnitAtATime = Value;
386 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
388 PassManagerBuilder *Builder = unwrap(PMB);
389 Builder->DisableUnrollLoops = Value;
393 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
395 // NOTE: The simplify-libcalls pass has been removed.
399 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
400 unsigned Threshold) {
401 PassManagerBuilder *Builder = unwrap(PMB);
402 Builder->Inliner = createFunctionInliningPass(Threshold);
406 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
407 LLVMPassManagerRef PM) {
408 PassManagerBuilder *Builder = unwrap(PMB);
409 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
410 Builder->populateFunctionPassManager(*FPM);
414 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
415 LLVMPassManagerRef PM) {
416 PassManagerBuilder *Builder = unwrap(PMB);
417 PassManagerBase *MPM = unwrap(PM);
418 Builder->populateModulePassManager(*MPM);
421 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
422 LLVMPassManagerRef PM,
423 LLVMBool Internalize,
424 LLVMBool RunInliner) {
425 PassManagerBuilder *Builder = unwrap(PMB);
426 PassManagerBase *LPM = unwrap(PM);
427 Builder->populateLTOPassManager(*LPM, Internalize != 0, RunInliner != 0);