blob: 8fb2e582e1e8b82b81d92c05de6de64ac65e39fb [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 Lattner372dda82007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000049STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000052 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000054 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000055 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000056 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000057 else
58 SRThreshold = T;
59 }
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnered7b41e2003-05-27 15:45:27 +000061 bool runOnFunction(Function &F);
62
Chris Lattner38aec322003-09-11 16:45:55 +000063 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
65
Chris Lattnera15854c2003-08-31 00:45:13 +000066 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000069 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000070 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000071 AU.setPreservesCFG();
72 }
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
76
Bob Wilsonb742def2009-12-18 20:14:40 +000077 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
80
Chris Lattner39a1c042007-05-30 06:11:23 +000081 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
84 struct AllocaInfo {
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
86 bool isUnsafe : 1;
87
Chris Lattner39a1c042007-05-30 06:11:23 +000088 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 bool isMemCpySrc : 1;
90
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000091 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000092 bool isMemCpyDst : 1;
93
94 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +000095 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +000096 };
97
Devang Patelff366852007-07-09 21:19:23 +000098 unsigned SRThreshold;
99
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
101
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000102 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000103
Bob Wilsonb742def2009-12-18 20:14:40 +0000104 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000105 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000106 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000107 AllocaInfo &Info);
108 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
109 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000110 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000111 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
112 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000113
Victor Hernandez7b929da2009-10-23 21:09:37 +0000114 void DoScalarReplacement(AllocaInst *AI,
115 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000116 void DeleteDeadInstructions();
Victor Hernandez7b929da2009-10-23 21:09:37 +0000117 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000118
Bob Wilsonb742def2009-12-18 20:14:40 +0000119 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
120 SmallVector<AllocaInst*, 32> &NewElts);
121 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000126 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000127 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000132
Chris Lattner31d80102010-04-15 21:59:20 +0000133 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000134 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000135}
136
Dan Gohman844731a2008-05-13 00:00:25 +0000137char SROA::ID = 0;
138static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
139
Brian Gaeked0fde302003-11-11 22:41:34 +0000140// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000141FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
142 return new SROA(Threshold);
143}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000144
145
Chris Lattner4cc576b2010-04-16 00:24:57 +0000146//===----------------------------------------------------------------------===//
147// Convert To Scalar Optimization.
148//===----------------------------------------------------------------------===//
149
150namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000151/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
152/// optimization, which scans the uses of an alloca and determines if it can
153/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000154class ConvertToScalarInfo {
155 /// AllocaSize - The size of the alloca being considered.
156 unsigned AllocaSize;
157 const TargetData &TD;
158
Chris Lattnera0bada72010-04-16 02:32:17 +0000159 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000160 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000161 bool IsNotTrivial;
Chris Lattnera001b662010-04-16 00:38:19 +0000162
163 /// VectorTy - This tracks the type that we should promote the vector to if
164 /// it is possible to turn it into a vector. This starts out null, and if it
165 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000166 const Type *VectorTy;
Chris Lattnera001b662010-04-16 00:38:19 +0000167
168 /// HadAVector - True if there is at least one vector access to the alloca.
169 /// We don't want to turn random arrays into vectors and use vector element
170 /// insert/extract, but if there are element accesses to something that is
171 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000172 bool HadAVector;
173
174public:
175 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
176 : AllocaSize(Size), TD(td) {
177 IsNotTrivial = false;
178 VectorTy = 0;
179 HadAVector = false;
180 }
181
Chris Lattnera001b662010-04-16 00:38:19 +0000182 AllocaInst *TryConvert(AllocaInst *AI);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000183
184private:
185 bool CanConvertToScalar(Value *V, uint64_t Offset);
186 void MergeInType(const Type *In, uint64_t Offset);
187 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
188
189 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
190 uint64_t Offset, IRBuilder<> &Builder);
191 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
192 uint64_t Offset, IRBuilder<> &Builder);
193};
194} // end anonymous namespace.
195
Chris Lattnera001b662010-04-16 00:38:19 +0000196/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
197/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
198/// alloca if possible or null if not.
199AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
200 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
201 // out.
202 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
203 return 0;
204
205 // If we were able to find a vector type that can handle this with
206 // insert/extract elements, and if there was at least one use that had
207 // a vector type, promote this to a vector. We don't want to promote
208 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
209 // we just get a lot of insert/extracts. If at least one vector is
210 // involved, then we probably really do have a union of vector/array.
211 const Type *NewTy;
212 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
213 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
214 << *VectorTy << '\n');
215 NewTy = VectorTy; // Use the vector type.
216 } else {
217 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
218 // Create and insert the integer alloca.
219 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
220 }
221 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
222 ConvertUsesToScalar(AI, NewAI, 0);
223 return NewAI;
224}
225
226/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
227/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000228///
229/// There are two cases we handle here:
230/// 1) A union of vector types of the same size and potentially its elements.
231/// Here we turn element accesses into insert/extract element operations.
232/// This promotes a <4 x float> with a store of float to the third element
233/// into a <4 x float> that uses insert element.
234/// 2) A fully general blob of memory, which we turn into some (potentially
235/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000236/// and stores would mutate the memory. We mark this by setting VectorTy
237/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000238void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000239 // If we already decided to turn this into a blob of integer memory, there is
240 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000241 if (VectorTy && VectorTy->isVoidTy())
242 return;
243
244 // If this could be contributing to a vector, analyze it.
245
246 // If the In type is a vector that is the same size as the alloca, see if it
247 // matches the existing VecTy.
248 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000249 // Remember if we saw a vector type.
250 HadAVector = true;
251
Chris Lattner4cc576b2010-04-16 00:24:57 +0000252 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
253 // If we're storing/loading a vector of the right size, allow it as a
254 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000255 // we know the element size. If this is a subsequent access, ignore it
256 // even if it is a differing type but the same size. Worst case we can
257 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000258 if (VectorTy == 0)
259 VectorTy = VInTy;
260 return;
261 }
262 } else if (In->isFloatTy() || In->isDoubleTy() ||
263 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
264 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
265 // If we're accessing something that could be an element of a vector, see
266 // if the implied vector agrees with what we already have and if Offset is
267 // compatible with it.
268 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
269 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
270 (VectorTy == 0 ||
271 cast<VectorType>(VectorTy)->getElementType()
272 ->getPrimitiveSizeInBits()/8 == EltSize)) {
273 if (VectorTy == 0)
274 VectorTy = VectorType::get(In, AllocaSize/EltSize);
275 return;
276 }
277 }
278
279 // Otherwise, we have a case that we can't handle with an optimized vector
280 // form. We can still turn this into a large integer.
281 VectorTy = Type::getVoidTy(In->getContext());
282}
283
284/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
285/// its accesses to a single vector type, return true and set VecTy to
286/// the new type. If we could convert the alloca into a single promotable
287/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
288/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
289/// is the current offset from the base of the alloca being analyzed.
290///
291/// If we see at least one access to the value that is as a vector type, set the
292/// SawVec flag.
293bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
294 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
295 Instruction *User = cast<Instruction>(*UI);
296
297 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
298 // Don't break volatile loads.
299 if (LI->isVolatile())
300 return false;
301 MergeInType(LI->getType(), Offset);
302 continue;
303 }
304
305 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
306 // Storing the pointer, not into the value?
307 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
308 MergeInType(SI->getOperand(0)->getType(), Offset);
309 continue;
310 }
311
312 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000313 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000314 if (!CanConvertToScalar(BCI, Offset))
315 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000316 continue;
317 }
318
319 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
320 // If this is a GEP with a variable indices, we can't handle it.
321 if (!GEP->hasAllConstantIndices())
322 return false;
323
324 // Compute the offset that this GEP adds to the pointer.
325 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
326 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
327 &Indices[0], Indices.size());
328 // See if all uses can be converted.
329 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
330 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000331 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000332 continue;
333 }
334
335 // If this is a constant sized memset of a constant value (e.g. 0) we can
336 // handle it.
337 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
338 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000339 if (!isa<ConstantInt>(MSI->getValue()) ||
340 !isa<ConstantInt>(MSI->getLength()))
341 return false;
342 IsNotTrivial = true; // Can't be mem2reg'd.
343 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000344 }
345
346 // If this is a memcpy or memmove into or out of the whole allocation, we
347 // can handle it like a load or store of the scalar type.
348 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000349 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
350 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
351 return false;
352
353 IsNotTrivial = true; // Can't be mem2reg'd.
354 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000355 }
356
357 // Otherwise, we cannot handle this!
358 return false;
359 }
360
361 return true;
362}
363
364/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
365/// directly. This happens when we are converting an "integer union" to a
366/// single integer scalar, or when we are converting a "vector union" to a
367/// vector with insert/extractelement instructions.
368///
369/// Offset is an offset from the original alloca, in bits that need to be
370/// shifted to the right. By the end of this, there should be no uses of Ptr.
371void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
372 uint64_t Offset) {
373 while (!Ptr->use_empty()) {
374 Instruction *User = cast<Instruction>(Ptr->use_back());
375
376 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
377 ConvertUsesToScalar(CI, NewAI, Offset);
378 CI->eraseFromParent();
379 continue;
380 }
381
382 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
383 // Compute the offset that this GEP adds to the pointer.
384 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
385 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
386 &Indices[0], Indices.size());
387 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
388 GEP->eraseFromParent();
389 continue;
390 }
391
392 IRBuilder<> Builder(User->getParent(), User);
393
394 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
395 // The load is a bit extract from NewAI shifted right by Offset bits.
396 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
397 Value *NewLoadVal
398 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
399 LI->replaceAllUsesWith(NewLoadVal);
400 LI->eraseFromParent();
401 continue;
402 }
403
404 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
405 assert(SI->getOperand(0) != Ptr && "Consistency error!");
406 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
407 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
408 Builder);
409 Builder.CreateStore(New, NewAI);
410 SI->eraseFromParent();
411
412 // If the load we just inserted is now dead, then the inserted store
413 // overwrote the entire thing.
414 if (Old->use_empty())
415 Old->eraseFromParent();
416 continue;
417 }
418
419 // If this is a constant sized memset of a constant value (e.g. 0) we can
420 // transform it into a store of the expanded constant value.
421 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
422 assert(MSI->getRawDest() == Ptr && "Consistency error!");
423 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
424 if (NumBytes != 0) {
425 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
426
427 // Compute the value replicated the right number of times.
428 APInt APVal(NumBytes*8, Val);
429
430 // Splat the value if non-zero.
431 if (Val)
432 for (unsigned i = 1; i != NumBytes; ++i)
433 APVal |= APVal << 8;
434
435 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
436 Value *New = ConvertScalar_InsertValue(
437 ConstantInt::get(User->getContext(), APVal),
438 Old, Offset, Builder);
439 Builder.CreateStore(New, NewAI);
440
441 // If the load we just inserted is now dead, then the memset overwrote
442 // the entire thing.
443 if (Old->use_empty())
444 Old->eraseFromParent();
445 }
446 MSI->eraseFromParent();
447 continue;
448 }
449
450 // If this is a memcpy or memmove into or out of the whole allocation, we
451 // can handle it like a load or store of the scalar type.
452 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
453 assert(Offset == 0 && "must be store to start of alloca");
454
455 // If the source and destination are both to the same alloca, then this is
456 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
457 // as appropriate.
458 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
459
460 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
461 // Dest must be OrigAI, change this to be a load from the original
462 // pointer (bitcasted), then a store to our new alloca.
463 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
464 Value *SrcPtr = MTI->getSource();
465 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
466
467 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
468 SrcVal->setAlignment(MTI->getAlignment());
469 Builder.CreateStore(SrcVal, NewAI);
470 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
471 // Src must be OrigAI, change this to be a load from NewAI then a store
472 // through the original dest pointer (bitcasted).
473 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
474 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
475
476 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
477 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
478 NewStore->setAlignment(MTI->getAlignment());
479 } else {
480 // Noop transfer. Src == Dst
481 }
482
483 MTI->eraseFromParent();
484 continue;
485 }
486
487 llvm_unreachable("Unsupported operation!");
488 }
489}
490
491/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
492/// or vector value FromVal, extracting the bits from the offset specified by
493/// Offset. This returns the value, which is of type ToType.
494///
495/// This happens when we are converting an "integer union" to a single
496/// integer scalar, or when we are converting a "vector union" to a vector with
497/// insert/extractelement instructions.
498///
499/// Offset is an offset from the original alloca, in bits that need to be
500/// shifted to the right.
501Value *ConvertToScalarInfo::
502ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
503 uint64_t Offset, IRBuilder<> &Builder) {
504 // If the load is of the whole new alloca, no conversion is needed.
505 if (FromVal->getType() == ToType && Offset == 0)
506 return FromVal;
507
508 // If the result alloca is a vector type, this is either an element
509 // access or a bitcast to another vector type of the same size.
510 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
511 if (ToType->isVectorTy())
512 return Builder.CreateBitCast(FromVal, ToType, "tmp");
513
514 // Otherwise it must be an element access.
515 unsigned Elt = 0;
516 if (Offset) {
517 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
518 Elt = Offset/EltSize;
519 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
520 }
521 // Return the element extracted out of it.
522 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
523 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
524 if (V->getType() != ToType)
525 V = Builder.CreateBitCast(V, ToType, "tmp");
526 return V;
527 }
528
529 // If ToType is a first class aggregate, extract out each of the pieces and
530 // use insertvalue's to form the FCA.
531 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
532 const StructLayout &Layout = *TD.getStructLayout(ST);
533 Value *Res = UndefValue::get(ST);
534 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
535 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
536 Offset+Layout.getElementOffsetInBits(i),
537 Builder);
538 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
539 }
540 return Res;
541 }
542
543 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
544 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
545 Value *Res = UndefValue::get(AT);
546 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
547 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
548 Offset+i*EltSize, Builder);
549 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
550 }
551 return Res;
552 }
553
554 // Otherwise, this must be a union that was converted to an integer value.
555 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
556
557 // If this is a big-endian system and the load is narrower than the
558 // full alloca type, we need to do a shift to get the right bits.
559 int ShAmt = 0;
560 if (TD.isBigEndian()) {
561 // On big-endian machines, the lowest bit is stored at the bit offset
562 // from the pointer given by getTypeStoreSizeInBits. This matters for
563 // integers with a bitwidth that is not a multiple of 8.
564 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
565 TD.getTypeStoreSizeInBits(ToType) - Offset;
566 } else {
567 ShAmt = Offset;
568 }
569
570 // Note: we support negative bitwidths (with shl) which are not defined.
571 // We do this to support (f.e.) loads off the end of a structure where
572 // only some bits are used.
573 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
574 FromVal = Builder.CreateLShr(FromVal,
575 ConstantInt::get(FromVal->getType(),
576 ShAmt), "tmp");
577 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
578 FromVal = Builder.CreateShl(FromVal,
579 ConstantInt::get(FromVal->getType(),
580 -ShAmt), "tmp");
581
582 // Finally, unconditionally truncate the integer to the right width.
583 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
584 if (LIBitWidth < NTy->getBitWidth())
585 FromVal =
586 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
587 LIBitWidth), "tmp");
588 else if (LIBitWidth > NTy->getBitWidth())
589 FromVal =
590 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
591 LIBitWidth), "tmp");
592
593 // If the result is an integer, this is a trunc or bitcast.
594 if (ToType->isIntegerTy()) {
595 // Should be done.
596 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
597 // Just do a bitcast, we know the sizes match up.
598 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
599 } else {
600 // Otherwise must be a pointer.
601 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
602 }
603 assert(FromVal->getType() == ToType && "Didn't convert right?");
604 return FromVal;
605}
606
607/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
608/// or vector value "Old" at the offset specified by Offset.
609///
610/// This happens when we are converting an "integer union" to a
611/// single integer scalar, or when we are converting a "vector union" to a
612/// vector with insert/extractelement instructions.
613///
614/// Offset is an offset from the original alloca, in bits that need to be
615/// shifted to the right.
616Value *ConvertToScalarInfo::
617ConvertScalar_InsertValue(Value *SV, Value *Old,
618 uint64_t Offset, IRBuilder<> &Builder) {
619 // Convert the stored type to the actual type, shift it left to insert
620 // then 'or' into place.
621 const Type *AllocaType = Old->getType();
622 LLVMContext &Context = Old->getContext();
623
624 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
625 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
626 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
627
628 // Changing the whole vector with memset or with an access of a different
629 // vector type?
630 if (ValSize == VecSize)
631 return Builder.CreateBitCast(SV, AllocaType, "tmp");
632
633 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
634
635 // Must be an element insertion.
636 unsigned Elt = Offset/EltSize;
637
638 if (SV->getType() != VTy->getElementType())
639 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
640
641 SV = Builder.CreateInsertElement(Old, SV,
642 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
643 "tmp");
644 return SV;
645 }
646
647 // If SV is a first-class aggregate value, insert each value recursively.
648 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
649 const StructLayout &Layout = *TD.getStructLayout(ST);
650 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
651 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
652 Old = ConvertScalar_InsertValue(Elt, Old,
653 Offset+Layout.getElementOffsetInBits(i),
654 Builder);
655 }
656 return Old;
657 }
658
659 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
660 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
661 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
662 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
663 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
664 }
665 return Old;
666 }
667
668 // If SV is a float, convert it to the appropriate integer type.
669 // If it is a pointer, do the same.
670 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
671 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
672 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
673 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
674 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
675 SV = Builder.CreateBitCast(SV,
676 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
677 else if (SV->getType()->isPointerTy())
678 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
679
680 // Zero extend or truncate the value if needed.
681 if (SV->getType() != AllocaType) {
682 if (SV->getType()->getPrimitiveSizeInBits() <
683 AllocaType->getPrimitiveSizeInBits())
684 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
685 else {
686 // Truncation may be needed if storing more than the alloca can hold
687 // (undefined behavior).
688 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
689 SrcWidth = DestWidth;
690 SrcStoreWidth = DestStoreWidth;
691 }
692 }
693
694 // If this is a big-endian system and the store is narrower than the
695 // full alloca type, we need to do a shift to get the right bits.
696 int ShAmt = 0;
697 if (TD.isBigEndian()) {
698 // On big-endian machines, the lowest bit is stored at the bit offset
699 // from the pointer given by getTypeStoreSizeInBits. This matters for
700 // integers with a bitwidth that is not a multiple of 8.
701 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
702 } else {
703 ShAmt = Offset;
704 }
705
706 // Note: we support negative bitwidths (with shr) which are not defined.
707 // We do this to support (f.e.) stores off the end of a structure where
708 // only some bits in the structure are set.
709 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
710 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
711 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
712 ShAmt), "tmp");
713 Mask <<= ShAmt;
714 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
715 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
716 -ShAmt), "tmp");
717 Mask = Mask.lshr(-ShAmt);
718 }
719
720 // Mask out the bits we are about to insert from the old value, and or
721 // in the new bits.
722 if (SrcWidth != DestWidth) {
723 assert(DestWidth > SrcWidth);
724 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
725 SV = Builder.CreateOr(Old, SV, "ins");
726 }
727 return SV;
728}
729
730
731//===----------------------------------------------------------------------===//
732// SRoA Driver
733//===----------------------------------------------------------------------===//
734
735
Chris Lattnered7b41e2003-05-27 15:45:27 +0000736bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000737 TD = getAnalysisIfAvailable<TargetData>();
738
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000739 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000740
741 // FIXME: ScalarRepl currently depends on TargetData more than it
742 // theoretically needs to. It should be refactored in order to support
743 // target-independent IR. Until this is done, just skip the actual
744 // scalar-replacement portion of this pass.
745 if (!TD) return Changed;
746
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000747 while (1) {
748 bool LocalChange = performScalarRepl(F);
749 if (!LocalChange) break; // No need to repromote if no scalarrepl
750 Changed = true;
751 LocalChange = performPromotion(F);
752 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
753 }
Chris Lattner38aec322003-09-11 16:45:55 +0000754
755 return Changed;
756}
757
758
759bool SROA::performPromotion(Function &F) {
760 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000761 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000762 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000763
Chris Lattner02a3be02003-09-20 14:39:18 +0000764 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000765
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000766 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000767
Chris Lattner38aec322003-09-11 16:45:55 +0000768 while (1) {
769 Allocas.clear();
770
771 // Find allocas that are safe to promote, by looking at all instructions in
772 // the entry node
773 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
774 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000775 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000776 Allocas.push_back(AI);
777
778 if (Allocas.empty()) break;
779
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000780 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000781 NumPromoted += Allocas.size();
782 Changed = true;
783 }
784
785 return Changed;
786}
787
Chris Lattner4cc576b2010-04-16 00:24:57 +0000788
Bob Wilson3992feb2010-02-03 17:23:56 +0000789/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
790/// SROA. It must be a struct or array type with a small number of elements.
791static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
792 const Type *T = AI->getAllocatedType();
793 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000794 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000795 return ST->getNumElements() <= 32;
796 // Arrays are much less likely to be safe for SROA; only consider
797 // them if they are very small.
798 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
799 return AT->getNumElements() <= 8;
800 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000801}
802
Chris Lattnerc4472072010-04-15 23:50:26 +0000803
Chris Lattner38aec322003-09-11 16:45:55 +0000804// performScalarRepl - This algorithm is a simple worklist driven algorithm,
805// which runs on all of the malloc/alloca instructions in the function, removing
806// them if they are only used by getelementptr instructions.
807//
808bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000809 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000810
Chris Lattner31d80102010-04-15 21:59:20 +0000811 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000812 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000813 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000814 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000815 WorkList.push_back(A);
816
817 // Process the worklist
818 bool Changed = false;
819 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000820 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000821 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000822
Chris Lattneradd2bd72006-12-22 23:14:42 +0000823 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
824 // with unused elements.
825 if (AI->use_empty()) {
826 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000827 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000828 continue;
829 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000830
831 // If this alloca is impossible for us to promote, reject it early.
832 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
833 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000834
835 // Check to see if this allocation is only modified by a memcpy/memmove from
836 // a constant global. If this is the case, we can change all users to use
837 // the constant global instead. This is commonly produced by the CFE by
838 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
839 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000840 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000841 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
842 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000843 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000844 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000845 TheCopy->eraseFromParent(); // Don't mutate the global.
846 AI->eraseFromParent();
847 ++NumGlobals;
848 Changed = true;
849 continue;
850 }
Chris Lattner15c82772009-02-02 20:44:45 +0000851
Chris Lattner7809ecd2009-02-03 01:30:09 +0000852 // Check to see if we can perform the core SROA transformation. We cannot
853 // transform the allocation instruction if it is an array allocation
854 // (allocations OF arrays are ok though), and an allocation of a scalar
855 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000856 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000857
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000858 // Do not promote [0 x %struct].
859 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000860
861 // Do not promote any struct whose size is too big.
862 if (AllocaSize > SRThreshold) continue;
863
Bob Wilson3992feb2010-02-03 17:23:56 +0000864 // If the alloca looks like a good candidate for scalar replacement, and if
865 // all its users can be transformed, then split up the aggregate into its
866 // separate elements.
867 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
868 DoScalarReplacement(AI, WorkList);
869 Changed = true;
870 continue;
871 }
872
Chris Lattner6e733d32009-01-28 20:16:43 +0000873 // If we can turn this aggregate value (potentially with casts) into a
874 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000875 // IsNotTrivial tracks whether this is something that mem2reg could have
876 // promoted itself. If so, we don't want to transform it needlessly. Note
877 // that we can't just check based on the type: the alloca may be of an i32
878 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000879 if (AllocaInst *NewAI =
880 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000881 NewAI->takeName(AI);
882 AI->eraseFromParent();
883 ++NumConverted;
884 Changed = true;
885 continue;
Chris Lattner593375d2010-04-16 00:20:00 +0000886 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000887
Chris Lattner7809ecd2009-02-03 01:30:09 +0000888 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000889 }
890
891 return Changed;
892}
Chris Lattner5e062a12003-05-30 04:15:41 +0000893
Chris Lattnera10b29b2007-04-25 05:02:56 +0000894/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
895/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000896void SROA::DoScalarReplacement(AllocaInst *AI,
897 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000898 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000899 SmallVector<AllocaInst*, 32> ElementAllocas;
900 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
901 ElementAllocas.reserve(ST->getNumContainedTypes());
902 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000903 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000904 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000905 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000906 ElementAllocas.push_back(NA);
907 WorkList.push_back(NA); // Add to worklist for recursive processing
908 }
909 } else {
910 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
911 ElementAllocas.reserve(AT->getNumElements());
912 const Type *ElTy = AT->getElementType();
913 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000914 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000915 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000916 ElementAllocas.push_back(NA);
917 WorkList.push_back(NA); // Add to worklist for recursive processing
918 }
919 }
920
Bob Wilsonb742def2009-12-18 20:14:40 +0000921 // Now that we have created the new alloca instructions, rewrite all the
922 // uses of the old alloca.
923 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000924
Bob Wilsonb742def2009-12-18 20:14:40 +0000925 // Now erase any instructions that were made dead while rewriting the alloca.
926 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000927 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000928
Dan Gohmanfe601042010-06-22 15:08:57 +0000929 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000930}
Chris Lattnera59adc42009-12-14 05:11:02 +0000931
Bob Wilsonb742def2009-12-18 20:14:40 +0000932/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
933/// recursively including all their operands that become trivially dead.
934void SROA::DeleteDeadInstructions() {
935 while (!DeadInsts.empty()) {
936 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000937
Bob Wilsonb742def2009-12-18 20:14:40 +0000938 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
939 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
940 // Zero out the operand and see if it becomes trivially dead.
941 // (But, don't add allocas to the dead instruction list -- they are
942 // already on the worklist and will be deleted separately.)
943 *OI = 0;
944 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
945 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000946 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000947
948 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000949 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000950}
Bob Wilsonb742def2009-12-18 20:14:40 +0000951
Bob Wilsonb742def2009-12-18 20:14:40 +0000952/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
953/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000954/// the Info parameter. Offset indicates the position within AI that is
955/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000956void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000957 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000958 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
959 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000960
Bob Wilsonb742def2009-12-18 20:14:40 +0000961 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000962 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000963 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000964 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000965 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000966 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000967 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +0000968 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000969 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
970 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000971 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000972 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000973 else
974 MarkUnsafe(Info);
975 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
976 if (!LI->isVolatile()) {
977 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000978 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000979 LIType, false, Info);
980 } else
981 MarkUnsafe(Info);
982 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
983 // Store is ok if storing INTO the pointer, not storing the pointer
984 if (!SI->isVolatile() && SI->getOperand(0) != I) {
985 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000986 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000987 SIType, true, Info);
988 } else
989 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000990 } else {
991 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
992 MarkUnsafe(Info);
993 }
994 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000995 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000996}
Bob Wilson39c88a62009-12-17 18:34:24 +0000997
Bob Wilsonb742def2009-12-18 20:14:40 +0000998/// isSafeGEP - Check if a GEP instruction can be handled for scalar
999/// replacement. It is safe when all the indices are constant, in-bounds
1000/// references, and when the resulting offset corresponds to an element within
1001/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001002/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001003void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001004 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001005 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1006 if (GEPIt == E)
1007 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001008
Chris Lattner88e6dc82008-08-23 05:21:06 +00001009 // Walk through the GEP type indices, checking the types that this indexes
1010 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001011 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001012 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001013 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001014 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001015
Bob Wilsonb742def2009-12-18 20:14:40 +00001016 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1017 if (!IdxVal)
1018 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001019 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001020
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001021 // Compute the offset due to this GEP and check if the alloca has a
1022 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001023 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1024 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1025 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001026 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1027 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001028}
1029
Bob Wilsonb742def2009-12-18 20:14:40 +00001030/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1031/// alloca or has an offset and size that corresponds to a component element
1032/// within it. The offset checked here may have been formed from a GEP with a
1033/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001034void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001035 const Type *MemOpType, bool isStore,
1036 AllocaInfo &Info) {
1037 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001038 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001039 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1040 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1041 // (which are essentially the same as the MemIntrinsics, especially with
1042 // regard to copying padding between elements), or references using the
1043 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +00001044 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001045 if (!UsesAggregateType) {
1046 if (isStore)
1047 Info.isMemCpyDst = true;
1048 else
1049 Info.isMemCpySrc = true;
1050 }
1051 return;
1052 }
1053 }
1054 // Check if the offset/size correspond to a component within the alloca type.
1055 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001056 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +00001057 return;
1058
1059 return MarkUnsafe(Info);
1060}
1061
1062/// TypeHasComponent - Return true if T has a component type with the
1063/// specified offset and size. If Size is zero, do not check the size.
1064bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1065 const Type *EltTy;
1066 uint64_t EltSize;
1067 if (const StructType *ST = dyn_cast<StructType>(T)) {
1068 const StructLayout *Layout = TD->getStructLayout(ST);
1069 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1070 EltTy = ST->getContainedType(EltIdx);
1071 EltSize = TD->getTypeAllocSize(EltTy);
1072 Offset -= Layout->getElementOffset(EltIdx);
1073 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1074 EltTy = AT->getElementType();
1075 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001076 if (Offset >= AT->getNumElements() * EltSize)
1077 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001078 Offset %= EltSize;
1079 } else {
1080 return false;
1081 }
1082 if (Offset == 0 && (Size == 0 || EltSize == Size))
1083 return true;
1084 // Check if the component spans multiple elements.
1085 if (Offset + Size > EltSize)
1086 return false;
1087 return TypeHasComponent(EltTy, Offset, Size);
1088}
1089
1090/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1091/// the instruction I, which references it, to use the separate elements.
1092/// Offset indicates the position within AI that is referenced by this
1093/// instruction.
1094void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1095 SmallVector<AllocaInst*, 32> &NewElts) {
1096 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1097 Instruction *User = cast<Instruction>(*UI);
1098
1099 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1100 RewriteBitCast(BC, AI, Offset, NewElts);
1101 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1102 RewriteGEP(GEPI, AI, Offset, NewElts);
1103 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1104 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1105 uint64_t MemSize = Length->getZExtValue();
1106 if (Offset == 0 &&
1107 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1108 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001109 // Otherwise the intrinsic can only touch a single element and the
1110 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001111 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1112 const Type *LIType = LI->getType();
1113 if (LIType == AI->getAllocatedType()) {
1114 // Replace:
1115 // %res = load { i32, i32 }* %alloc
1116 // with:
1117 // %load.0 = load i32* %alloc.0
1118 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1119 // %load.1 = load i32* %alloc.1
1120 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1121 // (Also works for arrays instead of structs)
1122 Value *Insert = UndefValue::get(LIType);
1123 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1124 Value *Load = new LoadInst(NewElts[i], "load", LI);
1125 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1126 }
1127 LI->replaceAllUsesWith(Insert);
1128 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001129 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001130 TD->getTypeAllocSize(LIType) ==
1131 TD->getTypeAllocSize(AI->getAllocatedType())) {
1132 // If this is a load of the entire alloca to an integer, rewrite it.
1133 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1134 }
1135 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1136 Value *Val = SI->getOperand(0);
1137 const Type *SIType = Val->getType();
1138 if (SIType == AI->getAllocatedType()) {
1139 // Replace:
1140 // store { i32, i32 } %val, { i32, i32 }* %alloc
1141 // with:
1142 // %val.0 = extractvalue { i32, i32 } %val, 0
1143 // store i32 %val.0, i32* %alloc.0
1144 // %val.1 = extractvalue { i32, i32 } %val, 1
1145 // store i32 %val.1, i32* %alloc.1
1146 // (Also works for arrays instead of structs)
1147 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1148 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1149 new StoreInst(Extract, NewElts[i], SI);
1150 }
1151 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001152 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001153 TD->getTypeAllocSize(SIType) ==
1154 TD->getTypeAllocSize(AI->getAllocatedType())) {
1155 // If this is a store of the entire alloca from an integer, rewrite it.
1156 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1157 }
1158 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001159 }
1160}
1161
Bob Wilsonb742def2009-12-18 20:14:40 +00001162/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1163/// and recursively continue updating all of its uses.
1164void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1165 SmallVector<AllocaInst*, 32> &NewElts) {
1166 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1167 if (BC->getOperand(0) != AI)
1168 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001169
Bob Wilsonb742def2009-12-18 20:14:40 +00001170 // The bitcast references the original alloca. Replace its uses with
1171 // references to the first new element alloca.
1172 Instruction *Val = NewElts[0];
1173 if (Val->getType() != BC->getDestTy()) {
1174 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1175 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001176 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001177 BC->replaceAllUsesWith(Val);
1178 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001179}
1180
Bob Wilsonb742def2009-12-18 20:14:40 +00001181/// FindElementAndOffset - Return the index of the element containing Offset
1182/// within the specified type, which must be either a struct or an array.
1183/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001184/// element. IdxTy is set to the type of the index result to be used in a
1185/// GEP instruction.
1186uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1187 const Type *&IdxTy) {
1188 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001189 if (const StructType *ST = dyn_cast<StructType>(T)) {
1190 const StructLayout *Layout = TD->getStructLayout(ST);
1191 Idx = Layout->getElementContainingOffset(Offset);
1192 T = ST->getContainedType(Idx);
1193 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001194 IdxTy = Type::getInt32Ty(T->getContext());
1195 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001196 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001197 const ArrayType *AT = cast<ArrayType>(T);
1198 T = AT->getElementType();
1199 uint64_t EltSize = TD->getTypeAllocSize(T);
1200 Idx = Offset / EltSize;
1201 Offset -= Idx * EltSize;
1202 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001203 return Idx;
1204}
1205
1206/// RewriteGEP - Check if this GEP instruction moves the pointer across
1207/// elements of the alloca that are being split apart, and if so, rewrite
1208/// the GEP to be relative to the new element.
1209void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1210 SmallVector<AllocaInst*, 32> &NewElts) {
1211 uint64_t OldOffset = Offset;
1212 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1213 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1214 &Indices[0], Indices.size());
1215
1216 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1217
1218 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001219 const Type *IdxTy;
1220 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001221 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001222 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001223
1224 T = AI->getAllocatedType();
1225 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001226 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001227
1228 // If this GEP does not move the pointer across elements of the alloca
1229 // being split, then it does not needs to be rewritten.
1230 if (Idx == OldIdx)
1231 return;
1232
1233 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1234 SmallVector<Value*, 8> NewArgs;
1235 NewArgs.push_back(Constant::getNullValue(i32Ty));
1236 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001237 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1238 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001239 }
1240 Instruction *Val = NewElts[Idx];
1241 if (NewArgs.size() > 1) {
1242 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1243 NewArgs.end(), "", GEPI);
1244 Val->takeName(GEPI);
1245 }
1246 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001247 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001248 GEPI->replaceAllUsesWith(Val);
1249 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001250}
1251
1252/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1253/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001254void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001255 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001256 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001257 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001258 // appropriate type. The "Other" pointer is the pointer that goes to memory
1259 // that doesn't have anything to do with the alloca that we are promoting. For
1260 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001261 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001262 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001263 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001264 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001265 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001266 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001267 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001268 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001269 }
1270 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001271
Chris Lattnerd93afec2009-01-07 07:18:45 +00001272 // If there is an other pointer, we want to convert it to the same pointer
1273 // type as AI has, so we can GEP through it safely.
1274 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001275 unsigned AddrSpace =
1276 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001277
1278 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1279 // optimization, but it's also required to detect the corner case where
1280 // both pointer operands are referencing the same memory, and where
1281 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1282 // function is only called for mem intrinsics that access the whole
1283 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001284 OtherPtr = OtherPtr->stripPointerCasts();
1285
Bob Wilsona756b1d2010-01-19 04:32:48 +00001286 // Copying the alloca to itself is a no-op: just delete it.
1287 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1288 // This code will run twice for a no-op memcpy -- once for each operand.
1289 // Put only one reference to MI on the DeadInsts list.
1290 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1291 E = DeadInsts.end(); I != E; ++I)
1292 if (*I == MI) return;
1293 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001294 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001295 }
Chris Lattner372dda82007-03-05 07:52:57 +00001296
Chris Lattnerd93afec2009-01-07 07:18:45 +00001297 // If the pointer is not the right type, insert a bitcast to the right
1298 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001299 const Type *NewTy =
1300 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1301
1302 if (OtherPtr->getType() != NewTy)
1303 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001304 }
1305
1306 // Process each element of the aggregate.
Gabor Greifa9b23132010-04-20 13:13:04 +00001307 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001308 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +00001309 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +00001310
Owen Anderson1d0be152009-08-13 21:58:54 +00001311 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001312
1313 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1314 // If this is a memcpy/memmove, emit a GEP of the other element address.
1315 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001316 unsigned OtherEltAlign = MemAlignment;
1317
Bob Wilsona756b1d2010-01-19 04:32:48 +00001318 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001319 Value *Idx[2] = { Zero,
1320 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001321 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001322 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001323 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001324 uint64_t EltOffset;
1325 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001326 const Type *OtherTy = OtherPtrTy->getElementType();
1327 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001328 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1329 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001330 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001331 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001332 }
1333
1334 // The alignment of the other pointer is the guaranteed alignment of the
1335 // element, which is affected by both the known alignment of the whole
1336 // mem intrinsic and the alignment of the element. If the alignment of
1337 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1338 // known alignment is just 4 bytes.
1339 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001340 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001341
1342 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001343 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001344
1345 // If we got down to a scalar, insert a load or store as appropriate.
1346 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001347 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001348 if (SROADest) {
1349 // From Other to Alloca.
1350 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1351 new StoreInst(Elt, EltPtr, MI);
1352 } else {
1353 // From Alloca to Other.
1354 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1355 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1356 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001357 continue;
1358 }
1359 assert(isa<MemSetInst>(MI));
1360
1361 // If the stored element is zero (common case), just store a null
1362 // constant.
1363 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001364 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001365 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001366 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001367 } else {
1368 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001369 const Type *ValTy = EltTy->getScalarType();
1370
Chris Lattnerd93afec2009-01-07 07:18:45 +00001371 // Construct an integer with the right value.
1372 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1373 APInt OneVal(EltSize, CI->getZExtValue());
1374 APInt TotalVal(OneVal);
1375 // Set each byte.
1376 for (unsigned i = 0; 8*i < EltSize; ++i) {
1377 TotalVal = TotalVal.shl(8);
1378 TotalVal |= OneVal;
1379 }
1380
1381 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001382 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001383 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001384 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001385 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001386 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001387 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1388
1389 // If the requested value was a vector constant, create it.
1390 if (EltTy != ValTy) {
1391 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1392 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001393 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001394 }
1395 }
1396 new StoreInst(StoreVal, EltPtr, MI);
1397 continue;
1398 }
1399 // Otherwise, if we're storing a byte variable, use a memset call for
1400 // this element.
1401 }
1402
1403 // Cast the element pointer to BytePtrTy.
1404 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001405 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001406
1407 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +00001408 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1409 // Preserve address space of OtherElt
1410 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1411 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1412 if (OtherPTy->getElementType() != PTy->getElementType()) {
1413 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1414 OtherPTy->getAddressSpace());
1415 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
1416 OtherElt->getNameStr(), MI);
1417 }
1418 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001419
Duncan Sands777d2302009-05-09 07:06:46 +00001420 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001421
1422 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001423 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001424 Value *Ops[] = {
1425 SROADest ? EltPtr : OtherElt, // Dest ptr
1426 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001427 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +00001428 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +00001429 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1430 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +00001431 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001432 // In case we fold the address space overloaded memcpy of A to B
1433 // with memcpy of B to C, change the function to be a memcpy of A to C.
1434 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1435 Ops[2]->getType() };
1436 Module *M = MI->getParent()->getParent()->getParent();
1437 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1438 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001439 } else {
1440 assert(isa<MemSetInst>(MI));
1441 Value *Ops[] = {
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001442 EltPtr, MI->getArgOperand(1), // Dest, Value,
1443 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +00001444 Zero, // Align
1445 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +00001446 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001447 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1448 Module *M = MI->getParent()->getParent()->getParent();
1449 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1450 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001451 }
Chris Lattner372dda82007-03-05 07:52:57 +00001452 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001453 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001454}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001455
Bob Wilson39fdd692009-12-04 21:57:37 +00001456/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001457/// overwrites the entire allocation. Extract out the pieces of the stored
1458/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001459void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001460 SmallVector<AllocaInst*, 32> &NewElts){
1461 // Extract each element out of the integer according to its structure offset
1462 // and store the element value to the individual alloca.
1463 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001464 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001465 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001466
Eli Friedman41b33f42009-06-01 09:14:32 +00001467 // Handle tail padding by extending the operand
1468 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001469 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001470 IntegerType::get(SI->getContext(), AllocaSizeBits),
1471 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001472
David Greene504c7d82010-01-05 01:27:09 +00001473 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001474 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001475
1476 // There are two forms here: AI could be an array or struct. Both cases
1477 // have different ways to compute the element offset.
1478 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1479 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1480
1481 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1482 // Get the number of bits to shift SrcVal to get the value.
1483 const Type *FieldTy = EltSTy->getElementType(i);
1484 uint64_t Shift = Layout->getElementOffsetInBits(i);
1485
1486 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001487 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001488
1489 Value *EltVal = SrcVal;
1490 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001491 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001492 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1493 "sroa.store.elt", SI);
1494 }
1495
1496 // Truncate down to an integer of the right size.
1497 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +00001498
1499 // Ignore zero sized fields like {}, they obviously contain no data.
1500 if (FieldSizeBits == 0) continue;
1501
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001502 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001503 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001504 IntegerType::get(SI->getContext(), FieldSizeBits),
1505 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001506 Value *DestField = NewElts[i];
1507 if (EltVal->getType() == FieldTy) {
1508 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001509 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001510 // Bitcast to the right element type (for fp/vector values).
1511 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1512 } else {
1513 // Otherwise, bitcast the dest pointer (for aggregates).
1514 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001515 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001516 "", SI);
1517 }
1518 new StoreInst(EltVal, DestField, SI);
1519 }
1520
1521 } else {
1522 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1523 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001524 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001525 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1526
1527 uint64_t Shift;
1528
1529 if (TD->isBigEndian())
1530 Shift = AllocaSizeBits-ElementOffset;
1531 else
1532 Shift = 0;
1533
1534 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001535 // Ignore zero sized fields like {}, they obviously contain no data.
1536 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001537
1538 Value *EltVal = SrcVal;
1539 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001540 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001541 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1542 "sroa.store.elt", SI);
1543 }
1544
1545 // Truncate down to an integer of the right size.
1546 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001547 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001548 IntegerType::get(SI->getContext(),
1549 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001550 Value *DestField = NewElts[i];
1551 if (EltVal->getType() == ArrayEltTy) {
1552 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001553 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001554 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001555 // Bitcast to the right element type (for fp/vector values).
1556 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1557 } else {
1558 // Otherwise, bitcast the dest pointer (for aggregates).
1559 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001560 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001561 "", SI);
1562 }
1563 new StoreInst(EltVal, DestField, SI);
1564
1565 if (TD->isBigEndian())
1566 Shift -= ElementOffset;
1567 else
1568 Shift += ElementOffset;
1569 }
1570 }
1571
Bob Wilsonb742def2009-12-18 20:14:40 +00001572 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001573}
1574
Bob Wilson39fdd692009-12-04 21:57:37 +00001575/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001576/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001577void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001578 SmallVector<AllocaInst*, 32> &NewElts) {
1579 // Extract each element out of the NewElts according to its structure offset
1580 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001581 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001582 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001583
David Greene504c7d82010-01-05 01:27:09 +00001584 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001585 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001586
1587 // There are two forms here: AI could be an array or struct. Both cases
1588 // have different ways to compute the element offset.
1589 const StructLayout *Layout = 0;
1590 uint64_t ArrayEltBitOffset = 0;
1591 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1592 Layout = TD->getStructLayout(EltSTy);
1593 } else {
1594 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001595 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001596 }
Owen Andersone922c022009-07-22 00:24:57 +00001597
Owen Andersone922c022009-07-22 00:24:57 +00001598 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001599 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001600
1601 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1602 // Load the value from the alloca. If the NewElt is an aggregate, cast
1603 // the pointer to an integer of the same size before doing the load.
1604 Value *SrcField = NewElts[i];
1605 const Type *FieldTy =
1606 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001607 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1608
1609 // Ignore zero sized fields like {}, they obviously contain no data.
1610 if (FieldSizeBits == 0) continue;
1611
Owen Anderson1d0be152009-08-13 21:58:54 +00001612 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1613 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001614 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1615 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001616 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001617 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001618 "", LI);
1619 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1620
1621 // If SrcField is a fp or vector of the right size but that isn't an
1622 // integer type, bitcast to an integer so we can shift it.
1623 if (SrcField->getType() != FieldIntTy)
1624 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1625
1626 // Zero extend the field to be the same size as the final alloca so that
1627 // we can shift and insert it.
1628 if (SrcField->getType() != ResultVal->getType())
1629 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1630
1631 // Determine the number of bits to shift SrcField.
1632 uint64_t Shift;
1633 if (Layout) // Struct case.
1634 Shift = Layout->getElementOffsetInBits(i);
1635 else // Array case.
1636 Shift = i*ArrayEltBitOffset;
1637
1638 if (TD->isBigEndian())
1639 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1640
1641 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001642 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001643 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1644 }
1645
Chris Lattner14952472010-06-27 07:58:26 +00001646 // Don't create an 'or x, 0' on the first iteration.
1647 if (!isa<Constant>(ResultVal) ||
1648 !cast<Constant>(ResultVal)->isNullValue())
1649 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1650 else
1651 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001652 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001653
1654 // Handle tail padding by truncating the result
1655 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1656 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1657
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001658 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001659 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001660}
1661
Duncan Sands3cb36502007-11-04 14:43:57 +00001662/// HasPadding - Return true if the specified type has any structure or
1663/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001664static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001665 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1666 const StructLayout *SL = TD.getStructLayout(STy);
1667 unsigned PrevFieldBitOffset = 0;
1668 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001669 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1670
Chris Lattner39a1c042007-05-30 06:11:23 +00001671 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001672 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001673 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001674
Chris Lattner39a1c042007-05-30 06:11:23 +00001675 // Check to see if there is any padding between this element and the
1676 // previous one.
1677 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001678 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001679 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1680 if (PrevFieldEnd < FieldBitOffset)
1681 return true;
1682 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001683
Chris Lattner39a1c042007-05-30 06:11:23 +00001684 PrevFieldBitOffset = FieldBitOffset;
1685 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001686
Chris Lattner39a1c042007-05-30 06:11:23 +00001687 // Check for tail padding.
1688 if (unsigned EltCount = STy->getNumElements()) {
1689 unsigned PrevFieldEnd = PrevFieldBitOffset +
1690 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001691 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001692 return true;
1693 }
1694
1695 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001696 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001697 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001698 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001699 }
Duncan Sands777d2302009-05-09 07:06:46 +00001700 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001701}
Chris Lattner372dda82007-03-05 07:52:57 +00001702
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001703/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1704/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1705/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001706bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001707 // Loop over the use list of the alloca. We can only transform it if all of
1708 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001709 AllocaInfo Info;
1710
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001711 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001712 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001713 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001714 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001715 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001716
1717 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1718 // source and destination, we have to be careful. In particular, the memcpy
1719 // could be moving around elements that live in structure padding of the LLVM
1720 // types, but may actually be used. In these cases, we refuse to promote the
1721 // struct.
1722 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001723 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001724 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001725
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001726 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001727}
Chris Lattnera1888942005-12-12 07:19:13 +00001728
Chris Lattner800de312008-02-29 07:03:13 +00001729
Chris Lattner79b3bd32007-04-25 06:40:51 +00001730
1731/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1732/// some part of a constant global variable. This intentionally only accepts
1733/// constant expressions because we don't can't rewrite arbitrary instructions.
1734static bool PointsToConstantGlobal(Value *V) {
1735 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1736 return GV->isConstant();
1737 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1738 if (CE->getOpcode() == Instruction::BitCast ||
1739 CE->getOpcode() == Instruction::GetElementPtr)
1740 return PointsToConstantGlobal(CE->getOperand(0));
1741 return false;
1742}
1743
1744/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1745/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1746/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1747/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1748/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1749/// the alloca, and if the source pointer is a pointer to a constant global, we
1750/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001751static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001752 bool isOffset) {
1753 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001754 User *U = cast<Instruction>(*UI);
1755
1756 if (LoadInst *LI = dyn_cast<LoadInst>(U))
Chris Lattner6e733d32009-01-28 20:16:43 +00001757 // Ignore non-volatile loads, they are always ok.
1758 if (!LI->isVolatile())
1759 continue;
1760
Gabor Greif8a8a4352010-04-06 19:32:30 +00001761 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001762 // If uses of the bitcast are ok, we are ok.
1763 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1764 return false;
1765 continue;
1766 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001767 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001768 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1769 // doesn't, it does.
1770 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1771 isOffset || !GEP->hasAllZeroIndices()))
1772 return false;
1773 continue;
1774 }
1775
1776 // If this is isn't our memcpy/memmove, reject it as something we can't
1777 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001778 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1779 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001780 return false;
1781
1782 // If we already have seen a copy, reject the second one.
1783 if (TheCopy) return false;
1784
1785 // If the pointer has been offset from the start of the alloca, we can't
1786 // safely handle this.
1787 if (isOffset) return false;
1788
1789 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001790 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001791
Chris Lattner79b3bd32007-04-25 06:40:51 +00001792 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001793 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001794 return false;
1795
1796 // Otherwise, the transform is safe. Remember the copy instruction.
1797 TheCopy = MI;
1798 }
1799 return true;
1800}
1801
1802/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1803/// modified by a copy from a constant global. If we can prove this, we can
1804/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001805MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1806 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001807 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1808 return TheCopy;
1809 return 0;
1810}