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/Support/Compiler.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
31 STATISTIC(NumArgumentsProped
, "Number of args turned into constants");
32 STATISTIC(NumReturnValProped
, "Number of return values turned into constants");
35 /// IPCP - The interprocedural constant propagation pass
37 struct VISIBILITY_HIDDEN IPCP
: public ModulePass
{
38 static char ID
; // Pass identification, replacement for typeid
39 IPCP() : ModulePass(&ID
) {}
41 bool runOnModule(Module
&M
);
43 bool PropagateConstantsIntoArguments(Function
&F
);
44 bool PropagateConstantReturn(Function
&F
);
49 static RegisterPass
<IPCP
>
50 X("ipconstprop", "Interprocedural constant propagation");
52 ModulePass
*llvm::createIPConstantPropagationPass() { return new IPCP(); }
54 bool IPCP::runOnModule(Module
&M
) {
56 bool LocalChange
= true;
58 // FIXME: instead of using smart algorithms, we just iterate until we stop
62 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
)
63 if (!I
->isDeclaration()) {
64 // Delete any klingons.
65 I
->removeDeadConstantUsers();
66 if (I
->hasLocalLinkage())
67 LocalChange
|= PropagateConstantsIntoArguments(*I
);
68 Changed
|= PropagateConstantReturn(*I
);
70 Changed
|= LocalChange
;
75 /// PropagateConstantsIntoArguments - Look at all uses of the specified
76 /// function. If all uses are direct call sites, and all pass a particular
77 /// constant in for an argument, propagate that constant in as the argument.
79 bool IPCP::PropagateConstantsIntoArguments(Function
&F
) {
80 if (F
.arg_empty() || F
.use_empty()) return false; // No arguments? Early exit.
82 // For each argument, keep track of its constant value and whether it is a
83 // constant or not. The bool is driven to true when found to be non-constant.
84 SmallVector
<std::pair
<Constant
*, bool>, 16> ArgumentConstants
;
85 ArgumentConstants
.resize(F
.arg_size());
87 unsigned NumNonconstant
= 0;
88 for (Value::use_iterator UI
= F
.use_begin(), E
= F
.use_end(); UI
!= E
; ++UI
) {
89 // Used by a non-instruction, or not the callee of a function, do not
91 if (!isa
<CallInst
>(*UI
) && !isa
<InvokeInst
>(*UI
))
94 CallSite CS
= CallSite::get(cast
<Instruction
>(*UI
));
98 // Check out all of the potentially constant arguments. Note that we don't
99 // inspect varargs here.
100 CallSite::arg_iterator AI
= CS
.arg_begin();
101 Function::arg_iterator Arg
= F
.arg_begin();
102 for (unsigned i
= 0, e
= ArgumentConstants
.size(); i
!= e
;
105 // If this argument is known non-constant, ignore it.
106 if (ArgumentConstants
[i
].second
)
109 Constant
*C
= dyn_cast
<Constant
>(*AI
);
110 if (C
&& ArgumentConstants
[i
].first
== 0) {
111 ArgumentConstants
[i
].first
= C
; // First constant seen.
112 } else if (C
&& ArgumentConstants
[i
].first
== C
) {
113 // Still the constant value we think it is.
114 } else if (*AI
== &*Arg
) {
115 // Ignore recursive calls passing argument down.
117 // Argument became non-constant. If all arguments are non-constant now,
118 // give up on this function.
119 if (++NumNonconstant
== ArgumentConstants
.size())
121 ArgumentConstants
[i
].second
= true;
126 // If we got to this point, there is a constant argument!
127 assert(NumNonconstant
!= ArgumentConstants
.size());
128 bool MadeChange
= false;
129 Function::arg_iterator AI
= F
.arg_begin();
130 for (unsigned i
= 0, e
= ArgumentConstants
.size(); i
!= e
; ++i
, ++AI
) {
131 // Do we have a constant argument?
132 if (ArgumentConstants
[i
].second
|| AI
->use_empty())
135 Value
*V
= ArgumentConstants
[i
].first
;
136 if (V
== 0) V
= UndefValue::get(AI
->getType());
137 AI
->replaceAllUsesWith(V
);
138 ++NumArgumentsProped
;
145 // Check to see if this function returns one or more constants. If so, replace
146 // all callers that use those return values with the constant value. This will
147 // leave in the actual return values and instructions, but deadargelim will
150 // Additionally if a function always returns one of its arguments directly,
151 // callers will be updated to use the value they pass in directly instead of
152 // using the return value.
153 bool IPCP::PropagateConstantReturn(Function
&F
) {
154 if (F
.getReturnType() == Type::VoidTy
)
155 return false; // No return value.
157 // If this function could be overridden later in the link stage, we can't
158 // propagate information about its results into callers.
159 if (F
.mayBeOverridden())
162 // Check to see if this function returns a constant.
163 SmallVector
<Value
*,4> RetVals
;
164 const StructType
*STy
= dyn_cast
<StructType
>(F
.getReturnType());
166 for (unsigned i
= 0, e
= STy
->getNumElements(); i
< e
; ++i
)
167 RetVals
.push_back(UndefValue::get(STy
->getElementType(i
)));
169 RetVals
.push_back(UndefValue::get(F
.getReturnType()));
171 unsigned NumNonConstant
= 0;
172 for (Function::iterator BB
= F
.begin(), E
= F
.end(); BB
!= E
; ++BB
)
173 if (ReturnInst
*RI
= dyn_cast
<ReturnInst
>(BB
->getTerminator())) {
174 for (unsigned i
= 0, e
= RetVals
.size(); i
!= e
; ++i
) {
175 // Already found conflicting return values?
176 Value
*RV
= RetVals
[i
];
180 // Find the returned value
183 V
= RI
->getOperand(i
);
185 V
= FindInsertedValue(RI
->getOperand(0), i
);
188 // Ignore undefs, we can change them into anything
189 if (isa
<UndefValue
>(V
))
192 // Try to see if all the rets return the same constant or argument.
193 if (isa
<Constant
>(V
) || isa
<Argument
>(V
)) {
194 if (isa
<UndefValue
>(RV
)) {
195 // No value found yet? Try the current one.
199 // Returning the same value? Good.
204 // Different or no known return value? Don't propagate this return
207 // All values non constant? Stop looking.
208 if (++NumNonConstant
== RetVals
.size())
213 // If we got here, the function returns at least one constant value. Loop
214 // over all users, replacing any uses of the return value with the returned
216 bool MadeChange
= false;
217 for (Value::use_iterator UI
= F
.use_begin(), E
= F
.use_end(); UI
!= E
; ++UI
) {
218 CallSite CS
= CallSite::get(*UI
);
219 Instruction
* Call
= CS
.getInstruction();
221 // Not a call instruction or a call instruction that's not calling F
223 if (!Call
|| !CS
.isCallee(UI
))
226 // Call result not used?
227 if (Call
->use_empty())
233 Value
* New
= RetVals
[0];
234 if (Argument
*A
= dyn_cast
<Argument
>(New
))
235 // Was an argument returned? Then find the corresponding argument in
236 // the call instruction and use that.
237 New
= CS
.getArgument(A
->getArgNo());
238 Call
->replaceAllUsesWith(New
);
242 for (Value::use_iterator I
= Call
->use_begin(), E
= Call
->use_end();
244 Instruction
*Ins
= dyn_cast
<Instruction
>(*I
);
246 // Increment now, so we can remove the use
249 // Not an instruction? Ignore
253 // Find the index of the retval to replace with
255 if (ExtractValueInst
*EV
= dyn_cast
<ExtractValueInst
>(Ins
))
256 if (EV
->hasIndices())
257 index
= *EV
->idx_begin();
259 // If this use uses a specific return value, and we have a replacement,
262 Value
*New
= RetVals
[index
];
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();
275 if (MadeChange
) ++NumReturnValProped
;