about summary refs log tree commit diff homepage
path: root/lib/Module/Optimize.cpp
blob: 96577adef5bbfb96b1e2e998817df2c1a57490c9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// FIXME: This file is a bastard child of opt.cpp and llvm-ld's
// Optimize.cpp. This stuff should live in common code.


//===- Optimize.cpp - Optimize a complete program -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements all optimization of the linked module for llvm-ld.
//
//===----------------------------------------------------------------------===//

#include "klee/Config/Version.h"
#include "klee/Support/OptionCategories.h"

#ifdef USE_WORKAROUND_LLVM_PR39177
#include "Passes.h"
#endif

#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Scalar.h"

#if LLVM_VERSION_CODE >= LLVM_VERSION(3, 9)
#include "llvm/Transforms/IPO/FunctionAttrs.h"
#include "llvm/Transforms/Scalar/GVN.h"
#endif

#if LLVM_VERSION_CODE >= LLVM_VERSION(7, 0)
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#endif

using namespace llvm;

static cl::opt<bool>
    DisableInline("disable-inlining",
                  cl::desc("Do not run the inliner pass (default=false)"),
                  cl::init(false), cl::cat(klee::ModuleCat));

static cl::opt<bool> DisableInternalize(
    "disable-internalize",
    cl::desc("Do not mark all symbols as internal (default=false)"),
    cl::init(false), cl::cat(klee::ModuleCat));

static cl::opt<bool> VerifyEach(
    "verify-each",
    cl::desc("Verify intermediate results of all optimization passes (default=false)"),
    cl::init(false),
    cl::cat(klee::ModuleCat));

static cl::alias ExportDynamic("export-dynamic",
                               cl::aliasopt(DisableInternalize),
                               cl::desc("Alias for -disable-internalize"));

static cl::opt<bool>
    Strip("strip-all", cl::desc("Strip all symbol information from executable"),
          cl::init(false), cl::cat(klee::ModuleCat));

static cl::alias A0("s", cl::desc("Alias for --strip-all"),
                    cl::aliasopt(Strip));

static cl::opt<bool>
    StripDebug("strip-debug",
               cl::desc("Strip debugger symbol info from executable"),
               cl::init(false), cl::cat(klee::ModuleCat));

static cl::alias A1("S", cl::desc("Alias for --strip-debug"),
                    cl::aliasopt(StripDebug));

// A utility function that adds a pass to the pass manager but will also add
// a verifier pass after if we're supposed to verify.
static inline void addPass(legacy::PassManager &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);

  // If we are verifying all of the intermediate steps, add the verifier...
  if (VerifyEach)
    PM.add(createVerifierPass());
}

namespace llvm {


static void AddStandardCompilePasses(legacy::PassManager &PM) {
  PM.add(createVerifierPass());                  // Verify that input is correct

  // If the -strip-debug command line option was specified, do it.
  if (StripDebug)
    addPass(PM, createStripSymbolsPass(true));

  addPass(PM, createCFGSimplificationPass());    // Clean up disgusting code
  addPass(PM, createPromoteMemoryToRegisterPass());// Kill useless allocas
  addPass(PM, createGlobalOptimizerPass());      // Optimize out global vars
  addPass(PM, createGlobalDCEPass());            // Remove unused fns and globs
  addPass(PM, createIPConstantPropagationPass());// IP Constant Propagation
  addPass(PM, createDeadArgEliminationPass());   // Dead argument elimination
  addPass(PM, createInstructionCombiningPass()); // Clean up after IPCP & DAE
  addPass(PM, createCFGSimplificationPass());    // Clean up after IPCP & DAE

  addPass(PM, createPruneEHPass());              // Remove dead EH info
#if LLVM_VERSION_CODE >= LLVM_VERSION(3, 9)
  addPass(PM, createPostOrderFunctionAttrsLegacyPass());
#else
  addPass(PM, createPostOrderFunctionAttrsPass());
#endif
  addPass(PM, createReversePostOrderFunctionAttrsPass()); // Deduce function attrs

  if (!DisableInline)
    addPass(PM, createFunctionInliningPass());   // Inline small functions
  addPass(PM, createArgumentPromotionPass());    // Scalarize uninlined fn args

  addPass(PM, createInstructionCombiningPass()); // Cleanup for scalarrepl.
  addPass(PM, createJumpThreadingPass());        // Thread jumps.
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
#if LLVM_VERSION_CODE >= LLVM_VERSION(3, 9)
  addPass(PM, createSROAPass());                 // Break up aggregate allocas
#else
  addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
#endif
  addPass(PM, createInstructionCombiningPass()); // Combine silly seq's

  addPass(PM, createTailCallEliminationPass());  // Eliminate tail calls
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createReassociatePass());          // Reassociate expressions
  addPass(PM, createLoopRotatePass());
  addPass(PM, createLICMPass());                 // Hoist loop invariants
  addPass(PM, createLoopUnswitchPass());         // Unswitch loops.
  // FIXME : Removing instcombine causes nestedloop regression.
  addPass(PM, createInstructionCombiningPass());
  addPass(PM, createIndVarSimplifyPass());       // Canonicalize indvars
  addPass(PM, createLoopDeletionPass());         // Delete dead loops
  addPass(PM, createLoopUnrollPass());           // Unroll small loops
  addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
  addPass(PM, createGVNPass());                  // Remove redundancies
  addPass(PM, createMemCpyOptPass());            // Remove memcpy / form memset
  addPass(PM, createSCCPPass());                 // Constant prop with SCCP

