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/Analysis/ValueTracking.h"
25 #include "llvm/Support/CallSite.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 IPCP : public ModulePass {
37 static char ID; // Pass identification, replacement for typeid
38 IPCP() : ModulePass(&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->hasLocalLinkage())
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 // Ignore blockaddress uses.
89 if (isa<BlockAddress>(*UI)) continue;
91 // Used by a non-instruction, or not the callee of a function, do not
93 if (!isa<CallInst>(*UI) && !isa<InvokeInst>(*UI))
96 CallSite CS = CallSite::get(cast<Instruction>(*UI));
100 // Check out all of the potentially constant arguments. Note that we don't
101 // inspect varargs here.
102 CallSite::arg_iterator AI = CS.arg_begin();
103 Function::arg_iterator Arg = F.arg_begin();
104 for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
107 // If this argument is known non-constant, ignore it.
108 if (ArgumentConstants[i].second)
111 Constant *C = dyn_cast<Constant>(*AI);
112 if (C && ArgumentConstants[i].first == 0) {
113 ArgumentConstants[i].first = C; // First constant seen.
114 } else if (C && ArgumentConstants[i].first == C) {
115 // Still the constant value we think it is.
116 } else if (*AI == &*Arg) {
117 // Ignore recursive calls passing argument down.
119 // Argument became non-constant. If all arguments are non-constant now,
120 // give up on this function.
121 if (++NumNonconstant == ArgumentConstants.size())
123 ArgumentConstants[i].second = true;
128 // If we got to this point, there is a constant argument!
129 assert(NumNonconstant != ArgumentConstants.size());
130 bool MadeChange = false;
131 Function::arg_iterator AI = F.arg_begin();
132 for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
133 // Do we have a constant argument?
134 if (ArgumentConstants[i].second || AI->use_empty() ||
135 (AI->hasByValAttr() && !F.onlyReadsMemory()))
138 Value *V = ArgumentConstants[i].first;
139 if (V == 0) V = UndefValue::get(AI->getType());
140 AI->replaceAllUsesWith(V);
141 ++NumArgumentsProped;
148 // Check to see if this function returns one or more constants. If so, replace
149 // all callers that use those return values with the constant value. This will
150 // leave in the actual return values and instructions, but deadargelim will
153 // Additionally if a function always returns one of its arguments directly,
154 // callers will be updated to use the value they pass in directly instead of
155 // using the return value.
156 bool IPCP::PropagateConstantReturn(Function &F) {
157 if (F.getReturnType()->isVoidTy())
158 return false; // No return value.
160 // If this function could be overridden later in the link stage, we can't
161 // propagate information about its results into callers.
162 if (F.mayBeOverridden())
165 // Check to see if this function returns a constant.
166 SmallVector<Value *,4> RetVals;
167 const StructType *STy = dyn_cast<StructType>(F.getReturnType());
169 for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
170 RetVals.push_back(UndefValue::get(STy->getElementType(i)));
172 RetVals.push_back(UndefValue::get(F.getReturnType()));
174 unsigned NumNonConstant = 0;
175 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
176 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
177 for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
178 // Already found conflicting return values?
179 Value *RV = RetVals[i];
183 // Find the returned value
186 V = RI->getOperand(i);
188 V = FindInsertedValue(RI->getOperand(0), i);
191 // Ignore undefs, we can change them into anything
192 if (isa<UndefValue>(V))
195 // Try to see if all the rets return the same constant or argument.
196 if (isa<Constant>(V) || isa<Argument>(V)) {
197 if (isa<UndefValue>(RV)) {
198 // No value found yet? Try the current one.
202 // Returning the same value? Good.
207 // Different or no known return value? Don't propagate this return
210 // All values non constant? Stop looking.
211 if (++NumNonConstant == RetVals.size())
216 // If we got here, the function returns at least one constant value. Loop
217 // over all users, replacing any uses of the return value with the returned
219 bool MadeChange = false;
220 for (Value::use_iterator UI = F.use_begin(), E = F.use_end(); UI != E; ++UI) {
221 CallSite CS = CallSite::get(*UI);
222 Instruction* Call = CS.getInstruction();
224 // Not a call instruction or a call instruction that's not calling F
226 if (!Call || !CS.isCallee(UI))
229 // Call result not used?
230 if (Call->use_empty())
236 Value* New = RetVals[0];
237 if (Argument *A = dyn_cast<Argument>(New))
238 // Was an argument returned? Then find the corresponding argument in
239 // the call instruction and use that.
240 New = CS.getArgument(A->getArgNo());
241 Call->replaceAllUsesWith(New);
245 for (Value::use_iterator I = Call->use_begin(), E = Call->use_end();
247 Instruction *Ins = cast<Instruction>(*I);
249 // Increment now, so we can remove the use
252 // Find the index of the retval to replace with
254 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
255 if (EV->hasIndices())
256 index = *EV->idx_begin();
258 // If this use uses a specific return value, and we have a replacement,
261 Value *New = RetVals[index];
263 if (Argument *A = dyn_cast<Argument>(New))
264 // Was an argument returned? Then find the corresponding argument in
265 // the call instruction and use that.
266 New = CS.getArgument(A->getArgNo());
267 Ins->replaceAllUsesWith(New);
268 Ins->eraseFromParent();
274 if (MadeChange) ++NumReturnValProped;