blob: a80e7fb3b48bcbc4a2a7e4b747bd198fd60cdce3 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000033#include "llvm/Analysis/Dominators.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000034#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000035#include "llvm/Target/TargetData.h"
36#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000037#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000038#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000039#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000040#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000043#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000044#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000045#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000046#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000047#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Chris Lattner0e5f4992006-12-19 21:40:18 +000050STATISTIC(NumReplaced, "Number of allocas broken up");
51STATISTIC(NumPromoted, "Number of allocas promoted");
52STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000053STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000054
Chris Lattner0e5f4992006-12-19 21:40:18 +000055namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000056 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000057 SROA(int T, bool hasDT, char &ID)
58 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000059 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000060 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000061 else
62 SRThreshold = T;
63 }
Devang Patel794fd752007-05-01 21:15:47 +000064
Chris Lattnered7b41e2003-05-27 15:45:27 +000065 bool runOnFunction(Function &F);
66
Chris Lattner38aec322003-09-11 16:45:55 +000067 bool performScalarRepl(Function &F);
68 bool performPromotion(Function &F);
69
Chris Lattnered7b41e2003-05-27 15:45:27 +000070 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000071 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000072 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000073
Bob Wilsonb742def2009-12-18 20:14:40 +000074 /// DeadInsts - Keep track of instructions we have made dead, so that
75 /// we can remove them after we are done working.
76 SmallVector<Value*, 32> DeadInsts;
77
Chris Lattner39a1c042007-05-30 06:11:23 +000078 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
79 /// information about the uses. All these fields are initialized to false
80 /// and set to true when something is learned.
81 struct AllocaInfo {
82 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
83 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000084
Chris Lattner39a1c042007-05-30 06:11:23 +000085 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
86 bool isMemCpySrc : 1;
87
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000088 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000089 bool isMemCpyDst : 1;
90
Chris Lattner7e9b4272011-01-16 06:18:28 +000091 /// hasSubelementAccess - This is true if a subelement of the alloca is
92 /// ever accessed, or false if the alloca is only accessed with mem
93 /// intrinsics or load/store that only access the entire alloca at once.
94 bool hasSubelementAccess : 1;
95
96 /// hasALoadOrStore - This is true if there are any loads or stores to it.
97 /// The alloca may just be accessed with memcpy, for example, which would
98 /// not set this.
99 bool hasALoadOrStore : 1;
100
Chris Lattner39a1c042007-05-30 06:11:23 +0000101 AllocaInfo()
Chris Lattner7e9b4272011-01-16 06:18:28 +0000102 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
103 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000104 };
Bob Wilson69743022011-01-13 20:59:44 +0000105
Devang Patelff366852007-07-09 21:19:23 +0000106 unsigned SRThreshold;
107
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000108 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
109 I.isUnsafe = true;
110 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
111 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000112
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000113 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000114
Bob Wilsonb742def2009-12-18 20:14:40 +0000115 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000116 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000117 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000118 AllocaInfo &Info);
119 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000120 const Type *MemOpType, bool isStore, AllocaInfo &Info,
121 Instruction *TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +0000122 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000123 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
124 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000125
126 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000127 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000128 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000129
Bob Wilsonb742def2009-12-18 20:14:40 +0000130 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
131 SmallVector<AllocaInst*, 32> &NewElts);
132 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
133 SmallVector<AllocaInst*, 32> &NewElts);
134 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
135 SmallVector<AllocaInst*, 32> &NewElts);
136 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000137 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000138 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000139 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000140 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000141 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000142 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000143
Chris Lattner31d80102010-04-15 21:59:20 +0000144 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000145 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000146
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000147 // SROA_DT - SROA that uses DominatorTree.
148 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000149 static char ID;
150 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000151 SROA_DT(int T = -1) : SROA(T, true, ID) {
152 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000153 }
154
155 // getAnalysisUsage - This pass does not require any passes, but we know it
156 // will not alter the CFG, so say so.
157 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000159 AU.setPreservesCFG();
160 }
161 };
162
163 // SROA_SSAUp - SROA that uses SSAUpdater.
164 struct SROA_SSAUp : public SROA {
165 static char ID;
166 public:
167 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
168 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
169 }
170
171 // getAnalysisUsage - This pass does not require any passes, but we know it
172 // will not alter the CFG, so say so.
173 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
174 AU.setPreservesCFG();
175 }
176 };
177
Chris Lattnered7b41e2003-05-27 15:45:27 +0000178}
179
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000180char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000181char SROA_SSAUp::ID = 0;
182
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000183INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
184 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000185INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000186INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
187 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000188
189INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
190 "Scalar Replacement of Aggregates (SSAUp)", false, false)
191INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
192 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000193
Brian Gaeked0fde302003-11-11 22:41:34 +0000194// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000195FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000196 bool UseDomTree) {
197 if (UseDomTree)
198 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000199 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000200}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000201
202
Chris Lattner4cc576b2010-04-16 00:24:57 +0000203//===----------------------------------------------------------------------===//
204// Convert To Scalar Optimization.
205//===----------------------------------------------------------------------===//
206
207namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000208/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
209/// optimization, which scans the uses of an alloca and determines if it can
210/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000211class ConvertToScalarInfo {
212 /// AllocaSize - The size of the alloca being considered.
213 unsigned AllocaSize;
214 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000215
Chris Lattnera0bada72010-04-16 02:32:17 +0000216 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000217 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000218 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000219
Chris Lattnera001b662010-04-16 00:38:19 +0000220 /// VectorTy - This tracks the type that we should promote the vector to if
221 /// it is possible to turn it into a vector. This starts out null, and if it
222 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000223 const Type *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000224
Chris Lattnera001b662010-04-16 00:38:19 +0000225 /// HadAVector - True if there is at least one vector access to the alloca.
226 /// We don't want to turn random arrays into vectors and use vector element
227 /// insert/extract, but if there are element accesses to something that is
228 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000229 bool HadAVector;
230
231public:
232 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
233 : AllocaSize(Size), TD(td) {
234 IsNotTrivial = false;
235 VectorTy = 0;
236 HadAVector = false;
237 }
Bob Wilson69743022011-01-13 20:59:44 +0000238
Chris Lattnera001b662010-04-16 00:38:19 +0000239 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000240
Chris Lattner4cc576b2010-04-16 00:24:57 +0000241private:
242 bool CanConvertToScalar(Value *V, uint64_t Offset);
243 void MergeInType(const Type *In, uint64_t Offset);
244 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000245
Chris Lattner4cc576b2010-04-16 00:24:57 +0000246 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
247 uint64_t Offset, IRBuilder<> &Builder);
248 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
249 uint64_t Offset, IRBuilder<> &Builder);
250};
251} // end anonymous namespace.
252
Chris Lattner91abace2010-09-01 05:14:33 +0000253
Chris Lattnera001b662010-04-16 00:38:19 +0000254/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
255/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
256/// alloca if possible or null if not.
257AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
258 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
259 // out.
260 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
261 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000262
Chris Lattnera001b662010-04-16 00:38:19 +0000263 // If we were able to find a vector type that can handle this with
264 // insert/extract elements, and if there was at least one use that had
265 // a vector type, promote this to a vector. We don't want to promote
266 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
267 // we just get a lot of insert/extracts. If at least one vector is
268 // involved, then we probably really do have a union of vector/array.
269 const Type *NewTy;
Chris Lattner85a7c692011-01-23 06:40:33 +0000270 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
Chris Lattnera001b662010-04-16 00:38:19 +0000271 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
272 << *VectorTy << '\n');
273 NewTy = VectorTy; // Use the vector type.
274 } else {
275 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
276 // Create and insert the integer alloca.
277 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
278 }
279 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
280 ConvertUsesToScalar(AI, NewAI, 0);
281 return NewAI;
282}
283
284/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
285/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000286///
287/// There are two cases we handle here:
288/// 1) A union of vector types of the same size and potentially its elements.
289/// Here we turn element accesses into insert/extract element operations.
290/// This promotes a <4 x float> with a store of float to the third element
291/// into a <4 x float> that uses insert element.
292/// 2) A fully general blob of memory, which we turn into some (potentially
293/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000294/// and stores would mutate the memory. We mark this by setting VectorTy
295/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000296void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000297 // If we already decided to turn this into a blob of integer memory, there is
298 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000299 if (VectorTy && VectorTy->isVoidTy())
300 return;
Bob Wilson69743022011-01-13 20:59:44 +0000301
Chris Lattner4cc576b2010-04-16 00:24:57 +0000302 // If this could be contributing to a vector, analyze it.
303
304 // If the In type is a vector that is the same size as the alloca, see if it
305 // matches the existing VecTy.
306 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000307 // Remember if we saw a vector type.
308 HadAVector = true;
Bob Wilson69743022011-01-13 20:59:44 +0000309
Chris Lattner4cc576b2010-04-16 00:24:57 +0000310 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
311 // If we're storing/loading a vector of the right size, allow it as a
312 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000313 // we know the element size. If this is a subsequent access, ignore it
314 // even if it is a differing type but the same size. Worst case we can
315 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000316 if (VectorTy == 0)
317 VectorTy = VInTy;
318 return;
319 }
320 } else if (In->isFloatTy() || In->isDoubleTy() ||
321 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
322 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
323 // If we're accessing something that could be an element of a vector, see
324 // if the implied vector agrees with what we already have and if Offset is
325 // compatible with it.
326 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
327 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Bob Wilson69743022011-01-13 20:59:44 +0000328 (VectorTy == 0 ||
Chris Lattner4cc576b2010-04-16 00:24:57 +0000329 cast<VectorType>(VectorTy)->getElementType()
330 ->getPrimitiveSizeInBits()/8 == EltSize)) {
331 if (VectorTy == 0)
332 VectorTy = VectorType::get(In, AllocaSize/EltSize);
333 return;
334 }
335 }
Bob Wilson69743022011-01-13 20:59:44 +0000336
Chris Lattner4cc576b2010-04-16 00:24:57 +0000337 // Otherwise, we have a case that we can't handle with an optimized vector
338 // form. We can still turn this into a large integer.
339 VectorTy = Type::getVoidTy(In->getContext());
340}
341
342/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
343/// its accesses to a single vector type, return true and set VecTy to
344/// the new type. If we could convert the alloca into a single promotable
345/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
346/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
347/// is the current offset from the base of the alloca being analyzed.
348///
349/// If we see at least one access to the value that is as a vector type, set the
350/// SawVec flag.
351bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
352 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
353 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000354
Chris Lattner4cc576b2010-04-16 00:24:57 +0000355 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
356 // Don't break volatile loads.
357 if (LI->isVolatile())
358 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000359 // Don't touch MMX operations.
360 if (LI->getType()->isX86_MMXTy())
361 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000362 MergeInType(LI->getType(), Offset);
363 continue;
364 }
Bob Wilson69743022011-01-13 20:59:44 +0000365
Chris Lattner4cc576b2010-04-16 00:24:57 +0000366 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
367 // Storing the pointer, not into the value?
368 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000369 // Don't touch MMX operations.
370 if (SI->getOperand(0)->getType()->isX86_MMXTy())
371 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000372 MergeInType(SI->getOperand(0)->getType(), Offset);
373 continue;
374 }
Bob Wilson69743022011-01-13 20:59:44 +0000375
Chris Lattner4cc576b2010-04-16 00:24:57 +0000376 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000377 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000378 if (!CanConvertToScalar(BCI, Offset))
379 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000380 continue;
381 }
382
383 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
384 // If this is a GEP with a variable indices, we can't handle it.
385 if (!GEP->hasAllConstantIndices())
386 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000387
Chris Lattner4cc576b2010-04-16 00:24:57 +0000388 // Compute the offset that this GEP adds to the pointer.
389 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
390 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
391 &Indices[0], Indices.size());
392 // See if all uses can be converted.
393 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
394 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000395 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000396 continue;
397 }
398
399 // If this is a constant sized memset of a constant value (e.g. 0) we can
400 // handle it.
401 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
402 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000403 if (!isa<ConstantInt>(MSI->getValue()) ||
404 !isa<ConstantInt>(MSI->getLength()))
405 return false;
406 IsNotTrivial = true; // Can't be mem2reg'd.
407 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000408 }
409
410 // If this is a memcpy or memmove into or out of the whole allocation, we
411 // can handle it like a load or store of the scalar type.
412 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000413 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
414 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
415 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000416
Chris Lattnera001b662010-04-16 00:38:19 +0000417 IsNotTrivial = true; // Can't be mem2reg'd.
418 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000419 }
Bob Wilson69743022011-01-13 20:59:44 +0000420
Chris Lattner4cc576b2010-04-16 00:24:57 +0000421 // Otherwise, we cannot handle this!
422 return false;
423 }
Bob Wilson69743022011-01-13 20:59:44 +0000424
Chris Lattner4cc576b2010-04-16 00:24:57 +0000425 return true;
426}
427
428/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
429/// directly. This happens when we are converting an "integer union" to a
430/// single integer scalar, or when we are converting a "vector union" to a
431/// vector with insert/extractelement instructions.
432///
433/// Offset is an offset from the original alloca, in bits that need to be
434/// shifted to the right. By the end of this, there should be no uses of Ptr.
435void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
436 uint64_t Offset) {
437 while (!Ptr->use_empty()) {
438 Instruction *User = cast<Instruction>(Ptr->use_back());
439
440 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
441 ConvertUsesToScalar(CI, NewAI, Offset);
442 CI->eraseFromParent();
443 continue;
444 }
445
446 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
447 // Compute the offset that this GEP adds to the pointer.
448 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
449 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
450 &Indices[0], Indices.size());
451 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
452 GEP->eraseFromParent();
453 continue;
454 }
Bob Wilson69743022011-01-13 20:59:44 +0000455
Chris Lattner61db1f52010-12-26 22:57:41 +0000456 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000457
Chris Lattner4cc576b2010-04-16 00:24:57 +0000458 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
459 // The load is a bit extract from NewAI shifted right by Offset bits.
460 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
461 Value *NewLoadVal
462 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
463 LI->replaceAllUsesWith(NewLoadVal);
464 LI->eraseFromParent();
465 continue;
466 }
Bob Wilson69743022011-01-13 20:59:44 +0000467
Chris Lattner4cc576b2010-04-16 00:24:57 +0000468 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
469 assert(SI->getOperand(0) != Ptr && "Consistency error!");
470 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
471 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
472 Builder);
473 Builder.CreateStore(New, NewAI);
474 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000475
Chris Lattner4cc576b2010-04-16 00:24:57 +0000476 // If the load we just inserted is now dead, then the inserted store
477 // overwrote the entire thing.
478 if (Old->use_empty())
479 Old->eraseFromParent();
480 continue;
481 }
Bob Wilson69743022011-01-13 20:59:44 +0000482
Chris Lattner4cc576b2010-04-16 00:24:57 +0000483 // If this is a constant sized memset of a constant value (e.g. 0) we can
484 // transform it into a store of the expanded constant value.
485 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
486 assert(MSI->getRawDest() == Ptr && "Consistency error!");
487 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
488 if (NumBytes != 0) {
489 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000490
Chris Lattner4cc576b2010-04-16 00:24:57 +0000491 // Compute the value replicated the right number of times.
492 APInt APVal(NumBytes*8, Val);
493
494 // Splat the value if non-zero.
495 if (Val)
496 for (unsigned i = 1; i != NumBytes; ++i)
497 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000498
Chris Lattner4cc576b2010-04-16 00:24:57 +0000499 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
500 Value *New = ConvertScalar_InsertValue(
501 ConstantInt::get(User->getContext(), APVal),
502 Old, Offset, Builder);
503 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000504
Chris Lattner4cc576b2010-04-16 00:24:57 +0000505 // If the load we just inserted is now dead, then the memset overwrote
506 // the entire thing.
507 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000508 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000509 }
510 MSI->eraseFromParent();
511 continue;
512 }
513
514 // If this is a memcpy or memmove into or out of the whole allocation, we
515 // can handle it like a load or store of the scalar type.
516 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
517 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000518
Chris Lattner4cc576b2010-04-16 00:24:57 +0000519 // If the source and destination are both to the same alloca, then this is
520 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
521 // as appropriate.
Dan Gohman5034dd32010-12-15 20:02:24 +0000522 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000523
Dan Gohman5034dd32010-12-15 20:02:24 +0000524 if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000525 // Dest must be OrigAI, change this to be a load from the original
526 // pointer (bitcasted), then a store to our new alloca.
527 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
528 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000529 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
530 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
531 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
532 AIPTy = PointerType::get(AIPTy->getElementType(),
533 SPTy->getAddressSpace());
534 }
535 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
536
Chris Lattner4cc576b2010-04-16 00:24:57 +0000537 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
538 SrcVal->setAlignment(MTI->getAlignment());
539 Builder.CreateStore(SrcVal, NewAI);
Dan Gohman5034dd32010-12-15 20:02:24 +0000540 } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000541 // Src must be OrigAI, change this to be a load from NewAI then a store
542 // through the original dest pointer (bitcasted).
543 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
544 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
545
Mon P Wange90a6332010-12-23 01:41:32 +0000546 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
547 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
548 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
549 AIPTy = PointerType::get(AIPTy->getElementType(),
550 DPTy->getAddressSpace());
551 }
552 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
553
Chris Lattner4cc576b2010-04-16 00:24:57 +0000554 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
555 NewStore->setAlignment(MTI->getAlignment());
556 } else {
557 // Noop transfer. Src == Dst
558 }
559
560 MTI->eraseFromParent();
561 continue;
562 }
Bob Wilson69743022011-01-13 20:59:44 +0000563
Chris Lattner4cc576b2010-04-16 00:24:57 +0000564 llvm_unreachable("Unsupported operation!");
565 }
566}
567
568/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
569/// or vector value FromVal, extracting the bits from the offset specified by
570/// Offset. This returns the value, which is of type ToType.
571///
572/// This happens when we are converting an "integer union" to a single
573/// integer scalar, or when we are converting a "vector union" to a vector with
574/// insert/extractelement instructions.
575///
576/// Offset is an offset from the original alloca, in bits that need to be
577/// shifted to the right.
578Value *ConvertToScalarInfo::
579ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
580 uint64_t Offset, IRBuilder<> &Builder) {
581 // If the load is of the whole new alloca, no conversion is needed.
582 if (FromVal->getType() == ToType && Offset == 0)
583 return FromVal;
584
585 // If the result alloca is a vector type, this is either an element
586 // access or a bitcast to another vector type of the same size.
587 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
588 if (ToType->isVectorTy())
589 return Builder.CreateBitCast(FromVal, ToType, "tmp");
590
591 // Otherwise it must be an element access.
592 unsigned Elt = 0;
593 if (Offset) {
594 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
595 Elt = Offset/EltSize;
596 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
597 }
598 // Return the element extracted out of it.
599 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
600 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
601 if (V->getType() != ToType)
602 V = Builder.CreateBitCast(V, ToType, "tmp");
603 return V;
604 }
Bob Wilson69743022011-01-13 20:59:44 +0000605
Chris Lattner4cc576b2010-04-16 00:24:57 +0000606 // If ToType is a first class aggregate, extract out each of the pieces and
607 // use insertvalue's to form the FCA.
608 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
609 const StructLayout &Layout = *TD.getStructLayout(ST);
610 Value *Res = UndefValue::get(ST);
611 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
612 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
613 Offset+Layout.getElementOffsetInBits(i),
614 Builder);
615 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
616 }
617 return Res;
618 }
Bob Wilson69743022011-01-13 20:59:44 +0000619
Chris Lattner4cc576b2010-04-16 00:24:57 +0000620 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
621 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
622 Value *Res = UndefValue::get(AT);
623 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
624 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
625 Offset+i*EltSize, Builder);
626 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
627 }
628 return Res;
629 }
630
631 // Otherwise, this must be a union that was converted to an integer value.
632 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
633
634 // If this is a big-endian system and the load is narrower than the
635 // full alloca type, we need to do a shift to get the right bits.
636 int ShAmt = 0;
637 if (TD.isBigEndian()) {
638 // On big-endian machines, the lowest bit is stored at the bit offset
639 // from the pointer given by getTypeStoreSizeInBits. This matters for
640 // integers with a bitwidth that is not a multiple of 8.
641 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
642 TD.getTypeStoreSizeInBits(ToType) - Offset;
643 } else {
644 ShAmt = Offset;
645 }
646
647 // Note: we support negative bitwidths (with shl) which are not defined.
648 // We do this to support (f.e.) loads off the end of a structure where
649 // only some bits are used.
650 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
651 FromVal = Builder.CreateLShr(FromVal,
652 ConstantInt::get(FromVal->getType(),
653 ShAmt), "tmp");
654 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000655 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000656 ConstantInt::get(FromVal->getType(),
657 -ShAmt), "tmp");
658
659 // Finally, unconditionally truncate the integer to the right width.
660 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
661 if (LIBitWidth < NTy->getBitWidth())
662 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000663 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000664 LIBitWidth), "tmp");
665 else if (LIBitWidth > NTy->getBitWidth())
666 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000667 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000668 LIBitWidth), "tmp");
669
670 // If the result is an integer, this is a trunc or bitcast.
671 if (ToType->isIntegerTy()) {
672 // Should be done.
673 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
674 // Just do a bitcast, we know the sizes match up.
675 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
676 } else {
677 // Otherwise must be a pointer.
678 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
679 }
680 assert(FromVal->getType() == ToType && "Didn't convert right?");
681 return FromVal;
682}
683
684/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
685/// or vector value "Old" at the offset specified by Offset.
686///
687/// This happens when we are converting an "integer union" to a
688/// single integer scalar, or when we are converting a "vector union" to a
689/// vector with insert/extractelement instructions.
690///
691/// Offset is an offset from the original alloca, in bits that need to be
692/// shifted to the right.
693Value *ConvertToScalarInfo::
694ConvertScalar_InsertValue(Value *SV, Value *Old,
695 uint64_t Offset, IRBuilder<> &Builder) {
696 // Convert the stored type to the actual type, shift it left to insert
697 // then 'or' into place.
698 const Type *AllocaType = Old->getType();
699 LLVMContext &Context = Old->getContext();
700
701 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
702 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
703 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000704
Chris Lattner4cc576b2010-04-16 00:24:57 +0000705 // Changing the whole vector with memset or with an access of a different
706 // vector type?
707 if (ValSize == VecSize)
708 return Builder.CreateBitCast(SV, AllocaType, "tmp");
709
710 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
711
712 // Must be an element insertion.
713 unsigned Elt = Offset/EltSize;
Bob Wilson69743022011-01-13 20:59:44 +0000714
Chris Lattner4cc576b2010-04-16 00:24:57 +0000715 if (SV->getType() != VTy->getElementType())
716 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000717
718 SV = Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000719 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
720 "tmp");
721 return SV;
722 }
Bob Wilson69743022011-01-13 20:59:44 +0000723
Chris Lattner4cc576b2010-04-16 00:24:57 +0000724 // If SV is a first-class aggregate value, insert each value recursively.
725 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
726 const StructLayout &Layout = *TD.getStructLayout(ST);
727 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
728 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000729 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000730 Offset+Layout.getElementOffsetInBits(i),
731 Builder);
732 }
733 return Old;
734 }
Bob Wilson69743022011-01-13 20:59:44 +0000735
Chris Lattner4cc576b2010-04-16 00:24:57 +0000736 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
737 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
738 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
739 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
740 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
741 }
742 return Old;
743 }
744
745 // If SV is a float, convert it to the appropriate integer type.
746 // If it is a pointer, do the same.
747 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
748 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
749 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
750 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
751 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
752 SV = Builder.CreateBitCast(SV,
753 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
754 else if (SV->getType()->isPointerTy())
755 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
756
757 // Zero extend or truncate the value if needed.
758 if (SV->getType() != AllocaType) {
759 if (SV->getType()->getPrimitiveSizeInBits() <
760 AllocaType->getPrimitiveSizeInBits())
761 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
762 else {
763 // Truncation may be needed if storing more than the alloca can hold
764 // (undefined behavior).
765 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
766 SrcWidth = DestWidth;
767 SrcStoreWidth = DestStoreWidth;
768 }
769 }
770
771 // If this is a big-endian system and the store is narrower than the
772 // full alloca type, we need to do a shift to get the right bits.
773 int ShAmt = 0;
774 if (TD.isBigEndian()) {
775 // On big-endian machines, the lowest bit is stored at the bit offset
776 // from the pointer given by getTypeStoreSizeInBits. This matters for
777 // integers with a bitwidth that is not a multiple of 8.
778 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
779 } else {
780 ShAmt = Offset;
781 }
782
783 // Note: we support negative bitwidths (with shr) which are not defined.
784 // We do this to support (f.e.) stores off the end of a structure where
785 // only some bits in the structure are set.
786 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
787 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
788 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
789 ShAmt), "tmp");
790 Mask <<= ShAmt;
791 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
792 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
793 -ShAmt), "tmp");
794 Mask = Mask.lshr(-ShAmt);
795 }
796
797 // Mask out the bits we are about to insert from the old value, and or
798 // in the new bits.
799 if (SrcWidth != DestWidth) {
800 assert(DestWidth > SrcWidth);
801 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
802 SV = Builder.CreateOr(Old, SV, "ins");
803 }
804 return SV;
805}
806
807
808//===----------------------------------------------------------------------===//
809// SRoA Driver
810//===----------------------------------------------------------------------===//
811
812
Chris Lattnered7b41e2003-05-27 15:45:27 +0000813bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000814 TD = getAnalysisIfAvailable<TargetData>();
815
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000816 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000817
818 // FIXME: ScalarRepl currently depends on TargetData more than it
819 // theoretically needs to. It should be refactored in order to support
820 // target-independent IR. Until this is done, just skip the actual
821 // scalar-replacement portion of this pass.
822 if (!TD) return Changed;
823
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000824 while (1) {
825 bool LocalChange = performScalarRepl(F);
826 if (!LocalChange) break; // No need to repromote if no scalarrepl
827 Changed = true;
828 LocalChange = performPromotion(F);
829 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
830 }
Chris Lattner38aec322003-09-11 16:45:55 +0000831
832 return Changed;
833}
834
Chris Lattnerd0f56132011-01-14 19:50:47 +0000835namespace {
836class AllocaPromoter : public LoadAndStorePromoter {
837 AllocaInst *AI;
838public:
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000839 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
840 : LoadAndStorePromoter(Insts, S), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +0000841
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000842 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +0000843 // Remember which alloca we're promoting (for isInstInList).
844 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000845 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +0000846 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000847 }
848
Chris Lattnerd0f56132011-01-14 19:50:47 +0000849 virtual bool isInstInList(Instruction *I,
850 const SmallVectorImpl<Instruction*> &Insts) const {
851 if (LoadInst *LI = dyn_cast<LoadInst>(I))
852 return LI->getOperand(0) == AI;
853 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000854 }
Chris Lattnerd0f56132011-01-14 19:50:47 +0000855};
856} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +0000857
858bool SROA::performPromotion(Function &F) {
859 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000860 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000861 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000862 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +0000863
Chris Lattner02a3be02003-09-20 14:39:18 +0000864 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000865
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000866 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000867 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +0000868 while (1) {
869 Allocas.clear();
870
871 // Find allocas that are safe to promote, by looking at all instructions in
872 // the entry node
873 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
874 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000875 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000876 Allocas.push_back(AI);
877
878 if (Allocas.empty()) break;
879
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000880 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +0000881 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000882 else {
883 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000884 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
885 AllocaInst *AI = Allocas[i];
886
887 // Build list of instructions to promote.
888 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
889 UI != E; ++UI)
890 Insts.push_back(cast<Instruction>(*UI));
891
892 AllocaPromoter(Insts, SSA).run(AI, Insts);
893 Insts.clear();
894 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000895 }
Chris Lattner38aec322003-09-11 16:45:55 +0000896 NumPromoted += Allocas.size();
897 Changed = true;
898 }
899
900 return Changed;
901}
902
Chris Lattner4cc576b2010-04-16 00:24:57 +0000903
Bob Wilson3992feb2010-02-03 17:23:56 +0000904/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
905/// SROA. It must be a struct or array type with a small number of elements.
906static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
907 const Type *T = AI->getAllocatedType();
908 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000909 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000910 return ST->getNumElements() <= 32;
911 // Arrays are much less likely to be safe for SROA; only consider
912 // them if they are very small.
913 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
914 return AT->getNumElements() <= 8;
915 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000916}
917
Chris Lattnerc4472072010-04-15 23:50:26 +0000918
Chris Lattner38aec322003-09-11 16:45:55 +0000919// performScalarRepl - This algorithm is a simple worklist driven algorithm,
920// which runs on all of the malloc/alloca instructions in the function, removing
921// them if they are only used by getelementptr instructions.
922//
923bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000924 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000925
Chris Lattner31d80102010-04-15 21:59:20 +0000926 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000927 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000928 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000929 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000930 WorkList.push_back(A);
931
932 // Process the worklist
933 bool Changed = false;
934 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000935 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000936 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +0000937
Chris Lattneradd2bd72006-12-22 23:14:42 +0000938 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
939 // with unused elements.
940 if (AI->use_empty()) {
941 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000942 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000943 continue;
944 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000945
946 // If this alloca is impossible for us to promote, reject it early.
947 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
948 continue;
Bob Wilson69743022011-01-13 20:59:44 +0000949
Chris Lattner79b3bd32007-04-25 06:40:51 +0000950 // Check to see if this allocation is only modified by a memcpy/memmove from
951 // a constant global. If this is the case, we can change all users to use
952 // the constant global instead. This is commonly produced by the CFE by
953 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
954 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000955 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000956 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
957 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000958 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000959 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000960 TheCopy->eraseFromParent(); // Don't mutate the global.
961 AI->eraseFromParent();
962 ++NumGlobals;
963 Changed = true;
964 continue;
965 }
Bob Wilson69743022011-01-13 20:59:44 +0000966
Chris Lattner7809ecd2009-02-03 01:30:09 +0000967 // Check to see if we can perform the core SROA transformation. We cannot
968 // transform the allocation instruction if it is an array allocation
969 // (allocations OF arrays are ok though), and an allocation of a scalar
970 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000971 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000972
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000973 // Do not promote [0 x %struct].
974 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +0000975
Chris Lattner31d80102010-04-15 21:59:20 +0000976 // Do not promote any struct whose size is too big.
977 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +0000978
Bob Wilson3992feb2010-02-03 17:23:56 +0000979 // If the alloca looks like a good candidate for scalar replacement, and if
980 // all its users can be transformed, then split up the aggregate into its
981 // separate elements.
982 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
983 DoScalarReplacement(AI, WorkList);
984 Changed = true;
985 continue;
986 }
987
Chris Lattner6e733d32009-01-28 20:16:43 +0000988 // If we can turn this aggregate value (potentially with casts) into a
989 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000990 // IsNotTrivial tracks whether this is something that mem2reg could have
991 // promoted itself. If so, we don't want to transform it needlessly. Note
992 // that we can't just check based on the type: the alloca may be of an i32
993 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000994 if (AllocaInst *NewAI =
995 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000996 NewAI->takeName(AI);
997 AI->eraseFromParent();
998 ++NumConverted;
999 Changed = true;
1000 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001001 }
1002
Chris Lattner7809ecd2009-02-03 01:30:09 +00001003 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001004 }
1005
1006 return Changed;
1007}
Chris Lattner5e062a12003-05-30 04:15:41 +00001008
Chris Lattnera10b29b2007-04-25 05:02:56 +00001009/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1010/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001011void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001012 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001013 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001014 SmallVector<AllocaInst*, 32> ElementAllocas;
1015 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1016 ElementAllocas.reserve(ST->getNumContainedTypes());
1017 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001018 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001019 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001020 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001021 ElementAllocas.push_back(NA);
1022 WorkList.push_back(NA); // Add to worklist for recursive processing
1023 }
1024 } else {
1025 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1026 ElementAllocas.reserve(AT->getNumElements());
1027 const Type *ElTy = AT->getElementType();
1028 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001029 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001030 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001031 ElementAllocas.push_back(NA);
1032 WorkList.push_back(NA); // Add to worklist for recursive processing
1033 }
1034 }
1035
Bob Wilsonb742def2009-12-18 20:14:40 +00001036 // Now that we have created the new alloca instructions, rewrite all the
1037 // uses of the old alloca.
1038 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001039
Bob Wilsonb742def2009-12-18 20:14:40 +00001040 // Now erase any instructions that were made dead while rewriting the alloca.
1041 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001042 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001043
Dan Gohmanfe601042010-06-22 15:08:57 +00001044 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001045}
Chris Lattnera59adc42009-12-14 05:11:02 +00001046
Bob Wilsonb742def2009-12-18 20:14:40 +00001047/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1048/// recursively including all their operands that become trivially dead.
1049void SROA::DeleteDeadInstructions() {
1050 while (!DeadInsts.empty()) {
1051 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001052
Bob Wilsonb742def2009-12-18 20:14:40 +00001053 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1054 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1055 // Zero out the operand and see if it becomes trivially dead.
1056 // (But, don't add allocas to the dead instruction list -- they are
1057 // already on the worklist and will be deleted separately.)
1058 *OI = 0;
1059 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1060 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001061 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001062
1063 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001064 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001065}
Bob Wilson69743022011-01-13 20:59:44 +00001066
Bob Wilsonb742def2009-12-18 20:14:40 +00001067/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1068/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001069/// the Info parameter. Offset indicates the position within AI that is
1070/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +00001071void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001072 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001073 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1074 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001075
Bob Wilsonb742def2009-12-18 20:14:40 +00001076 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001077 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001078 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001079 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001080 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001081 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001082 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001083 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001084 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001085 if (Length == 0)
1086 return MarkUnsafe(Info, User);
1087 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
1088 UI.getOperandNo() == 0, Info, MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001089 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001090 if (LI->isVolatile())
1091 return MarkUnsafe(Info, User);
1092 const Type *LIType = LI->getType();
1093 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
1094 LIType, false, Info, LI);
1095 Info.hasALoadOrStore = true;
1096
Bob Wilsonb742def2009-12-18 20:14:40 +00001097 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1098 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001099 if (SI->isVolatile() || SI->getOperand(0) == I)
1100 return MarkUnsafe(Info, User);
1101
1102 const Type *SIType = SI->getOperand(0)->getType();
1103 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
1104 SIType, true, Info, SI);
1105 Info.hasALoadOrStore = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001106 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001107 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001108 }
1109 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001110 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001111}
Bob Wilson39c88a62009-12-17 18:34:24 +00001112
Bob Wilsonb742def2009-12-18 20:14:40 +00001113/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1114/// replacement. It is safe when all the indices are constant, in-bounds
1115/// references, and when the resulting offset corresponds to an element within
1116/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001117/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001118void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001119 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001120 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1121 if (GEPIt == E)
1122 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001123
Chris Lattner88e6dc82008-08-23 05:21:06 +00001124 // Walk through the GEP type indices, checking the types that this indexes
1125 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001126 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001127 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001128 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001129 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001130
Bob Wilsonb742def2009-12-18 20:14:40 +00001131 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1132 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001133 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001134 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001135
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001136 // Compute the offset due to this GEP and check if the alloca has a
1137 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001138 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1139 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1140 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001141 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001142 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001143}
1144
Bob Wilson704d1342011-01-13 17:45:11 +00001145/// isHomogeneousAggregate - Check if type T is a struct or array containing
1146/// elements of the same type (which is always true for arrays). If so,
1147/// return true with NumElts and EltTy set to the number of elements and the
1148/// element type, respectively.
1149static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1150 const Type *&EltTy) {
1151 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1152 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001153 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001154 return true;
1155 }
1156 if (const StructType *ST = dyn_cast<StructType>(T)) {
1157 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001158 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001159 for (unsigned n = 1; n < NumElts; ++n) {
1160 if (ST->getContainedType(n) != EltTy)
1161 return false;
1162 }
1163 return true;
1164 }
1165 return false;
1166}
1167
1168/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1169/// "homogeneous" aggregates with the same element type and number of elements.
1170static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1171 if (T1 == T2)
1172 return true;
1173
1174 unsigned NumElts1, NumElts2;
1175 const Type *EltTy1, *EltTy2;
1176 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1177 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1178 NumElts1 == NumElts2 &&
1179 EltTy1 == EltTy2)
1180 return true;
1181
1182 return false;
1183}
1184
Bob Wilsonb742def2009-12-18 20:14:40 +00001185/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1186/// alloca or has an offset and size that corresponds to a component element
1187/// within it. The offset checked here may have been formed from a GEP with a
1188/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001189void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001190 const Type *MemOpType, bool isStore,
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001191 AllocaInfo &Info, Instruction *TheAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001192 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001193 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001194 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1195 // loads/stores (which are essentially the same as the MemIntrinsics with
1196 // regard to copying padding between elements). But, if an alloca is
1197 // flagged as both a source and destination of such operations, we'll need
1198 // to check later for padding between elements.
1199 if (!MemOpType || MemOpType->isIntegerTy()) {
1200 if (isStore)
1201 Info.isMemCpyDst = true;
1202 else
1203 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001204 return;
1205 }
Bob Wilson704d1342011-01-13 17:45:11 +00001206 // This is also safe for references using a type that is compatible with
1207 // the type of the alloca, so that loads/stores can be rewritten using
1208 // insertvalue/extractvalue.
Chris Lattner7e9b4272011-01-16 06:18:28 +00001209 if (isCompatibleAggregate(MemOpType, AI->getAllocatedType())) {
1210 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001211 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001212 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001213 }
1214 // Check if the offset/size correspond to a component within the alloca type.
1215 const Type *T = AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001216 if (TypeHasComponent(T, Offset, MemSize)) {
1217 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001218 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001219 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001220
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001221 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001222}
1223
1224/// TypeHasComponent - Return true if T has a component type with the
1225/// specified offset and size. If Size is zero, do not check the size.
1226bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1227 const Type *EltTy;
1228 uint64_t EltSize;
1229 if (const StructType *ST = dyn_cast<StructType>(T)) {
1230 const StructLayout *Layout = TD->getStructLayout(ST);
1231 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1232 EltTy = ST->getContainedType(EltIdx);
1233 EltSize = TD->getTypeAllocSize(EltTy);
1234 Offset -= Layout->getElementOffset(EltIdx);
1235 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1236 EltTy = AT->getElementType();
1237 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001238 if (Offset >= AT->getNumElements() * EltSize)
1239 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001240 Offset %= EltSize;
1241 } else {
1242 return false;
1243 }
1244 if (Offset == 0 && (Size == 0 || EltSize == Size))
1245 return true;
1246 // Check if the component spans multiple elements.
1247 if (Offset + Size > EltSize)
1248 return false;
1249 return TypeHasComponent(EltTy, Offset, Size);
1250}
1251
1252/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1253/// the instruction I, which references it, to use the separate elements.
1254/// Offset indicates the position within AI that is referenced by this
1255/// instruction.
1256void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1257 SmallVector<AllocaInst*, 32> &NewElts) {
1258 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1259 Instruction *User = cast<Instruction>(*UI);
1260
1261 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1262 RewriteBitCast(BC, AI, Offset, NewElts);
1263 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1264 RewriteGEP(GEPI, AI, Offset, NewElts);
1265 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1266 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1267 uint64_t MemSize = Length->getZExtValue();
1268 if (Offset == 0 &&
1269 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1270 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001271 // Otherwise the intrinsic can only touch a single element and the
1272 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001273 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1274 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001275
Bob Wilson704d1342011-01-13 17:45:11 +00001276 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001277 // Replace:
1278 // %res = load { i32, i32 }* %alloc
1279 // with:
1280 // %load.0 = load i32* %alloc.0
1281 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1282 // %load.1 = load i32* %alloc.1
1283 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1284 // (Also works for arrays instead of structs)
1285 Value *Insert = UndefValue::get(LIType);
1286 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1287 Value *Load = new LoadInst(NewElts[i], "load", LI);
1288 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1289 }
1290 LI->replaceAllUsesWith(Insert);
1291 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001292 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001293 TD->getTypeAllocSize(LIType) ==
1294 TD->getTypeAllocSize(AI->getAllocatedType())) {
1295 // If this is a load of the entire alloca to an integer, rewrite it.
1296 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1297 }
1298 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1299 Value *Val = SI->getOperand(0);
1300 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001301 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001302 // Replace:
1303 // store { i32, i32 } %val, { i32, i32 }* %alloc
1304 // with:
1305 // %val.0 = extractvalue { i32, i32 } %val, 0
1306 // store i32 %val.0, i32* %alloc.0
1307 // %val.1 = extractvalue { i32, i32 } %val, 1
1308 // store i32 %val.1, i32* %alloc.1
1309 // (Also works for arrays instead of structs)
1310 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1311 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1312 new StoreInst(Extract, NewElts[i], SI);
1313 }
1314 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001315 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001316 TD->getTypeAllocSize(SIType) ==
1317 TD->getTypeAllocSize(AI->getAllocatedType())) {
1318 // If this is a store of the entire alloca from an integer, rewrite it.
1319 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1320 }
1321 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001322 }
1323}
1324
Bob Wilsonb742def2009-12-18 20:14:40 +00001325/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1326/// and recursively continue updating all of its uses.
1327void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1328 SmallVector<AllocaInst*, 32> &NewElts) {
1329 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1330 if (BC->getOperand(0) != AI)
1331 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001332
Bob Wilsonb742def2009-12-18 20:14:40 +00001333 // The bitcast references the original alloca. Replace its uses with
1334 // references to the first new element alloca.
1335 Instruction *Val = NewElts[0];
1336 if (Val->getType() != BC->getDestTy()) {
1337 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1338 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001339 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001340 BC->replaceAllUsesWith(Val);
1341 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001342}
1343
Bob Wilsonb742def2009-12-18 20:14:40 +00001344/// FindElementAndOffset - Return the index of the element containing Offset
1345/// within the specified type, which must be either a struct or an array.
1346/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001347/// element. IdxTy is set to the type of the index result to be used in a
1348/// GEP instruction.
1349uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1350 const Type *&IdxTy) {
1351 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001352 if (const StructType *ST = dyn_cast<StructType>(T)) {
1353 const StructLayout *Layout = TD->getStructLayout(ST);
1354 Idx = Layout->getElementContainingOffset(Offset);
1355 T = ST->getContainedType(Idx);
1356 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001357 IdxTy = Type::getInt32Ty(T->getContext());
1358 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001359 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001360 const ArrayType *AT = cast<ArrayType>(T);
1361 T = AT->getElementType();
1362 uint64_t EltSize = TD->getTypeAllocSize(T);
1363 Idx = Offset / EltSize;
1364 Offset -= Idx * EltSize;
1365 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001366 return Idx;
1367}
1368
1369/// RewriteGEP - Check if this GEP instruction moves the pointer across
1370/// elements of the alloca that are being split apart, and if so, rewrite
1371/// the GEP to be relative to the new element.
1372void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1373 SmallVector<AllocaInst*, 32> &NewElts) {
1374 uint64_t OldOffset = Offset;
1375 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1376 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1377 &Indices[0], Indices.size());
1378
1379 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1380
1381 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001382 const Type *IdxTy;
1383 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001384 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001385 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001386
1387 T = AI->getAllocatedType();
1388 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001389 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001390
1391 // If this GEP does not move the pointer across elements of the alloca
1392 // being split, then it does not needs to be rewritten.
1393 if (Idx == OldIdx)
1394 return;
1395
1396 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1397 SmallVector<Value*, 8> NewArgs;
1398 NewArgs.push_back(Constant::getNullValue(i32Ty));
1399 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001400 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1401 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001402 }
1403 Instruction *Val = NewElts[Idx];
1404 if (NewArgs.size() > 1) {
1405 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1406 NewArgs.end(), "", GEPI);
1407 Val->takeName(GEPI);
1408 }
1409 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001410 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001411 GEPI->replaceAllUsesWith(Val);
1412 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001413}
1414
1415/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1416/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001417void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001418 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001419 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001420 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001421 // appropriate type. The "Other" pointer is the pointer that goes to memory
1422 // that doesn't have anything to do with the alloca that we are promoting. For
1423 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001424 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001425 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001426 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001427 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001428 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001429 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001430 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001431 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001432 }
1433 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001434
Chris Lattnerd93afec2009-01-07 07:18:45 +00001435 // If there is an other pointer, we want to convert it to the same pointer
1436 // type as AI has, so we can GEP through it safely.
1437 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001438 unsigned AddrSpace =
1439 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001440
1441 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1442 // optimization, but it's also required to detect the corner case where
1443 // both pointer operands are referencing the same memory, and where
1444 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1445 // function is only called for mem intrinsics that access the whole
1446 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001447 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00001448
Bob Wilsona756b1d2010-01-19 04:32:48 +00001449 // Copying the alloca to itself is a no-op: just delete it.
1450 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1451 // This code will run twice for a no-op memcpy -- once for each operand.
1452 // Put only one reference to MI on the DeadInsts list.
1453 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1454 E = DeadInsts.end(); I != E; ++I)
1455 if (*I == MI) return;
1456 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001457 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001458 }
Bob Wilson69743022011-01-13 20:59:44 +00001459
Chris Lattnerd93afec2009-01-07 07:18:45 +00001460 // If the pointer is not the right type, insert a bitcast to the right
1461 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001462 const Type *NewTy =
1463 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00001464
Chris Lattner0238f8c2010-07-08 00:27:05 +00001465 if (OtherPtr->getType() != NewTy)
1466 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001467 }
Bob Wilson69743022011-01-13 20:59:44 +00001468
Chris Lattnerd93afec2009-01-07 07:18:45 +00001469 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00001470 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00001471
Owen Anderson1d0be152009-08-13 21:58:54 +00001472 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001473
1474 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1475 // If this is a memcpy/memmove, emit a GEP of the other element address.
1476 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001477 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00001478
Bob Wilsona756b1d2010-01-19 04:32:48 +00001479 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001480 Value *Idx[2] = { Zero,
1481 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001482 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001483 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001484 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001485 uint64_t EltOffset;
1486 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001487 const Type *OtherTy = OtherPtrTy->getElementType();
1488 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001489 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1490 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001491 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001492 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001493 }
Bob Wilson69743022011-01-13 20:59:44 +00001494
Chris Lattner1541e0f2009-03-04 19:20:50 +00001495 // The alignment of the other pointer is the guaranteed alignment of the
1496 // element, which is affected by both the known alignment of the whole
1497 // mem intrinsic and the alignment of the element. If the alignment of
1498 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1499 // known alignment is just 4 bytes.
1500 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001501 }
Bob Wilson69743022011-01-13 20:59:44 +00001502
Chris Lattnerd93afec2009-01-07 07:18:45 +00001503 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001504 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00001505
Chris Lattnerd93afec2009-01-07 07:18:45 +00001506 // If we got down to a scalar, insert a load or store as appropriate.
1507 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001508 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001509 if (SROADest) {
1510 // From Other to Alloca.
1511 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1512 new StoreInst(Elt, EltPtr, MI);
1513 } else {
1514 // From Alloca to Other.
1515 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1516 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1517 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001518 continue;
1519 }
1520 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00001521
Chris Lattnerd93afec2009-01-07 07:18:45 +00001522 // If the stored element is zero (common case), just store a null
1523 // constant.
1524 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001525 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001526 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001527 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001528 } else {
1529 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001530 const Type *ValTy = EltTy->getScalarType();
1531
Chris Lattnerd93afec2009-01-07 07:18:45 +00001532 // Construct an integer with the right value.
1533 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1534 APInt OneVal(EltSize, CI->getZExtValue());
1535 APInt TotalVal(OneVal);
1536 // Set each byte.
1537 for (unsigned i = 0; 8*i < EltSize; ++i) {
1538 TotalVal = TotalVal.shl(8);
1539 TotalVal |= OneVal;
1540 }
Bob Wilson69743022011-01-13 20:59:44 +00001541
Chris Lattnerd93afec2009-01-07 07:18:45 +00001542 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001543 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001544 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001545 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001546 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001547 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001548 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00001549
Chris Lattnerd93afec2009-01-07 07:18:45 +00001550 // If the requested value was a vector constant, create it.
1551 if (EltTy != ValTy) {
1552 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1553 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001554 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001555 }
1556 }
1557 new StoreInst(StoreVal, EltPtr, MI);
1558 continue;
1559 }
1560 // Otherwise, if we're storing a byte variable, use a memset call for
1561 // this element.
1562 }
Bob Wilson69743022011-01-13 20:59:44 +00001563
Duncan Sands777d2302009-05-09 07:06:46 +00001564 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001565
Chris Lattner61db1f52010-12-26 22:57:41 +00001566 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00001567
Chris Lattnerd93afec2009-01-07 07:18:45 +00001568 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00001569 if (isa<MemSetInst>(MI)) {
1570 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1571 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001572 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00001573 assert(isa<MemTransferInst>(MI));
1574 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
1575 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00001576
Chris Lattner61db1f52010-12-26 22:57:41 +00001577 if (isa<MemCpyInst>(MI))
1578 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1579 else
1580 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001581 }
Chris Lattner372dda82007-03-05 07:52:57 +00001582 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001583 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001584}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001585
Bob Wilson39fdd692009-12-04 21:57:37 +00001586/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001587/// overwrites the entire allocation. Extract out the pieces of the stored
1588/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001589void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001590 SmallVector<AllocaInst*, 32> &NewElts){
1591 // Extract each element out of the integer according to its structure offset
1592 // and store the element value to the individual alloca.
1593 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001594 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001595 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001596
Chris Lattner70728532011-01-16 05:58:24 +00001597 IRBuilder<> Builder(SI);
1598
Eli Friedman41b33f42009-06-01 09:14:32 +00001599 // Handle tail padding by extending the operand
1600 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001601 SrcVal = Builder.CreateZExt(SrcVal,
1602 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001603
David Greene504c7d82010-01-05 01:27:09 +00001604 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001605 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001606
1607 // There are two forms here: AI could be an array or struct. Both cases
1608 // have different ways to compute the element offset.
1609 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1610 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00001611
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001612 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1613 // Get the number of bits to shift SrcVal to get the value.
1614 const Type *FieldTy = EltSTy->getElementType(i);
1615 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00001616
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001617 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001618 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001619
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001620 Value *EltVal = SrcVal;
1621 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001622 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001623 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001624 }
Bob Wilson69743022011-01-13 20:59:44 +00001625
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001626 // Truncate down to an integer of the right size.
1627 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001628
Chris Lattner583dd602009-01-09 18:18:43 +00001629 // Ignore zero sized fields like {}, they obviously contain no data.
1630 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001631
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001632 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001633 EltVal = Builder.CreateTrunc(EltVal,
1634 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001635 Value *DestField = NewElts[i];
1636 if (EltVal->getType() == FieldTy) {
1637 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001638 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001639 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00001640 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001641 } else {
1642 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00001643 DestField = Builder.CreateBitCast(DestField,
1644 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001645 }
1646 new StoreInst(EltVal, DestField, SI);
1647 }
Bob Wilson69743022011-01-13 20:59:44 +00001648
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001649 } else {
1650 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1651 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001652 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001653 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1654
1655 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00001656
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001657 if (TD->isBigEndian())
1658 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001659 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001660 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00001661
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001662 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001663 // Ignore zero sized fields like {}, they obviously contain no data.
1664 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001665
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001666 Value *EltVal = SrcVal;
1667 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001668 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001669 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001670 }
Bob Wilson69743022011-01-13 20:59:44 +00001671
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001672 // Truncate down to an integer of the right size.
1673 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001674 EltVal = Builder.CreateTrunc(EltVal,
1675 IntegerType::get(SI->getContext(),
1676 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001677 Value *DestField = NewElts[i];
1678 if (EltVal->getType() == ArrayEltTy) {
1679 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001680 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001681 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001682 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00001683 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001684 } else {
1685 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00001686 DestField = Builder.CreateBitCast(DestField,
1687 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001688 }
1689 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00001690
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001691 if (TD->isBigEndian())
1692 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001693 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001694 Shift += ElementOffset;
1695 }
1696 }
Bob Wilson69743022011-01-13 20:59:44 +00001697
Bob Wilsonb742def2009-12-18 20:14:40 +00001698 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001699}
1700
Bob Wilson39fdd692009-12-04 21:57:37 +00001701/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001702/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001703void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001704 SmallVector<AllocaInst*, 32> &NewElts) {
1705 // Extract each element out of the NewElts according to its structure offset
1706 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001707 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001708 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001709
David Greene504c7d82010-01-05 01:27:09 +00001710 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001711 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00001712
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001713 // There are two forms here: AI could be an array or struct. Both cases
1714 // have different ways to compute the element offset.
1715 const StructLayout *Layout = 0;
1716 uint64_t ArrayEltBitOffset = 0;
1717 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1718 Layout = TD->getStructLayout(EltSTy);
1719 } else {
1720 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001721 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001722 }
1723
1724 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001725 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00001726
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001727 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1728 // Load the value from the alloca. If the NewElt is an aggregate, cast
1729 // the pointer to an integer of the same size before doing the load.
1730 Value *SrcField = NewElts[i];
1731 const Type *FieldTy =
1732 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001733 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001734
Chris Lattner583dd602009-01-09 18:18:43 +00001735 // Ignore zero sized fields like {}, they obviously contain no data.
1736 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001737
1738 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00001739 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001740 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1741 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001742 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001743 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001744 "", LI);
1745 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1746
1747 // If SrcField is a fp or vector of the right size but that isn't an
1748 // integer type, bitcast to an integer so we can shift it.
1749 if (SrcField->getType() != FieldIntTy)
1750 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1751
1752 // Zero extend the field to be the same size as the final alloca so that
1753 // we can shift and insert it.
1754 if (SrcField->getType() != ResultVal->getType())
1755 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00001756
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001757 // Determine the number of bits to shift SrcField.
1758 uint64_t Shift;
1759 if (Layout) // Struct case.
1760 Shift = Layout->getElementOffsetInBits(i);
1761 else // Array case.
1762 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001763
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001764 if (TD->isBigEndian())
1765 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00001766
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001767 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001768 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001769 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1770 }
1771
Chris Lattner14952472010-06-27 07:58:26 +00001772 // Don't create an 'or x, 0' on the first iteration.
1773 if (!isa<Constant>(ResultVal) ||
1774 !cast<Constant>(ResultVal)->isNullValue())
1775 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1776 else
1777 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001778 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001779
1780 // Handle tail padding by truncating the result
1781 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1782 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1783
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001784 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001785 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001786}
1787
Duncan Sands3cb36502007-11-04 14:43:57 +00001788/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00001789/// alignment padding in between the elements that would be split apart
1790/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001791static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00001792 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1793 Ty = ATy->getElementType();
1794 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001795 }
Bob Wilson694a10e2011-01-13 17:45:08 +00001796
1797 // SROA currently handles only Arrays and Structs.
1798 const StructType *STy = cast<StructType>(Ty);
1799 const StructLayout *SL = TD.getStructLayout(STy);
1800 unsigned PrevFieldBitOffset = 0;
1801 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1802 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1803
1804 // Check to see if there is any padding between this element and the
1805 // previous one.
1806 if (i) {
1807 unsigned PrevFieldEnd =
1808 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1809 if (PrevFieldEnd < FieldBitOffset)
1810 return true;
1811 }
1812 PrevFieldBitOffset = FieldBitOffset;
1813 }
1814 // Check for tail padding.
1815 if (unsigned EltCount = STy->getNumElements()) {
1816 unsigned PrevFieldEnd = PrevFieldBitOffset +
1817 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1818 if (PrevFieldEnd < SL->getSizeInBits())
1819 return true;
1820 }
1821 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00001822}
Chris Lattner372dda82007-03-05 07:52:57 +00001823
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001824/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1825/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1826/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001827bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001828 // Loop over the use list of the alloca. We can only transform it if all of
1829 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001830 AllocaInfo Info;
Bob Wilson69743022011-01-13 20:59:44 +00001831
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001832 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001833 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001834 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001835 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001836 }
Bob Wilson69743022011-01-13 20:59:44 +00001837
Chris Lattner39a1c042007-05-30 06:11:23 +00001838 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1839 // source and destination, we have to be careful. In particular, the memcpy
1840 // could be moving around elements that live in structure padding of the LLVM
1841 // types, but may actually be used. In these cases, we refuse to promote the
1842 // struct.
1843 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001844 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001845 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001846
Chris Lattner396a0562011-01-16 17:46:19 +00001847 // If the alloca never has an access to just *part* of it, but is accessed
1848 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00001849 // the alloca instead of promoting each piece at a time and inserting fission
1850 // and fusion code.
1851 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
1852 // If the struct/array just has one element, use basic SRoA.
1853 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1854 if (ST->getNumElements() > 1) return false;
1855 } else {
1856 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
1857 return false;
1858 }
1859 }
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001860 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001861}
Chris Lattnera1888942005-12-12 07:19:13 +00001862
Chris Lattner800de312008-02-29 07:03:13 +00001863
Chris Lattner79b3bd32007-04-25 06:40:51 +00001864
1865/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1866/// some part of a constant global variable. This intentionally only accepts
1867/// constant expressions because we don't can't rewrite arbitrary instructions.
1868static bool PointsToConstantGlobal(Value *V) {
1869 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1870 return GV->isConstant();
1871 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00001872 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00001873 CE->getOpcode() == Instruction::GetElementPtr)
1874 return PointsToConstantGlobal(CE->getOperand(0));
1875 return false;
1876}
1877
1878/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1879/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1880/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1881/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1882/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00001883/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00001884/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001885static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001886 bool isOffset) {
1887 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001888 User *U = cast<Instruction>(*UI);
1889
Chris Lattner2e618492010-11-18 06:20:47 +00001890 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001891 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00001892 if (LI->isVolatile()) return false;
1893 continue;
1894 }
Bob Wilson69743022011-01-13 20:59:44 +00001895
Gabor Greif8a8a4352010-04-06 19:32:30 +00001896 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001897 // If uses of the bitcast are ok, we are ok.
1898 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1899 return false;
1900 continue;
1901 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001902 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001903 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1904 // doesn't, it does.
1905 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1906 isOffset || !GEP->hasAllZeroIndices()))
1907 return false;
1908 continue;
1909 }
Bob Wilson69743022011-01-13 20:59:44 +00001910
Chris Lattner62480652010-11-18 06:41:51 +00001911 if (CallSite CS = U) {
1912 // If this is a readonly/readnone call site, then we know it is just a
1913 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00001914 if (CS.onlyReadsMemory())
1915 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00001916
1917 // If this is the function being called then we treat it like a load and
1918 // ignore it.
1919 if (CS.isCallee(UI))
1920 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001921
Chris Lattner62480652010-11-18 06:41:51 +00001922 // If this is being passed as a byval argument, the caller is making a
1923 // copy, so it is only a read of the alloca.
1924 unsigned ArgNo = CS.getArgumentNo(UI);
1925 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
1926 continue;
1927 }
Bob Wilson69743022011-01-13 20:59:44 +00001928
Chris Lattner79b3bd32007-04-25 06:40:51 +00001929 // If this is isn't our memcpy/memmove, reject it as something we can't
1930 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001931 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1932 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001933 return false;
Bob Wilson69743022011-01-13 20:59:44 +00001934
Chris Lattner2e618492010-11-18 06:20:47 +00001935 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00001936 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00001937 if (UI.getOperandNo() == 1) {
1938 if (MI->isVolatile()) return false;
1939 continue;
1940 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00001941
1942 // If we already have seen a copy, reject the second one.
1943 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00001944
Chris Lattner79b3bd32007-04-25 06:40:51 +00001945 // If the pointer has been offset from the start of the alloca, we can't
1946 // safely handle this.
1947 if (isOffset) return false;
1948
1949 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001950 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00001951
Chris Lattner79b3bd32007-04-25 06:40:51 +00001952 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001953 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001954 return false;
Bob Wilson69743022011-01-13 20:59:44 +00001955
Chris Lattner79b3bd32007-04-25 06:40:51 +00001956 // Otherwise, the transform is safe. Remember the copy instruction.
1957 TheCopy = MI;
1958 }
1959 return true;
1960}
1961
1962/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1963/// modified by a copy from a constant global. If we can prove this, we can
1964/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001965MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1966 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001967 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1968 return TheCopy;
1969 return 0;
1970}