  // Run instcombine after redundancy elimination to exploit opportunities
  // opened up by them.
  addPass(PM, createInstructionCombiningPass());

  addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
  addPass(PM, createAggressiveDCEPass());        // Delete dead instructions
  addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
  addPass(PM, createStripDeadPrototypesPass());  // Get rid of dead prototypes
  addPass(PM, createConstantMergePass());        // Merge dup global constants
}

/// Optimize - Perform link time optimizations. This will run the scalar
/// optimizations, any loaded plugin-optimization modules, and then the
/// inter-procedural optimizations if applicable.
void Optimize(Module *M, llvm::ArrayRef<const char *> preservedFunctions) {

  // Instantiate the pass manager to organize the passes.
  legacy::PassManager Passes;

  // If we're verifying, start off with a verification pass.
  if (VerifyEach)
    Passes.add(createVerifierPass());

#ifdef USE_WORKAROUND_LLVM_PR39177
  addPass(Passes, new klee::WorkaroundLLVMPR39177Pass());
#endif

  // DWD - Run the opt standard pass list as well.
  AddStandardCompilePasses(Passes);

  // Now that composite has been compiled, scan through the module, looking
  // for a main function.  If main is defined, mark all other functions
  // internal.
  if (!DisableInternalize) {
#if LLVM_VERSION_CODE >= LLVM_VERSION(3, 9)
    auto PreserveFunctions = [=](const GlobalValue &GV) {
      StringRef GVName = GV.getName();

      for (const char *fun : preservedFunctions)
        if (GVName.equals(fun))
          return true;

      return false;
    };
    ModulePass *pass = createInternalizePass(PreserveFunctions);
#else
    ModulePass *pass = createInternalizePass(preservedFunctions);
#endif
    addPass(Passes, pass);
  }

  // Propagate constants at call sites into the functions they call.  This
  // opens opportunities for globalopt (and inlining) by substituting function
  // pointers passed as arguments to direct uses of functions.
  addPass(Passes, createIPSCCPPass());

  // Now that we internalized some globals, see if we can hack on them!
  addPass(Passes, createGlobalOptimizerPass());

  // Linking modules together can lead to duplicated global constants, only
  // keep one copy of each constant...
  addPass(Passes, createConstantMergePass());

  // Remove unused arguments from functions...
  addPass(Passes, createDeadArgEliminationPass());

  // Reduce the code after globalopt and ipsccp.  Both can open up significant
  // simplification opportunities, and both can propagate functions through
  // function pointers.  When this happens, we often have to resolve varargs
  // calls, etc, so let instcombine do this.
  addPass(Passes, createInstructionCombiningPass());

  if (!DisableInline)
    addPass(Passes, createFunctionInliningPass()); // Inline small functions

  addPass(Passes, createPruneEHPass());         // Remove dead EH info
  addPass(Passes, createGlobalOptimizerPass()); // Optimize globals again.
  addPass(Passes, createGlobalDCEPass());       // Remove dead functions

  // If we didn't decide to inline a function, check to see if we can
  // transform it to pass arguments by value instead of by reference.
  addPass(Passes, createArgumentPromotionPass());

  // The IPO passes may leave cruft around.  Clean up after them.
  addPass(Passes, createInstructionCombiningPass());
  addPass(Passes, createJumpThreadingPass()); // Thread jumps.
#if LLVM_VERSION_CODE >= LLVM_VERSION(3, 9)
  addPass(Passes, createSROAPass()); // Break up allocas
#else
  addPass(Passes, createScalarReplAggregatesPass()); // Break up allocas
#endif

  // Run a few AA driven optimizations here and now, to cleanup the code.
#if LLVM_VERSION_CODE >= LLVM_VERSION(3, 9)
  addPass(Passes, createPostOrderFunctionAttrsLegacyPass());
#else
  addPass(Passes, createPostOrderFunctionAttrsPass());
#endif
  addPass(Passes, createReversePostOrderFunctionAttrsPass()); // Add nocapture
  addPass(Passes, createGlobalsAAWrapperPass()); // IP alias analysis

  addPass(Passes, createLICMPass());                 // Hoist loop invariants
  addPass(Passes, createGVNPass());                  // Remove redundancies
  addPass(Passes, createMemCpyOptPass());            // Remove dead memcpy's
  addPass(Passes, createDeadStoreEliminationPass()); // Nuke dead stores

  // Cleanup and simplify the code after the scalar optimizations.
  addPass(Passes, createInstructionCombiningPass());

  addPass(Passes, createJumpThreadingPass());           // Thread jumps.
  addPass(Passes, createPromoteMemoryToRegisterPass()); // Cleanup jumpthread.

  // Delete basic blocks, which optimization passes may have killed...
  addPass(Passes, createCFGSimplificationPass());

  // Now that we have optimized the program, discard unreachable functions...
  addPass(Passes, createGlobalDCEPass());

  // If the -s or -S command line options were specified, strip the symbols out
  // of the resulting program to make it smaller.  -s and -S are GNU ld options
  // that we are supporting; they alias -strip-all and -strip-debug.
  if (Strip || StripDebug)
    addPass(Passes, createStripSymbolsPass(StripDebug && !Strip));

  // The user's passes may leave cruft around; clean up after them.
  addPass(Passes, createInstructionCombiningPass());
  addPass(Passes, createCFGSimplificationPass());
  addPass(Passes, createAggressiveDCEPass());
  addPass(Passes, createGlobalDCEPass());

  // Run our queue of passes all at once now, efficiently.
  Passes.run(*M);
}
}