IPConstantPropagation.cpp revision d54353779c9a33c745178f01785113300c7acb0e
1//===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
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 pass implements an _extremely_ simple interprocedural constant
11// propagation pass.  It could certainly be improved in many different ways,
12// like using a worklist.  This pass makes arguments dead, but does not remove
13// them.  The existing dead argument elimination pass should be run after this
14// to clean up the mess.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "ipconstprop"
19#include "llvm/Transforms/IPO.h"
20#include "llvm/Constants.h"
21#include "llvm/Instructions.h"
22#include "llvm/LLVMContext.h"
23#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/Support/CallSite.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/SmallVector.h"
30using namespace llvm;
31
32STATISTIC(NumArgumentsProped, "Number of args turned into constants");
33STATISTIC(NumReturnValProped, "Number of return values turned into constants");
34
35namespace {
36  /// IPCP - The interprocedural constant propagation pass
37  ///
38  struct VISIBILITY_HIDDEN IPCP : public ModulePass {
39    static char ID; // Pass identification, replacement for typeid
40    IPCP() : ModulePass(&ID) {}
41
42    bool runOnModule(Module &M);
43  private:
44    bool PropagateConstantsIntoArguments(Function &F);
45    bool PropagateConstantReturn(Function &F);
46  };
47}
48
49char IPCP::ID = 0;
50static RegisterPass<IPCP>
51X("ipconstprop", "Interprocedural constant propagation");
52
53ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
54
55bool IPCP::runOnModule(Module &M) {
56  bool Changed = false;
57  bool LocalChange = true;
58
59  // FIXME: instead of using smart algorithms, we just iterate until we stop
60  // making changes.
61  while (LocalChange) {
62    LocalChange = false;
63    for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
64      if (!I->isDeclaration()) {
65        // Delete any klingons.
66        I->removeDeadConstantUsers();
67        if (I->hasLocalLinkage())
68          LocalChange |= PropagateConstantsIntoArguments(*I);
69        Changed |= PropagateConstantReturn(*I);
70      }
71    Changed |= LocalChange;
72  }
73  return Changed;
74}
75
76/// PropagateConstantsIntoArguments - Look at all uses of the specified
77/// function.  If all uses are direct call sites, and all pass a particular
78/// constant in for an argument, propagate that constant in as the argument.
79///
80bool IPCP::PropagateConstantsIntoArguments(Function &F) {
81  if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
82
83  // For each argument, keep track of its constant value and whether it is a
84  // constant or not.  The bool is driven to true when found to be non-constant.
85  SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
86  ArgumentConstants.resize(F.arg_size());
87
88  unsigned NumNonconstant = 0;
89  for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
90    // Used by a non-instruction, or not the callee of a function, do not
91    // transform.
92    if (!isa<CallInst>(*UI) && !isa<InvokeInst>(*UI))
93      return false;
94
95    CallSite CS = CallSite::get(cast<Instruction>(*UI));
96    if (!CS.isCallee(UI))
97      return false;
98
99    // Check out all of the potentially constant arguments.  Note that we don't
100    // inspect varargs here.
101    CallSite::arg_iterator AI = CS.arg_begin();
102    Function::arg_iterator Arg = F.arg_begin();
103    for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
104         ++i, ++AI, ++Arg) {
105
106      // If this argument is known non-constant, ignore it.
107      if (ArgumentConstants[i].second)
108        continue;
109
110      Constant *C = dyn_cast<Constant>(*AI);
111      if (C && ArgumentConstants[i].first == 0) {
112        ArgumentConstants[i].first = C;   // First constant seen.
113      } else if (C && ArgumentConstants[i].first == C) {
114        // Still the constant value we think it is.
115      } else if (*AI == &*Arg) {
116        // Ignore recursive calls passing argument down.
117      } else {
118        // Argument became non-constant.  If all arguments are non-constant now,
119        // give up on this function.
120        if (++NumNonconstant == ArgumentConstants.size())
121          return false;
122        ArgumentConstants[i].second = true;
123      }
124    }
125  }
126
127  // If we got to this point, there is a constant argument!
128  assert(NumNonconstant != ArgumentConstants.size());
129  bool MadeChange = false;
130  Function::arg_iterator AI = F.arg_begin();
131  for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
132    // Do we have a constant argument?
133    if (ArgumentConstants[i].second || AI->use_empty() ||
134        (AI->hasByValAttr() && isa<PointerType>(AI->getType())))
135      continue;
136
137    Value *V = ArgumentConstants[i].first;
138    if (V == 0) V = UndefValue::get(AI->getType());
139    AI->replaceAllUsesWith(V);
140    ++NumArgumentsProped;
141    MadeChange = true;
142  }
143  return MadeChange;
144}
145
146
147// Check to see if this function returns one or more constants. If so, replace
148// all callers that use those return values with the constant value. This will
149// leave in the actual return values and instructions, but deadargelim will
150// clean that up.
151//
152// Additionally if a function always returns one of its arguments directly,
153// callers will be updated to use the value they pass in directly instead of
154// using the return value.
155bool IPCP::PropagateConstantReturn(Function &F) {
156  if (F.getReturnType() == Type::getVoidTy(F.getContext()))
157    return false; // No return value.
158
159  // If this function could be overridden later in the link stage, we can't
160  // propagate information about its results into callers.
161  if (F.mayBeOverridden())
162    return false;
163
164  LLVMContext &Context = F.getContext();
165
166  // Check to see if this function returns a constant.
167  SmallVector<Value *,4> RetVals;
168  const StructType *STy = dyn_cast<StructType>(F.getReturnType());
169  if (STy)
170    for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
171      RetVals.push_back(UndefValue::get(STy->getElementType(i)));
172  else
173    RetVals.push_back(UndefValue::get(F.getReturnType()));
174
175  unsigned NumNonConstant = 0;
176  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
177    if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
178      for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
179        // Already found conflicting return values?
180        Value *RV = RetVals[i];
181        if (!RV)
182          continue;
183
184        // Find the returned value
185        Value *V;
186        if (!STy)
187          V = RI->getOperand(i);
188        else
189          V = FindInsertedValue(RI->getOperand(0), i, Context);
190
191        if (V) {
192          // Ignore undefs, we can change them into anything
193          if (isa<UndefValue>(V))
194            continue;
195
196          // Try to see if all the rets return the same constant or argument.
197          if (isa<Constant>(V) || isa<Argument>(V)) {
198            if (isa<UndefValue>(RV)) {
199              // No value found yet? Try the current one.
200              RetVals[i] = V;
201              continue;
202            }
203            // Returning the same value? Good.
204            if (RV == V)
205              continue;
206          }
207        }
208        // Different or no known return value? Don't propagate this return
209        // value.
210        RetVals[i] = 0;
211        // All values non constant? Stop looking.
212        if (++NumNonConstant == RetVals.size())
213          return false;
214      }
215    }
216
217  // If we got here, the function returns at least one constant value.  Loop
218  // over all users, replacing any uses of the return value with the returned
219  // constant.
220  bool MadeChange = false;
221  for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
222    CallSite CS = CallSite::get(*UI);
223    Instruction* Call = CS.getInstruction();
224
225    // Not a call instruction or a call instruction that's not calling F
226    // directly?
227    if (!Call || !CS.isCallee(UI))
228      continue;
229
230    // Call result not used?
231    if (Call->use_empty())
232      continue;
233
234    MadeChange = true;
235
236    if (STy == 0) {
237      Value* New = RetVals[0];
238      if (Argument *A = dyn_cast<Argument>(New))
239        // Was an argument returned? Then find the corresponding argument in
240        // the call instruction and use that.
241        New = CS.getArgument(A->getArgNo());
242      Call->replaceAllUsesWith(New);
243      continue;
244    }
245
246    for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
247         I != E;) {
248      Instruction *Ins = cast<Instruction>(*I);
249
250      // Increment now, so we can remove the use
251      ++I;
252
253      // Find the index of the retval to replace with
254      int index = -1;
255      if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
256        if (EV->hasIndices())
257          index = *EV->idx_begin();
258
259      // If this use uses a specific return value, and we have a replacement,
260      // replace it.
261      if (index != -1) {
262        Value *New = RetVals[index];
263        if (New) {
264          if (Argument *A = dyn_cast<Argument>(New))
265            // Was an argument returned? Then find the corresponding argument in
266            // the call instruction and use that.
267            New = CS.getArgument(A->getArgNo());
268          Ins->replaceAllUsesWith(New);
269          Ins->eraseFromParent();
270        }
271      }
272    }
273  }
274
275  if (MadeChange) ++NumReturnValProped;
276  return MadeChange;
277}
278