PassManagerBuilder.cpp revision 0ea3a0c2361e508f07c6c88465799814627ab6cc
1//===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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++.
12//
13//===----------------------------------------------------------------------===//
14
15
16#include "llvm/Transforms/IPO/PassManagerBuilder.h"
17
18#include "llvm-c/Transforms/PassManagerBuilder.h"
19
20#include "llvm/PassManager.h"
21#include "llvm/DefaultPasses.h"
22#include "llvm/PassManager.h"
23#include "llvm/Analysis/Passes.h"
24#include "llvm/Target/TargetLibraryInfo.h"
25#include "llvm/Transforms/Scalar.h"
26#include "llvm/Transforms/IPO.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/Support/ManagedStatic.h"
29
30using namespace llvm;
31
32PassManagerBuilder::PassManagerBuilder() {
33    OptLevel = 2;
34    SizeLevel = 0;
35    LibraryInfo = 0;
36    Inliner = 0;
37    DisableSimplifyLibCalls = false;
38    DisableUnitAtATime = false;
39    DisableUnrollLoops = false;
40}
41
42PassManagerBuilder::~PassManagerBuilder() {
43  delete LibraryInfo;
44  delete Inliner;
45}
46
47/// Set of global extensions, automatically added as part of the standard set.
48static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
49   PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
50
51void PassManagerBuilder::addGlobalExtension(
52    PassManagerBuilder::ExtensionPointTy Ty,
53    PassManagerBuilder::ExtensionFn Fn) {
54  GlobalExtensions->push_back(std::make_pair(Ty, Fn));
55}
56
57void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
58  Extensions.push_back(std::make_pair(Ty, Fn));
59}
60
61void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
62                                           PassManagerBase &PM) const {
63  for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
64    if ((*GlobalExtensions)[i].first == ETy)
65      (*GlobalExtensions)[i].second(*this, PM);
66  for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
67    if (Extensions[i].first == ETy)
68      Extensions[i].second(*this, PM);
69}
70
71void
72PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
73  // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
74  // BasicAliasAnalysis wins if they disagree. This is intended to help
75  // support "obvious" type-punning idioms.
76  PM.add(createTypeBasedAliasAnalysisPass());
77  PM.add(createBasicAliasAnalysisPass());
78}
79
80void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
81  addExtensionsToPM(EP_EarlyAsPossible, FPM);
82
83  // Add LibraryInfo if we have some.
84  if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
85
86  if (OptLevel == 0) return;
87
88  addInitialAliasAnalysisPasses(FPM);
89
90  FPM.add(createCFGSimplificationPass());
91  FPM.add(createScalarReplAggregatesPass());
92  FPM.add(createEarlyCSEPass());
93  FPM.add(createLowerExpectIntrinsicPass());
94}
95
96void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
97  // If all optimizations are disabled, just run the always-inline pass.
98  if (OptLevel == 0) {
99    if (Inliner) {
100      MPM.add(Inliner);
101      Inliner = 0;
102    }
103    addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
104    return;
105  }
106
107  // Add LibraryInfo if we have some.
108  if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
109
110  addInitialAliasAnalysisPasses(MPM);
111
112  if (!DisableUnitAtATime) {
113    MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
114
115    MPM.add(createIPSCCPPass());              // IP SCCP
116    MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
117
118    MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
119    MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
120  }
121
122  // Start of CallGraph SCC passes.
123  if (!DisableUnitAtATime)
124    MPM.add(createPruneEHPass());             // Remove dead EH info
125  if (Inliner) {
126    MPM.add(Inliner);
127    Inliner = 0;
128  }
129  if (!DisableUnitAtATime)
130    MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
131  if (OptLevel > 2)
132    MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
133
134  // Start of function pass.
135  // Break up aggregate allocas, using SSAUpdater.
136  MPM.add(createScalarReplAggregatesPass(-1, false));
137  MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
138  if (!DisableSimplifyLibCalls)
139    MPM.add(createSimplifyLibCallsPass());    // Library Call Optimizations
140  MPM.add(createJumpThreadingPass());         // Thread jumps.
141  MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
142  MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
143  MPM.add(createInstructionCombiningPass());  // Combine silly seq's
144
145  MPM.add(createTailCallEliminationPass());   // Eliminate tail calls
146  MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
147  MPM.add(createReassociatePass());           // Reassociate expressions
148  MPM.add(createLoopRotatePass());            // Rotate Loop
149  MPM.add(createLICMPass());                  // Hoist loop invariants
150  MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
151  MPM.add(createInstructionCombiningPass());
152  MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
153  MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
154  MPM.add(createLoopDeletionPass());          // Delete dead loops
155  if (!DisableUnrollLoops)
156    MPM.add(createLoopUnrollPass());          // Unroll small loops
157  addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
158
159  if (OptLevel > 1)
160    MPM.add(createGVNPass());                 // Remove redundancies
161  MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
162  MPM.add(createSCCPPass());                  // Constant prop with SCCP
163
164  // Run instcombine after redundancy elimination to exploit opportunities
165  // opened up by them.
166  MPM.add(createInstructionCombiningPass());
167  MPM.add(createJumpThreadingPass());         // Thread jumps
168  MPM.add(createCorrelatedValuePropagationPass());
169  MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
170
171  addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
172
173  MPM.add(createAggressiveDCEPass());         // Delete dead instructions
174  MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
175  MPM.add(createInstructionCombiningPass());  // Clean up after everything.
176
177  if (!DisableUnitAtATime) {
178    // FIXME: We shouldn't bother with this anymore.
179    MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
180
181    // GlobalOpt already deletes dead functions and globals, at -O3 try a
182    // late pass of GlobalDCE.  It is capable of deleting dead cycles.
183    if (OptLevel > 2)
184      MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
185
186    if (OptLevel > 1)
187      MPM.add(createConstantMergePass());     // Merge dup global constants
188  }
189}
190
191void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
192                                                bool Internalize,
193                                                bool RunInliner) {
194  // Provide AliasAnalysis services for optimizations.
195  addInitialAliasAnalysisPasses(PM);
196
197  // Now that composite has been compiled, scan through the module, looking
198  // for a main function.  If main is defined, mark all other functions
199  // internal.
200  if (Internalize)
201    PM.add(createInternalizePass(true));
202
203  // Propagate constants at call sites into the functions they call.  This
204  // opens opportunities for globalopt (and inlining) by substituting function
205  // pointers passed as arguments to direct uses of functions.
206  PM.add(createIPSCCPPass());
207
208  // Now that we internalized some globals, see if we can hack on them!
209  PM.add(createGlobalOptimizerPass());
210
211  // Linking modules together can lead to duplicated global constants, only
212  // keep one copy of each constant.
213  PM.add(createConstantMergePass());
214
215  // Remove unused arguments from functions.
216  PM.add(createDeadArgEliminationPass());
217
218  // Reduce the code after globalopt and ipsccp.  Both can open up significant
219  // simplification opportunities, and both can propagate functions through
220  // function pointers.  When this happens, we often have to resolve varargs
221  // calls, etc, so let instcombine do this.
222  PM.add(createInstructionCombiningPass());
223
224  // Inline small functions
225  if (RunInliner)
226    PM.add(createFunctionInliningPass());
227
228  PM.add(createPruneEHPass());   // Remove dead EH info.
229
230  // Optimize globals again if we ran the inliner.
231  if (RunInliner)
232    PM.add(createGlobalOptimizerPass());
233  PM.add(createGlobalDCEPass()); // Remove dead functions.
234
235  // If we didn't decide to inline a function, check to see if we can
236  // transform it to pass arguments by value instead of by reference.
237  PM.add(createArgumentPromotionPass());
238
239  // The IPO passes may leave cruft around.  Clean up after them.
240  PM.add(createInstructionCombiningPass());
241  PM.add(createJumpThreadingPass());
242  // Break up allocas
243  PM.add(createScalarReplAggregatesPass());
244
245  // Run a few AA driven optimizations here and now, to cleanup the code.
246  PM.add(createFunctionAttrsPass()); // Add nocapture.
247  PM.add(createGlobalsModRefPass()); // IP alias analysis.
248
249  PM.add(createLICMPass());      // Hoist loop invariants.
250  PM.add(createGVNPass());       // Remove redundancies.
251  PM.add(createMemCpyOptPass()); // Remove dead memcpys.
252  // Nuke dead stores.
253  PM.add(createDeadStoreEliminationPass());
254
255  // Cleanup and simplify the code after the scalar optimizations.
256  PM.add(createInstructionCombiningPass());
257
258  PM.add(createJumpThreadingPass());
259
260  // Delete basic blocks, which optimization passes may have killed.
261  PM.add(createCFGSimplificationPass());
262
263  // Now that we have optimized the program, discard unreachable functions.
264  PM.add(createGlobalDCEPass());
265}
266
267LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void) {
268  PassManagerBuilder *PMB = new PassManagerBuilder();
269  return wrap(PMB);
270}
271
272void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
273  PassManagerBuilder *Builder = unwrap(PMB);
274  delete Builder;
275}
276
277void
278LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
279                                  unsigned OptLevel) {
280  PassManagerBuilder *Builder = unwrap(PMB);
281  Builder->OptLevel = OptLevel;
282}
283
284void
285LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
286                                   unsigned SizeLevel) {
287  PassManagerBuilder *Builder = unwrap(PMB);
288  Builder->SizeLevel = SizeLevel;
289}
290
291void
292LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
293                                            LLVMBool Value) {
294  PassManagerBuilder *Builder = unwrap(PMB);
295  Builder->DisableUnitAtATime = Value;
296}
297
298void
299LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
300                                            LLVMBool Value) {
301  PassManagerBuilder *Builder = unwrap(PMB);
302  Builder->DisableUnrollLoops = Value;
303}
304
305void
306LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
307                                                 LLVMBool Value) {
308  PassManagerBuilder *Builder = unwrap(PMB);
309  Builder->DisableSimplifyLibCalls = Value;
310}
311
312void
313LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
314                                              unsigned Threshold) {
315  PassManagerBuilder *Builder = unwrap(PMB);
316  Builder->Inliner = createFunctionInliningPass(Threshold);
317}
318
319void
320LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
321                                                  LLVMPassManagerRef PM) {
322  PassManagerBuilder *Builder = unwrap(PMB);
323  FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
324  Builder->populateFunctionPassManager(*FPM);
325}
326
327void
328LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
329                                                LLVMPassManagerRef PM) {
330  PassManagerBuilder *Builder = unwrap(PMB);
331  PassManagerBase *MPM = unwrap(PM);
332  Builder->populateModulePassManager(*MPM);
333}
334
335void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
336                                                  LLVMPassManagerRef PM,
337                                                  bool Internalize,
338                                                  bool RunInliner) {
339  PassManagerBuilder *Builder = unwrap(PMB);
340  PassManagerBase *LPM = unwrap(PM);
341  Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);
342}
343