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);
46 RegisterPass<IPCP> X("ipconstprop", "Interprocedural constant propagation");
49 ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
51 bool IPCP::runOnModule(Module &M) {
53 bool LocalChange = true;
55 // FIXME: instead of using smart algorithms, we just iterate until we stop
59 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
60 if (!I->isDeclaration()) {
61 // Delete any klingons.
62 I->removeDeadConstantUsers();
63 if (I->hasInternalLinkage())
64 LocalChange |= PropagateConstantsIntoArguments(*I);
65 Changed |= PropagateConstantReturn(*I);
67 Changed |= LocalChange;
72 /// PropagateConstantsIntoArguments - Look at all uses of the specified
73 /// function. If all uses are direct call sites, and all pass a particular
74 /// constant in for an argument, propagate that constant in as the argument.
76 bool IPCP::PropagateConstantsIntoArguments(Function &F) {
77 if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
79 std::vector<std::pair<Constant*, bool> > ArgumentConstants;
80 ArgumentConstants.resize(F.arg_size());
82 unsigned NumNonconstant = 0;
84 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I)
85 if (!isa<Instruction>(*I))
86 return false; // Used by a non-instruction, do not transform
88 CallSite CS = CallSite::get(cast<Instruction>(*I));
89 if (CS.getInstruction() == 0 ||
90 CS.getCalledFunction() != &F)
91 return false; // Not a direct call site?
93 // Check out all of the potentially constant arguments
94 CallSite::arg_iterator AI = CS.arg_begin();
95 Function::arg_iterator Arg = F.arg_begin();
96 for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
98 if (*AI == &F) return false; // Passes the function into itself
100 if (!ArgumentConstants[i].second) {
101 if (Constant *C = dyn_cast<Constant>(*AI)) {
102 if (!ArgumentConstants[i].first)
103 ArgumentConstants[i].first = C;
104 else if (ArgumentConstants[i].first != C) {
105 // Became non-constant
106 ArgumentConstants[i].second = true;
108 if (NumNonconstant == ArgumentConstants.size()) return false;
110 } else if (*AI != &*Arg) { // Ignore recursive calls with same arg
111 // This is not a constant argument. Mark the argument as
113 ArgumentConstants[i].second = true;
115 if (NumNonconstant == ArgumentConstants.size()) return false;
121 // If we got to this point, there is a constant argument!
122 assert(NumNonconstant != ArgumentConstants.size());
123 Function::arg_iterator AI = F.arg_begin();
124 bool MadeChange = false;
125 for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI)
126 // Do we have a constant argument!?
127 if (!ArgumentConstants[i].second && !AI->use_empty()) {
128 Value *V = ArgumentConstants[i].first;
129 if (V == 0) V = UndefValue::get(AI->getType());
130 AI->replaceAllUsesWith(V);
131 ++NumArgumentsProped;
138 // Check to see if this function returns a constant. If so, replace all callers
139 // that user the return value with the returned valued. If we can replace ALL
141 bool IPCP::PropagateConstantReturn(Function &F) {
142 if (F.getReturnType() == Type::VoidTy)
143 return false; // No return value.
145 // Check to see if this function returns a constant.
146 SmallVector<Value *,4> RetVals;
148 const StructType *STy = dyn_cast<StructType>(F.getReturnType());
150 N = STy->getNumElements();
153 for (unsigned i = 0; i < N; ++i)
154 RetVals.push_back(0);
156 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
157 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
158 assert (N == RI->getNumOperands() && "Invalid ReturnInst operands!");
159 for (unsigned i = 0; i < N; ++i) {
160 if (isa<UndefValue>(RI->getOperand(i))) {
162 } else if (Constant *C = dyn_cast<Constant>(RI->getOperand(i))) {
163 Value *RV = RetVals[i];
167 return false; // Does not return the same constant.
169 return false; // Does not return a constant.
176 RetVals[0] = UndefValue::get(F.getReturnType());
178 for (unsigned i = 0; i < N; ++i) {
179 Value *RetVal = RetVals[i];
181 RetVals[i] = UndefValue::get(STy->getElementType(i));
185 // If we got here, the function returns a constant value. Loop over all
186 // users, replacing any uses of the return value with the returned constant.
187 bool ReplacedAllUsers = true;
188 bool MadeChange = false;
189 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I)
190 if (!isa<Instruction>(*I))
191 ReplacedAllUsers = false;
193 CallSite CS = CallSite::get(cast<Instruction>(*I));
194 if (CS.getInstruction() == 0 ||
195 CS.getCalledFunction() != &F) {
196 ReplacedAllUsers = false;
198 Instruction *Call = CS.getInstruction();
199 if (!Call->use_empty()) {
201 Call->replaceAllUsesWith(RetVals[0]);
203 for(Value::use_iterator CUI = Call->use_begin(), CUE = Call->use_end();
205 GetResultInst *GR = cast<GetResultInst>(CUI);
206 GR->replaceAllUsesWith(RetVals[GR->getIndex()]);
207 GR->eraseFromParent();
215 // If we replace all users with the returned constant, and there can be no
216 // other callers of the function, replace the constant being returned in the
217 // function with an undef value.
218 if (ReplacedAllUsers && F.hasInternalLinkage()) {
219 for (unsigned i = 0; i < N; ++i) {
220 Value *RetVal = RetVals[i];
221 if (isa<UndefValue>(RetVal))
223 Value *RV = UndefValue::get(RetVal->getType());
224 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
225 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
226 if (RI->getOperand(i) != RV) {
227 RI->setOperand(i, RV);
234 if (MadeChange) ++NumReturnValProped;