blob: c245b1432739223ee271d0ac4a3ac4b08998c6da [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
Owen Anderson90c579d2010-08-06 18:33:48 +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();
Chris Lattner3126f1c2010-08-18 02:37:06 +0000117
Bob Wilsonb742def2009-12-18 20:14:40 +0000118 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
119 SmallVector<AllocaInst*, 32> &NewElts);
120 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
121 SmallVector<AllocaInst*, 32> &NewElts);
122 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
123 SmallVector<AllocaInst*, 32> &NewElts);
124 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000125 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000126 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000127 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000128 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000129 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000130 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000131
Chris Lattner31d80102010-04-15 21:59:20 +0000132 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000133 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000134}
135
Dan Gohman844731a2008-05-13 00:00:25 +0000136char SROA::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000137INITIALIZE_PASS(SROA, "scalarrepl",
138 "Scalar Replacement of Aggregates", false, false);
Dan Gohman844731a2008-05-13 00:00:25 +0000139
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 Lattner91abace2010-09-01 05:14:33 +0000196
197/// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
198/// allowed to form. We do this to avoid MMX types, which is a complete hack,
199/// but is required until the backend is fixed.
200static bool IsVerbotenVectorType(const VectorType *VTy) {
201 // Reject all the MMX vector types.
202 switch (VTy->getNumElements()) {
203 default: return false;
204 case 1: return VTy->getElementType()->isIntegerTy(64);
205 case 2: return VTy->getElementType()->isIntegerTy(32);
206 case 4: return VTy->getElementType()->isIntegerTy(16);
207 case 8: return VTy->getElementType()->isIntegerTy(8);
208 }
209}
210
211
Chris Lattnera001b662010-04-16 00:38:19 +0000212/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
213/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
214/// alloca if possible or null if not.
215AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
216 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
217 // out.
218 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
219 return 0;
220
221 // If we were able to find a vector type that can handle this with
222 // insert/extract elements, and if there was at least one use that had
223 // a vector type, promote this to a vector. We don't want to promote
224 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
225 // we just get a lot of insert/extracts. If at least one vector is
226 // involved, then we probably really do have a union of vector/array.
227 const Type *NewTy;
Chris Lattner91abace2010-09-01 05:14:33 +0000228 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
229 !IsVerbotenVectorType(cast<VectorType>(VectorTy))) {
Chris Lattnera001b662010-04-16 00:38:19 +0000230 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
231 << *VectorTy << '\n');
232 NewTy = VectorTy; // Use the vector type.
233 } else {
234 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
235 // Create and insert the integer alloca.
236 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
237 }
238 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
239 ConvertUsesToScalar(AI, NewAI, 0);
240 return NewAI;
241}
242
243/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
244/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000245///
246/// There are two cases we handle here:
247/// 1) A union of vector types of the same size and potentially its elements.
248/// Here we turn element accesses into insert/extract element operations.
249/// This promotes a <4 x float> with a store of float to the third element
250/// into a <4 x float> that uses insert element.
251/// 2) A fully general blob of memory, which we turn into some (potentially
252/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000253/// and stores would mutate the memory. We mark this by setting VectorTy
254/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000255void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000256 // If we already decided to turn this into a blob of integer memory, there is
257 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000258 if (VectorTy && VectorTy->isVoidTy())
259 return;
260
261 // If this could be contributing to a vector, analyze it.
262
263 // If the In type is a vector that is the same size as the alloca, see if it
264 // matches the existing VecTy.
265 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000266 // Remember if we saw a vector type.
267 HadAVector = true;
268
Chris Lattner4cc576b2010-04-16 00:24:57 +0000269 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
270 // If we're storing/loading a vector of the right size, allow it as a
271 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000272 // we know the element size. If this is a subsequent access, ignore it
273 // even if it is a differing type but the same size. Worst case we can
274 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000275 if (VectorTy == 0)
276 VectorTy = VInTy;
277 return;
278 }
279 } else if (In->isFloatTy() || In->isDoubleTy() ||
280 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
281 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
282 // If we're accessing something that could be an element of a vector, see
283 // if the implied vector agrees with what we already have and if Offset is
284 // compatible with it.
285 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
286 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
287 (VectorTy == 0 ||
288 cast<VectorType>(VectorTy)->getElementType()
289 ->getPrimitiveSizeInBits()/8 == EltSize)) {
290 if (VectorTy == 0)
291 VectorTy = VectorType::get(In, AllocaSize/EltSize);
292 return;
293 }
294 }
295
296 // Otherwise, we have a case that we can't handle with an optimized vector
297 // form. We can still turn this into a large integer.
298 VectorTy = Type::getVoidTy(In->getContext());
299}
300
301/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
302/// its accesses to a single vector type, return true and set VecTy to
303/// the new type. If we could convert the alloca into a single promotable
304/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
305/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
306/// is the current offset from the base of the alloca being analyzed.
307///
308/// If we see at least one access to the value that is as a vector type, set the
309/// SawVec flag.
310bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
311 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
312 Instruction *User = cast<Instruction>(*UI);
313
314 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
315 // Don't break volatile loads.
316 if (LI->isVolatile())
317 return false;
318 MergeInType(LI->getType(), Offset);
319 continue;
320 }
321
322 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
323 // Storing the pointer, not into the value?
324 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
325 MergeInType(SI->getOperand(0)->getType(), Offset);
326 continue;
327 }
328
329 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000330 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000331 if (!CanConvertToScalar(BCI, Offset))
332 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000333 continue;
334 }
335
336 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
337 // If this is a GEP with a variable indices, we can't handle it.
338 if (!GEP->hasAllConstantIndices())
339 return false;
340
341 // Compute the offset that this GEP adds to the pointer.
342 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
343 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
344 &Indices[0], Indices.size());
345 // See if all uses can be converted.
346 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
347 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000348 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000349 continue;
350 }
351
352 // If this is a constant sized memset of a constant value (e.g. 0) we can
353 // handle it.
354 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
355 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000356 if (!isa<ConstantInt>(MSI->getValue()) ||
357 !isa<ConstantInt>(MSI->getLength()))
358 return false;
359 IsNotTrivial = true; // Can't be mem2reg'd.
360 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000361 }
362
363 // If this is a memcpy or memmove into or out of the whole allocation, we
364 // can handle it like a load or store of the scalar type.
365 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000366 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
367 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
368 return false;
369
370 IsNotTrivial = true; // Can't be mem2reg'd.
371 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000372 }
373
374 // Otherwise, we cannot handle this!
375 return false;
376 }
377
378 return true;
379}
380
381/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
382/// directly. This happens when we are converting an "integer union" to a
383/// single integer scalar, or when we are converting a "vector union" to a
384/// vector with insert/extractelement instructions.
385///
386/// Offset is an offset from the original alloca, in bits that need to be
387/// shifted to the right. By the end of this, there should be no uses of Ptr.
388void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
389 uint64_t Offset) {
390 while (!Ptr->use_empty()) {
391 Instruction *User = cast<Instruction>(Ptr->use_back());
392
393 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
394 ConvertUsesToScalar(CI, NewAI, Offset);
395 CI->eraseFromParent();
396 continue;
397 }
398
399 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
400 // Compute the offset that this GEP adds to the pointer.
401 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
402 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
403 &Indices[0], Indices.size());
404 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
405 GEP->eraseFromParent();
406 continue;
407 }
408
409 IRBuilder<> Builder(User->getParent(), User);
410
411 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
412 // The load is a bit extract from NewAI shifted right by Offset bits.
413 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
414 Value *NewLoadVal
415 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
416 LI->replaceAllUsesWith(NewLoadVal);
417 LI->eraseFromParent();
418 continue;
419 }
420
421 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
422 assert(SI->getOperand(0) != Ptr && "Consistency error!");
423 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
424 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
425 Builder);
426 Builder.CreateStore(New, NewAI);
427 SI->eraseFromParent();
428
429 // If the load we just inserted is now dead, then the inserted store
430 // overwrote the entire thing.
431 if (Old->use_empty())
432 Old->eraseFromParent();
433 continue;
434 }
435
436 // If this is a constant sized memset of a constant value (e.g. 0) we can
437 // transform it into a store of the expanded constant value.
438 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
439 assert(MSI->getRawDest() == Ptr && "Consistency error!");
440 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
441 if (NumBytes != 0) {
442 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
443
444 // Compute the value replicated the right number of times.
445 APInt APVal(NumBytes*8, Val);
446
447 // Splat the value if non-zero.
448 if (Val)
449 for (unsigned i = 1; i != NumBytes; ++i)
450 APVal |= APVal << 8;
451
452 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
453 Value *New = ConvertScalar_InsertValue(
454 ConstantInt::get(User->getContext(), APVal),
455 Old, Offset, Builder);
456 Builder.CreateStore(New, NewAI);
457
458 // If the load we just inserted is now dead, then the memset overwrote
459 // the entire thing.
460 if (Old->use_empty())
461 Old->eraseFromParent();
462 }
463 MSI->eraseFromParent();
464 continue;
465 }
466
467 // If this is a memcpy or memmove into or out of the whole allocation, we
468 // can handle it like a load or store of the scalar type.
469 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
470 assert(Offset == 0 && "must be store to start of alloca");
471
472 // If the source and destination are both to the same alloca, then this is
473 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
474 // as appropriate.
475 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
476
477 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
478 // Dest must be OrigAI, change this to be a load from the original
479 // pointer (bitcasted), then a store to our new alloca.
480 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
481 Value *SrcPtr = MTI->getSource();
482 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
483
484 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
485 SrcVal->setAlignment(MTI->getAlignment());
486 Builder.CreateStore(SrcVal, NewAI);
487 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
488 // Src must be OrigAI, change this to be a load from NewAI then a store
489 // through the original dest pointer (bitcasted).
490 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
491 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
492
493 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
494 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
495 NewStore->setAlignment(MTI->getAlignment());
496 } else {
497 // Noop transfer. Src == Dst
498 }
499
500 MTI->eraseFromParent();
501 continue;
502 }
503
504 llvm_unreachable("Unsupported operation!");
505 }
506}
507
508/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
509/// or vector value FromVal, extracting the bits from the offset specified by
510/// Offset. This returns the value, which is of type ToType.
511///
512/// This happens when we are converting an "integer union" to a single
513/// integer scalar, or when we are converting a "vector union" to a vector with
514/// insert/extractelement instructions.
515///
516/// Offset is an offset from the original alloca, in bits that need to be
517/// shifted to the right.
518Value *ConvertToScalarInfo::
519ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
520 uint64_t Offset, IRBuilder<> &Builder) {
521 // If the load is of the whole new alloca, no conversion is needed.
522 if (FromVal->getType() == ToType && Offset == 0)
523 return FromVal;
524
525 // If the result alloca is a vector type, this is either an element
526 // access or a bitcast to another vector type of the same size.
527 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
528 if (ToType->isVectorTy())
529 return Builder.CreateBitCast(FromVal, ToType, "tmp");
530
531 // Otherwise it must be an element access.
532 unsigned Elt = 0;
533 if (Offset) {
534 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
535 Elt = Offset/EltSize;
536 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
537 }
538 // Return the element extracted out of it.
539 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
540 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
541 if (V->getType() != ToType)
542 V = Builder.CreateBitCast(V, ToType, "tmp");
543 return V;
544 }
545
546 // If ToType is a first class aggregate, extract out each of the pieces and
547 // use insertvalue's to form the FCA.
548 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
549 const StructLayout &Layout = *TD.getStructLayout(ST);
550 Value *Res = UndefValue::get(ST);
551 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
552 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
553 Offset+Layout.getElementOffsetInBits(i),
554 Builder);
555 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
556 }
557 return Res;
558 }
559
560 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
561 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
562 Value *Res = UndefValue::get(AT);
563 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
564 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
565 Offset+i*EltSize, Builder);
566 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
567 }
568 return Res;
569 }
570
571 // Otherwise, this must be a union that was converted to an integer value.
572 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
573
574 // If this is a big-endian system and the load is narrower than the
575 // full alloca type, we need to do a shift to get the right bits.
576 int ShAmt = 0;
577 if (TD.isBigEndian()) {
578 // On big-endian machines, the lowest bit is stored at the bit offset
579 // from the pointer given by getTypeStoreSizeInBits. This matters for
580 // integers with a bitwidth that is not a multiple of 8.
581 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
582 TD.getTypeStoreSizeInBits(ToType) - Offset;
583 } else {
584 ShAmt = Offset;
585 }
586
587 // Note: we support negative bitwidths (with shl) which are not defined.
588 // We do this to support (f.e.) loads off the end of a structure where
589 // only some bits are used.
590 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
591 FromVal = Builder.CreateLShr(FromVal,
592 ConstantInt::get(FromVal->getType(),
593 ShAmt), "tmp");
594 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
595 FromVal = Builder.CreateShl(FromVal,
596 ConstantInt::get(FromVal->getType(),
597 -ShAmt), "tmp");
598
599 // Finally, unconditionally truncate the integer to the right width.
600 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
601 if (LIBitWidth < NTy->getBitWidth())
602 FromVal =
603 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
604 LIBitWidth), "tmp");
605 else if (LIBitWidth > NTy->getBitWidth())
606 FromVal =
607 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
608 LIBitWidth), "tmp");
609
610 // If the result is an integer, this is a trunc or bitcast.
611 if (ToType->isIntegerTy()) {
612 // Should be done.
613 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
614 // Just do a bitcast, we know the sizes match up.
615 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
616 } else {
617 // Otherwise must be a pointer.
618 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
619 }
620 assert(FromVal->getType() == ToType && "Didn't convert right?");
621 return FromVal;
622}
623
624/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
625/// or vector value "Old" at the offset specified by Offset.
626///
627/// This happens when we are converting an "integer union" to a
628/// single integer scalar, or when we are converting a "vector union" to a
629/// vector with insert/extractelement instructions.
630///
631/// Offset is an offset from the original alloca, in bits that need to be
632/// shifted to the right.
633Value *ConvertToScalarInfo::
634ConvertScalar_InsertValue(Value *SV, Value *Old,
635 uint64_t Offset, IRBuilder<> &Builder) {
636 // Convert the stored type to the actual type, shift it left to insert
637 // then 'or' into place.
638 const Type *AllocaType = Old->getType();
639 LLVMContext &Context = Old->getContext();
640
641 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
642 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
643 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
644
645 // Changing the whole vector with memset or with an access of a different
646 // vector type?
647 if (ValSize == VecSize)
648 return Builder.CreateBitCast(SV, AllocaType, "tmp");
649
650 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
651
652 // Must be an element insertion.
653 unsigned Elt = Offset/EltSize;
654
655 if (SV->getType() != VTy->getElementType())
656 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
657
658 SV = Builder.CreateInsertElement(Old, SV,
659 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
660 "tmp");
661 return SV;
662 }
663
664 // If SV is a first-class aggregate value, insert each value recursively.
665 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
666 const StructLayout &Layout = *TD.getStructLayout(ST);
667 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
668 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
669 Old = ConvertScalar_InsertValue(Elt, Old,
670 Offset+Layout.getElementOffsetInBits(i),
671 Builder);
672 }
673 return Old;
674 }
675
676 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
677 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
678 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
679 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
680 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
681 }
682 return Old;
683 }
684
685 // If SV is a float, convert it to the appropriate integer type.
686 // If it is a pointer, do the same.
687 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
688 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
689 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
690 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
691 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
692 SV = Builder.CreateBitCast(SV,
693 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
694 else if (SV->getType()->isPointerTy())
695 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
696
697 // Zero extend or truncate the value if needed.
698 if (SV->getType() != AllocaType) {
699 if (SV->getType()->getPrimitiveSizeInBits() <
700 AllocaType->getPrimitiveSizeInBits())
701 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
702 else {
703 // Truncation may be needed if storing more than the alloca can hold
704 // (undefined behavior).
705 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
706 SrcWidth = DestWidth;
707 SrcStoreWidth = DestStoreWidth;
708 }
709 }
710
711 // If this is a big-endian system and the store is narrower than the
712 // full alloca type, we need to do a shift to get the right bits.
713 int ShAmt = 0;
714 if (TD.isBigEndian()) {
715 // On big-endian machines, the lowest bit is stored at the bit offset
716 // from the pointer given by getTypeStoreSizeInBits. This matters for
717 // integers with a bitwidth that is not a multiple of 8.
718 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
719 } else {
720 ShAmt = Offset;
721 }
722
723 // Note: we support negative bitwidths (with shr) which are not defined.
724 // We do this to support (f.e.) stores off the end of a structure where
725 // only some bits in the structure are set.
726 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
727 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
728 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
729 ShAmt), "tmp");
730 Mask <<= ShAmt;
731 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
732 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
733 -ShAmt), "tmp");
734 Mask = Mask.lshr(-ShAmt);
735 }
736
737 // Mask out the bits we are about to insert from the old value, and or
738 // in the new bits.
739 if (SrcWidth != DestWidth) {
740 assert(DestWidth > SrcWidth);
741 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
742 SV = Builder.CreateOr(Old, SV, "ins");
743 }
744 return SV;
745}
746
747
748//===----------------------------------------------------------------------===//
749// SRoA Driver
750//===----------------------------------------------------------------------===//
751
752
Chris Lattnered7b41e2003-05-27 15:45:27 +0000753bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000754 TD = getAnalysisIfAvailable<TargetData>();
755
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000756 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000757
758 // FIXME: ScalarRepl currently depends on TargetData more than it
759 // theoretically needs to. It should be refactored in order to support
760 // target-independent IR. Until this is done, just skip the actual
761 // scalar-replacement portion of this pass.
762 if (!TD) return Changed;
763
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000764 while (1) {
765 bool LocalChange = performScalarRepl(F);
766 if (!LocalChange) break; // No need to repromote if no scalarrepl
767 Changed = true;
768 LocalChange = performPromotion(F);
769 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
770 }
Chris Lattner38aec322003-09-11 16:45:55 +0000771
772 return Changed;
773}
774
775
776bool SROA::performPromotion(Function &F) {
777 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000778 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000779 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000780
Chris Lattner02a3be02003-09-20 14:39:18 +0000781 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000782
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000783 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000784
Chris Lattner38aec322003-09-11 16:45:55 +0000785 while (1) {
786 Allocas.clear();
787
788 // Find allocas that are safe to promote, by looking at all instructions in
789 // the entry node
790 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
791 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000792 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000793 Allocas.push_back(AI);
794
795 if (Allocas.empty()) break;
796
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000797 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000798 NumPromoted += Allocas.size();
799 Changed = true;
800 }
801
802 return Changed;
803}
804
Chris Lattner4cc576b2010-04-16 00:24:57 +0000805
Bob Wilson3992feb2010-02-03 17:23:56 +0000806/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
807/// SROA. It must be a struct or array type with a small number of elements.
808static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
809 const Type *T = AI->getAllocatedType();
810 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000811 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000812 return ST->getNumElements() <= 32;
813 // Arrays are much less likely to be safe for SROA; only consider
814 // them if they are very small.
815 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
816 return AT->getNumElements() <= 8;
817 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000818}
819
Chris Lattnerc4472072010-04-15 23:50:26 +0000820
Chris Lattner38aec322003-09-11 16:45:55 +0000821// performScalarRepl - This algorithm is a simple worklist driven algorithm,
822// which runs on all of the malloc/alloca instructions in the function, removing
823// them if they are only used by getelementptr instructions.
824//
825bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000826 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000827
Chris Lattner31d80102010-04-15 21:59:20 +0000828 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000829 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000830 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000831 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000832 WorkList.push_back(A);
833
834 // Process the worklist
835 bool Changed = false;
836 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000837 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000838 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000839
Chris Lattneradd2bd72006-12-22 23:14:42 +0000840 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
841 // with unused elements.
842 if (AI->use_empty()) {
843 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000844 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000845 continue;
846 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000847
848 // If this alloca is impossible for us to promote, reject it early.
849 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
850 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000851
852 // Check to see if this allocation is only modified by a memcpy/memmove from
853 // a constant global. If this is the case, we can change all users to use
854 // the constant global instead. This is commonly produced by the CFE by
855 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
856 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000857 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000858 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
859 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000860 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000861 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000862 TheCopy->eraseFromParent(); // Don't mutate the global.
863 AI->eraseFromParent();
864 ++NumGlobals;
865 Changed = true;
866 continue;
867 }
Chris Lattner15c82772009-02-02 20:44:45 +0000868
Chris Lattner7809ecd2009-02-03 01:30:09 +0000869 // Check to see if we can perform the core SROA transformation. We cannot
870 // transform the allocation instruction if it is an array allocation
871 // (allocations OF arrays are ok though), and an allocation of a scalar
872 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000873 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000874
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000875 // Do not promote [0 x %struct].
876 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000877
878 // Do not promote any struct whose size is too big.
879 if (AllocaSize > SRThreshold) continue;
880
Bob Wilson3992feb2010-02-03 17:23:56 +0000881 // If the alloca looks like a good candidate for scalar replacement, and if
882 // all its users can be transformed, then split up the aggregate into its
883 // separate elements.
884 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
885 DoScalarReplacement(AI, WorkList);
886 Changed = true;
887 continue;
888 }
889
Chris Lattner6e733d32009-01-28 20:16:43 +0000890 // If we can turn this aggregate value (potentially with casts) into a
891 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000892 // IsNotTrivial tracks whether this is something that mem2reg could have
893 // promoted itself. If so, we don't want to transform it needlessly. Note
894 // that we can't just check based on the type: the alloca may be of an i32
895 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000896 if (AllocaInst *NewAI =
897 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000898 NewAI->takeName(AI);
899 AI->eraseFromParent();
900 ++NumConverted;
901 Changed = true;
902 continue;
Chris Lattner593375d2010-04-16 00:20:00 +0000903 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000904
Chris Lattner7809ecd2009-02-03 01:30:09 +0000905 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000906 }
907
908 return Changed;
909}
Chris Lattner5e062a12003-05-30 04:15:41 +0000910
Chris Lattnera10b29b2007-04-25 05:02:56 +0000911/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
912/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000913void SROA::DoScalarReplacement(AllocaInst *AI,
914 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000915 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000916 SmallVector<AllocaInst*, 32> ElementAllocas;
917 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
918 ElementAllocas.reserve(ST->getNumContainedTypes());
919 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000920 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000921 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000922 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000923 ElementAllocas.push_back(NA);
924 WorkList.push_back(NA); // Add to worklist for recursive processing
925 }
926 } else {
927 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
928 ElementAllocas.reserve(AT->getNumElements());
929 const Type *ElTy = AT->getElementType();
930 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000931 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000932 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000933 ElementAllocas.push_back(NA);
934 WorkList.push_back(NA); // Add to worklist for recursive processing
935 }
936 }
937
Bob Wilsonb742def2009-12-18 20:14:40 +0000938 // Now that we have created the new alloca instructions, rewrite all the
939 // uses of the old alloca.
940 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000941
Bob Wilsonb742def2009-12-18 20:14:40 +0000942 // Now erase any instructions that were made dead while rewriting the alloca.
943 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000944 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000945
Dan Gohmanfe601042010-06-22 15:08:57 +0000946 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000947}
Chris Lattnera59adc42009-12-14 05:11:02 +0000948
Bob Wilsonb742def2009-12-18 20:14:40 +0000949/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
950/// recursively including all their operands that become trivially dead.
951void SROA::DeleteDeadInstructions() {
952 while (!DeadInsts.empty()) {
953 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000954
Bob Wilsonb742def2009-12-18 20:14:40 +0000955 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
956 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
957 // Zero out the operand and see if it becomes trivially dead.
958 // (But, don't add allocas to the dead instruction list -- they are
959 // already on the worklist and will be deleted separately.)
960 *OI = 0;
961 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
962 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000963 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000964
965 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000966 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000967}
Bob Wilsonb742def2009-12-18 20:14:40 +0000968
Bob Wilsonb742def2009-12-18 20:14:40 +0000969/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
970/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000971/// the Info parameter. Offset indicates the position within AI that is
972/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000973void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000974 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000975 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
976 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000977
Bob Wilsonb742def2009-12-18 20:14:40 +0000978 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000979 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000980 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000981 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000982 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000983 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000984 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +0000985 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000986 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
987 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000988 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000989 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000990 else
991 MarkUnsafe(Info);
992 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
993 if (!LI->isVolatile()) {
994 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000995 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000996 LIType, false, Info);
997 } else
998 MarkUnsafe(Info);
999 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1000 // Store is ok if storing INTO the pointer, not storing the pointer
1001 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1002 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001003 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001004 SIType, true, Info);
1005 } else
1006 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001007 } else {
1008 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1009 MarkUnsafe(Info);
1010 }
1011 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001012 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001013}
Bob Wilson39c88a62009-12-17 18:34:24 +00001014
Bob Wilsonb742def2009-12-18 20:14:40 +00001015/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1016/// replacement. It is safe when all the indices are constant, in-bounds
1017/// references, and when the resulting offset corresponds to an element within
1018/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001019/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001020void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001021 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001022 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1023 if (GEPIt == E)
1024 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001025
Chris Lattner88e6dc82008-08-23 05:21:06 +00001026 // Walk through the GEP type indices, checking the types that this indexes
1027 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001028 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001029 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001030 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001031 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001032
Bob Wilsonb742def2009-12-18 20:14:40 +00001033 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1034 if (!IdxVal)
1035 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001036 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001037
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001038 // Compute the offset due to this GEP and check if the alloca has a
1039 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001040 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1041 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1042 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001043 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1044 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001045}
1046
Bob Wilsonb742def2009-12-18 20:14:40 +00001047/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1048/// alloca or has an offset and size that corresponds to a component element
1049/// within it. The offset checked here may have been formed from a GEP with a
1050/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001051void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001052 const Type *MemOpType, bool isStore,
1053 AllocaInfo &Info) {
1054 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001055 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001056 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1057 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1058 // (which are essentially the same as the MemIntrinsics, especially with
1059 // regard to copying padding between elements), or references using the
1060 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +00001061 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001062 if (!UsesAggregateType) {
1063 if (isStore)
1064 Info.isMemCpyDst = true;
1065 else
1066 Info.isMemCpySrc = true;
1067 }
1068 return;
1069 }
1070 }
1071 // Check if the offset/size correspond to a component within the alloca type.
1072 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001073 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +00001074 return;
1075
1076 return MarkUnsafe(Info);
1077}
1078
1079/// TypeHasComponent - Return true if T has a component type with the
1080/// specified offset and size. If Size is zero, do not check the size.
1081bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1082 const Type *EltTy;
1083 uint64_t EltSize;
1084 if (const StructType *ST = dyn_cast<StructType>(T)) {
1085 const StructLayout *Layout = TD->getStructLayout(ST);
1086 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1087 EltTy = ST->getContainedType(EltIdx);
1088 EltSize = TD->getTypeAllocSize(EltTy);
1089 Offset -= Layout->getElementOffset(EltIdx);
1090 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1091 EltTy = AT->getElementType();
1092 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001093 if (Offset >= AT->getNumElements() * EltSize)
1094 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001095 Offset %= EltSize;
1096 } else {
1097 return false;
1098 }
1099 if (Offset == 0 && (Size == 0 || EltSize == Size))
1100 return true;
1101 // Check if the component spans multiple elements.
1102 if (Offset + Size > EltSize)
1103 return false;
1104 return TypeHasComponent(EltTy, Offset, Size);
1105}
1106
1107/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1108/// the instruction I, which references it, to use the separate elements.
1109/// Offset indicates the position within AI that is referenced by this
1110/// instruction.
1111void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1112 SmallVector<AllocaInst*, 32> &NewElts) {
1113 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1114 Instruction *User = cast<Instruction>(*UI);
1115
1116 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1117 RewriteBitCast(BC, AI, Offset, NewElts);
1118 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1119 RewriteGEP(GEPI, AI, Offset, NewElts);
1120 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1121 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1122 uint64_t MemSize = Length->getZExtValue();
1123 if (Offset == 0 &&
1124 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1125 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001126 // Otherwise the intrinsic can only touch a single element and the
1127 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001128 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1129 const Type *LIType = LI->getType();
1130 if (LIType == AI->getAllocatedType()) {
1131 // Replace:
1132 // %res = load { i32, i32 }* %alloc
1133 // with:
1134 // %load.0 = load i32* %alloc.0
1135 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1136 // %load.1 = load i32* %alloc.1
1137 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1138 // (Also works for arrays instead of structs)
1139 Value *Insert = UndefValue::get(LIType);
1140 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1141 Value *Load = new LoadInst(NewElts[i], "load", LI);
1142 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1143 }
1144 LI->replaceAllUsesWith(Insert);
1145 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001146 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001147 TD->getTypeAllocSize(LIType) ==
1148 TD->getTypeAllocSize(AI->getAllocatedType())) {
1149 // If this is a load of the entire alloca to an integer, rewrite it.
1150 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1151 }
1152 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1153 Value *Val = SI->getOperand(0);
1154 const Type *SIType = Val->getType();
1155 if (SIType == AI->getAllocatedType()) {
1156 // Replace:
1157 // store { i32, i32 } %val, { i32, i32 }* %alloc
1158 // with:
1159 // %val.0 = extractvalue { i32, i32 } %val, 0
1160 // store i32 %val.0, i32* %alloc.0
1161 // %val.1 = extractvalue { i32, i32 } %val, 1
1162 // store i32 %val.1, i32* %alloc.1
1163 // (Also works for arrays instead of structs)
1164 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1165 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1166 new StoreInst(Extract, NewElts[i], SI);
1167 }
1168 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001169 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001170 TD->getTypeAllocSize(SIType) ==
1171 TD->getTypeAllocSize(AI->getAllocatedType())) {
1172 // If this is a store of the entire alloca from an integer, rewrite it.
1173 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1174 }
1175 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001176 }
1177}
1178
Bob Wilsonb742def2009-12-18 20:14:40 +00001179/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1180/// and recursively continue updating all of its uses.
1181void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1182 SmallVector<AllocaInst*, 32> &NewElts) {
1183 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1184 if (BC->getOperand(0) != AI)
1185 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001186
Bob Wilsonb742def2009-12-18 20:14:40 +00001187 // The bitcast references the original alloca. Replace its uses with
1188 // references to the first new element alloca.
1189 Instruction *Val = NewElts[0];
1190 if (Val->getType() != BC->getDestTy()) {
1191 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1192 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001193 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001194 BC->replaceAllUsesWith(Val);
1195 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001196}
1197
Bob Wilsonb742def2009-12-18 20:14:40 +00001198/// FindElementAndOffset - Return the index of the element containing Offset
1199/// within the specified type, which must be either a struct or an array.
1200/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001201/// element. IdxTy is set to the type of the index result to be used in a
1202/// GEP instruction.
1203uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1204 const Type *&IdxTy) {
1205 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001206 if (const StructType *ST = dyn_cast<StructType>(T)) {
1207 const StructLayout *Layout = TD->getStructLayout(ST);
1208 Idx = Layout->getElementContainingOffset(Offset);
1209 T = ST->getContainedType(Idx);
1210 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001211 IdxTy = Type::getInt32Ty(T->getContext());
1212 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001213 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001214 const ArrayType *AT = cast<ArrayType>(T);
1215 T = AT->getElementType();
1216 uint64_t EltSize = TD->getTypeAllocSize(T);
1217 Idx = Offset / EltSize;
1218 Offset -= Idx * EltSize;
1219 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001220 return Idx;
1221}
1222
1223/// RewriteGEP - Check if this GEP instruction moves the pointer across
1224/// elements of the alloca that are being split apart, and if so, rewrite
1225/// the GEP to be relative to the new element.
1226void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1227 SmallVector<AllocaInst*, 32> &NewElts) {
1228 uint64_t OldOffset = Offset;
1229 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1230 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1231 &Indices[0], Indices.size());
1232
1233 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1234
1235 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001236 const Type *IdxTy;
1237 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001238 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001239 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001240
1241 T = AI->getAllocatedType();
1242 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001243 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001244
1245 // If this GEP does not move the pointer across elements of the alloca
1246 // being split, then it does not needs to be rewritten.
1247 if (Idx == OldIdx)
1248 return;
1249
1250 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1251 SmallVector<Value*, 8> NewArgs;
1252 NewArgs.push_back(Constant::getNullValue(i32Ty));
1253 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001254 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1255 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001256 }
1257 Instruction *Val = NewElts[Idx];
1258 if (NewArgs.size() > 1) {
1259 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1260 NewArgs.end(), "", GEPI);
1261 Val->takeName(GEPI);
1262 }
1263 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001264 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001265 GEPI->replaceAllUsesWith(Val);
1266 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001267}
1268
1269/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1270/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001271void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001272 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001273 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001274 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001275 // appropriate type. The "Other" pointer is the pointer that goes to memory
1276 // that doesn't have anything to do with the alloca that we are promoting. For
1277 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001278 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001279 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001280 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001281 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001282 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001283 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001284 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001285 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001286 }
1287 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001288
Chris Lattnerd93afec2009-01-07 07:18:45 +00001289 // If there is an other pointer, we want to convert it to the same pointer
1290 // type as AI has, so we can GEP through it safely.
1291 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001292 unsigned AddrSpace =
1293 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001294
1295 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1296 // optimization, but it's also required to detect the corner case where
1297 // both pointer operands are referencing the same memory, and where
1298 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1299 // function is only called for mem intrinsics that access the whole
1300 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001301 OtherPtr = OtherPtr->stripPointerCasts();
1302
Bob Wilsona756b1d2010-01-19 04:32:48 +00001303 // Copying the alloca to itself is a no-op: just delete it.
1304 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1305 // This code will run twice for a no-op memcpy -- once for each operand.
1306 // Put only one reference to MI on the DeadInsts list.
1307 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1308 E = DeadInsts.end(); I != E; ++I)
1309 if (*I == MI) return;
1310 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001311 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001312 }
Chris Lattner372dda82007-03-05 07:52:57 +00001313
Chris Lattnerd93afec2009-01-07 07:18:45 +00001314 // If the pointer is not the right type, insert a bitcast to the right
1315 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001316 const Type *NewTy =
1317 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1318
1319 if (OtherPtr->getType() != NewTy)
1320 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001321 }
1322
1323 // Process each element of the aggregate.
Gabor Greifa9b23132010-04-20 13:13:04 +00001324 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001325 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +00001326 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +00001327
Owen Anderson1d0be152009-08-13 21:58:54 +00001328 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001329
1330 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1331 // If this is a memcpy/memmove, emit a GEP of the other element address.
1332 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001333 unsigned OtherEltAlign = MemAlignment;
1334
Bob Wilsona756b1d2010-01-19 04:32:48 +00001335 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001336 Value *Idx[2] = { Zero,
1337 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001338 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001339 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001340 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001341 uint64_t EltOffset;
1342 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001343 const Type *OtherTy = OtherPtrTy->getElementType();
1344 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001345 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1346 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001347 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001348 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001349 }
1350
1351 // The alignment of the other pointer is the guaranteed alignment of the
1352 // element, which is affected by both the known alignment of the whole
1353 // mem intrinsic and the alignment of the element. If the alignment of
1354 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1355 // known alignment is just 4 bytes.
1356 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001357 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001358
1359 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001360 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001361
1362 // If we got down to a scalar, insert a load or store as appropriate.
1363 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001364 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001365 if (SROADest) {
1366 // From Other to Alloca.
1367 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1368 new StoreInst(Elt, EltPtr, MI);
1369 } else {
1370 // From Alloca to Other.
1371 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1372 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1373 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001374 continue;
1375 }
1376 assert(isa<MemSetInst>(MI));
1377
1378 // If the stored element is zero (common case), just store a null
1379 // constant.
1380 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001381 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001382 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001383 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001384 } else {
1385 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001386 const Type *ValTy = EltTy->getScalarType();
1387
Chris Lattnerd93afec2009-01-07 07:18:45 +00001388 // Construct an integer with the right value.
1389 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1390 APInt OneVal(EltSize, CI->getZExtValue());
1391 APInt TotalVal(OneVal);
1392 // Set each byte.
1393 for (unsigned i = 0; 8*i < EltSize; ++i) {
1394 TotalVal = TotalVal.shl(8);
1395 TotalVal |= OneVal;
1396 }
1397
1398 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001399 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001400 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001401 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001402 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001403 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001404 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1405
1406 // If the requested value was a vector constant, create it.
1407 if (EltTy != ValTy) {
1408 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1409 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001410 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001411 }
1412 }
1413 new StoreInst(StoreVal, EltPtr, MI);
1414 continue;
1415 }
1416 // Otherwise, if we're storing a byte variable, use a memset call for
1417 // this element.
1418 }
1419
1420 // Cast the element pointer to BytePtrTy.
1421 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001422 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001423
1424 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +00001425 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1426 // Preserve address space of OtherElt
1427 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1428 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1429 if (OtherPTy->getElementType() != PTy->getElementType()) {
1430 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1431 OtherPTy->getAddressSpace());
1432 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
1433 OtherElt->getNameStr(), MI);
1434 }
1435 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001436
Duncan Sands777d2302009-05-09 07:06:46 +00001437 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001438
1439 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001440 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001441 Value *Ops[] = {
1442 SROADest ? EltPtr : OtherElt, // Dest ptr
1443 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001444 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +00001445 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +00001446 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1447 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +00001448 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001449 // In case we fold the address space overloaded memcpy of A to B
1450 // with memcpy of B to C, change the function to be a memcpy of A to C.
1451 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1452 Ops[2]->getType() };
1453 Module *M = MI->getParent()->getParent()->getParent();
1454 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1455 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001456 } else {
1457 assert(isa<MemSetInst>(MI));
1458 Value *Ops[] = {
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001459 EltPtr, MI->getArgOperand(1), // Dest, Value,
1460 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +00001461 Zero, // Align
1462 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +00001463 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001464 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1465 Module *M = MI->getParent()->getParent()->getParent();
1466 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1467 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001468 }
Chris Lattner372dda82007-03-05 07:52:57 +00001469 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001470 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001471}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001472
Bob Wilson39fdd692009-12-04 21:57:37 +00001473/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001474/// overwrites the entire allocation. Extract out the pieces of the stored
1475/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001476void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001477 SmallVector<AllocaInst*, 32> &NewElts){
1478 // Extract each element out of the integer according to its structure offset
1479 // and store the element value to the individual alloca.
1480 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001481 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001482 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001483
Eli Friedman41b33f42009-06-01 09:14:32 +00001484 // Handle tail padding by extending the operand
1485 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001486 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001487 IntegerType::get(SI->getContext(), AllocaSizeBits),
1488 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001489
David Greene504c7d82010-01-05 01:27:09 +00001490 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001491 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001492
1493 // There are two forms here: AI could be an array or struct. Both cases
1494 // have different ways to compute the element offset.
1495 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1496 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1497
1498 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1499 // Get the number of bits to shift SrcVal to get the value.
1500 const Type *FieldTy = EltSTy->getElementType(i);
1501 uint64_t Shift = Layout->getElementOffsetInBits(i);
1502
1503 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001504 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001505
1506 Value *EltVal = SrcVal;
1507 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001508 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001509 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1510 "sroa.store.elt", SI);
1511 }
1512
1513 // Truncate down to an integer of the right size.
1514 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +00001515
1516 // Ignore zero sized fields like {}, they obviously contain no data.
1517 if (FieldSizeBits == 0) continue;
1518
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001519 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001520 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001521 IntegerType::get(SI->getContext(), FieldSizeBits),
1522 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001523 Value *DestField = NewElts[i];
1524 if (EltVal->getType() == FieldTy) {
1525 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001526 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001527 // Bitcast to the right element type (for fp/vector values).
1528 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1529 } else {
1530 // Otherwise, bitcast the dest pointer (for aggregates).
1531 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001532 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001533 "", SI);
1534 }
1535 new StoreInst(EltVal, DestField, SI);
1536 }
1537
1538 } else {
1539 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1540 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001541 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001542 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1543
1544 uint64_t Shift;
1545
1546 if (TD->isBigEndian())
1547 Shift = AllocaSizeBits-ElementOffset;
1548 else
1549 Shift = 0;
1550
1551 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001552 // Ignore zero sized fields like {}, they obviously contain no data.
1553 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001554
1555 Value *EltVal = SrcVal;
1556 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001557 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001558 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1559 "sroa.store.elt", SI);
1560 }
1561
1562 // Truncate down to an integer of the right size.
1563 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001564 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001565 IntegerType::get(SI->getContext(),
1566 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001567 Value *DestField = NewElts[i];
1568 if (EltVal->getType() == ArrayEltTy) {
1569 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001570 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001571 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001572 // Bitcast to the right element type (for fp/vector values).
1573 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1574 } else {
1575 // Otherwise, bitcast the dest pointer (for aggregates).
1576 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001577 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001578 "", SI);
1579 }
1580 new StoreInst(EltVal, DestField, SI);
1581
1582 if (TD->isBigEndian())
1583 Shift -= ElementOffset;
1584 else
1585 Shift += ElementOffset;
1586 }
1587 }
1588
Bob Wilsonb742def2009-12-18 20:14:40 +00001589 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001590}
1591
Bob Wilson39fdd692009-12-04 21:57:37 +00001592/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001593/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001594void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001595 SmallVector<AllocaInst*, 32> &NewElts) {
1596 // Extract each element out of the NewElts according to its structure offset
1597 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001598 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001599 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001600
David Greene504c7d82010-01-05 01:27:09 +00001601 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001602 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001603
1604 // There are two forms here: AI could be an array or struct. Both cases
1605 // have different ways to compute the element offset.
1606 const StructLayout *Layout = 0;
1607 uint64_t ArrayEltBitOffset = 0;
1608 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1609 Layout = TD->getStructLayout(EltSTy);
1610 } else {
1611 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001612 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001613 }
Owen Andersone922c022009-07-22 00:24:57 +00001614
Owen Andersone922c022009-07-22 00:24:57 +00001615 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001616 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001617
1618 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1619 // Load the value from the alloca. If the NewElt is an aggregate, cast
1620 // the pointer to an integer of the same size before doing the load.
1621 Value *SrcField = NewElts[i];
1622 const Type *FieldTy =
1623 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001624 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1625
1626 // Ignore zero sized fields like {}, they obviously contain no data.
1627 if (FieldSizeBits == 0) continue;
1628
Owen Anderson1d0be152009-08-13 21:58:54 +00001629 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1630 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001631 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1632 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001633 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001634 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001635 "", LI);
1636 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1637
1638 // If SrcField is a fp or vector of the right size but that isn't an
1639 // integer type, bitcast to an integer so we can shift it.
1640 if (SrcField->getType() != FieldIntTy)
1641 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1642
1643 // Zero extend the field to be the same size as the final alloca so that
1644 // we can shift and insert it.
1645 if (SrcField->getType() != ResultVal->getType())
1646 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1647
1648 // Determine the number of bits to shift SrcField.
1649 uint64_t Shift;
1650 if (Layout) // Struct case.
1651 Shift = Layout->getElementOffsetInBits(i);
1652 else // Array case.
1653 Shift = i*ArrayEltBitOffset;
1654
1655 if (TD->isBigEndian())
1656 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1657
1658 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001659 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001660 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1661 }
1662
Chris Lattner14952472010-06-27 07:58:26 +00001663 // Don't create an 'or x, 0' on the first iteration.
1664 if (!isa<Constant>(ResultVal) ||
1665 !cast<Constant>(ResultVal)->isNullValue())
1666 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1667 else
1668 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001669 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001670
1671 // Handle tail padding by truncating the result
1672 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1673 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1674
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001675 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001676 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001677}
1678
Duncan Sands3cb36502007-11-04 14:43:57 +00001679/// HasPadding - Return true if the specified type has any structure or
1680/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001681static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner91abace2010-09-01 05:14:33 +00001682 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
1683 return HasPadding(ATy->getElementType(), TD);
1684
1685 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
1686 return HasPadding(VTy->getElementType(), TD);
1687
Chris Lattner39a1c042007-05-30 06:11:23 +00001688 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1689 const StructLayout *SL = TD.getStructLayout(STy);
1690 unsigned PrevFieldBitOffset = 0;
1691 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001692 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1693
Chris Lattner39a1c042007-05-30 06:11:23 +00001694 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001695 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001696 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001697
Chris Lattner39a1c042007-05-30 06:11:23 +00001698 // Check to see if there is any padding between this element and the
1699 // previous one.
1700 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001701 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001702 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1703 if (PrevFieldEnd < FieldBitOffset)
1704 return true;
1705 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001706
Chris Lattner39a1c042007-05-30 06:11:23 +00001707 PrevFieldBitOffset = FieldBitOffset;
1708 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001709
Chris Lattner39a1c042007-05-30 06:11:23 +00001710 // Check for tail padding.
1711 if (unsigned EltCount = STy->getNumElements()) {
1712 unsigned PrevFieldEnd = PrevFieldBitOffset +
1713 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001714 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001715 return true;
1716 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001717 }
Chris Lattner91abace2010-09-01 05:14:33 +00001718
Duncan Sands777d2302009-05-09 07:06:46 +00001719 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001720}
Chris Lattner372dda82007-03-05 07:52:57 +00001721
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001722/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1723/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1724/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001725bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001726 // Loop over the use list of the alloca. We can only transform it if all of
1727 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001728 AllocaInfo Info;
1729
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001730 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001731 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001732 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001733 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001734 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001735
1736 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1737 // source and destination, we have to be careful. In particular, the memcpy
1738 // could be moving around elements that live in structure padding of the LLVM
1739 // types, but may actually be used. In these cases, we refuse to promote the
1740 // struct.
1741 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001742 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001743 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001744
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001745 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001746}
Chris Lattnera1888942005-12-12 07:19:13 +00001747
Chris Lattner800de312008-02-29 07:03:13 +00001748
Chris Lattner79b3bd32007-04-25 06:40:51 +00001749
1750/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1751/// some part of a constant global variable. This intentionally only accepts
1752/// constant expressions because we don't can't rewrite arbitrary instructions.
1753static bool PointsToConstantGlobal(Value *V) {
1754 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1755 return GV->isConstant();
1756 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1757 if (CE->getOpcode() == Instruction::BitCast ||
1758 CE->getOpcode() == Instruction::GetElementPtr)
1759 return PointsToConstantGlobal(CE->getOperand(0));
1760 return false;
1761}
1762
1763/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1764/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1765/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1766/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1767/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1768/// the alloca, and if the source pointer is a pointer to a constant global, we
1769/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001770static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001771 bool isOffset) {
1772 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001773 User *U = cast<Instruction>(*UI);
1774
1775 if (LoadInst *LI = dyn_cast<LoadInst>(U))
Chris Lattner6e733d32009-01-28 20:16:43 +00001776 // Ignore non-volatile loads, they are always ok.
1777 if (!LI->isVolatile())
1778 continue;
1779
Gabor Greif8a8a4352010-04-06 19:32:30 +00001780 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001781 // If uses of the bitcast are ok, we are ok.
1782 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1783 return false;
1784 continue;
1785 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001786 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001787 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1788 // doesn't, it does.
1789 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1790 isOffset || !GEP->hasAllZeroIndices()))
1791 return false;
1792 continue;
1793 }
1794
1795 // If this is isn't our memcpy/memmove, reject it as something we can't
1796 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001797 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1798 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001799 return false;
1800
1801 // If we already have seen a copy, reject the second one.
1802 if (TheCopy) return false;
1803
1804 // If the pointer has been offset from the start of the alloca, we can't
1805 // safely handle this.
1806 if (isOffset) return false;
1807
1808 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001809 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001810
Chris Lattner79b3bd32007-04-25 06:40:51 +00001811 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001812 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001813 return false;
1814
1815 // Otherwise, the transform is safe. Remember the copy instruction.
1816 TheCopy = MI;
1817 }
1818 return true;
1819}
1820
1821/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1822/// modified by a copy from a constant global. If we can prove this, we can
1823/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001824MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1825 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001826 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1827 return TheCopy;
1828 return 0;
1829}