blob: a67332d067a855befddb6481fd9b9bc68540954d [file] [log] [blame]
Chris Lattner254f8f82004-05-23 21:21:17 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner483ae012004-03-07 21:29:54 +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 Lattner483ae012004-03-07 21:29:54 +00008//===----------------------------------------------------------------------===//
9//
10// This pass promotes "by reference" arguments to be "by value" arguments. In
11// practice, this means looking for internal functions that have pointer
Gordon Henriksen78c63ac2007-10-26 03:03:51 +000012// arguments. If it can prove, through the use of alias analysis, that an
13// argument is *only* loaded, then it can pass the value into the function
Chris Lattner483ae012004-03-07 21:29:54 +000014// instead of the address of the value. This can cause recursive simplification
Chris Lattner254f8f82004-05-23 21:21:17 +000015// of code and lead to the elimination of allocas (especially in C++ template
16// code like the STL).
Chris Lattner483ae012004-03-07 21:29:54 +000017//
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000018// This pass also handles aggregate arguments that are passed into a function,
19// scalarizing them if the elements of the aggregate are only loaded. Note that
Matthijs Kooijmanfd307042008-07-29 10:00:13 +000020// by default it refuses to scalarize aggregates which would require passing in
21// more than three operands to the function, because passing thousands of
Duncan Sands1ea0d2e2008-09-07 09:54:09 +000022// operands for a large array or structure is unprofitable! This limit can be
Matthijs Kooijmanfd307042008-07-29 10:00:13 +000023// configured or disabled, however.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000024//
Chris Lattner483ae012004-03-07 21:29:54 +000025// Note that this transformation could also be done for arguments that are only
Gordon Henriksen78c63ac2007-10-26 03:03:51 +000026// stored to (returning the value instead), but does not currently. This case
27// would be best handled when and if LLVM begins supporting multiple return
28// values from functions.
Chris Lattner483ae012004-03-07 21:29:54 +000029//
30//===----------------------------------------------------------------------===//
31
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/ADT/DepthFirstIterator.h"
33#include "llvm/ADT/Statistic.h"
Chris Lattner06fa1762009-08-24 03:52:50 +000034#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000036#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000037#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Analysis/CallGraph.h"
Chandler Carruth839a98e2013-01-07 15:26:48 +000039#include "llvm/Analysis/CallGraphSCCPass.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000040#include "llvm/Analysis/Loads.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000041#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000042#include "llvm/IR/CFG.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000043#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Constants.h"
Hal Finkel2e42c342014-07-10 05:27:53 +000045#include "llvm/IR/DataLayout.h"
David Blaikiee844cd52014-07-01 21:13:37 +000046#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/DerivedTypes.h"
48#include "llvm/IR/Instructions.h"
49#include "llvm/IR/LLVMContext.h"
50#include "llvm/IR/Module.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/raw_ostream.h"
Chandler Carruthae9ce3d2017-01-29 08:03:19 +000053#include "llvm/Transforms/IPO.h"
Chris Lattner483ae012004-03-07 21:29:54 +000054#include <set>
55using namespace llvm;
56
Chandler Carruth964daaa2014-04-22 02:55:47 +000057#define DEBUG_TYPE "argpromotion"
58
Chandler Carruthae9ce3d2017-01-29 08:03:19 +000059STATISTIC(NumArgumentsPromoted, "Number of pointer arguments promoted");
Chris Lattner1631bcb2006-12-19 22:09:18 +000060STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
Chandler Carruthae9ce3d2017-01-29 08:03:19 +000061STATISTIC(NumByValArgsPromoted, "Number of byval arguments promoted");
62STATISTIC(NumArgumentsDead, "Number of dead pointer args eliminated");
Chris Lattner483ae012004-03-07 21:29:54 +000063
Sean Silvae2133e72016-07-02 18:59:51 +000064/// A vector used to hold the indices of a single GEP instruction
65typedef std::vector<uint64_t> IndicesVector;
66
Chris Lattner254f8f82004-05-23 21:21:17 +000067/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner37b6c4f2004-09-18 00:34:13 +000068/// arguments, and returns the new function. At this point, we know that it's
69/// safe to do so.
Sean Silvae2133e72016-07-02 18:59:51 +000070static CallGraphNode *
Chandler Carruth8e9c0a82017-01-29 08:03:21 +000071doPromotion(Function *F, SmallPtrSetImpl<Argument *> &ArgsToPromote,
Sean Silvae2133e72016-07-02 18:59:51 +000072 SmallPtrSetImpl<Argument *> &ByValArgsToTransform, CallGraph &CG) {
Misha Brukmanb1c93172005-04-21 23:48:37 +000073
Chris Lattner483ae012004-03-07 21:29:54 +000074 // Start by computing a new prototype for the function, which is the same as
75 // the old function, but has modified arguments.
Chris Lattner229907c2011-07-18 04:54:35 +000076 FunctionType *FTy = F->getFunctionType();
Chandler Carruthae9ce3d2017-01-29 08:03:19 +000077 std::vector<Type *> Params;
Chris Lattner483ae012004-03-07 21:29:54 +000078
David Blaikie72edd882015-03-14 21:40:12 +000079 typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable;
Chris Lattner1c676f72004-06-21 00:07:58 +000080
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000081 // ScalarizedElements - If we are promoting a pointer that has elements
82 // accessed out of it, keep track of which elements are accessed so that we
83 // can add one argument for each.
84 //
85 // Arguments that are directly loaded will have a zero element value here, to
86 // handle cases where there are both a direct load and GEP accesses.
87 //
Chandler Carruthae9ce3d2017-01-29 08:03:19 +000088 std::map<Argument *, ScalarizeTable> ScalarizedElements;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000089
Chris Lattner254f8f82004-05-23 21:21:17 +000090 // OriginalLoads - Keep track of a representative load instruction from the
91 // original function so that we can tell the alias analysis implementation
92 // what the new GEP/Load instructions we are inserting look like.
Manman Renbc376582013-11-15 20:41:15 +000093 // We need to keep the original loads for each argument and the elements
94 // of the argument that are accessed.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +000095 std::map<std::pair<Argument *, IndicesVector>, LoadInst *> OriginalLoads;
Chris Lattner254f8f82004-05-23 21:21:17 +000096
Bill Wendling3d7b0b82012-12-19 07:18:57 +000097 // Attribute - Keep track of the parameter attributes for the arguments
Duncan Sandsad0ea2d2007-11-27 13:23:08 +000098 // that we are *not* promoting. For the ones that we do promote, the parameter
99 // attributes are lost
Bill Wendling37a52df2013-01-27 01:57:28 +0000100 SmallVector<AttributeSet, 8> AttributesVec;
Bill Wendlinge94d8432012-12-07 23:16:57 +0000101 const AttributeSet &PAL = F->getAttributes();
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000102
Duncan Sands9aa789f2008-02-01 20:37:16 +0000103 // Add any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +0000104 if (PAL.hasAttributes(AttributeSet::ReturnIndex))
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000105 AttributesVec.push_back(
106 AttributeSet::get(F->getContext(), PAL.getRetAttributes()));
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000107
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000108 // First, determine the new argument list
Chris Lattner5630c4f2008-01-17 01:17:03 +0000109 unsigned ArgIndex = 1;
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000110 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
Chris Lattner5630c4f2008-01-17 01:17:03 +0000111 ++I, ++ArgIndex) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000112 if (ByValArgsToTransform.count(&*I)) {
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000113 // Simple byval argument? Just add all the struct element types.
Chris Lattner229907c2011-07-18 04:54:35 +0000114 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
115 StructType *STy = cast<StructType>(AgTy);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +0000116 Params.insert(Params.end(), STy->element_begin(), STy->element_end());
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000117 ++NumByValArgsPromoted;
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000118 } else if (!ArgsToPromote.count(&*I)) {
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000119 // Unchanged argument
Chris Lattner483ae012004-03-07 21:29:54 +0000120 Params.push_back(I->getType());
Bill Wendling49bc76c2013-01-23 06:14:59 +0000121 AttributeSet attrs = PAL.getParamAttributes(ArgIndex);
122 if (attrs.hasAttributes(ArgIndex)) {
Bill Wendling37a52df2013-01-27 01:57:28 +0000123 AttrBuilder B(attrs, ArgIndex);
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000124 AttributesVec.push_back(
125 AttributeSet::get(F->getContext(), Params.size(), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +0000126 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000127 } else if (I->use_empty()) {
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000128 // Dead argument (which are always marked as promotable)
Chris Lattner254f8f82004-05-23 21:21:17 +0000129 ++NumArgumentsDead;
130 } else {
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000131 // Okay, this is being promoted. This means that the only uses are loads
132 // or GEPs which are only used by loads
133
134 // In this table, we will track which indices are loaded from the argument
135 // (where direct loads are tracked as no indices).
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000136 ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
Chandler Carruthcdf47882014-03-09 03:16:01 +0000137 for (User *U : I->users()) {
138 Instruction *UI = cast<Instruction>(U);
David Blaikie76826632015-03-14 21:11:26 +0000139 Type *SrcTy;
140 if (LoadInst *L = dyn_cast<LoadInst>(UI))
141 SrcTy = L->getType();
142 else
143 SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType();
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000144 IndicesVector Indices;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000145 Indices.reserve(UI->getNumOperands() - 1);
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000146 // Since loads will only have a single operand, and GEPs only a single
147 // non-index operand, this will record direct loads without any indices,
148 // and gep+loads with the GEP indices.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000149 for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end();
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000150 II != IE; ++II)
151 Indices.push_back(cast<ConstantInt>(*II)->getSExtValue());
152 // GEPs with a single 0 index can be merged with direct loads
153 if (Indices.size() == 1 && Indices.front() == 0)
154 Indices.clear();
David Blaikie76826632015-03-14 21:11:26 +0000155 ArgIndices.insert(std::make_pair(SrcTy, Indices));
Owen Andersonedadd3f2006-09-15 05:22:51 +0000156 LoadInst *OrigLoad;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000157 if (LoadInst *L = dyn_cast<LoadInst>(UI))
Owen Andersonedadd3f2006-09-15 05:22:51 +0000158 OrigLoad = L;
159 else
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000160 // Take any load, we will use it only to update Alias Analysis
Chandler Carruthcdf47882014-03-09 03:16:01 +0000161 OrigLoad = cast<LoadInst>(UI->user_back());
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000162 OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000163 }
164
165 // Add a parameter to the function for each element passed in.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000166 for (const auto &ArgIndex : ArgIndices) {
Torok Edwin026259f2008-11-16 17:21:25 +0000167 // not allowed to dereference ->begin() if size() is 0
David Blaikied288fb82015-03-30 21:41:43 +0000168 Params.push_back(GetElementPtrInst::getIndexedType(
169 cast<PointerType>(I->getType()->getScalarType())->getElementType(),
Benjamin Kramer135f7352016-06-26 12:28:59 +0000170 ArgIndex.second));
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000171 assert(Params.back());
172 }
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000173
David Blaikie76826632015-03-14 21:11:26 +0000174 if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty())
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000175 ++NumArgumentsPromoted;
176 else
177 ++NumAggregatesPromoted;
Chris Lattner483ae012004-03-07 21:29:54 +0000178 }
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000179 }
Chris Lattner483ae012004-03-07 21:29:54 +0000180
Devang Patela05633e2008-09-26 22:53:05 +0000181 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +0000182 if (PAL.hasAttributes(AttributeSet::FunctionIndex))
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000183 AttributesVec.push_back(
184 AttributeSet::get(FTy->getContext(), PAL.getFnAttributes()));
Devang Patela05633e2008-09-26 22:53:05 +0000185
Chris Lattner229907c2011-07-18 04:54:35 +0000186 Type *RetTy = FTy->getReturnType();
Chris Lattner483ae012004-03-07 21:29:54 +0000187
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000188 // Construct the new function type using the new arguments.
Owen Anderson4056ca92009-07-29 22:17:13 +0000189 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000190
Chris Lattnere0987212009-09-15 05:40:35 +0000191 // Create the new function body and insert it into the module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000192 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000193 NF->copyAttributesFrom(F);
Chris Lattner5630c4f2008-01-17 01:17:03 +0000194
David Blaikiee844cd52014-07-01 21:13:37 +0000195 // Patch the pointer to LLVM function in debug info descriptor.
Peter Collingbourned4bff302015-11-05 22:03:56 +0000196 NF->setSubprogram(F->getSubprogram());
197 F->setSubprogram(nullptr);
David Blaikie8e9cfa52014-07-23 22:09:29 +0000198
David Greenecf0addf2010-01-05 01:28:37 +0000199 DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n"
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000200 << "From: " << *F);
201
Chris Lattner5630c4f2008-01-17 01:17:03 +0000202 // Recompute the parameter attributes list based on the new arguments for
203 // the function.
Bill Wendlinge94d8432012-12-07 23:16:57 +0000204 NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec));
Devang Patel4c758ea2008-09-25 21:00:45 +0000205 AttributesVec.clear();
Duncan Sandsdd7daee2008-05-26 19:58:59 +0000206
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000207 F->getParent()->getFunctionList().insert(F->getIterator(), NF);
Zhou Shenga30cdb92008-03-20 08:05:05 +0000208 NF->takeName(F);
Chris Lattner254f8f82004-05-23 21:21:17 +0000209
Chris Lattner305b1152009-08-31 00:19:58 +0000210 // Get a new callgraph node for NF.
211 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
Duncan Sands3cf7d862008-09-08 11:07:35 +0000212
Chris Lattner483ae012004-03-07 21:29:54 +0000213 // Loop over all of the callers of the function, transforming the call sites
214 // to pass in the loaded pointers.
215 //
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000216 SmallVector<Value *, 16> Args;
Chris Lattner483ae012004-03-07 21:29:54 +0000217 while (!F->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000218 CallSite CS(F->user_back());
Gabor Greif161cb042010-03-23 14:40:20 +0000219 assert(CS.getCalledFunction() == F);
Chris Lattner483ae012004-03-07 21:29:54 +0000220 Instruction *Call = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +0000221 const AttributeSet &CallPAL = CS.getAttributes();
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000222
Duncan Sands9aa789f2008-02-01 20:37:16 +0000223 // Add any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +0000224 if (CallPAL.hasAttributes(AttributeSet::ReturnIndex))
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000225 AttributesVec.push_back(
226 AttributeSet::get(F->getContext(), CallPAL.getRetAttributes()));
Duncan Sands9aa789f2008-02-01 20:37:16 +0000227
Chris Lattner254f8f82004-05-23 21:21:17 +0000228 // Loop over the operands, inserting GEP and loads in the caller as
229 // appropriate.
Chris Lattner483ae012004-03-07 21:29:54 +0000230 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner5630c4f2008-01-17 01:17:03 +0000231 ArgIndex = 1;
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000232 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
233 ++I, ++AI, ++ArgIndex)
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000234 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000235 Args.push_back(*AI); // Unmodified argument
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000236
Bill Wendling49bc76c2013-01-23 06:14:59 +0000237 if (CallPAL.hasAttributes(ArgIndex)) {
Bill Wendling37a52df2013-01-27 01:57:28 +0000238 AttrBuilder B(CallPAL, ArgIndex);
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000239 AttributesVec.push_back(
240 AttributeSet::get(F->getContext(), Args.size(), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +0000241 }
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000242 } else if (ByValArgsToTransform.count(&*I)) {
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000243 // Emit a GEP and load for each element of the struct.
Chris Lattner229907c2011-07-18 04:54:35 +0000244 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
245 StructType *STy = cast<StructType>(AgTy);
Owen Anderson55f1c092009-08-13 21:58:54 +0000246 Value *Idxs[2] = {
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000247 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr};
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000248 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000249 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
David Blaikie76826632015-03-14 21:11:26 +0000250 Value *Idx = GetElementPtrInst::Create(
Benjamin Kramerdba7ee92015-05-28 11:24:24 +0000251 STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i), Call);
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000252 // TODO: Tell AA about the new values?
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000253 Args.push_back(new LoadInst(Idx, Idx->getName() + ".val", Call));
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000254 }
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000255 } else if (!I->use_empty()) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000256 // Non-dead argument: insert GEPs and loads as appropriate.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000257 ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000258 // Store the Value* version of the indices in here, but declare it now
Gabor Greif161cb042010-03-23 14:40:20 +0000259 // for reuse.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000260 std::vector<Value *> Ops;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000261 for (const auto &ArgIndex : ArgIndices) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000262 Value *V = *AI;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000263 LoadInst *OrigLoad =
264 OriginalLoads[std::make_pair(&*I, ArgIndex.second)];
265 if (!ArgIndex.second.empty()) {
266 Ops.reserve(ArgIndex.second.size());
Chris Lattner229907c2011-07-18 04:54:35 +0000267 Type *ElTy = V->getType();
Benjamin Kramer135f7352016-06-26 12:28:59 +0000268 for (unsigned long II : ArgIndex.second) {
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000269 // Use i32 to index structs, and i64 for others (pointers/arrays).
270 // This satisfies GEP constraints.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000271 Type *IdxTy =
272 (ElTy->isStructTy() ? Type::getInt32Ty(F->getContext())
273 : Type::getInt64Ty(F->getContext()));
Benjamin Kramer135f7352016-06-26 12:28:59 +0000274 Ops.push_back(ConstantInt::get(IdxTy, II));
Gabor Greif161cb042010-03-23 14:40:20 +0000275 // Keep track of the type we're currently indexing.
Peter Collingbourne45681582016-12-02 03:05:41 +0000276 if (auto *ElPTy = dyn_cast<PointerType>(ElTy))
277 ElTy = ElPTy->getElementType();
278 else
279 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(II);
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000280 }
Gabor Greif161cb042010-03-23 14:40:20 +0000281 // And create a GEP to extract those indices.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000282 V = GetElementPtrInst::Create(ArgIndex.first, V, Ops,
David Blaikie72edd882015-03-14 21:40:12 +0000283 V->getName() + ".idx", Call);
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000284 Ops.clear();
Chris Lattner254f8f82004-05-23 21:21:17 +0000285 }
Eric Christopher81c03442010-03-27 01:54:00 +0000286 // Since we're replacing a load make sure we take the alignment
287 // of the previous load.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000288 LoadInst *newLoad = new LoadInst(V, V->getName() + ".val", Call);
Eric Christopher81c03442010-03-27 01:54:00 +0000289 newLoad->setAlignment(OrigLoad->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +0000290 // Transfer the AA info too.
291 AAMDNodes AAInfo;
292 OrigLoad->getAAMetadata(AAInfo);
293 newLoad->setAAMetadata(AAInfo);
294
Eric Christopher81c03442010-03-27 01:54:00 +0000295 Args.push_back(newLoad);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000296 }
Chris Lattner483ae012004-03-07 21:29:54 +0000297 }
298
Gabor Greif161cb042010-03-23 14:40:20 +0000299 // Push any varargs arguments on the list.
Chris Lattner5630c4f2008-01-17 01:17:03 +0000300 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) {
Chris Lattner483ae012004-03-07 21:29:54 +0000301 Args.push_back(*AI);
Bill Wendling49bc76c2013-01-23 06:14:59 +0000302 if (CallPAL.hasAttributes(ArgIndex)) {
Bill Wendling37a52df2013-01-27 01:57:28 +0000303 AttrBuilder B(CallPAL, ArgIndex);
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000304 AttributesVec.push_back(
305 AttributeSet::get(F->getContext(), Args.size(), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +0000306 }
Chris Lattner5630c4f2008-01-17 01:17:03 +0000307 }
Chris Lattner483ae012004-03-07 21:29:54 +0000308
Devang Patela05633e2008-09-26 22:53:05 +0000309 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +0000310 if (CallPAL.hasAttributes(AttributeSet::FunctionIndex))
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000311 AttributesVec.push_back(
312 AttributeSet::get(Call->getContext(), CallPAL.getFnAttributes()));
Devang Patela05633e2008-09-26 22:53:05 +0000313
David Majnemercd24bb12016-04-29 04:56:12 +0000314 SmallVector<OperandBundleDef, 1> OpBundles;
315 CS.getOperandBundlesAsDefs(OpBundles);
316
Chris Lattner483ae012004-03-07 21:29:54 +0000317 Instruction *New;
318 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greife9ecc682008-04-06 20:25:17 +0000319 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
David Majnemercd24bb12016-04-29 04:56:12 +0000320 Args, OpBundles, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000321 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000322 cast<InvokeInst>(New)->setAttributes(
323 AttributeSet::get(II->getContext(), AttributesVec));
Chris Lattner483ae012004-03-07 21:29:54 +0000324 } else {
David Majnemercd24bb12016-04-29 04:56:12 +0000325 New = CallInst::Create(NF, Args, OpBundles, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000326 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000327 cast<CallInst>(New)->setAttributes(
328 AttributeSet::get(New->getContext(), AttributesVec));
David Majnemerd5648c72016-11-25 22:35:09 +0000329 cast<CallInst>(New)->setTailCallKind(
330 cast<CallInst>(Call)->getTailCallKind());
Chris Lattner483ae012004-03-07 21:29:54 +0000331 }
David Blaikieb0cdf5302014-06-27 05:32:09 +0000332 New->setDebugLoc(Call->getDebugLoc());
Chris Lattner483ae012004-03-07 21:29:54 +0000333 Args.clear();
Devang Patel4c758ea2008-09-25 21:00:45 +0000334 AttributesVec.clear();
Chris Lattner483ae012004-03-07 21:29:54 +0000335
Duncan Sands3cf7d862008-09-08 11:07:35 +0000336 // Update the callgraph to know that the callsite has been transformed.
Chris Lattner9b463722009-09-01 18:52:39 +0000337 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000338 CalleeNode->replaceCallEdge(CS, CallSite(New), NF_CGN);
Duncan Sands3cf7d862008-09-08 11:07:35 +0000339
Chris Lattner483ae012004-03-07 21:29:54 +0000340 if (!Call->use_empty()) {
341 Call->replaceAllUsesWith(New);
Chris Lattner8d4c36b2007-02-11 01:08:35 +0000342 New->takeName(Call);
Chris Lattner483ae012004-03-07 21:29:54 +0000343 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000344
Chris Lattner483ae012004-03-07 21:29:54 +0000345 // Finally, remove the old call from the program, reducing the use-count of
346 // F.
Chris Lattner4062a622008-01-11 19:20:39 +0000347 Call->eraseFromParent();
Chris Lattner483ae012004-03-07 21:29:54 +0000348 }
349
350 // Since we have now created the new function, splice the body of the old
351 // function right into the new function, leaving the old rotting hulk of the
352 // function empty.
353 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
354
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000355 // Loop over the argument list, transferring uses of the old arguments over to
356 // the new arguments, also transferring over the names as well.
Chris Lattner483ae012004-03-07 21:29:54 +0000357 //
Chris Lattnera06a8fd2007-02-13 02:10:56 +0000358 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000359 I2 = NF->arg_begin();
360 I != E; ++I) {
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000361 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) {
Chris Lattner483ae012004-03-07 21:29:54 +0000362 // If this is an unmodified argument, move the name and users over to the
363 // new version.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000364 I->replaceAllUsesWith(&*I2);
365 I2->takeName(&*I);
Chris Lattner483ae012004-03-07 21:29:54 +0000366 ++I2;
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000367 continue;
Chris Lattner483ae012004-03-07 21:29:54 +0000368 }
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000369
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000370 if (ByValArgsToTransform.count(&*I)) {
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000371 // In the callee, we create an alloca, and store each of the new incoming
372 // arguments into the alloca.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000373 Instruction *InsertPt = &NF->begin()->front();
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000374
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000375 // Just add all the struct element types.
Chris Lattner229907c2011-07-18 04:54:35 +0000376 Type *AgTy = cast<PointerType>(I->getType())->getElementType();
Craig Topperf40110f2014-04-25 05:29:35 +0000377 Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt);
Chris Lattner229907c2011-07-18 04:54:35 +0000378 StructType *STy = cast<StructType>(AgTy);
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000379 Value *Idxs[2] = {ConstantInt::get(Type::getInt32Ty(F->getContext()), 0),
380 nullptr};
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000381
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000382 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Owen Anderson55f1c092009-08-13 21:58:54 +0000383 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i);
David Blaikie096b1da2015-03-14 19:53:33 +0000384 Value *Idx = GetElementPtrInst::Create(
385 AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i),
386 InsertPt);
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000387 I2->setName(I->getName() + "." + Twine(i));
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000388 new StoreInst(&*I2++, Idx, InsertPt);
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000389 }
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000390
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000391 // Anything that used the arg should now use the alloca.
392 I->replaceAllUsesWith(TheAlloca);
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000393 TheAlloca->takeName(&*I);
Rafael Espindola2a05ea52014-01-23 17:19:42 +0000394
395 // If the alloca is used in a call, we must clear the tail flag since
396 // the callee now uses an alloca from the caller.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000397 for (User *U : TheAlloca->users()) {
398 CallInst *Call = dyn_cast<CallInst>(U);
Rafael Espindola2a05ea52014-01-23 17:19:42 +0000399 if (!Call)
400 continue;
401 Call->setTailCall(false);
402 }
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000403 continue;
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000404 }
405
Chandler Carrutha1032a02015-07-22 09:49:59 +0000406 if (I->use_empty())
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000407 continue;
Duncan Sands1ea0d2e2008-09-07 09:54:09 +0000408
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000409 // Otherwise, if we promoted this argument, then all users are load
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000410 // instructions (or GEPs with only load users), and all loads should be
411 // using the new argument that we added.
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000412 ScalarizeTable &ArgIndices = ScalarizedElements[&*I];
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000413
414 while (!I->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000415 if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) {
David Blaikie76826632015-03-14 21:11:26 +0000416 assert(ArgIndices.begin()->second.empty() &&
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000417 "Load element should sort to front!");
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000418 I2->setName(I->getName() + ".val");
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000419 LI->replaceAllUsesWith(&*I2);
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000420 LI->eraseFromParent();
David Greenecf0addf2010-01-05 01:28:37 +0000421 DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName()
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000422 << "' in function '" << F->getName() << "'\n");
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000423 } else {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000424 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back());
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000425 IndicesVector Operands;
426 Operands.reserve(GEP->getNumIndices());
427 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
428 II != IE; ++II)
429 Operands.push_back(cast<ConstantInt>(*II)->getSExtValue());
430
431 // GEPs with a single 0 index can be merged with direct loads
432 if (Operands.size() == 1 && Operands.front() == 0)
433 Operands.clear();
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000434
435 Function::arg_iterator TheArg = I2;
436 for (ScalarizeTable::iterator It = ArgIndices.begin();
David Blaikie76826632015-03-14 21:11:26 +0000437 It->second != Operands; ++It, ++TheArg) {
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000438 assert(It != ArgIndices.end() && "GEP not handled??");
439 }
440
441 std::string NewName = I->getName();
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000442 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000443 NewName += "." + utostr(Operands[i]);
Matthijs Kooijmanfd307042008-07-29 10:00:13 +0000444 }
445 NewName += ".val";
446 TheArg->setName(NewName);
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000447
David Greenecf0addf2010-01-05 01:28:37 +0000448 DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName()
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000449 << "' of function '" << NF->getName() << "'\n");
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000450
451 // All of the uses must be load instructions. Replace them all with
452 // the argument specified by ArgNo.
453 while (!GEP->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000454 LoadInst *L = cast<LoadInst>(GEP->user_back());
Duncan P. N. Exon Smith17323402015-10-13 17:51:03 +0000455 L->replaceAllUsesWith(&*TheArg);
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000456 L->eraseFromParent();
457 }
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000458 GEP->eraseFromParent();
459 }
460 }
461
462 // Increment I2 past all of the arguments added for this promoted pointer.
Benjamin Kramer84036252012-09-30 17:31:56 +0000463 std::advance(I2, ArgIndices.size());
Chris Lattnerb5bd9242008-01-11 22:31:41 +0000464 }
Chris Lattner483ae012004-03-07 21:29:54 +0000465
Chris Lattner305b1152009-08-31 00:19:58 +0000466 NF_CGN->stealCalledFunctionsFrom(CG[F]);
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000467
Chris Lattnere9384672010-04-20 00:46:50 +0000468 // Now that the old function is dead, delete it. If there is a dangling
469 // reference to the CallgraphNode, just leave the dead function around for
470 // someone else to nuke.
471 CallGraphNode *CGN = CG[F];
472 if (CGN->getNumReferences() == 0)
473 delete CG.removeFunctionFromModule(CGN);
474 else
475 F->setLinkage(Function::ExternalLinkage);
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000476
Chris Lattner305b1152009-08-31 00:19:58 +0000477 return NF_CGN;
Chris Lattner483ae012004-03-07 21:29:54 +0000478}
David Blaikiee844cd52014-07-01 21:13:37 +0000479
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000480/// AllCallersPassInValidPointerForArgument - Return true if we can prove that
481/// all callees pass in a valid pointer for the specified function argument.
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000482static bool allCallersPassInValidPointerForArgument(Argument *Arg) {
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000483 Function *Callee = Arg->getParent();
484 const DataLayout &DL = Callee->getParent()->getDataLayout();
485
486 unsigned ArgNo = Arg->getArgNo();
487
488 // Look at all call sites of the function. At this point we know we only have
489 // direct callees.
490 for (User *U : Callee->users()) {
491 CallSite CS(U);
492 assert(CS && "Should only have direct calls!");
493
494 if (!isDereferenceablePointer(CS.getArgument(ArgNo), DL))
495 return false;
496 }
497 return true;
498}
499
500/// Returns true if Prefix is a prefix of longer. That means, Longer has a size
501/// that is greater than or equal to the size of prefix, and each of the
502/// elements in Prefix is the same as the corresponding elements in Longer.
503///
504/// This means it also returns true when Prefix and Longer are equal!
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000505static bool isPrefix(const IndicesVector &Prefix, const IndicesVector &Longer) {
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000506 if (Prefix.size() > Longer.size())
507 return false;
508 return std::equal(Prefix.begin(), Prefix.end(), Longer.begin());
509}
510
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000511/// Checks if Indices, or a prefix of Indices, is in Set.
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000512static bool prefixIn(const IndicesVector &Indices,
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000513 std::set<IndicesVector> &Set) {
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000514 std::set<IndicesVector>::iterator Low;
515 Low = Set.upper_bound(Indices);
516 if (Low != Set.begin())
517 Low--;
518 // Low is now the last element smaller than or equal to Indices. This means
519 // it points to a prefix of Indices (possibly Indices itself), if such
520 // prefix exists.
521 //
522 // This load is safe if any prefix of its operands is safe to load.
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000523 return Low != Set.end() && isPrefix(*Low, Indices);
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000524}
525
526/// Mark the given indices (ToMark) as safe in the given set of indices
527/// (Safe). Marking safe usually means adding ToMark to Safe. However, if there
528/// is already a prefix of Indices in Safe, Indices are implicitely marked safe
529/// already. Furthermore, any indices that Indices is itself a prefix of, are
530/// removed from Safe (since they are implicitely safe because of Indices now).
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000531static void markIndicesSafe(const IndicesVector &ToMark,
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000532 std::set<IndicesVector> &Safe) {
533 std::set<IndicesVector>::iterator Low;
534 Low = Safe.upper_bound(ToMark);
535 // Guard against the case where Safe is empty
536 if (Low != Safe.begin())
537 Low--;
538 // Low is now the last element smaller than or equal to Indices. This
539 // means it points to a prefix of Indices (possibly Indices itself), if
540 // such prefix exists.
541 if (Low != Safe.end()) {
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000542 if (isPrefix(*Low, ToMark))
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000543 // If there is already a prefix of these indices (or exactly these
544 // indices) marked a safe, don't bother adding these indices
545 return;
546
547 // Increment Low, so we can use it as a "insert before" hint
548 ++Low;
549 }
550 // Insert
551 Low = Safe.insert(Low, ToMark);
552 ++Low;
553 // If there we're a prefix of longer index list(s), remove those
554 std::set<IndicesVector>::iterator End = Safe.end();
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000555 while (Low != End && isPrefix(ToMark, *Low)) {
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000556 std::set<IndicesVector>::iterator Remove = Low;
557 ++Low;
558 Safe.erase(Remove);
559 }
560}
561
562/// isSafeToPromoteArgument - As you might guess from the name of this method,
563/// it checks to see if it is both safe and useful to promote the argument.
564/// This method limits promotion of aggregates to only promote up to three
565/// elements of the aggregate in order to avoid exploding the number of
566/// arguments passed in.
567static bool isSafeToPromoteArgument(Argument *Arg, bool isByValOrInAlloca,
568 AAResults &AAR, unsigned MaxElements) {
569 typedef std::set<IndicesVector> GEPIndicesSet;
570
571 // Quick exit for unused arguments
572 if (Arg->use_empty())
573 return true;
574
575 // We can only promote this argument if all of the uses are loads, or are GEP
576 // instructions (with constant indices) that are subsequently loaded.
577 //
578 // Promoting the argument causes it to be loaded in the caller
579 // unconditionally. This is only safe if we can prove that either the load
580 // would have happened in the callee anyway (ie, there is a load in the entry
581 // block) or the pointer passed in at every call site is guaranteed to be
582 // valid.
583 // In the former case, invalid loads can happen, but would have happened
584 // anyway, in the latter case, invalid loads won't happen. This prevents us
585 // from introducing an invalid load that wouldn't have happened in the
586 // original code.
587 //
588 // This set will contain all sets of indices that are loaded in the entry
589 // block, and thus are safe to unconditionally load in the caller.
590 //
591 // This optimization is also safe for InAlloca parameters, because it verifies
592 // that the address isn't captured.
593 GEPIndicesSet SafeToUnconditionallyLoad;
594
595 // This set contains all the sets of indices that we are planning to promote.
596 // This makes it possible to limit the number of arguments added.
597 GEPIndicesSet ToPromote;
598
599 // If the pointer is always valid, any load with first index 0 is valid.
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000600 if (isByValOrInAlloca || allCallersPassInValidPointerForArgument(Arg))
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000601 SafeToUnconditionallyLoad.insert(IndicesVector(1, 0));
602
603 // First, iterate the entry block and mark loads of (geps of) arguments as
604 // safe.
605 BasicBlock &EntryBlock = Arg->getParent()->front();
606 // Declare this here so we can reuse it
607 IndicesVector Indices;
608 for (Instruction &I : EntryBlock)
609 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
610 Value *V = LI->getPointerOperand();
611 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
612 V = GEP->getPointerOperand();
613 if (V == Arg) {
614 // This load actually loads (part of) Arg? Check the indices then.
615 Indices.reserve(GEP->getNumIndices());
616 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end();
617 II != IE; ++II)
618 if (ConstantInt *CI = dyn_cast<ConstantInt>(*II))
619 Indices.push_back(CI->getSExtValue());
620 else
621 // We found a non-constant GEP index for this argument? Bail out
622 // right away, can't promote this argument at all.
623 return false;
624
625 // Indices checked out, mark them as safe
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000626 markIndicesSafe(Indices, SafeToUnconditionallyLoad);
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000627 Indices.clear();
628 }
629 } else if (V == Arg) {
630 // Direct loads are equivalent to a GEP with a single 0 index.
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000631 markIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad);
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000632 }
633 }
634
635 // Now, iterate all uses of the argument to see if there are any uses that are
636 // not (GEP+)loads, or any (GEP+)loads that are not safe to promote.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000637 SmallVector<LoadInst *, 16> Loads;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000638 IndicesVector Operands;
639 for (Use &U : Arg->uses()) {
640 User *UR = U.getUser();
641 Operands.clear();
642 if (LoadInst *LI = dyn_cast<LoadInst>(UR)) {
643 // Don't hack volatile/atomic loads
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000644 if (!LI->isSimple())
645 return false;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000646 Loads.push_back(LI);
647 // Direct loads are equivalent to a GEP with a zero index and then a load.
648 Operands.push_back(0);
649 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) {
650 if (GEP->use_empty()) {
651 // Dead GEP's cause trouble later. Just remove them if we run into
652 // them.
653 GEP->eraseFromParent();
654 // TODO: This runs the above loop over and over again for dead GEPs
655 // Couldn't we just do increment the UI iterator earlier and erase the
656 // use?
657 return isSafeToPromoteArgument(Arg, isByValOrInAlloca, AAR,
658 MaxElements);
659 }
660
661 // Ensure that all of the indices are constants.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000662 for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end(); i != e;
663 ++i)
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000664 if (ConstantInt *C = dyn_cast<ConstantInt>(*i))
665 Operands.push_back(C->getSExtValue());
666 else
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000667 return false; // Not a constant operand GEP!
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000668
669 // Ensure that the only users of the GEP are load instructions.
670 for (User *GEPU : GEP->users())
671 if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) {
672 // Don't hack volatile/atomic loads
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000673 if (!LI->isSimple())
674 return false;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000675 Loads.push_back(LI);
676 } else {
677 // Other uses than load?
678 return false;
679 }
680 } else {
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000681 return false; // Not a load or a GEP.
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000682 }
683
684 // Now, see if it is safe to promote this load / loads of this GEP. Loading
685 // is safe if Operands, or a prefix of Operands, is marked as safe.
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000686 if (!prefixIn(Operands, SafeToUnconditionallyLoad))
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000687 return false;
688
689 // See if we are already promoting a load with these indices. If not, check
690 // to make sure that we aren't promoting too many elements. If so, nothing
691 // to do.
692 if (ToPromote.find(Operands) == ToPromote.end()) {
693 if (MaxElements > 0 && ToPromote.size() == MaxElements) {
694 DEBUG(dbgs() << "argpromotion not promoting argument '"
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000695 << Arg->getName()
696 << "' because it would require adding more "
697 << "than " << MaxElements
698 << " arguments to the function.\n");
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000699 // We limit aggregate promotion to only promoting up to a fixed number
700 // of elements of the aggregate.
701 return false;
702 }
703 ToPromote.insert(std::move(Operands));
704 }
705 }
706
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000707 if (Loads.empty())
708 return true; // No users, this is a dead argument.
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000709
710 // Okay, now we know that the argument is only used by load instructions and
711 // it is safe to unconditionally perform all of them. Use alias analysis to
712 // check to see if the pointer is guaranteed to not be modified from entry of
713 // the function to each of the load instructions.
714
715 // Because there could be several/many load instructions, remember which
716 // blocks we know to be transparent to the load.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000717 df_iterator_default_set<BasicBlock *, 16> TranspBlocks;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000718
719 for (LoadInst *Load : Loads) {
720 // Check to see if the load is invalidated from the start of the block to
721 // the load itself.
722 BasicBlock *BB = Load->getParent();
723
724 MemoryLocation Loc = MemoryLocation::get(Load);
725 if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, MRI_Mod))
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000726 return false; // Pointer is invalidated!
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000727
728 // Now check every path from the entry block to the load for transparency.
729 // To do this, we perform a depth first search on the inverse CFG from the
730 // loading block.
731 for (BasicBlock *P : predecessors(BB)) {
732 for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks))
733 if (AAR.canBasicBlockModify(*TranspBB, Loc))
734 return false;
735 }
736 }
737
738 // If the path from the entry of the function to each load is free of
739 // instructions that potentially invalidate the load, we can make the
740 // transformation!
741 return true;
742}
743
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000744/// \brief Checks if a type could have padding bytes.
745static bool isDenselyPacked(Type *type, const DataLayout &DL) {
746
747 // There is no size information, so be conservative.
748 if (!type->isSized())
749 return false;
750
751 // If the alloc size is not equal to the storage size, then there are padding
752 // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128.
753 if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type))
754 return false;
755
756 if (!isa<CompositeType>(type))
757 return true;
758
759 // For homogenous sequential types, check for padding within members.
760 if (SequentialType *seqTy = dyn_cast<SequentialType>(type))
761 return isDenselyPacked(seqTy->getElementType(), DL);
762
763 // Check for padding within and between elements of a struct.
764 StructType *StructTy = cast<StructType>(type);
765 const StructLayout *Layout = DL.getStructLayout(StructTy);
766 uint64_t StartPos = 0;
767 for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) {
768 Type *ElTy = StructTy->getElementType(i);
769 if (!isDenselyPacked(ElTy, DL))
770 return false;
771 if (StartPos != Layout->getElementOffsetInBits(i))
772 return false;
773 StartPos += DL.getTypeAllocSizeInBits(ElTy);
774 }
775
776 return true;
777}
778
779/// \brief Checks if the padding bytes of an argument could be accessed.
780static bool canPaddingBeAccessed(Argument *arg) {
781
782 assert(arg->hasByValAttr());
783
784 // Track all the pointers to the argument to make sure they are not captured.
785 SmallPtrSet<Value *, 16> PtrValues;
786 PtrValues.insert(arg);
787
788 // Track all of the stores.
789 SmallVector<StoreInst *, 16> Stores;
790
791 // Scan through the uses recursively to make sure the pointer is always used
792 // sanely.
793 SmallVector<Value *, 16> WorkList;
794 WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end());
795 while (!WorkList.empty()) {
796 Value *V = WorkList.back();
797 WorkList.pop_back();
798 if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) {
799 if (PtrValues.insert(V).second)
800 WorkList.insert(WorkList.end(), V->user_begin(), V->user_end());
801 } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) {
802 Stores.push_back(Store);
803 } else if (!isa<LoadInst>(V)) {
804 return true;
805 }
806 }
807
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000808 // Check to make sure the pointers aren't captured
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000809 for (StoreInst *Store : Stores)
810 if (PtrValues.count(Store->getValueOperand()))
811 return true;
812
813 return false;
814}
815
816/// PromoteArguments - This method checks the specified function to see if there
817/// are any promotable arguments and if it is safe to promote the function (for
818/// example, all callers are direct). If safe to promote some arguments, it
819/// calls the DoPromotion method.
820///
821static CallGraphNode *
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000822promoteArguments(CallGraphNode *CGN, CallGraph &CG,
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000823 function_ref<AAResults &(Function &F)> AARGetter,
824 unsigned MaxElements) {
825 Function *F = CGN->getFunction();
826
827 // Make sure that it is local to this module.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000828 if (!F || !F->hasLocalLinkage())
829 return nullptr;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000830
831 // Don't promote arguments for variadic functions. Adding, removing, or
832 // changing non-pack parameters can change the classification of pack
833 // parameters. Frontends encode that classification at the call site in the
834 // IR, while in the callee the classification is determined dynamically based
835 // on the number of registers consumed so far.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000836 if (F->isVarArg())
837 return nullptr;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000838
839 // First check: see if there are any pointer arguments! If not, quick exit.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000840 SmallVector<Argument *, 16> PointerArgs;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000841 for (Argument &I : F->args())
842 if (I.getType()->isPointerTy())
843 PointerArgs.push_back(&I);
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000844 if (PointerArgs.empty())
845 return nullptr;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000846
847 // Second check: make sure that all callers are direct callers. We can't
848 // transform functions that have indirect callers. Also see if the function
849 // is self-recursive.
850 bool isSelfRecursive = false;
851 for (Use &U : F->uses()) {
852 CallSite CS(U.getUser());
853 // Must be a direct call.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000854 if (CS.getInstruction() == nullptr || !CS.isCallee(&U))
855 return nullptr;
856
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000857 if (CS.getInstruction()->getParent()->getParent() == F)
858 isSelfRecursive = true;
859 }
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000860
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000861 const DataLayout &DL = F->getParent()->getDataLayout();
862
863 AAResults &AAR = AARGetter(*F);
864
865 // Check to see which arguments are promotable. If an argument is promotable,
866 // add it to ArgsToPromote.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000867 SmallPtrSet<Argument *, 8> ArgsToPromote;
868 SmallPtrSet<Argument *, 8> ByValArgsToTransform;
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000869 for (Argument *PtrArg : PointerArgs) {
870 Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
871
872 // Replace sret attribute with noalias. This reduces register pressure by
873 // avoiding a register copy.
874 if (PtrArg->hasStructRetAttr()) {
875 unsigned ArgNo = PtrArg->getArgNo();
876 F->setAttributes(
877 F->getAttributes()
878 .removeAttribute(F->getContext(), ArgNo + 1, Attribute::StructRet)
879 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
880 for (Use &U : F->uses()) {
881 CallSite CS(U.getUser());
882 CS.setAttributes(
883 CS.getAttributes()
884 .removeAttribute(F->getContext(), ArgNo + 1,
885 Attribute::StructRet)
886 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias));
887 }
888 }
889
890 // If this is a byval argument, and if the aggregate type is small, just
891 // pass the elements, which is always safe, if the passed value is densely
892 // packed or if we can prove the padding bytes are never accessed. This does
893 // not apply to inalloca.
894 bool isSafeToPromote =
895 PtrArg->hasByValAttr() &&
896 (isDenselyPacked(AgTy, DL) || !canPaddingBeAccessed(PtrArg));
897 if (isSafeToPromote) {
898 if (StructType *STy = dyn_cast<StructType>(AgTy)) {
899 if (MaxElements > 0 && STy->getNumElements() > MaxElements) {
900 DEBUG(dbgs() << "argpromotion disable promoting argument '"
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000901 << PtrArg->getName()
902 << "' because it would require adding more"
903 << " than " << MaxElements
904 << " arguments to the function.\n");
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000905 continue;
906 }
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000907
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000908 // If all the elements are single-value types, we can promote it.
909 bool AllSimple = true;
910 for (const auto *EltTy : STy->elements()) {
911 if (!EltTy->isSingleValueType()) {
912 AllSimple = false;
913 break;
914 }
915 }
916
917 // Safe to transform, don't even bother trying to "promote" it.
918 // Passing the elements as a scalar will allow sroa to hack on
919 // the new alloca we introduce.
920 if (AllSimple) {
921 ByValArgsToTransform.insert(PtrArg);
922 continue;
923 }
924 }
925 }
926
927 // If the argument is a recursive type and we're in a recursive
928 // function, we could end up infinitely peeling the function argument.
929 if (isSelfRecursive) {
930 if (StructType *STy = dyn_cast<StructType>(AgTy)) {
931 bool RecursiveType = false;
932 for (const auto *EltTy : STy->elements()) {
933 if (EltTy == PtrArg->getType()) {
934 RecursiveType = true;
935 break;
936 }
937 }
938 if (RecursiveType)
939 continue;
940 }
941 }
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000942
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000943 // Otherwise, see if we can promote the pointer to its value.
944 if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr(), AAR,
945 MaxElements))
946 ArgsToPromote.insert(PtrArg);
947 }
948
949 // No promotable pointer arguments.
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000950 if (ArgsToPromote.empty() && ByValArgsToTransform.empty())
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000951 return nullptr;
952
Chandler Carruth8e9c0a82017-01-29 08:03:21 +0000953 return doPromotion(F, ArgsToPromote, ByValArgsToTransform, CG);
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000954}
955
956namespace {
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000957/// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
958///
959struct ArgPromotion : public CallGraphSCCPass {
960 void getAnalysisUsage(AnalysisUsage &AU) const override {
961 AU.addRequired<AssumptionCacheTracker>();
962 AU.addRequired<TargetLibraryInfoWrapperPass>();
963 getAAResultsAnalysisUsage(AU);
964 CallGraphSCCPass::getAnalysisUsage(AU);
965 }
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000966
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000967 bool runOnSCC(CallGraphSCC &SCC) override;
968 static char ID; // Pass identification, replacement for typeid
969 explicit ArgPromotion(unsigned MaxElements = 3)
970 : CallGraphSCCPass(ID), MaxElements(MaxElements) {
971 initializeArgPromotionPass(*PassRegistry::getPassRegistry());
972 }
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000973
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000974private:
975 using llvm::Pass::doInitialization;
976 bool doInitialization(CallGraph &CG) override;
977 /// The maximum number of elements to expand, or 0 for unlimited.
978 unsigned MaxElements;
979};
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000980}
981
982char ArgPromotion::ID = 0;
983INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion",
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000984 "Promote 'by reference' arguments to scalars", false,
985 false)
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000986INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
987INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
988INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
989INITIALIZE_PASS_END(ArgPromotion, "argpromotion",
Chandler Carruthae9ce3d2017-01-29 08:03:19 +0000990 "Promote 'by reference' arguments to scalars", false, false)
Chandler Carruthcd836cd2017-01-29 08:03:16 +0000991
992Pass *llvm::createArgumentPromotionPass(unsigned MaxElements) {
993 return new ArgPromotion(MaxElements);
994}
995
996bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
997 if (skipSCC(SCC))
998 return false;
999
1000 // Get the callgraph information that we need to update to reflect our
1001 // changes.
1002 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1003
1004 // We compute dedicated AA results for each function in the SCC as needed. We
1005 // use a lambda referencing external objects so that they live long enough to
1006 // be queried, but we re-use them each time.
1007 Optional<BasicAAResult> BAR;
1008 Optional<AAResults> AAR;
1009 auto AARGetter = [&](Function &F) -> AAResults & {
1010 BAR.emplace(createLegacyPMBasicAAResult(*this, F));
1011 AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
1012 return *AAR;
1013 };
1014
1015 bool Changed = false, LocalChange;
1016
1017 // Iterate until we stop promoting from this SCC.
1018 do {
1019 LocalChange = false;
1020 // Attempt to promote arguments from all functions in this SCC.
1021 for (CallGraphNode *OldNode : SCC) {
1022 if (CallGraphNode *NewNode =
Chandler Carruth8e9c0a82017-01-29 08:03:21 +00001023 promoteArguments(OldNode, CG, AARGetter, MaxElements)) {
Chandler Carruthcd836cd2017-01-29 08:03:16 +00001024 LocalChange = true;
1025 SCC.ReplaceNode(OldNode, NewNode);
1026 }
1027 }
1028 // Remember that we changed something.
1029 Changed |= LocalChange;
1030 } while (LocalChange);
1031
1032 return Changed;
1033}
1034
David Blaikiee844cd52014-07-01 21:13:37 +00001035bool ArgPromotion::doInitialization(CallGraph &CG) {
David Blaikiee844cd52014-07-01 21:13:37 +00001036 return CallGraphSCCPass::doInitialization(CG);
1037}