1 //===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
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 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.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "ipconstprop"
19 #include "llvm/Transforms/IPO.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/SmallVector.h"
30 STATISTIC(NumArgumentsProped, "Number of args turned into constants");
31 STATISTIC(NumReturnValProped, "Number of return values turned into constants");
34 /// IPCP - The interprocedural constant propagation pass
36 struct VISIBILITY_HIDDEN IPCP : public ModulePass {
37 static char ID; // Pass identification, replacement for typeid
38 IPCP() : ModulePass((intptr_t)&ID) {}
40 bool runOnModule(Module &M);
42 bool PropagateConstantsIntoArguments(Function &F);
43 bool PropagateConstantReturn(Function &F);
48 static RegisterPass<IPCP>
49 X("ipconstprop", "Interprocedural constant propagation");
51 ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
53 bool IPCP::runOnModule(Module &M) {
55 bool LocalChange = true;
57 // FIXME: instead of using smart algorithms, we just iterate until we stop
61 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
62 if (!I->isDeclaration()) {
63 // Delete any klingons.
64 I->removeDeadConstantUsers();
65 if (I->hasInternalLinkage())
66 LocalChange |= PropagateConstantsIntoArguments(*I);
67 Changed |= PropagateConstantReturn(*I);
69 Changed |= LocalChange;
74 /// PropagateConstantsIntoArguments - Look at all uses of the specified
75 /// function. If all uses are direct call sites, and all pass a particular
76 /// constant in for an argument, propagate that constant in as the argument.
78 bool IPCP::PropagateConstantsIntoArguments(Function &F) {
79 if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
81 // For each argument, keep track of its constant value and whether it is a
82 // constant or not. The bool is driven to true when found to be non-constant.
83 SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
84 ArgumentConstants.resize(F.arg_size());
86 unsigned NumNonconstant = 0;
87 for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
88 // Used by a non-instruction, or not the callee of a function, do not
90 if (UI.getOperandNo() != 0 ||
91 (!isa<CallInst>(*UI) && !isa<InvokeInst>(*UI)))
94 CallSite CS = CallSite::get(cast<Instruction>(*UI));
96 // Check out all of the potentially constant arguments. Note that we don't
97 // inspect varargs here.
98 CallSite::arg_iterator AI = CS.arg_begin();
99 Function::arg_iterator Arg = F.arg_begin();
100 for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
103 // If this argument is known non-constant, ignore it.
104 if (ArgumentConstants[i].second)
107 Constant *C = dyn_cast<Constant>(*AI);
108 if (C && ArgumentConstants[i].first == 0) {
109 ArgumentConstants[i].first = C; // First constant seen.
110 } else if (C && ArgumentConstants[i].first == C) {
111 // Still the constant value we think it is.
112 } else if (*AI == &*Arg) {
113 // Ignore recursive calls passing argument down.
115 // Argument became non-constant. If all arguments are non-constant now,
116 // give up on this function.
117 if (++NumNonconstant == ArgumentConstants.size())
119 ArgumentConstants[i].second = true;
124 // If we got to this point, there is a constant argument!
125 assert(NumNonconstant != ArgumentConstants.size());
126 bool MadeChange = false;
127 Function::arg_iterator AI = F.arg_begin();
128 for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
129 // Do we have a constant argument?
130 if (ArgumentConstants[i].second || AI->use_empty())
133 Value *V = ArgumentConstants[i].first;
134 if (V == 0) V = UndefValue::get(AI->getType());
135 AI->replaceAllUsesWith(V);
136 ++NumArgumentsProped;
143 // Check to see if this function returns a constant. If so, replace all callers
144 // that user the return value with the returned valued. If we can replace ALL
146 bool IPCP::PropagateConstantReturn(Function &F) {
147 if (F.getReturnType() == Type::VoidTy)
148 return false; // No return value.
150 // Check to see if this function returns a constant.
151 SmallVector<Value *,4> RetVals;
152 const StructType *STy = dyn_cast<StructType>(F.getReturnType());
154 RetVals.assign(STy->getNumElements(), 0);
156 RetVals.push_back(0);
158 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
159 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
160 assert(RetVals.size() == RI->getNumOperands() &&
161 "Invalid ReturnInst operands!");
162 for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
163 if (isa<UndefValue>(RI->getOperand(i)))
165 Constant *C = dyn_cast<Constant>(RI->getOperand(i));
167 return false; // Does not return a constant.
169 Value *RV = RetVals[i];
173 return false; // Does not return the same constant.
178 for (unsigned i = 0, e = RetVals.size(); i < e; ++i)
180 RetVals[i] = UndefValue::get(STy->getElementType(i));
182 assert(RetVals.size() == 1);
184 RetVals[0] = UndefValue::get(F.getReturnType());
187 // If we got here, the function returns a constant value. Loop over all
188 // users, replacing any uses of the return value with the returned constant.
189 bool ReplacedAllUsers = true;
190 bool MadeChange = false;
191 for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
192 // Make sure this is an invoke or call and that the use is for the callee.
193 if (!(isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) ||
194 UI.getOperandNo() != 0) {
195 ReplacedAllUsers = false;
199 Instruction *Call = cast<Instruction>(*UI);
200 if (Call->use_empty())
206 Call->replaceAllUsesWith(RetVals[0]);
210 while (!Call->use_empty()) {
211 GetResultInst *GR = cast<GetResultInst>(Call->use_back());
212 GR->replaceAllUsesWith(RetVals[GR->getIndex()]);
213 GR->eraseFromParent();
217 // If we replace all users with the returned constant, and there can be no
218 // other callers of the function, replace the constant being returned in the
219 // function with an undef value.
220 if (ReplacedAllUsers && F.hasInternalLinkage()) {
221 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
222 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
223 for (unsigned i = 0, e = RetVals.size(); i < e; ++i) {
224 Value *RetVal = RetVals[i];
225 if (isa<UndefValue>(RetVal))
227 Value *RV = UndefValue::get(RetVal->getType());
228 if (RI->getOperand(i) != RV) {
229 RI->setOperand(i, RV);
237 if (MadeChange) ++NumReturnValProped;