blob: 98519afa0d9f7cbe4a766caff5dec478d191bee3 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000033#include "llvm/Analysis/Dominators.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000034#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000035#include "llvm/Target/TargetData.h"
36#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000037#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000038#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000039#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000041#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000042#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000043#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000044#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000045#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000046#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000047using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000048
Chris Lattner0e5f4992006-12-19 21:40:18 +000049STATISTIC(NumReplaced, "Number of allocas broken up");
50STATISTIC(NumPromoted, "Number of allocas promoted");
51STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000052STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000053
Chris Lattner0e5f4992006-12-19 21:40:18 +000054namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000055 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000056 static char ID; // Pass identification, replacement for typeid
Owen Anderson90c579d2010-08-06 18:33:48 +000057 explicit SROA(signed T = -1) : FunctionPass(ID) {
Owen Anderson081c34b2010-10-19 17:21:58 +000058 initializeSROAPass(*PassRegistry::getPassRegistry());
Devang Patelff366852007-07-09 21:19:23 +000059 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000060 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000061 else
62 SRThreshold = T;
63 }
Devang Patel794fd752007-05-01 21:15:47 +000064
Chris Lattnered7b41e2003-05-27 15:45:27 +000065 bool runOnFunction(Function &F);
66
Chris Lattner38aec322003-09-11 16:45:55 +000067 bool performScalarRepl(Function &F);
68 bool performPromotion(Function &F);
69
Chris Lattnera15854c2003-08-31 00:45:13 +000070 // getAnalysisUsage - This pass does not require any passes, but we know it
71 // will not alter the CFG, so say so.
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000073 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000074 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000075 AU.setPreservesCFG();
76 }
77
Chris Lattnered7b41e2003-05-27 15:45:27 +000078 private:
Chris Lattner56c38522009-01-07 06:34:28 +000079 TargetData *TD;
80
Bob Wilsonb742def2009-12-18 20:14:40 +000081 /// DeadInsts - Keep track of instructions we have made dead, so that
82 /// we can remove them after we are done working.
83 SmallVector<Value*, 32> DeadInsts;
84
Chris Lattner39a1c042007-05-30 06:11:23 +000085 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
86 /// information about the uses. All these fields are initialized to false
87 /// and set to true when something is learned.
88 struct AllocaInfo {
89 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
90 bool isUnsafe : 1;
91
Chris Lattner39a1c042007-05-30 06:11:23 +000092 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
93 bool isMemCpySrc : 1;
94
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000095 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000096 bool isMemCpyDst : 1;
97
98 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +000099 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 };
101
Devang Patelff366852007-07-09 21:19:23 +0000102 unsigned SRThreshold;
103
Chris Lattner39a1c042007-05-30 06:11:23 +0000104 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
105
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000106 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000107
Bob Wilsonb742def2009-12-18 20:14:40 +0000108 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000109 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000110 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000111 AllocaInfo &Info);
112 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
113 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000114 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000115 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
116 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000117
Victor Hernandez7b929da2009-10-23 21:09:37 +0000118 void DoScalarReplacement(AllocaInst *AI,
119 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000120 void DeleteDeadInstructions();
Chris Lattner3126f1c2010-08-18 02:37:06 +0000121
Bob Wilsonb742def2009-12-18 20:14:40 +0000122 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
123 SmallVector<AllocaInst*, 32> &NewElts);
124 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
125 SmallVector<AllocaInst*, 32> &NewElts);
126 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
127 SmallVector<AllocaInst*, 32> &NewElts);
128 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000129 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000130 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000131 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000132 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000133 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000134 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000135
Chris Lattner31d80102010-04-15 21:59:20 +0000136 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000137 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000138}
139
Dan Gohman844731a2008-05-13 00:00:25 +0000140char SROA::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000141INITIALIZE_PASS_BEGIN(SROA, "scalarrepl",
142 "Scalar Replacement of Aggregates", false, false)
143INITIALIZE_PASS_DEPENDENCY(DominatorTree)
144INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
145INITIALIZE_PASS_END(SROA, "scalarrepl",
Owen Andersonce665bd2010-10-07 22:25:06 +0000146 "Scalar Replacement of Aggregates", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000147
Brian Gaeked0fde302003-11-11 22:41:34 +0000148// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000149FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
150 return new SROA(Threshold);
151}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000152
153
Chris Lattner4cc576b2010-04-16 00:24:57 +0000154//===----------------------------------------------------------------------===//
155// Convert To Scalar Optimization.
156//===----------------------------------------------------------------------===//
157
158namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000159/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
160/// optimization, which scans the uses of an alloca and determines if it can
161/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000162class ConvertToScalarInfo {
163 /// AllocaSize - The size of the alloca being considered.
164 unsigned AllocaSize;
165 const TargetData &TD;
166
Chris Lattnera0bada72010-04-16 02:32:17 +0000167 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000168 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000169 bool IsNotTrivial;
Chris Lattnera001b662010-04-16 00:38:19 +0000170
171 /// VectorTy - This tracks the type that we should promote the vector to if
172 /// it is possible to turn it into a vector. This starts out null, and if it
173 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000174 const Type *VectorTy;
Chris Lattnera001b662010-04-16 00:38:19 +0000175
176 /// HadAVector - True if there is at least one vector access to the alloca.
177 /// We don't want to turn random arrays into vectors and use vector element
178 /// insert/extract, but if there are element accesses to something that is
179 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000180 bool HadAVector;
181
182public:
183 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
184 : AllocaSize(Size), TD(td) {
185 IsNotTrivial = false;
186 VectorTy = 0;
187 HadAVector = false;
188 }
189
Chris Lattnera001b662010-04-16 00:38:19 +0000190 AllocaInst *TryConvert(AllocaInst *AI);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000191
192private:
193 bool CanConvertToScalar(Value *V, uint64_t Offset);
194 void MergeInType(const Type *In, uint64_t Offset);
195 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
196
197 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
198 uint64_t Offset, IRBuilder<> &Builder);
199 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
200 uint64_t Offset, IRBuilder<> &Builder);
201};
202} // end anonymous namespace.
203
Chris Lattner91abace2010-09-01 05:14:33 +0000204
205/// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
206/// allowed to form. We do this to avoid MMX types, which is a complete hack,
207/// but is required until the backend is fixed.
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000208static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
209 StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
210 if (!Triple.startswith("i386") &&
211 !Triple.startswith("x86_64"))
212 return false;
213
Chris Lattner91abace2010-09-01 05:14:33 +0000214 // Reject all the MMX vector types.
215 switch (VTy->getNumElements()) {
216 default: return false;
217 case 1: return VTy->getElementType()->isIntegerTy(64);
218 case 2: return VTy->getElementType()->isIntegerTy(32);
219 case 4: return VTy->getElementType()->isIntegerTy(16);
220 case 8: return VTy->getElementType()->isIntegerTy(8);
221 }
222}
223
224
Chris Lattnera001b662010-04-16 00:38:19 +0000225/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
226/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
227/// alloca if possible or null if not.
228AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
229 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
230 // out.
231 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
232 return 0;
233
234 // If we were able to find a vector type that can handle this with
235 // insert/extract elements, and if there was at least one use that had
236 // a vector type, promote this to a vector. We don't want to promote
237 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
238 // we just get a lot of insert/extracts. If at least one vector is
239 // involved, then we probably really do have a union of vector/array.
240 const Type *NewTy;
Chris Lattner91abace2010-09-01 05:14:33 +0000241 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000242 !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000243 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
244 << *VectorTy << '\n');
245 NewTy = VectorTy; // Use the vector type.
246 } else {
247 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
248 // Create and insert the integer alloca.
249 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
250 }
251 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
252 ConvertUsesToScalar(AI, NewAI, 0);
253 return NewAI;
254}
255
256/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
257/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000258///
259/// There are two cases we handle here:
260/// 1) A union of vector types of the same size and potentially its elements.
261/// Here we turn element accesses into insert/extract element operations.
262/// This promotes a <4 x float> with a store of float to the third element
263/// into a <4 x float> that uses insert element.
264/// 2) A fully general blob of memory, which we turn into some (potentially
265/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000266/// and stores would mutate the memory. We mark this by setting VectorTy
267/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000268void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000269 // If we already decided to turn this into a blob of integer memory, there is
270 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000271 if (VectorTy && VectorTy->isVoidTy())
272 return;
273
274 // If this could be contributing to a vector, analyze it.
275
276 // If the In type is a vector that is the same size as the alloca, see if it
277 // matches the existing VecTy.
278 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000279 // Remember if we saw a vector type.
280 HadAVector = true;
281
Chris Lattner4cc576b2010-04-16 00:24:57 +0000282 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
283 // If we're storing/loading a vector of the right size, allow it as a
284 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000285 // we know the element size. If this is a subsequent access, ignore it
286 // even if it is a differing type but the same size. Worst case we can
287 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000288 if (VectorTy == 0)
289 VectorTy = VInTy;
290 return;
291 }
292 } else if (In->isFloatTy() || In->isDoubleTy() ||
293 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
294 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
295 // If we're accessing something that could be an element of a vector, see
296 // if the implied vector agrees with what we already have and if Offset is
297 // compatible with it.
298 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
299 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
300 (VectorTy == 0 ||
301 cast<VectorType>(VectorTy)->getElementType()
302 ->getPrimitiveSizeInBits()/8 == EltSize)) {
303 if (VectorTy == 0)
304 VectorTy = VectorType::get(In, AllocaSize/EltSize);
305 return;
306 }
307 }
308
309 // Otherwise, we have a case that we can't handle with an optimized vector
310 // form. We can still turn this into a large integer.
311 VectorTy = Type::getVoidTy(In->getContext());
312}
313
314/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
315/// its accesses to a single vector type, return true and set VecTy to
316/// the new type. If we could convert the alloca into a single promotable
317/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
318/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
319/// is the current offset from the base of the alloca being analyzed.
320///
321/// If we see at least one access to the value that is as a vector type, set the
322/// SawVec flag.
323bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
324 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
325 Instruction *User = cast<Instruction>(*UI);
326
327 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
328 // Don't break volatile loads.
329 if (LI->isVolatile())
330 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000331 // Don't touch MMX operations.
332 if (LI->getType()->isX86_MMXTy())
333 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000334 MergeInType(LI->getType(), Offset);
335 continue;
336 }
337
338 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
339 // Storing the pointer, not into the value?
340 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000341 // Don't touch MMX operations.
342 if (SI->getOperand(0)->getType()->isX86_MMXTy())
343 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000344 MergeInType(SI->getOperand(0)->getType(), Offset);
345 continue;
346 }
347
348 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000349 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000350 if (!CanConvertToScalar(BCI, Offset))
351 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000352 continue;
353 }
354
355 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
356 // If this is a GEP with a variable indices, we can't handle it.
357 if (!GEP->hasAllConstantIndices())
358 return false;
359
360 // Compute the offset that this GEP adds to the pointer.
361 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
362 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
363 &Indices[0], Indices.size());
364 // See if all uses can be converted.
365 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
366 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000367 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000368 continue;
369 }
370
371 // If this is a constant sized memset of a constant value (e.g. 0) we can
372 // handle it.
373 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
374 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000375 if (!isa<ConstantInt>(MSI->getValue()) ||
376 !isa<ConstantInt>(MSI->getLength()))
377 return false;
378 IsNotTrivial = true; // Can't be mem2reg'd.
379 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000380 }
381
382 // If this is a memcpy or memmove into or out of the whole allocation, we
383 // can handle it like a load or store of the scalar type.
384 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000385 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
386 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
387 return false;
388
389 IsNotTrivial = true; // Can't be mem2reg'd.
390 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000391 }
392
393 // Otherwise, we cannot handle this!
394 return false;
395 }
396
397 return true;
398}
399
400/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
401/// directly. This happens when we are converting an "integer union" to a
402/// single integer scalar, or when we are converting a "vector union" to a
403/// vector with insert/extractelement instructions.
404///
405/// Offset is an offset from the original alloca, in bits that need to be
406/// shifted to the right. By the end of this, there should be no uses of Ptr.
407void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
408 uint64_t Offset) {
409 while (!Ptr->use_empty()) {
410 Instruction *User = cast<Instruction>(Ptr->use_back());
411
412 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
413 ConvertUsesToScalar(CI, NewAI, Offset);
414 CI->eraseFromParent();
415 continue;
416 }
417
418 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
419 // Compute the offset that this GEP adds to the pointer.
420 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
421 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
422 &Indices[0], Indices.size());
423 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
424 GEP->eraseFromParent();
425 continue;
426 }
427
428 IRBuilder<> Builder(User->getParent(), User);
429
430 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
431 // The load is a bit extract from NewAI shifted right by Offset bits.
432 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
433 Value *NewLoadVal
434 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
435 LI->replaceAllUsesWith(NewLoadVal);
436 LI->eraseFromParent();
437 continue;
438 }
439
440 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
441 assert(SI->getOperand(0) != Ptr && "Consistency error!");
442 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
443 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
444 Builder);
445 Builder.CreateStore(New, NewAI);
446 SI->eraseFromParent();
447
448 // If the load we just inserted is now dead, then the inserted store
449 // overwrote the entire thing.
450 if (Old->use_empty())
451 Old->eraseFromParent();
452 continue;
453 }
454
455 // If this is a constant sized memset of a constant value (e.g. 0) we can
456 // transform it into a store of the expanded constant value.
457 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
458 assert(MSI->getRawDest() == Ptr && "Consistency error!");
459 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
460 if (NumBytes != 0) {
461 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
462
463 // Compute the value replicated the right number of times.
464 APInt APVal(NumBytes*8, Val);
465
466 // Splat the value if non-zero.
467 if (Val)
468 for (unsigned i = 1; i != NumBytes; ++i)
469 APVal |= APVal << 8;
470
471 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
472 Value *New = ConvertScalar_InsertValue(
473 ConstantInt::get(User->getContext(), APVal),
474 Old, Offset, Builder);
475 Builder.CreateStore(New, NewAI);
476
477 // If the load we just inserted is now dead, then the memset overwrote
478 // the entire thing.
479 if (Old->use_empty())
480 Old->eraseFromParent();
481 }
482 MSI->eraseFromParent();
483 continue;
484 }
485
486 // If this is a memcpy or memmove into or out of the whole allocation, we
487 // can handle it like a load or store of the scalar type.
488 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
489 assert(Offset == 0 && "must be store to start of alloca");
490
491 // If the source and destination are both to the same alloca, then this is
492 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
493 // as appropriate.
Dan Gohman5034dd32010-12-15 20:02:24 +0000494 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000495
Dan Gohman5034dd32010-12-15 20:02:24 +0000496 if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000497 // Dest must be OrigAI, change this to be a load from the original
498 // pointer (bitcasted), then a store to our new alloca.
499 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
500 Value *SrcPtr = MTI->getSource();
501 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
502
503 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
504 SrcVal->setAlignment(MTI->getAlignment());
505 Builder.CreateStore(SrcVal, NewAI);
Dan Gohman5034dd32010-12-15 20:02:24 +0000506 } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000507 // Src must be OrigAI, change this to be a load from NewAI then a store
508 // through the original dest pointer (bitcasted).
509 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
510 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
511
512 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
513 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
514 NewStore->setAlignment(MTI->getAlignment());
515 } else {
516 // Noop transfer. Src == Dst
517 }
518
519 MTI->eraseFromParent();
520 continue;
521 }
522
523 llvm_unreachable("Unsupported operation!");
524 }
525}
526
527/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
528/// or vector value FromVal, extracting the bits from the offset specified by
529/// Offset. This returns the value, which is of type ToType.
530///
531/// This happens when we are converting an "integer union" to a single
532/// integer scalar, or when we are converting a "vector union" to a vector with
533/// insert/extractelement instructions.
534///
535/// Offset is an offset from the original alloca, in bits that need to be
536/// shifted to the right.
537Value *ConvertToScalarInfo::
538ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
539 uint64_t Offset, IRBuilder<> &Builder) {
540 // If the load is of the whole new alloca, no conversion is needed.
541 if (FromVal->getType() == ToType && Offset == 0)
542 return FromVal;
543
544 // If the result alloca is a vector type, this is either an element
545 // access or a bitcast to another vector type of the same size.
546 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
547 if (ToType->isVectorTy())
548 return Builder.CreateBitCast(FromVal, ToType, "tmp");
549
550 // Otherwise it must be an element access.
551 unsigned Elt = 0;
552 if (Offset) {
553 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
554 Elt = Offset/EltSize;
555 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
556 }
557 // Return the element extracted out of it.
558 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
559 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
560 if (V->getType() != ToType)
561 V = Builder.CreateBitCast(V, ToType, "tmp");
562 return V;
563 }
564
565 // If ToType is a first class aggregate, extract out each of the pieces and
566 // use insertvalue's to form the FCA.
567 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
568 const StructLayout &Layout = *TD.getStructLayout(ST);
569 Value *Res = UndefValue::get(ST);
570 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
571 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
572 Offset+Layout.getElementOffsetInBits(i),
573 Builder);
574 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
575 }
576 return Res;
577 }
578
579 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
580 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
581 Value *Res = UndefValue::get(AT);
582 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
583 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
584 Offset+i*EltSize, Builder);
585 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
586 }
587 return Res;
588 }
589
590 // Otherwise, this must be a union that was converted to an integer value.
591 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
592
593 // If this is a big-endian system and the load is narrower than the
594 // full alloca type, we need to do a shift to get the right bits.
595 int ShAmt = 0;
596 if (TD.isBigEndian()) {
597 // On big-endian machines, the lowest bit is stored at the bit offset
598 // from the pointer given by getTypeStoreSizeInBits. This matters for
599 // integers with a bitwidth that is not a multiple of 8.
600 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
601 TD.getTypeStoreSizeInBits(ToType) - Offset;
602 } else {
603 ShAmt = Offset;
604 }
605
606 // Note: we support negative bitwidths (with shl) which are not defined.
607 // We do this to support (f.e.) loads off the end of a structure where
608 // only some bits are used.
609 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
610 FromVal = Builder.CreateLShr(FromVal,
611 ConstantInt::get(FromVal->getType(),
612 ShAmt), "tmp");
613 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
614 FromVal = Builder.CreateShl(FromVal,
615 ConstantInt::get(FromVal->getType(),
616 -ShAmt), "tmp");
617
618 // Finally, unconditionally truncate the integer to the right width.
619 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
620 if (LIBitWidth < NTy->getBitWidth())
621 FromVal =
622 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
623 LIBitWidth), "tmp");
624 else if (LIBitWidth > NTy->getBitWidth())
625 FromVal =
626 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
627 LIBitWidth), "tmp");
628
629 // If the result is an integer, this is a trunc or bitcast.
630 if (ToType->isIntegerTy()) {
631 // Should be done.
632 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
633 // Just do a bitcast, we know the sizes match up.
634 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
635 } else {
636 // Otherwise must be a pointer.
637 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
638 }
639 assert(FromVal->getType() == ToType && "Didn't convert right?");
640 return FromVal;
641}
642
643/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
644/// or vector value "Old" at the offset specified by Offset.
645///
646/// This happens when we are converting an "integer union" to a
647/// single integer scalar, or when we are converting a "vector union" to a
648/// vector with insert/extractelement instructions.
649///
650/// Offset is an offset from the original alloca, in bits that need to be
651/// shifted to the right.
652Value *ConvertToScalarInfo::
653ConvertScalar_InsertValue(Value *SV, Value *Old,
654 uint64_t Offset, IRBuilder<> &Builder) {
655 // Convert the stored type to the actual type, shift it left to insert
656 // then 'or' into place.
657 const Type *AllocaType = Old->getType();
658 LLVMContext &Context = Old->getContext();
659
660 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
661 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
662 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
663
664 // Changing the whole vector with memset or with an access of a different
665 // vector type?
666 if (ValSize == VecSize)
667 return Builder.CreateBitCast(SV, AllocaType, "tmp");
668
669 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
670
671 // Must be an element insertion.
672 unsigned Elt = Offset/EltSize;
673
674 if (SV->getType() != VTy->getElementType())
675 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
676
677 SV = Builder.CreateInsertElement(Old, SV,
678 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
679 "tmp");
680 return SV;
681 }
682
683 // If SV is a first-class aggregate value, insert each value recursively.
684 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
685 const StructLayout &Layout = *TD.getStructLayout(ST);
686 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
687 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
688 Old = ConvertScalar_InsertValue(Elt, Old,
689 Offset+Layout.getElementOffsetInBits(i),
690 Builder);
691 }
692 return Old;
693 }
694
695 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
696 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
697 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
698 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
699 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
700 }
701 return Old;
702 }
703
704 // If SV is a float, convert it to the appropriate integer type.
705 // If it is a pointer, do the same.
706 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
707 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
708 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
709 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
710 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
711 SV = Builder.CreateBitCast(SV,
712 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
713 else if (SV->getType()->isPointerTy())
714 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
715
716 // Zero extend or truncate the value if needed.
717 if (SV->getType() != AllocaType) {
718 if (SV->getType()->getPrimitiveSizeInBits() <
719 AllocaType->getPrimitiveSizeInBits())
720 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
721 else {
722 // Truncation may be needed if storing more than the alloca can hold
723 // (undefined behavior).
724 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
725 SrcWidth = DestWidth;
726 SrcStoreWidth = DestStoreWidth;
727 }
728 }
729
730 // If this is a big-endian system and the store is narrower than the
731 // full alloca type, we need to do a shift to get the right bits.
732 int ShAmt = 0;
733 if (TD.isBigEndian()) {
734 // On big-endian machines, the lowest bit is stored at the bit offset
735 // from the pointer given by getTypeStoreSizeInBits. This matters for
736 // integers with a bitwidth that is not a multiple of 8.
737 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
738 } else {
739 ShAmt = Offset;
740 }
741
742 // Note: we support negative bitwidths (with shr) which are not defined.
743 // We do this to support (f.e.) stores off the end of a structure where
744 // only some bits in the structure are set.
745 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
746 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
747 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
748 ShAmt), "tmp");
749 Mask <<= ShAmt;
750 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
751 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
752 -ShAmt), "tmp");
753 Mask = Mask.lshr(-ShAmt);
754 }
755
756 // Mask out the bits we are about to insert from the old value, and or
757 // in the new bits.
758 if (SrcWidth != DestWidth) {
759 assert(DestWidth > SrcWidth);
760 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
761 SV = Builder.CreateOr(Old, SV, "ins");
762 }
763 return SV;
764}
765
766
767//===----------------------------------------------------------------------===//
768// SRoA Driver
769//===----------------------------------------------------------------------===//
770
771
Chris Lattnered7b41e2003-05-27 15:45:27 +0000772bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000773 TD = getAnalysisIfAvailable<TargetData>();
774
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000775 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000776
777 // FIXME: ScalarRepl currently depends on TargetData more than it
778 // theoretically needs to. It should be refactored in order to support
779 // target-independent IR. Until this is done, just skip the actual
780 // scalar-replacement portion of this pass.
781 if (!TD) return Changed;
782
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000783 while (1) {
784 bool LocalChange = performScalarRepl(F);
785 if (!LocalChange) break; // No need to repromote if no scalarrepl
786 Changed = true;
787 LocalChange = performPromotion(F);
788 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
789 }
Chris Lattner38aec322003-09-11 16:45:55 +0000790
791 return Changed;
792}
793
794
795bool SROA::performPromotion(Function &F) {
796 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000797 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000798 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000799
Chris Lattner02a3be02003-09-20 14:39:18 +0000800 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000801
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000802 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000803
Chris Lattner38aec322003-09-11 16:45:55 +0000804 while (1) {
805 Allocas.clear();
806
807 // Find allocas that are safe to promote, by looking at all instructions in
808 // the entry node
809 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
810 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000811 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000812 Allocas.push_back(AI);
813
814 if (Allocas.empty()) break;
815
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000816 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000817 NumPromoted += Allocas.size();
818 Changed = true;
819 }
820
821 return Changed;
822}
823
Chris Lattner4cc576b2010-04-16 00:24:57 +0000824
Bob Wilson3992feb2010-02-03 17:23:56 +0000825/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
826/// SROA. It must be a struct or array type with a small number of elements.
827static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
828 const Type *T = AI->getAllocatedType();
829 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000830 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000831 return ST->getNumElements() <= 32;
832 // Arrays are much less likely to be safe for SROA; only consider
833 // them if they are very small.
834 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
835 return AT->getNumElements() <= 8;
836 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000837}
838
Chris Lattnerc4472072010-04-15 23:50:26 +0000839
Chris Lattner38aec322003-09-11 16:45:55 +0000840// performScalarRepl - This algorithm is a simple worklist driven algorithm,
841// which runs on all of the malloc/alloca instructions in the function, removing
842// them if they are only used by getelementptr instructions.
843//
844bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000845 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000846
Chris Lattner31d80102010-04-15 21:59:20 +0000847 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000848 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000849 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000850 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000851 WorkList.push_back(A);
852
853 // Process the worklist
854 bool Changed = false;
855 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000856 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000857 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000858
Chris Lattneradd2bd72006-12-22 23:14:42 +0000859 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
860 // with unused elements.
861 if (AI->use_empty()) {
862 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000863 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000864 continue;
865 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000866
867 // If this alloca is impossible for us to promote, reject it early.
868 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
869 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000870
871 // Check to see if this allocation is only modified by a memcpy/memmove from
872 // a constant global. If this is the case, we can change all users to use
873 // the constant global instead. This is commonly produced by the CFE by
874 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
875 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000876 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000877 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
878 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000879 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000880 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000881 TheCopy->eraseFromParent(); // Don't mutate the global.
882 AI->eraseFromParent();
883 ++NumGlobals;
884 Changed = true;
885 continue;
886 }
Chris Lattner15c82772009-02-02 20:44:45 +0000887
Chris Lattner7809ecd2009-02-03 01:30:09 +0000888 // Check to see if we can perform the core SROA transformation. We cannot
889 // transform the allocation instruction if it is an array allocation
890 // (allocations OF arrays are ok though), and an allocation of a scalar
891 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000892 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000893
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000894 // Do not promote [0 x %struct].
895 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000896
897 // Do not promote any struct whose size is too big.
898 if (AllocaSize > SRThreshold) continue;
899
Bob Wilson3992feb2010-02-03 17:23:56 +0000900 // If the alloca looks like a good candidate for scalar replacement, and if
901 // all its users can be transformed, then split up the aggregate into its
902 // separate elements.
903 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
904 DoScalarReplacement(AI, WorkList);
905 Changed = true;
906 continue;
907 }
908
Chris Lattner6e733d32009-01-28 20:16:43 +0000909 // If we can turn this aggregate value (potentially with casts) into a
910 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000911 // IsNotTrivial tracks whether this is something that mem2reg could have
912 // promoted itself. If so, we don't want to transform it needlessly. Note
913 // that we can't just check based on the type: the alloca may be of an i32
914 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000915 if (AllocaInst *NewAI =
916 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000917 NewAI->takeName(AI);
918 AI->eraseFromParent();
919 ++NumConverted;
920 Changed = true;
921 continue;
Chris Lattner593375d2010-04-16 00:20:00 +0000922 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000923
Chris Lattner7809ecd2009-02-03 01:30:09 +0000924 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000925 }
926
927 return Changed;
928}
Chris Lattner5e062a12003-05-30 04:15:41 +0000929
Chris Lattnera10b29b2007-04-25 05:02:56 +0000930/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
931/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000932void SROA::DoScalarReplacement(AllocaInst *AI,
933 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000934 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000935 SmallVector<AllocaInst*, 32> ElementAllocas;
936 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
937 ElementAllocas.reserve(ST->getNumContainedTypes());
938 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000939 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000940 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000941 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000942 ElementAllocas.push_back(NA);
943 WorkList.push_back(NA); // Add to worklist for recursive processing
944 }
945 } else {
946 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
947 ElementAllocas.reserve(AT->getNumElements());
948 const Type *ElTy = AT->getElementType();
949 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000950 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000951 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000952 ElementAllocas.push_back(NA);
953 WorkList.push_back(NA); // Add to worklist for recursive processing
954 }
955 }
956
Bob Wilsonb742def2009-12-18 20:14:40 +0000957 // Now that we have created the new alloca instructions, rewrite all the
958 // uses of the old alloca.
959 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000960
Bob Wilsonb742def2009-12-18 20:14:40 +0000961 // Now erase any instructions that were made dead while rewriting the alloca.
962 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000963 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000964
Dan Gohmanfe601042010-06-22 15:08:57 +0000965 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000966}
Chris Lattnera59adc42009-12-14 05:11:02 +0000967
Bob Wilsonb742def2009-12-18 20:14:40 +0000968/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
969/// recursively including all their operands that become trivially dead.
970void SROA::DeleteDeadInstructions() {
971 while (!DeadInsts.empty()) {
972 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000973
Bob Wilsonb742def2009-12-18 20:14:40 +0000974 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
975 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
976 // Zero out the operand and see if it becomes trivially dead.
977 // (But, don't add allocas to the dead instruction list -- they are
978 // already on the worklist and will be deleted separately.)
979 *OI = 0;
980 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
981 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000982 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000983
984 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000985 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000986}
Bob Wilsonb742def2009-12-18 20:14:40 +0000987
Bob Wilsonb742def2009-12-18 20:14:40 +0000988/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
989/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000990/// the Info parameter. Offset indicates the position within AI that is
991/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000992void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000993 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000994 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
995 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000996
Bob Wilsonb742def2009-12-18 20:14:40 +0000997 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000998 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000999 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001000 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001001 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001002 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001003 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001004 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001005 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1006 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001007 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001008 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001009 else
1010 MarkUnsafe(Info);
1011 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1012 if (!LI->isVolatile()) {
1013 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001014 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001015 LIType, false, Info);
1016 } else
1017 MarkUnsafe(Info);
1018 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1019 // Store is ok if storing INTO the pointer, not storing the pointer
1020 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1021 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001022 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001023 SIType, true, Info);
1024 } else
1025 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001026 } else {
1027 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1028 MarkUnsafe(Info);
1029 }
1030 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001031 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001032}
Bob Wilson39c88a62009-12-17 18:34:24 +00001033
Bob Wilsonb742def2009-12-18 20:14:40 +00001034/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1035/// replacement. It is safe when all the indices are constant, in-bounds
1036/// references, and when the resulting offset corresponds to an element within
1037/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001038/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001039void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001040 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001041 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1042 if (GEPIt == E)
1043 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001044
Chris Lattner88e6dc82008-08-23 05:21:06 +00001045 // Walk through the GEP type indices, checking the types that this indexes
1046 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001047 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001048 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001049 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001050 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001051
Bob Wilsonb742def2009-12-18 20:14:40 +00001052 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1053 if (!IdxVal)
1054 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001055 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001056
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001057 // Compute the offset due to this GEP and check if the alloca has a
1058 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001059 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1060 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1061 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001062 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1063 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001064}
1065
Bob Wilsonb742def2009-12-18 20:14:40 +00001066/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1067/// alloca or has an offset and size that corresponds to a component element
1068/// within it. The offset checked here may have been formed from a GEP with a
1069/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001070void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001071 const Type *MemOpType, bool isStore,
1072 AllocaInfo &Info) {
1073 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001074 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001075 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1076 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1077 // (which are essentially the same as the MemIntrinsics, especially with
1078 // regard to copying padding between elements), or references using the
1079 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +00001080 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001081 if (!UsesAggregateType) {
1082 if (isStore)
1083 Info.isMemCpyDst = true;
1084 else
1085 Info.isMemCpySrc = true;
1086 }
1087 return;
1088 }
1089 }
1090 // Check if the offset/size correspond to a component within the alloca type.
1091 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001092 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +00001093 return;
1094
1095 return MarkUnsafe(Info);
1096}
1097
1098/// TypeHasComponent - Return true if T has a component type with the
1099/// specified offset and size. If Size is zero, do not check the size.
1100bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1101 const Type *EltTy;
1102 uint64_t EltSize;
1103 if (const StructType *ST = dyn_cast<StructType>(T)) {
1104 const StructLayout *Layout = TD->getStructLayout(ST);
1105 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1106 EltTy = ST->getContainedType(EltIdx);
1107 EltSize = TD->getTypeAllocSize(EltTy);
1108 Offset -= Layout->getElementOffset(EltIdx);
1109 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1110 EltTy = AT->getElementType();
1111 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001112 if (Offset >= AT->getNumElements() * EltSize)
1113 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001114 Offset %= EltSize;
1115 } else {
1116 return false;
1117 }
1118 if (Offset == 0 && (Size == 0 || EltSize == Size))
1119 return true;
1120 // Check if the component spans multiple elements.
1121 if (Offset + Size > EltSize)
1122 return false;
1123 return TypeHasComponent(EltTy, Offset, Size);
1124}
1125
1126/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1127/// the instruction I, which references it, to use the separate elements.
1128/// Offset indicates the position within AI that is referenced by this
1129/// instruction.
1130void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1131 SmallVector<AllocaInst*, 32> &NewElts) {
1132 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1133 Instruction *User = cast<Instruction>(*UI);
1134
1135 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1136 RewriteBitCast(BC, AI, Offset, NewElts);
1137 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1138 RewriteGEP(GEPI, AI, Offset, NewElts);
1139 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1140 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1141 uint64_t MemSize = Length->getZExtValue();
1142 if (Offset == 0 &&
1143 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1144 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001145 // Otherwise the intrinsic can only touch a single element and the
1146 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001147 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1148 const Type *LIType = LI->getType();
1149 if (LIType == AI->getAllocatedType()) {
1150 // Replace:
1151 // %res = load { i32, i32 }* %alloc
1152 // with:
1153 // %load.0 = load i32* %alloc.0
1154 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1155 // %load.1 = load i32* %alloc.1
1156 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1157 // (Also works for arrays instead of structs)
1158 Value *Insert = UndefValue::get(LIType);
1159 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1160 Value *Load = new LoadInst(NewElts[i], "load", LI);
1161 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1162 }
1163 LI->replaceAllUsesWith(Insert);
1164 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001165 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001166 TD->getTypeAllocSize(LIType) ==
1167 TD->getTypeAllocSize(AI->getAllocatedType())) {
1168 // If this is a load of the entire alloca to an integer, rewrite it.
1169 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1170 }
1171 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1172 Value *Val = SI->getOperand(0);
1173 const Type *SIType = Val->getType();
1174 if (SIType == AI->getAllocatedType()) {
1175 // Replace:
1176 // store { i32, i32 } %val, { i32, i32 }* %alloc
1177 // with:
1178 // %val.0 = extractvalue { i32, i32 } %val, 0
1179 // store i32 %val.0, i32* %alloc.0
1180 // %val.1 = extractvalue { i32, i32 } %val, 1
1181 // store i32 %val.1, i32* %alloc.1
1182 // (Also works for arrays instead of structs)
1183 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1184 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1185 new StoreInst(Extract, NewElts[i], SI);
1186 }
1187 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001188 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001189 TD->getTypeAllocSize(SIType) ==
1190 TD->getTypeAllocSize(AI->getAllocatedType())) {
1191 // If this is a store of the entire alloca from an integer, rewrite it.
1192 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1193 }
1194 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001195 }
1196}
1197
Bob Wilsonb742def2009-12-18 20:14:40 +00001198/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1199/// and recursively continue updating all of its uses.
1200void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1201 SmallVector<AllocaInst*, 32> &NewElts) {
1202 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1203 if (BC->getOperand(0) != AI)
1204 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001205
Bob Wilsonb742def2009-12-18 20:14:40 +00001206 // The bitcast references the original alloca. Replace its uses with
1207 // references to the first new element alloca.
1208 Instruction *Val = NewElts[0];
1209 if (Val->getType() != BC->getDestTy()) {
1210 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1211 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001212 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001213 BC->replaceAllUsesWith(Val);
1214 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001215}
1216
Bob Wilsonb742def2009-12-18 20:14:40 +00001217/// FindElementAndOffset - Return the index of the element containing Offset
1218/// within the specified type, which must be either a struct or an array.
1219/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001220/// element. IdxTy is set to the type of the index result to be used in a
1221/// GEP instruction.
1222uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1223 const Type *&IdxTy) {
1224 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001225 if (const StructType *ST = dyn_cast<StructType>(T)) {
1226 const StructLayout *Layout = TD->getStructLayout(ST);
1227 Idx = Layout->getElementContainingOffset(Offset);
1228 T = ST->getContainedType(Idx);
1229 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001230 IdxTy = Type::getInt32Ty(T->getContext());
1231 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001232 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001233 const ArrayType *AT = cast<ArrayType>(T);
1234 T = AT->getElementType();
1235 uint64_t EltSize = TD->getTypeAllocSize(T);
1236 Idx = Offset / EltSize;
1237 Offset -= Idx * EltSize;
1238 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001239 return Idx;
1240}
1241
1242/// RewriteGEP - Check if this GEP instruction moves the pointer across
1243/// elements of the alloca that are being split apart, and if so, rewrite
1244/// the GEP to be relative to the new element.
1245void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1246 SmallVector<AllocaInst*, 32> &NewElts) {
1247 uint64_t OldOffset = Offset;
1248 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1249 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1250 &Indices[0], Indices.size());
1251
1252 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1253
1254 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001255 const Type *IdxTy;
1256 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001257 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001258 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001259
1260 T = AI->getAllocatedType();
1261 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001262 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001263
1264 // If this GEP does not move the pointer across elements of the alloca
1265 // being split, then it does not needs to be rewritten.
1266 if (Idx == OldIdx)
1267 return;
1268
1269 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1270 SmallVector<Value*, 8> NewArgs;
1271 NewArgs.push_back(Constant::getNullValue(i32Ty));
1272 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001273 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1274 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001275 }
1276 Instruction *Val = NewElts[Idx];
1277 if (NewArgs.size() > 1) {
1278 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1279 NewArgs.end(), "", GEPI);
1280 Val->takeName(GEPI);
1281 }
1282 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001283 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001284 GEPI->replaceAllUsesWith(Val);
1285 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001286}
1287
1288/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1289/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001290void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001291 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001292 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001293 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001294 // appropriate type. The "Other" pointer is the pointer that goes to memory
1295 // that doesn't have anything to do with the alloca that we are promoting. For
1296 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001297 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001298 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001299 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001300 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001301 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001302 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001303 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001304 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001305 }
1306 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001307
Chris Lattnerd93afec2009-01-07 07:18:45 +00001308 // If there is an other pointer, we want to convert it to the same pointer
1309 // type as AI has, so we can GEP through it safely.
1310 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001311 unsigned AddrSpace =
1312 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001313
1314 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1315 // optimization, but it's also required to detect the corner case where
1316 // both pointer operands are referencing the same memory, and where
1317 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1318 // function is only called for mem intrinsics that access the whole
1319 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001320 OtherPtr = OtherPtr->stripPointerCasts();
1321
Bob Wilsona756b1d2010-01-19 04:32:48 +00001322 // Copying the alloca to itself is a no-op: just delete it.
1323 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1324 // This code will run twice for a no-op memcpy -- once for each operand.
1325 // Put only one reference to MI on the DeadInsts list.
1326 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1327 E = DeadInsts.end(); I != E; ++I)
1328 if (*I == MI) return;
1329 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001330 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001331 }
Chris Lattner372dda82007-03-05 07:52:57 +00001332
Chris Lattnerd93afec2009-01-07 07:18:45 +00001333 // If the pointer is not the right type, insert a bitcast to the right
1334 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001335 const Type *NewTy =
1336 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1337
1338 if (OtherPtr->getType() != NewTy)
1339 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001340 }
1341
1342 // Process each element of the aggregate.
Gabor Greifa9b23132010-04-20 13:13:04 +00001343 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001344 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +00001345 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +00001346
Owen Anderson1d0be152009-08-13 21:58:54 +00001347 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001348
1349 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1350 // If this is a memcpy/memmove, emit a GEP of the other element address.
1351 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001352 unsigned OtherEltAlign = MemAlignment;
1353
Bob Wilsona756b1d2010-01-19 04:32:48 +00001354 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001355 Value *Idx[2] = { Zero,
1356 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001357 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001358 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001359 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001360 uint64_t EltOffset;
1361 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001362 const Type *OtherTy = OtherPtrTy->getElementType();
1363 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001364 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1365 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001366 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001367 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001368 }
1369
1370 // The alignment of the other pointer is the guaranteed alignment of the
1371 // element, which is affected by both the known alignment of the whole
1372 // mem intrinsic and the alignment of the element. If the alignment of
1373 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1374 // known alignment is just 4 bytes.
1375 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001376 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001377
1378 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001379 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001380
1381 // If we got down to a scalar, insert a load or store as appropriate.
1382 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001383 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001384 if (SROADest) {
1385 // From Other to Alloca.
1386 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1387 new StoreInst(Elt, EltPtr, MI);
1388 } else {
1389 // From Alloca to Other.
1390 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1391 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1392 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001393 continue;
1394 }
1395 assert(isa<MemSetInst>(MI));
1396
1397 // If the stored element is zero (common case), just store a null
1398 // constant.
1399 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001400 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001401 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001402 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001403 } else {
1404 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001405 const Type *ValTy = EltTy->getScalarType();
1406
Chris Lattnerd93afec2009-01-07 07:18:45 +00001407 // Construct an integer with the right value.
1408 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1409 APInt OneVal(EltSize, CI->getZExtValue());
1410 APInt TotalVal(OneVal);
1411 // Set each byte.
1412 for (unsigned i = 0; 8*i < EltSize; ++i) {
1413 TotalVal = TotalVal.shl(8);
1414 TotalVal |= OneVal;
1415 }
1416
1417 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001418 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001419 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001420 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001421 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001422 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001423 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1424
1425 // If the requested value was a vector constant, create it.
1426 if (EltTy != ValTy) {
1427 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1428 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001429 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001430 }
1431 }
1432 new StoreInst(StoreVal, EltPtr, MI);
1433 continue;
1434 }
1435 // Otherwise, if we're storing a byte variable, use a memset call for
1436 // this element.
1437 }
1438
1439 // Cast the element pointer to BytePtrTy.
1440 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001441 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001442
1443 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +00001444 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1445 // Preserve address space of OtherElt
1446 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1447 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1448 if (OtherPTy->getElementType() != PTy->getElementType()) {
1449 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1450 OtherPTy->getAddressSpace());
1451 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
Benjamin Krameraf812352010-10-16 11:28:23 +00001452 OtherElt->getName(), MI);
Mon P Wang20adc9d2010-04-04 03:10:48 +00001453 }
1454 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001455
Duncan Sands777d2302009-05-09 07:06:46 +00001456 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001457
1458 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001459 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001460 Value *Ops[] = {
1461 SROADest ? EltPtr : OtherElt, // Dest ptr
1462 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001463 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +00001464 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +00001465 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1466 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +00001467 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001468 // In case we fold the address space overloaded memcpy of A to B
1469 // with memcpy of B to C, change the function to be a memcpy of A to C.
1470 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1471 Ops[2]->getType() };
1472 Module *M = MI->getParent()->getParent()->getParent();
1473 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1474 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001475 } else {
1476 assert(isa<MemSetInst>(MI));
1477 Value *Ops[] = {
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001478 EltPtr, MI->getArgOperand(1), // Dest, Value,
1479 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +00001480 Zero, // Align
Benjamin Kramerf601d6d2010-11-20 18:43:35 +00001481 ConstantInt::getFalse(MI->getContext()) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +00001482 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001483 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1484 Module *M = MI->getParent()->getParent()->getParent();
1485 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1486 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001487 }
Chris Lattner372dda82007-03-05 07:52:57 +00001488 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001489 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001490}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001491
Bob Wilson39fdd692009-12-04 21:57:37 +00001492/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001493/// overwrites the entire allocation. Extract out the pieces of the stored
1494/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001495void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001496 SmallVector<AllocaInst*, 32> &NewElts){
1497 // Extract each element out of the integer according to its structure offset
1498 // and store the element value to the individual alloca.
1499 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001500 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001501 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001502
Eli Friedman41b33f42009-06-01 09:14:32 +00001503 // Handle tail padding by extending the operand
1504 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001505 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001506 IntegerType::get(SI->getContext(), AllocaSizeBits),
1507 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001508
David Greene504c7d82010-01-05 01:27:09 +00001509 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001510 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001511
1512 // There are two forms here: AI could be an array or struct. Both cases
1513 // have different ways to compute the element offset.
1514 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1515 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1516
1517 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1518 // Get the number of bits to shift SrcVal to get the value.
1519 const Type *FieldTy = EltSTy->getElementType(i);
1520 uint64_t Shift = Layout->getElementOffsetInBits(i);
1521
1522 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001523 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001524
1525 Value *EltVal = SrcVal;
1526 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001527 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001528 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1529 "sroa.store.elt", SI);
1530 }
1531
1532 // Truncate down to an integer of the right size.
1533 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +00001534
1535 // Ignore zero sized fields like {}, they obviously contain no data.
1536 if (FieldSizeBits == 0) continue;
1537
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001538 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001539 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001540 IntegerType::get(SI->getContext(), FieldSizeBits),
1541 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001542 Value *DestField = NewElts[i];
1543 if (EltVal->getType() == FieldTy) {
1544 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001545 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001546 // Bitcast to the right element type (for fp/vector values).
1547 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1548 } else {
1549 // Otherwise, bitcast the dest pointer (for aggregates).
1550 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001551 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001552 "", SI);
1553 }
1554 new StoreInst(EltVal, DestField, SI);
1555 }
1556
1557 } else {
1558 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1559 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001560 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001561 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1562
1563 uint64_t Shift;
1564
1565 if (TD->isBigEndian())
1566 Shift = AllocaSizeBits-ElementOffset;
1567 else
1568 Shift = 0;
1569
1570 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001571 // Ignore zero sized fields like {}, they obviously contain no data.
1572 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001573
1574 Value *EltVal = SrcVal;
1575 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001576 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001577 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1578 "sroa.store.elt", SI);
1579 }
1580
1581 // Truncate down to an integer of the right size.
1582 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001583 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001584 IntegerType::get(SI->getContext(),
1585 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001586 Value *DestField = NewElts[i];
1587 if (EltVal->getType() == ArrayEltTy) {
1588 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001589 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001590 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001591 // Bitcast to the right element type (for fp/vector values).
1592 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1593 } else {
1594 // Otherwise, bitcast the dest pointer (for aggregates).
1595 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001596 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001597 "", SI);
1598 }
1599 new StoreInst(EltVal, DestField, SI);
1600
1601 if (TD->isBigEndian())
1602 Shift -= ElementOffset;
1603 else
1604 Shift += ElementOffset;
1605 }
1606 }
1607
Bob Wilsonb742def2009-12-18 20:14:40 +00001608 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001609}
1610
Bob Wilson39fdd692009-12-04 21:57:37 +00001611/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001612/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001613void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001614 SmallVector<AllocaInst*, 32> &NewElts) {
1615 // Extract each element out of the NewElts according to its structure offset
1616 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001617 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001618 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001619
David Greene504c7d82010-01-05 01:27:09 +00001620 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001621 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001622
1623 // There are two forms here: AI could be an array or struct. Both cases
1624 // have different ways to compute the element offset.
1625 const StructLayout *Layout = 0;
1626 uint64_t ArrayEltBitOffset = 0;
1627 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1628 Layout = TD->getStructLayout(EltSTy);
1629 } else {
1630 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001631 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001632 }
Owen Andersone922c022009-07-22 00:24:57 +00001633
Owen Andersone922c022009-07-22 00:24:57 +00001634 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001635 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001636
1637 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1638 // Load the value from the alloca. If the NewElt is an aggregate, cast
1639 // the pointer to an integer of the same size before doing the load.
1640 Value *SrcField = NewElts[i];
1641 const Type *FieldTy =
1642 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001643 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1644
1645 // Ignore zero sized fields like {}, they obviously contain no data.
1646 if (FieldSizeBits == 0) continue;
1647
Owen Anderson1d0be152009-08-13 21:58:54 +00001648 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1649 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001650 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1651 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001652 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001653 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001654 "", LI);
1655 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1656
1657 // If SrcField is a fp or vector of the right size but that isn't an
1658 // integer type, bitcast to an integer so we can shift it.
1659 if (SrcField->getType() != FieldIntTy)
1660 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1661
1662 // Zero extend the field to be the same size as the final alloca so that
1663 // we can shift and insert it.
1664 if (SrcField->getType() != ResultVal->getType())
1665 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1666
1667 // Determine the number of bits to shift SrcField.
1668 uint64_t Shift;
1669 if (Layout) // Struct case.
1670 Shift = Layout->getElementOffsetInBits(i);
1671 else // Array case.
1672 Shift = i*ArrayEltBitOffset;
1673
1674 if (TD->isBigEndian())
1675 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1676
1677 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001678 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001679 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1680 }
1681
Chris Lattner14952472010-06-27 07:58:26 +00001682 // Don't create an 'or x, 0' on the first iteration.
1683 if (!isa<Constant>(ResultVal) ||
1684 !cast<Constant>(ResultVal)->isNullValue())
1685 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1686 else
1687 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001688 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001689
1690 // Handle tail padding by truncating the result
1691 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1692 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1693
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001694 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001695 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001696}
1697
Duncan Sands3cb36502007-11-04 14:43:57 +00001698/// HasPadding - Return true if the specified type has any structure or
1699/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001700static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner91abace2010-09-01 05:14:33 +00001701 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
1702 return HasPadding(ATy->getElementType(), TD);
1703
1704 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
1705 return HasPadding(VTy->getElementType(), TD);
1706
Chris Lattner39a1c042007-05-30 06:11:23 +00001707 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1708 const StructLayout *SL = TD.getStructLayout(STy);
1709 unsigned PrevFieldBitOffset = 0;
1710 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001711 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1712
Chris Lattner39a1c042007-05-30 06:11:23 +00001713 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001714 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001715 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001716
Chris Lattner39a1c042007-05-30 06:11:23 +00001717 // Check to see if there is any padding between this element and the
1718 // previous one.
1719 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001720 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001721 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1722 if (PrevFieldEnd < FieldBitOffset)
1723 return true;
1724 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001725
Chris Lattner39a1c042007-05-30 06:11:23 +00001726 PrevFieldBitOffset = FieldBitOffset;
1727 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001728
Chris Lattner39a1c042007-05-30 06:11:23 +00001729 // Check for tail padding.
1730 if (unsigned EltCount = STy->getNumElements()) {
1731 unsigned PrevFieldEnd = PrevFieldBitOffset +
1732 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001733 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001734 return true;
1735 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001736 }
Chris Lattner91abace2010-09-01 05:14:33 +00001737
Duncan Sands777d2302009-05-09 07:06:46 +00001738 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001739}
Chris Lattner372dda82007-03-05 07:52:57 +00001740
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001741/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1742/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1743/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001744bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001745 // Loop over the use list of the alloca. We can only transform it if all of
1746 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001747 AllocaInfo Info;
1748
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001749 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001750 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001751 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001752 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001753 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001754
1755 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1756 // source and destination, we have to be careful. In particular, the memcpy
1757 // could be moving around elements that live in structure padding of the LLVM
1758 // types, but may actually be used. In these cases, we refuse to promote the
1759 // struct.
1760 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001761 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001762 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001763
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001764 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001765}
Chris Lattnera1888942005-12-12 07:19:13 +00001766
Chris Lattner800de312008-02-29 07:03:13 +00001767
Chris Lattner79b3bd32007-04-25 06:40:51 +00001768
1769/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1770/// some part of a constant global variable. This intentionally only accepts
1771/// constant expressions because we don't can't rewrite arbitrary instructions.
1772static bool PointsToConstantGlobal(Value *V) {
1773 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1774 return GV->isConstant();
1775 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1776 if (CE->getOpcode() == Instruction::BitCast ||
1777 CE->getOpcode() == Instruction::GetElementPtr)
1778 return PointsToConstantGlobal(CE->getOperand(0));
1779 return false;
1780}
1781
1782/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1783/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1784/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1785/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1786/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00001787/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00001788/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001789static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001790 bool isOffset) {
1791 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001792 User *U = cast<Instruction>(*UI);
1793
Chris Lattner2e618492010-11-18 06:20:47 +00001794 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001795 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00001796 if (LI->isVolatile()) return false;
1797 continue;
1798 }
Chris Lattner6e733d32009-01-28 20:16:43 +00001799
Gabor Greif8a8a4352010-04-06 19:32:30 +00001800 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001801 // If uses of the bitcast are ok, we are ok.
1802 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1803 return false;
1804 continue;
1805 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001806 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001807 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1808 // doesn't, it does.
1809 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1810 isOffset || !GEP->hasAllZeroIndices()))
1811 return false;
1812 continue;
1813 }
1814
Chris Lattner62480652010-11-18 06:41:51 +00001815 if (CallSite CS = U) {
1816 // If this is a readonly/readnone call site, then we know it is just a
1817 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00001818 if (CS.onlyReadsMemory())
1819 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00001820
1821 // If this is the function being called then we treat it like a load and
1822 // ignore it.
1823 if (CS.isCallee(UI))
1824 continue;
Chris Lattner62480652010-11-18 06:41:51 +00001825
1826 // If this is being passed as a byval argument, the caller is making a
1827 // copy, so it is only a read of the alloca.
1828 unsigned ArgNo = CS.getArgumentNo(UI);
1829 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
1830 continue;
1831 }
Chris Lattnera9be1df2010-11-18 06:26:49 +00001832
Chris Lattner79b3bd32007-04-25 06:40:51 +00001833 // If this is isn't our memcpy/memmove, reject it as something we can't
1834 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001835 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1836 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001837 return false;
Chris Lattner2e618492010-11-18 06:20:47 +00001838
1839 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00001840 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00001841 if (UI.getOperandNo() == 1) {
1842 if (MI->isVolatile()) return false;
1843 continue;
1844 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00001845
1846 // If we already have seen a copy, reject the second one.
1847 if (TheCopy) return false;
1848
1849 // If the pointer has been offset from the start of the alloca, we can't
1850 // safely handle this.
1851 if (isOffset) return false;
1852
1853 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001854 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001855
Chris Lattner79b3bd32007-04-25 06:40:51 +00001856 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001857 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001858 return false;
1859
1860 // Otherwise, the transform is safe. Remember the copy instruction.
1861 TheCopy = MI;
1862 }
1863 return true;
1864}
1865
1866/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1867/// modified by a copy from a constant global. If we can prove this, we can
1868/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001869MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1870 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001871 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1872 return TheCopy;
1873 return 0;
1874}