IPConstantPropagation.cpp revision 14ce9ef2e9013ba56e1daafebd91fe3ee1e8647e
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      continue;
135
136    Value *V = ArgumentConstants[i].first;
137    if (V == 0) V = Context->getUndef(AI->getType());
138    AI->replaceAllUsesWith(V);
139    ++NumArgumentsProped;
140    MadeChange = true;
141  }
142  return MadeChange;
143}
144
145
146// Check to see if this function returns one or more constants. If so, replace
147// all callers that use those return values with the constant value. This will
148// leave in the actual return values and instructions, but deadargelim will
149// clean that up.
150//
151// Additionally if a function always returns one of its arguments directly,
152// callers will be updated to use the value they pass in directly instead of
153// using the return value.
154bool IPCP::PropagateConstantReturn(Function &F) {
155  if (F.getReturnType() == Type::VoidTy)
156    return false; // No return value.
157
158  // If this function could be overridden later in the link stage, we can't
159  // propagate information about its results into callers.
160  if (F.mayBeOverridden())
161    return false;
162
163  // Check to see if this function returns a constant.
164  SmallVector<Value *,4> RetVals;
165  const StructType *STy = dyn_cast<StructType>(F.getReturnType());
166  if (STy)
167    for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
168      RetVals.push_back(Context->getUndef(STy->getElementType(i)));
169  else
170    RetVals.push_back(Context->getUndef(F.getReturnType()));
171
172  unsigned NumNonConstant = 0;
173  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
174    if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
175      for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
176        // Already found conflicting return values?
177        Value *RV = RetVals[i];
178        if (!RV)
179          continue;
180
181        // Find the returned value
182        Value *V;
183        if (!STy)
184          V = RI->getOperand(i);
185        else
186          V = FindInsertedValue(RI->getOperand(0), i);
187
188        if (V) {
189          // Ignore undefs, we can change them into anything
190          if (isa<UndefValue>(V))
191            continue;
192
193          // Try to see if all the rets return the same constant or argument.
194          if (isa<Constant>(V) || isa<Argument>(V)) {
195            if (isa<UndefValue>(RV)) {
196              // No value found yet? Try the current one.
197              RetVals[i] = V;
198              continue;
199            }
200            // Returning the same value? Good.
201            if (RV == V)
202              continue;
203          }
204        }
205        // Different or no known return value? Don't propagate this return
206        // value.
207        RetVals[i] = 0;
208        // All values non constant? Stop looking.
209        if (++NumNonConstant == RetVals.size())
210          return false;
211      }
212    }
213
214  // If we got here, the function returns at least one constant value.  Loop
215  // over all users, replacing any uses of the return value with the returned
216  // constant.
217  bool MadeChange = false;
218  for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
219    CallSite CS = CallSite::get(*UI);
220    Instruction* Call = CS.getInstruction();
221
222    // Not a call instruction or a call instruction that's not calling F
223    // directly?
224    if (!Call || !CS.isCallee(UI))
225      continue;
226
227    // Call result not used?
228    if (Call->use_empty())
229      continue;
230
231    MadeChange = true;
232
233    if (STy == 0) {
234      Value* New = RetVals[0];
235      if (Argument *A = dyn_cast<Argument>(New))
236        // Was an argument returned? Then find the corresponding argument in
237        // the call instruction and use that.
238        New = CS.getArgument(A->getArgNo());
239      Call->replaceAllUsesWith(New);
240      continue;
241    }
242
243    for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
244         I != E;) {
245      Instruction *Ins = cast<Instruction>(*I);
246
247      // Increment now, so we can remove the use
248      ++I;
249
250      // Find the index of the retval to replace with
251      int index = -1;
252      if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
253        if (EV->hasIndices())
254          index = *EV->idx_begin();
255
256      // If this use uses a specific return value, and we have a replacement,
257      // replace it.
258      if (index != -1) {
259        Value *New = RetVals[index];
260        if (New) {
261          if (Argument *A = dyn_cast<Argument>(New))
262            // Was an argument returned? Then find the corresponding argument in
263            // the call instruction and use that.
264            New = CS.getArgument(A->getArgNo());
265          Ins->replaceAllUsesWith(New);
266          Ins->eraseFromParent();
267        }
268      }
269    }
270  }
271
272  if (MadeChange) ++NumReturnValProped;
273  return MadeChange;
274}
275