blob: f79b61037f1dba2c0168cb1dc7becd308e99f8d0 [file] [log] [blame]
Chris Lattnerf516c692003-10-23 16:52:27 +00001//===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattnerf516c692003-10-23 16:52:27 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattnerf516c692003-10-23 16:52:27 +00008//===----------------------------------------------------------------------===//
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
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000021#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/Instructions.h"
24#include "llvm/IR/Module.h"
Chris Lattnerf516c692003-10-23 16:52:27 +000025#include "llvm/Pass.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000026#include "llvm/Transforms/IPO.h"
Chris Lattnerf52e03c2003-11-21 21:54:22 +000027using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000028
Chandler Carruth964daaa2014-04-22 02:55:47 +000029#define DEBUG_TYPE "ipconstprop"
30
Chris Lattner1631bcb2006-12-19 22:09:18 +000031STATISTIC(NumArgumentsProped, "Number of args turned into constants");
32STATISTIC(NumReturnValProped, "Number of return values turned into constants");
Chris Lattnerf516c692003-10-23 16:52:27 +000033
Chris Lattner1631bcb2006-12-19 22:09:18 +000034namespace {
Chris Lattnerf516c692003-10-23 16:52:27 +000035 /// IPCP - The interprocedural constant propagation pass
36 ///
Nick Lewycky02d5f772009-10-25 06:33:48 +000037 struct IPCP : public ModulePass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000038 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000039 IPCP() : ModulePass(ID) {
40 initializeIPCPPass(*PassRegistry::getPassRegistry());
41 }
Devang Patel09f162c2007-05-01 21:15:47 +000042
Craig Topper3e4c6972014-03-05 09:10:37 +000043 bool runOnModule(Module &M) override;
Chris Lattnerf516c692003-10-23 16:52:27 +000044 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +000045}
Chris Lattnerf516c692003-10-23 16:52:27 +000046
Chris Lattneraf555ad2004-11-14 06:10:11 +000047/// PropagateConstantsIntoArguments - Look at all uses of the specified
48/// function. If all uses are direct call sites, and all pass a particular
49/// constant in for an argument, propagate that constant in as the argument.
Chris Lattnerf516c692003-10-23 16:52:27 +000050///
Davide Italiano296d12c2016-05-03 20:08:24 +000051static bool PropagateConstantsIntoArguments(Function &F) {
Chris Lattnerc2d3d312006-08-27 22:42:52 +000052 if (F.arg_empty() || F.use_empty()) return false; // No arguments? Early exit.
Chris Lattnerf516c692003-10-23 16:52:27 +000053
Chris Lattnera82d6912008-04-23 06:16:27 +000054 // For each argument, keep track of its constant value and whether it is a
55 // constant or not. The bool is driven to true when found to be non-constant.
56 SmallVector<std::pair<Constant*, bool>, 16> ArgumentConstants;
Chris Lattner531f9e92005-03-15 04:54:21 +000057 ArgumentConstants.resize(F.arg_size());
Chris Lattnerf516c692003-10-23 16:52:27 +000058
59 unsigned NumNonconstant = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +000060 for (Use &U : F.uses()) {
61 User *UR = U.getUser();
Chris Lattner1a8b80e2009-11-01 06:11:53 +000062 // Ignore blockaddress uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +000063 if (isa<BlockAddress>(UR)) continue;
Chris Lattner1a8b80e2009-11-01 06:11:53 +000064
Chris Lattnera82d6912008-04-23 06:16:27 +000065 // Used by a non-instruction, or not the callee of a function, do not
66 // transform.
Chandler Carruthcdf47882014-03-09 03:16:01 +000067 if (!isa<CallInst>(UR) && !isa<InvokeInst>(UR))
Chris Lattnera82d6912008-04-23 06:16:27 +000068 return false;
69
Chandler Carruthcdf47882014-03-09 03:16:01 +000070 CallSite CS(cast<Instruction>(UR));
71 if (!CS.isCallee(&U))
Gabor Greiff4013372009-01-22 21:35:57 +000072 return false;
Chris Lattnerf516c692003-10-23 16:52:27 +000073
Chris Lattnera82d6912008-04-23 06:16:27 +000074 // Check out all of the potentially constant arguments. Note that we don't
75 // inspect varargs here.
76 CallSite::arg_iterator AI = CS.arg_begin();
77 Function::arg_iterator Arg = F.arg_begin();
78 for (unsigned i = 0, e = ArgumentConstants.size(); i != e;
79 ++i, ++AI, ++Arg) {
80
81 // If this argument is known non-constant, ignore it.
82 if (ArgumentConstants[i].second)
83 continue;
84
85 Constant *C = dyn_cast<Constant>(*AI);
Craig Topperf40110f2014-04-25 05:29:35 +000086 if (C && ArgumentConstants[i].first == nullptr) {
Chris Lattnera82d6912008-04-23 06:16:27 +000087 ArgumentConstants[i].first = C; // First constant seen.
88 } else if (C && ArgumentConstants[i].first == C) {
89 // Still the constant value we think it is.
90 } else if (*AI == &*Arg) {
91 // Ignore recursive calls passing argument down.
92 } else {
93 // Argument became non-constant. If all arguments are non-constant now,
94 // give up on this function.
95 if (++NumNonconstant == ArgumentConstants.size())
96 return false;
97 ArgumentConstants[i].second = true;
Chris Lattnerf516c692003-10-23 16:52:27 +000098 }
99 }
Chris Lattnera82d6912008-04-23 06:16:27 +0000100 }
Chris Lattnerf516c692003-10-23 16:52:27 +0000101
102 // If we got to this point, there is a constant argument!
103 assert(NumNonconstant != ArgumentConstants.size());
Chris Lattner5e004e82003-10-27 21:09:00 +0000104 bool MadeChange = false;
Chris Lattnera82d6912008-04-23 06:16:27 +0000105 Function::arg_iterator AI = F.arg_begin();
106 for (unsigned i = 0, e = ArgumentConstants.size(); i != e; ++i, ++AI) {
107 // Do we have a constant argument?
Torok Edwin21bd8c92009-09-24 18:33:42 +0000108 if (ArgumentConstants[i].second || AI->use_empty() ||
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000109 AI->hasInAllocaAttr() || (AI->hasByValAttr() && !F.onlyReadsMemory()))
Chris Lattnera82d6912008-04-23 06:16:27 +0000110 continue;
111
112 Value *V = ArgumentConstants[i].first;
Craig Topperf40110f2014-04-25 05:29:35 +0000113 if (!V) V = UndefValue::get(AI->getType());
Chris Lattnera82d6912008-04-23 06:16:27 +0000114 AI->replaceAllUsesWith(V);
115 ++NumArgumentsProped;
116 MadeChange = true;
117 }
Chris Lattner5e004e82003-10-27 21:09:00 +0000118 return MadeChange;
Chris Lattnerf516c692003-10-23 16:52:27 +0000119}
Brian Gaeke960707c2003-11-11 22:41:34 +0000120
Chris Lattneraf555ad2004-11-14 06:10:11 +0000121
Matthijs Kooijman97034592008-06-18 08:09:27 +0000122// Check to see if this function returns one or more constants. If so, replace
123// all callers that use those return values with the constant value. This will
124// leave in the actual return values and instructions, but deadargelim will
125// clean that up.
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000126//
127// Additionally if a function always returns one of its arguments directly,
128// callers will be updated to use the value they pass in directly instead of
129// using the return value.
Davide Italiano296d12c2016-05-03 20:08:24 +0000130static bool PropagateConstantReturn(Function &F) {
Nick Lewycky39dbfd32009-11-23 03:29:18 +0000131 if (F.getReturnType()->isVoidTy())
Chris Lattneraf555ad2004-11-14 06:10:11 +0000132 return false; // No return value.
133
Sanjoy Das5ce32722016-04-08 00:48:30 +0000134 // We can infer and propagate the return value only when we know that the
135 // definition we'll get at link time is *exactly* the definition we see now.
136 // For more details, see GlobalValue::mayBeDerefined.
137 if (!F.isDefinitionExact())
Chris Lattnerdbd595f2008-06-09 07:58:07 +0000138 return false;
Davide Italianoec493132017-02-04 19:44:14 +0000139
140 // Don't touch naked functions. The may contain asm returning
141 // value we don't see, so we may end up interprocedurally propagating
142 // the return value incorrectly.
143 if (F.hasFnAttribute(Attribute::Naked))
144 return false;
145
Chris Lattneraf555ad2004-11-14 06:10:11 +0000146 // Check to see if this function returns a constant.
Devang Patel73581652008-03-11 22:24:29 +0000147 SmallVector<Value *,4> RetVals;
Chris Lattner229907c2011-07-18 04:54:35 +0000148 StructType *STy = dyn_cast<StructType>(F.getReturnType());
Devang Patel73581652008-03-11 22:24:29 +0000149 if (STy)
Matthijs Kooijman97034592008-06-18 08:09:27 +0000150 for (unsigned i = 0, e = STy->getNumElements(); i < e; ++i)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000151 RetVals.push_back(UndefValue::get(STy->getElementType(i)));
Devang Patel73581652008-03-11 22:24:29 +0000152 else
Owen Andersonb292b8c2009-07-30 23:03:37 +0000153 RetVals.push_back(UndefValue::get(F.getReturnType()));
Devang Patel73581652008-03-11 22:24:29 +0000154
Matthijs Kooijman97034592008-06-18 08:09:27 +0000155 unsigned NumNonConstant = 0;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000156 for (BasicBlock &BB : F)
157 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
Chris Lattner5f1802c2008-04-23 05:59:23 +0000158 for (unsigned i = 0, e = RetVals.size(); i != e; ++i) {
Matthijs Kooijman97034592008-06-18 08:09:27 +0000159 // Already found conflicting return values?
Chris Lattner5f1802c2008-04-23 05:59:23 +0000160 Value *RV = RetVals[i];
Matthijs Kooijman97034592008-06-18 08:09:27 +0000161 if (!RV)
162 continue;
163
164 // Find the returned value
165 Value *V;
Dan Gohmane2190392008-10-03 22:21:24 +0000166 if (!STy)
Jay Foad11522092011-04-04 07:44:02 +0000167 V = RI->getOperand(0);
Matthijs Kooijman97034592008-06-18 08:09:27 +0000168 else
Nick Lewycky39dbfd32009-11-23 03:29:18 +0000169 V = FindInsertedValue(RI->getOperand(0), i);
Matthijs Kooijman97034592008-06-18 08:09:27 +0000170
171 if (V) {
172 // Ignore undefs, we can change them into anything
173 if (isa<UndefValue>(V))
174 continue;
175
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000176 // Try to see if all the rets return the same constant or argument.
177 if (isa<Constant>(V) || isa<Argument>(V)) {
Matthijs Kooijman97034592008-06-18 08:09:27 +0000178 if (isa<UndefValue>(RV)) {
179 // No value found yet? Try the current one.
180 RetVals[i] = V;
181 continue;
182 }
183 // Returning the same value? Good.
184 if (RV == V)
185 continue;
186 }
187 }
188 // Different or no known return value? Don't propagate this return
189 // value.
Craig Topperf40110f2014-04-25 05:29:35 +0000190 RetVals[i] = nullptr;
Alp Tokerf907b892013-12-05 05:44:44 +0000191 // All values non-constant? Stop looking.
Matthijs Kooijman97034592008-06-18 08:09:27 +0000192 if (++NumNonConstant == RetVals.size())
193 return false;
Chris Lattneraf555ad2004-11-14 06:10:11 +0000194 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000195 }
Chris Lattneraf555ad2004-11-14 06:10:11 +0000196
Matthijs Kooijman97034592008-06-18 08:09:27 +0000197 // If we got here, the function returns at least one constant value. Loop
198 // over all users, replacing any uses of the return value with the returned
199 // constant.
Chris Lattneraf555ad2004-11-14 06:10:11 +0000200 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000201 for (Use &U : F.uses()) {
202 CallSite CS(U.getUser());
Matthijs Kooijman0c717322008-06-19 08:53:24 +0000203 Instruction* Call = CS.getInstruction();
204
205 // Not a call instruction or a call instruction that's not calling F
206 // directly?
Chandler Carruthcdf47882014-03-09 03:16:01 +0000207 if (!Call || !CS.isCallee(&U))
Chris Lattner5f1802c2008-04-23 05:59:23 +0000208 continue;
Chris Lattner5f1802c2008-04-23 05:59:23 +0000209
Matthijs Kooijman0c717322008-06-19 08:53:24 +0000210 // Call result not used?
Chris Lattner5f1802c2008-04-23 05:59:23 +0000211 if (Call->use_empty())
212 continue;
Chris Lattneraf555ad2004-11-14 06:10:11 +0000213
Chris Lattner5f1802c2008-04-23 05:59:23 +0000214 MadeChange = true;
215
Craig Topperf40110f2014-04-25 05:29:35 +0000216 if (!STy) {
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000217 Value* New = RetVals[0];
218 if (Argument *A = dyn_cast<Argument>(New))
219 // Was an argument returned? Then find the corresponding argument in
Matthijs Kooijman0c717322008-06-19 08:53:24 +0000220 // the call instruction and use that.
221 New = CS.getArgument(A->getArgNo());
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000222 Call->replaceAllUsesWith(New);
Chris Lattner5f1802c2008-04-23 05:59:23 +0000223 continue;
224 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000225
226 for (auto I = Call->user_begin(), E = Call->user_end(); I != E;) {
Jay Foade57ba2e2009-06-06 17:49:35 +0000227 Instruction *Ins = cast<Instruction>(*I);
Matthijs Kooijman97034592008-06-18 08:09:27 +0000228
229 // Increment now, so we can remove the use
230 ++I;
231
Matthijs Kooijman97034592008-06-18 08:09:27 +0000232 // Find the index of the retval to replace with
233 int index = -1;
Dan Gohmanfa1211f2008-07-23 00:34:11 +0000234 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Ins))
Matthijs Kooijman97034592008-06-18 08:09:27 +0000235 if (EV->hasIndices())
236 index = *EV->idx_begin();
237
238 // If this use uses a specific return value, and we have a replacement,
239 // replace it.
240 if (index != -1) {
241 Value *New = RetVals[index];
242 if (New) {
Matthijs Kooijmanfd173572008-06-18 08:30:37 +0000243 if (Argument *A = dyn_cast<Argument>(New))
244 // Was an argument returned? Then find the corresponding argument in
Matthijs Kooijman0c717322008-06-19 08:53:24 +0000245 // the call instruction and use that.
246 New = CS.getArgument(A->getArgNo());
Matthijs Kooijman97034592008-06-18 08:09:27 +0000247 Ins->replaceAllUsesWith(New);
248 Ins->eraseFromParent();
Chris Lattner263b0a12004-12-11 17:00:14 +0000249 }
Devang Patel5ca2ea62008-03-20 18:30:32 +0000250 }
Devang Patel73581652008-03-11 22:24:29 +0000251 }
Chris Lattneraf555ad2004-11-14 06:10:11 +0000252 }
253
254 if (MadeChange) ++NumReturnValProped;
Chris Lattneraf555ad2004-11-14 06:10:11 +0000255 return MadeChange;
256}
Davide Italiano296d12c2016-05-03 20:08:24 +0000257
258char IPCP::ID = 0;
259INITIALIZE_PASS(IPCP, "ipconstprop",
260 "Interprocedural constant propagation", false, false)
261
262ModulePass *llvm::createIPConstantPropagationPass() { return new IPCP(); }
263
264bool IPCP::runOnModule(Module &M) {
265 if (skipModule(M))
266 return false;
267
268 bool Changed = false;
269 bool LocalChange = true;
270
271 // FIXME: instead of using smart algorithms, we just iterate until we stop
272 // making changes.
273 while (LocalChange) {
274 LocalChange = false;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000275 for (Function &F : M)
276 if (!F.isDeclaration()) {
Davide Italiano296d12c2016-05-03 20:08:24 +0000277 // Delete any klingons.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000278 F.removeDeadConstantUsers();
279 if (F.hasLocalLinkage())
280 LocalChange |= PropagateConstantsIntoArguments(F);
281 Changed |= PropagateConstantReturn(F);
Davide Italiano296d12c2016-05-03 20:08:24 +0000282 }
283 Changed |= LocalChange;
284 }
285 return Changed;
286}