blob: a068556b734bf694ffbdb832054a7bdb4259fc63 [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 Lattner9fc5cdf2011-01-02 22:09:33 +000033#include "llvm/Analysis/DominanceFrontier.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000034#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000035#include "llvm/Target/TargetData.h"
36#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000037#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000038#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000039#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000040#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000043#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000044#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000045#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000046#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000047#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Chris Lattner0e5f4992006-12-19 21:40:18 +000050STATISTIC(NumReplaced, "Number of allocas broken up");
51STATISTIC(NumPromoted, "Number of allocas promoted");
52STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000053STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000054
Chris Lattner0e5f4992006-12-19 21:40:18 +000055namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000056 struct SROA : public FunctionPass {
Chris Lattnerb352d6e2011-01-14 08:13:00 +000057 SROA(int T, bool hasDF, char &ID)
58 : FunctionPass(ID), HasDomFrontiers(hasDF) {
Devang Patelff366852007-07-09 21:19:23 +000059 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000060 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000061 else
62 SRThreshold = T;
63 }
Devang Patel794fd752007-05-01 21:15:47 +000064
Chris Lattnered7b41e2003-05-27 15:45:27 +000065 bool runOnFunction(Function &F);
66
Chris Lattner38aec322003-09-11 16:45:55 +000067 bool performScalarRepl(Function &F);
68 bool performPromotion(Function &F);
69
Chris Lattnered7b41e2003-05-27 15:45:27 +000070 private:
Chris Lattnerb352d6e2011-01-14 08:13:00 +000071 bool HasDomFrontiers;
Chris Lattner56c38522009-01-07 06:34:28 +000072 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000073
Bob Wilsonb742def2009-12-18 20:14:40 +000074 /// DeadInsts - Keep track of instructions we have made dead, so that
75 /// we can remove them after we are done working.
76 SmallVector<Value*, 32> DeadInsts;
77
Chris Lattner39a1c042007-05-30 06:11:23 +000078 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
79 /// information about the uses. All these fields are initialized to false
80 /// and set to true when something is learned.
81 struct AllocaInfo {
82 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
83 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000084
Chris Lattner39a1c042007-05-30 06:11:23 +000085 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
86 bool isMemCpySrc : 1;
87
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000088 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000089 bool isMemCpyDst : 1;
90
Chris Lattner7e9b4272011-01-16 06:18:28 +000091 /// hasSubelementAccess - This is true if a subelement of the alloca is
92 /// ever accessed, or false if the alloca is only accessed with mem
93 /// intrinsics or load/store that only access the entire alloca at once.
94 bool hasSubelementAccess : 1;
95
96 /// hasALoadOrStore - This is true if there are any loads or stores to it.
97 /// The alloca may just be accessed with memcpy, for example, which would
98 /// not set this.
99 bool hasALoadOrStore : 1;
100
Chris Lattner39a1c042007-05-30 06:11:23 +0000101 AllocaInfo()
Chris Lattner7e9b4272011-01-16 06:18:28 +0000102 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
103 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000104 };
Bob Wilson69743022011-01-13 20:59:44 +0000105
Devang Patelff366852007-07-09 21:19:23 +0000106 unsigned SRThreshold;
107
Chris Lattner39a1c042007-05-30 06:11:23 +0000108 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
109
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000110 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000111
Bob Wilsonb742def2009-12-18 20:14:40 +0000112 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000113 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000114 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000115 AllocaInfo &Info);
116 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
117 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000118 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000119 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
120 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000121
122 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000123 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000124 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000125
Bob Wilsonb742def2009-12-18 20:14:40 +0000126 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
127 SmallVector<AllocaInst*, 32> &NewElts);
128 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
129 SmallVector<AllocaInst*, 32> &NewElts);
130 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
131 SmallVector<AllocaInst*, 32> &NewElts);
132 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000133 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000134 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000135 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000136 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000137 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000138 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000139
Chris Lattner31d80102010-04-15 21:59:20 +0000140 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000141 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000142
143 // SROA_DF - SROA that uses DominanceFrontier.
144 struct SROA_DF : public SROA {
145 static char ID;
146 public:
147 SROA_DF(int T = -1) : SROA(T, true, ID) {
148 initializeSROA_DFPass(*PassRegistry::getPassRegistry());
149 }
150
151 // getAnalysisUsage - This pass does not require any passes, but we know it
152 // will not alter the CFG, so say so.
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<DominatorTree>();
Cameron Zwarichb1086a92011-01-17 07:26:51 +0000155 AU.addRequired<DominanceFrontier>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000156 AU.setPreservesCFG();
157 }
158 };
159
160 // SROA_SSAUp - SROA that uses SSAUpdater.
161 struct SROA_SSAUp : public SROA {
162 static char ID;
163 public:
164 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
165 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
166 }
167
168 // getAnalysisUsage - This pass does not require any passes, but we know it
169 // will not alter the CFG, so say so.
170 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
171 AU.setPreservesCFG();
172 }
173 };
174
Chris Lattnered7b41e2003-05-27 15:45:27 +0000175}
176
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000177char SROA_DF::ID = 0;
178char SROA_SSAUp::ID = 0;
179
180INITIALIZE_PASS_BEGIN(SROA_DF, "scalarrepl",
181 "Scalar Replacement of Aggregates (DF)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000182INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1086a92011-01-17 07:26:51 +0000183INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000184INITIALIZE_PASS_END(SROA_DF, "scalarrepl",
185 "Scalar Replacement of Aggregates (DF)", false, false)
186
187INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
188 "Scalar Replacement of Aggregates (SSAUp)", false, false)
189INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
190 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000191
Brian Gaeked0fde302003-11-11 22:41:34 +0000192// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000193FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
194 bool UseDomFrontier) {
195 if (UseDomFrontier)
196 return new SROA_DF(Threshold);
197 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000198}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000199
200
Chris Lattner4cc576b2010-04-16 00:24:57 +0000201//===----------------------------------------------------------------------===//
202// Convert To Scalar Optimization.
203//===----------------------------------------------------------------------===//
204
205namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000206/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
207/// optimization, which scans the uses of an alloca and determines if it can
208/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000209class ConvertToScalarInfo {
210 /// AllocaSize - The size of the alloca being considered.
211 unsigned AllocaSize;
212 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000213
Chris Lattnera0bada72010-04-16 02:32:17 +0000214 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000215 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000216 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000217
Chris Lattnera001b662010-04-16 00:38:19 +0000218 /// VectorTy - This tracks the type that we should promote the vector to if
219 /// it is possible to turn it into a vector. This starts out null, and if it
220 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000221 const Type *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000222
Chris Lattnera001b662010-04-16 00:38:19 +0000223 /// HadAVector - True if there is at least one vector access to the alloca.
224 /// We don't want to turn random arrays into vectors and use vector element
225 /// insert/extract, but if there are element accesses to something that is
226 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000227 bool HadAVector;
228
229public:
230 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
231 : AllocaSize(Size), TD(td) {
232 IsNotTrivial = false;
233 VectorTy = 0;
234 HadAVector = false;
235 }
Bob Wilson69743022011-01-13 20:59:44 +0000236
Chris Lattnera001b662010-04-16 00:38:19 +0000237 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000238
Chris Lattner4cc576b2010-04-16 00:24:57 +0000239private:
240 bool CanConvertToScalar(Value *V, uint64_t Offset);
241 void MergeInType(const Type *In, uint64_t Offset);
242 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000243
Chris Lattner4cc576b2010-04-16 00:24:57 +0000244 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
245 uint64_t Offset, IRBuilder<> &Builder);
246 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
247 uint64_t Offset, IRBuilder<> &Builder);
248};
249} // end anonymous namespace.
250
Chris Lattner91abace2010-09-01 05:14:33 +0000251
252/// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
253/// allowed to form. We do this to avoid MMX types, which is a complete hack,
254/// but is required until the backend is fixed.
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000255static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
256 StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
257 if (!Triple.startswith("i386") &&
258 !Triple.startswith("x86_64"))
259 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000260
Chris Lattner91abace2010-09-01 05:14:33 +0000261 // Reject all the MMX vector types.
262 switch (VTy->getNumElements()) {
263 default: return false;
264 case 1: return VTy->getElementType()->isIntegerTy(64);
265 case 2: return VTy->getElementType()->isIntegerTy(32);
266 case 4: return VTy->getElementType()->isIntegerTy(16);
267 case 8: return VTy->getElementType()->isIntegerTy(8);
268 }
269}
270
271
Chris Lattnera001b662010-04-16 00:38:19 +0000272/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
273/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
274/// alloca if possible or null if not.
275AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
276 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
277 // out.
278 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
279 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000280
Chris Lattnera001b662010-04-16 00:38:19 +0000281 // If we were able to find a vector type that can handle this with
282 // insert/extract elements, and if there was at least one use that had
283 // a vector type, promote this to a vector. We don't want to promote
284 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
285 // we just get a lot of insert/extracts. If at least one vector is
286 // involved, then we probably really do have a union of vector/array.
287 const Type *NewTy;
Chris Lattner91abace2010-09-01 05:14:33 +0000288 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000289 !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000290 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
291 << *VectorTy << '\n');
292 NewTy = VectorTy; // Use the vector type.
293 } else {
294 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
295 // Create and insert the integer alloca.
296 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
297 }
298 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
299 ConvertUsesToScalar(AI, NewAI, 0);
300 return NewAI;
301}
302
303/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
304/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000305///
306/// There are two cases we handle here:
307/// 1) A union of vector types of the same size and potentially its elements.
308/// Here we turn element accesses into insert/extract element operations.
309/// This promotes a <4 x float> with a store of float to the third element
310/// into a <4 x float> that uses insert element.
311/// 2) A fully general blob of memory, which we turn into some (potentially
312/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000313/// and stores would mutate the memory. We mark this by setting VectorTy
314/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000315void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000316 // If we already decided to turn this into a blob of integer memory, there is
317 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000318 if (VectorTy && VectorTy->isVoidTy())
319 return;
Bob Wilson69743022011-01-13 20:59:44 +0000320
Chris Lattner4cc576b2010-04-16 00:24:57 +0000321 // If this could be contributing to a vector, analyze it.
322
323 // If the In type is a vector that is the same size as the alloca, see if it
324 // matches the existing VecTy.
325 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000326 // Remember if we saw a vector type.
327 HadAVector = true;
Bob Wilson69743022011-01-13 20:59:44 +0000328
Chris Lattner4cc576b2010-04-16 00:24:57 +0000329 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
330 // If we're storing/loading a vector of the right size, allow it as a
331 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000332 // we know the element size. If this is a subsequent access, ignore it
333 // even if it is a differing type but the same size. Worst case we can
334 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000335 if (VectorTy == 0)
336 VectorTy = VInTy;
337 return;
338 }
339 } else if (In->isFloatTy() || In->isDoubleTy() ||
340 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
341 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
342 // If we're accessing something that could be an element of a vector, see
343 // if the implied vector agrees with what we already have and if Offset is
344 // compatible with it.
345 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
346 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Bob Wilson69743022011-01-13 20:59:44 +0000347 (VectorTy == 0 ||
Chris Lattner4cc576b2010-04-16 00:24:57 +0000348 cast<VectorType>(VectorTy)->getElementType()
349 ->getPrimitiveSizeInBits()/8 == EltSize)) {
350 if (VectorTy == 0)
351 VectorTy = VectorType::get(In, AllocaSize/EltSize);
352 return;
353 }
354 }
Bob Wilson69743022011-01-13 20:59:44 +0000355
Chris Lattner4cc576b2010-04-16 00:24:57 +0000356 // Otherwise, we have a case that we can't handle with an optimized vector
357 // form. We can still turn this into a large integer.
358 VectorTy = Type::getVoidTy(In->getContext());
359}
360
361/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
362/// its accesses to a single vector type, return true and set VecTy to
363/// the new type. If we could convert the alloca into a single promotable
364/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
365/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
366/// is the current offset from the base of the alloca being analyzed.
367///
368/// If we see at least one access to the value that is as a vector type, set the
369/// SawVec flag.
370bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
371 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
372 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000373
Chris Lattner4cc576b2010-04-16 00:24:57 +0000374 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
375 // Don't break volatile loads.
376 if (LI->isVolatile())
377 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000378 // Don't touch MMX operations.
379 if (LI->getType()->isX86_MMXTy())
380 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000381 MergeInType(LI->getType(), Offset);
382 continue;
383 }
Bob Wilson69743022011-01-13 20:59:44 +0000384
Chris Lattner4cc576b2010-04-16 00:24:57 +0000385 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
386 // Storing the pointer, not into the value?
387 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000388 // Don't touch MMX operations.
389 if (SI->getOperand(0)->getType()->isX86_MMXTy())
390 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000391 MergeInType(SI->getOperand(0)->getType(), Offset);
392 continue;
393 }
Bob Wilson69743022011-01-13 20:59:44 +0000394
Chris Lattner4cc576b2010-04-16 00:24:57 +0000395 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000396 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000397 if (!CanConvertToScalar(BCI, Offset))
398 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000399 continue;
400 }
401
402 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
403 // If this is a GEP with a variable indices, we can't handle it.
404 if (!GEP->hasAllConstantIndices())
405 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000406
Chris Lattner4cc576b2010-04-16 00:24:57 +0000407 // Compute the offset that this GEP adds to the pointer.
408 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
409 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
410 &Indices[0], Indices.size());
411 // See if all uses can be converted.
412 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
413 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000414 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000415 continue;
416 }
417
418 // If this is a constant sized memset of a constant value (e.g. 0) we can
419 // handle it.
420 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
421 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000422 if (!isa<ConstantInt>(MSI->getValue()) ||
423 !isa<ConstantInt>(MSI->getLength()))
424 return false;
425 IsNotTrivial = true; // Can't be mem2reg'd.
426 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000427 }
428
429 // If this is a memcpy or memmove into or out of the whole allocation, we
430 // can handle it like a load or store of the scalar type.
431 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000432 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
433 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
434 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000435
Chris Lattnera001b662010-04-16 00:38:19 +0000436 IsNotTrivial = true; // Can't be mem2reg'd.
437 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000438 }
Bob Wilson69743022011-01-13 20:59:44 +0000439
Chris Lattner4cc576b2010-04-16 00:24:57 +0000440 // Otherwise, we cannot handle this!
441 return false;
442 }
Bob Wilson69743022011-01-13 20:59:44 +0000443
Chris Lattner4cc576b2010-04-16 00:24:57 +0000444 return true;
445}
446
447/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
448/// directly. This happens when we are converting an "integer union" to a
449/// single integer scalar, or when we are converting a "vector union" to a
450/// vector with insert/extractelement instructions.
451///
452/// Offset is an offset from the original alloca, in bits that need to be
453/// shifted to the right. By the end of this, there should be no uses of Ptr.
454void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
455 uint64_t Offset) {
456 while (!Ptr->use_empty()) {
457 Instruction *User = cast<Instruction>(Ptr->use_back());
458
459 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
460 ConvertUsesToScalar(CI, NewAI, Offset);
461 CI->eraseFromParent();
462 continue;
463 }
464
465 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
466 // Compute the offset that this GEP adds to the pointer.
467 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
468 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
469 &Indices[0], Indices.size());
470 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
471 GEP->eraseFromParent();
472 continue;
473 }
Bob Wilson69743022011-01-13 20:59:44 +0000474
Chris Lattner61db1f52010-12-26 22:57:41 +0000475 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000476
Chris Lattner4cc576b2010-04-16 00:24:57 +0000477 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
478 // The load is a bit extract from NewAI shifted right by Offset bits.
479 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
480 Value *NewLoadVal
481 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
482 LI->replaceAllUsesWith(NewLoadVal);
483 LI->eraseFromParent();
484 continue;
485 }
Bob Wilson69743022011-01-13 20:59:44 +0000486
Chris Lattner4cc576b2010-04-16 00:24:57 +0000487 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
488 assert(SI->getOperand(0) != Ptr && "Consistency error!");
489 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
490 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
491 Builder);
492 Builder.CreateStore(New, NewAI);
493 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000494
Chris Lattner4cc576b2010-04-16 00:24:57 +0000495 // If the load we just inserted is now dead, then the inserted store
496 // overwrote the entire thing.
497 if (Old->use_empty())
498 Old->eraseFromParent();
499 continue;
500 }
Bob Wilson69743022011-01-13 20:59:44 +0000501
Chris Lattner4cc576b2010-04-16 00:24:57 +0000502 // If this is a constant sized memset of a constant value (e.g. 0) we can
503 // transform it into a store of the expanded constant value.
504 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
505 assert(MSI->getRawDest() == Ptr && "Consistency error!");
506 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
507 if (NumBytes != 0) {
508 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000509
Chris Lattner4cc576b2010-04-16 00:24:57 +0000510 // Compute the value replicated the right number of times.
511 APInt APVal(NumBytes*8, Val);
512
513 // Splat the value if non-zero.
514 if (Val)
515 for (unsigned i = 1; i != NumBytes; ++i)
516 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000517
Chris Lattner4cc576b2010-04-16 00:24:57 +0000518 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
519 Value *New = ConvertScalar_InsertValue(
520 ConstantInt::get(User->getContext(), APVal),
521 Old, Offset, Builder);
522 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000523
Chris Lattner4cc576b2010-04-16 00:24:57 +0000524 // If the load we just inserted is now dead, then the memset overwrote
525 // the entire thing.
526 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000527 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000528 }
529 MSI->eraseFromParent();
530 continue;
531 }
532
533 // If this is a memcpy or memmove into or out of the whole allocation, we
534 // can handle it like a load or store of the scalar type.
535 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
536 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000537
Chris Lattner4cc576b2010-04-16 00:24:57 +0000538 // If the source and destination are both to the same alloca, then this is
539 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
540 // as appropriate.
Dan Gohman5034dd32010-12-15 20:02:24 +0000541 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000542
Dan Gohman5034dd32010-12-15 20:02:24 +0000543 if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000544 // Dest must be OrigAI, change this to be a load from the original
545 // pointer (bitcasted), then a store to our new alloca.
546 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
547 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000548 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
549 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
550 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
551 AIPTy = PointerType::get(AIPTy->getElementType(),
552 SPTy->getAddressSpace());
553 }
554 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
555
Chris Lattner4cc576b2010-04-16 00:24:57 +0000556 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
557 SrcVal->setAlignment(MTI->getAlignment());
558 Builder.CreateStore(SrcVal, NewAI);
Dan Gohman5034dd32010-12-15 20:02:24 +0000559 } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000560 // Src must be OrigAI, change this to be a load from NewAI then a store
561 // through the original dest pointer (bitcasted).
562 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
563 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
564
Mon P Wange90a6332010-12-23 01:41:32 +0000565 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
566 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
567 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
568 AIPTy = PointerType::get(AIPTy->getElementType(),
569 DPTy->getAddressSpace());
570 }
571 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
572
Chris Lattner4cc576b2010-04-16 00:24:57 +0000573 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
574 NewStore->setAlignment(MTI->getAlignment());
575 } else {
576 // Noop transfer. Src == Dst
577 }
578
579 MTI->eraseFromParent();
580 continue;
581 }
Bob Wilson69743022011-01-13 20:59:44 +0000582
Chris Lattner4cc576b2010-04-16 00:24:57 +0000583 llvm_unreachable("Unsupported operation!");
584 }
585}
586
587/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
588/// or vector value FromVal, extracting the bits from the offset specified by
589/// Offset. This returns the value, which is of type ToType.
590///
591/// This happens when we are converting an "integer union" to a single
592/// integer scalar, or when we are converting a "vector union" to a vector with
593/// insert/extractelement instructions.
594///
595/// Offset is an offset from the original alloca, in bits that need to be
596/// shifted to the right.
597Value *ConvertToScalarInfo::
598ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
599 uint64_t Offset, IRBuilder<> &Builder) {
600 // If the load is of the whole new alloca, no conversion is needed.
601 if (FromVal->getType() == ToType && Offset == 0)
602 return FromVal;
603
604 // If the result alloca is a vector type, this is either an element
605 // access or a bitcast to another vector type of the same size.
606 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
607 if (ToType->isVectorTy())
608 return Builder.CreateBitCast(FromVal, ToType, "tmp");
609
610 // Otherwise it must be an element access.
611 unsigned Elt = 0;
612 if (Offset) {
613 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
614 Elt = Offset/EltSize;
615 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
616 }
617 // Return the element extracted out of it.
618 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
619 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
620 if (V->getType() != ToType)
621 V = Builder.CreateBitCast(V, ToType, "tmp");
622 return V;
623 }
Bob Wilson69743022011-01-13 20:59:44 +0000624
Chris Lattner4cc576b2010-04-16 00:24:57 +0000625 // If ToType is a first class aggregate, extract out each of the pieces and
626 // use insertvalue's to form the FCA.
627 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
628 const StructLayout &Layout = *TD.getStructLayout(ST);
629 Value *Res = UndefValue::get(ST);
630 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
631 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
632 Offset+Layout.getElementOffsetInBits(i),
633 Builder);
634 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
635 }
636 return Res;
637 }
Bob Wilson69743022011-01-13 20:59:44 +0000638
Chris Lattner4cc576b2010-04-16 00:24:57 +0000639 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
640 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
641 Value *Res = UndefValue::get(AT);
642 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
643 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
644 Offset+i*EltSize, Builder);
645 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
646 }
647 return Res;
648 }
649
650 // Otherwise, this must be a union that was converted to an integer value.
651 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
652
653 // If this is a big-endian system and the load is narrower than the
654 // full alloca type, we need to do a shift to get the right bits.
655 int ShAmt = 0;
656 if (TD.isBigEndian()) {
657 // On big-endian machines, the lowest bit is stored at the bit offset
658 // from the pointer given by getTypeStoreSizeInBits. This matters for
659 // integers with a bitwidth that is not a multiple of 8.
660 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
661 TD.getTypeStoreSizeInBits(ToType) - Offset;
662 } else {
663 ShAmt = Offset;
664 }
665
666 // Note: we support negative bitwidths (with shl) which are not defined.
667 // We do this to support (f.e.) loads off the end of a structure where
668 // only some bits are used.
669 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
670 FromVal = Builder.CreateLShr(FromVal,
671 ConstantInt::get(FromVal->getType(),
672 ShAmt), "tmp");
673 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000674 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000675 ConstantInt::get(FromVal->getType(),
676 -ShAmt), "tmp");
677
678 // Finally, unconditionally truncate the integer to the right width.
679 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
680 if (LIBitWidth < NTy->getBitWidth())
681 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000682 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000683 LIBitWidth), "tmp");
684 else if (LIBitWidth > NTy->getBitWidth())
685 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000686 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000687 LIBitWidth), "tmp");
688
689 // If the result is an integer, this is a trunc or bitcast.
690 if (ToType->isIntegerTy()) {
691 // Should be done.
692 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
693 // Just do a bitcast, we know the sizes match up.
694 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
695 } else {
696 // Otherwise must be a pointer.
697 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
698 }
699 assert(FromVal->getType() == ToType && "Didn't convert right?");
700 return FromVal;
701}
702
703/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
704/// or vector value "Old" at the offset specified by Offset.
705///
706/// This happens when we are converting an "integer union" to a
707/// single integer scalar, or when we are converting a "vector union" to a
708/// vector with insert/extractelement instructions.
709///
710/// Offset is an offset from the original alloca, in bits that need to be
711/// shifted to the right.
712Value *ConvertToScalarInfo::
713ConvertScalar_InsertValue(Value *SV, Value *Old,
714 uint64_t Offset, IRBuilder<> &Builder) {
715 // Convert the stored type to the actual type, shift it left to insert
716 // then 'or' into place.
717 const Type *AllocaType = Old->getType();
718 LLVMContext &Context = Old->getContext();
719
720 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
721 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
722 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000723
Chris Lattner4cc576b2010-04-16 00:24:57 +0000724 // Changing the whole vector with memset or with an access of a different
725 // vector type?
726 if (ValSize == VecSize)
727 return Builder.CreateBitCast(SV, AllocaType, "tmp");
728
729 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
730
731 // Must be an element insertion.
732 unsigned Elt = Offset/EltSize;
Bob Wilson69743022011-01-13 20:59:44 +0000733
Chris Lattner4cc576b2010-04-16 00:24:57 +0000734 if (SV->getType() != VTy->getElementType())
735 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000736
737 SV = Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000738 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
739 "tmp");
740 return SV;
741 }
Bob Wilson69743022011-01-13 20:59:44 +0000742
Chris Lattner4cc576b2010-04-16 00:24:57 +0000743 // If SV is a first-class aggregate value, insert each value recursively.
744 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
745 const StructLayout &Layout = *TD.getStructLayout(ST);
746 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
747 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000748 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000749 Offset+Layout.getElementOffsetInBits(i),
750 Builder);
751 }
752 return Old;
753 }
Bob Wilson69743022011-01-13 20:59:44 +0000754
Chris Lattner4cc576b2010-04-16 00:24:57 +0000755 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
756 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
757 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
758 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
759 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
760 }
761 return Old;
762 }
763
764 // If SV is a float, convert it to the appropriate integer type.
765 // If it is a pointer, do the same.
766 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
767 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
768 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
769 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
770 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
771 SV = Builder.CreateBitCast(SV,
772 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
773 else if (SV->getType()->isPointerTy())
774 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
775
776 // Zero extend or truncate the value if needed.
777 if (SV->getType() != AllocaType) {
778 if (SV->getType()->getPrimitiveSizeInBits() <
779 AllocaType->getPrimitiveSizeInBits())
780 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
781 else {
782 // Truncation may be needed if storing more than the alloca can hold
783 // (undefined behavior).
784 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
785 SrcWidth = DestWidth;
786 SrcStoreWidth = DestStoreWidth;
787 }
788 }
789
790 // If this is a big-endian system and the store is narrower than the
791 // full alloca type, we need to do a shift to get the right bits.
792 int ShAmt = 0;
793 if (TD.isBigEndian()) {
794 // On big-endian machines, the lowest bit is stored at the bit offset
795 // from the pointer given by getTypeStoreSizeInBits. This matters for
796 // integers with a bitwidth that is not a multiple of 8.
797 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
798 } else {
799 ShAmt = Offset;
800 }
801
802 // Note: we support negative bitwidths (with shr) which are not defined.
803 // We do this to support (f.e.) stores off the end of a structure where
804 // only some bits in the structure are set.
805 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
806 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
807 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
808 ShAmt), "tmp");
809 Mask <<= ShAmt;
810 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
811 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
812 -ShAmt), "tmp");
813 Mask = Mask.lshr(-ShAmt);
814 }
815
816 // Mask out the bits we are about to insert from the old value, and or
817 // in the new bits.
818 if (SrcWidth != DestWidth) {
819 assert(DestWidth > SrcWidth);
820 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
821 SV = Builder.CreateOr(Old, SV, "ins");
822 }
823 return SV;
824}
825
826
827//===----------------------------------------------------------------------===//
828// SRoA Driver
829//===----------------------------------------------------------------------===//
830
831
Chris Lattnered7b41e2003-05-27 15:45:27 +0000832bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000833 TD = getAnalysisIfAvailable<TargetData>();
834
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000835 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000836
837 // FIXME: ScalarRepl currently depends on TargetData more than it
838 // theoretically needs to. It should be refactored in order to support
839 // target-independent IR. Until this is done, just skip the actual
840 // scalar-replacement portion of this pass.
841 if (!TD) return Changed;
842
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000843 while (1) {
844 bool LocalChange = performScalarRepl(F);
845 if (!LocalChange) break; // No need to repromote if no scalarrepl
846 Changed = true;
847 LocalChange = performPromotion(F);
848 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
849 }
Chris Lattner38aec322003-09-11 16:45:55 +0000850
851 return Changed;
852}
853
Chris Lattnerd0f56132011-01-14 19:50:47 +0000854namespace {
855class AllocaPromoter : public LoadAndStorePromoter {
856 AllocaInst *AI;
857public:
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000858 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
859 : LoadAndStorePromoter(Insts, S), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +0000860
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000861 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +0000862 // Remember which alloca we're promoting (for isInstInList).
863 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000864 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +0000865 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000866 }
867
Chris Lattnerd0f56132011-01-14 19:50:47 +0000868 virtual bool isInstInList(Instruction *I,
869 const SmallVectorImpl<Instruction*> &Insts) const {
870 if (LoadInst *LI = dyn_cast<LoadInst>(I))
871 return LI->getOperand(0) == AI;
872 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000873 }
Chris Lattnerd0f56132011-01-14 19:50:47 +0000874};
875} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +0000876
877bool SROA::performPromotion(Function &F) {
878 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000879 DominatorTree *DT = 0;
Cameron Zwarichb1086a92011-01-17 07:26:51 +0000880 DominanceFrontier *DF = 0;
881 if (HasDomFrontiers) {
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000882 DT = &getAnalysis<DominatorTree>();
Cameron Zwarichb1086a92011-01-17 07:26:51 +0000883 DF = &getAnalysis<DominanceFrontier>();
884 }
Chris Lattner38aec322003-09-11 16:45:55 +0000885
Chris Lattner02a3be02003-09-20 14:39:18 +0000886 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000887
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000888 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000889 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +0000890 while (1) {
891 Allocas.clear();
892
893 // Find allocas that are safe to promote, by looking at all instructions in
894 // the entry node
895 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
896 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000897 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000898 Allocas.push_back(AI);
899
900 if (Allocas.empty()) break;
901
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000902 if (HasDomFrontiers)
Cameron Zwarichb1086a92011-01-17 07:26:51 +0000903 PromoteMemToReg(Allocas, *DT, *DF);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000904 else {
905 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000906 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
907 AllocaInst *AI = Allocas[i];
908
909 // Build list of instructions to promote.
910 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
911 UI != E; ++UI)
912 Insts.push_back(cast<Instruction>(*UI));
913
914 AllocaPromoter(Insts, SSA).run(AI, Insts);
915 Insts.clear();
916 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000917 }
Chris Lattner38aec322003-09-11 16:45:55 +0000918 NumPromoted += Allocas.size();
919 Changed = true;
920 }
921
922 return Changed;
923}
924
Chris Lattner4cc576b2010-04-16 00:24:57 +0000925
Bob Wilson3992feb2010-02-03 17:23:56 +0000926/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
927/// SROA. It must be a struct or array type with a small number of elements.
928static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
929 const Type *T = AI->getAllocatedType();
930 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000931 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000932 return ST->getNumElements() <= 32;
933 // Arrays are much less likely to be safe for SROA; only consider
934 // them if they are very small.
935 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
936 return AT->getNumElements() <= 8;
937 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000938}
939
Chris Lattnerc4472072010-04-15 23:50:26 +0000940
Chris Lattner38aec322003-09-11 16:45:55 +0000941// performScalarRepl - This algorithm is a simple worklist driven algorithm,
942// which runs on all of the malloc/alloca instructions in the function, removing
943// them if they are only used by getelementptr instructions.
944//
945bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000946 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000947
Chris Lattner31d80102010-04-15 21:59:20 +0000948 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000949 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000950 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000951 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000952 WorkList.push_back(A);
953
954 // Process the worklist
955 bool Changed = false;
956 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000957 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000958 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +0000959
Chris Lattneradd2bd72006-12-22 23:14:42 +0000960 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
961 // with unused elements.
962 if (AI->use_empty()) {
963 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000964 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000965 continue;
966 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000967
968 // If this alloca is impossible for us to promote, reject it early.
969 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
970 continue;
Bob Wilson69743022011-01-13 20:59:44 +0000971
Chris Lattner79b3bd32007-04-25 06:40:51 +0000972 // Check to see if this allocation is only modified by a memcpy/memmove from
973 // a constant global. If this is the case, we can change all users to use
974 // the constant global instead. This is commonly produced by the CFE by
975 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
976 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000977 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000978 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
979 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000980 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000981 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000982 TheCopy->eraseFromParent(); // Don't mutate the global.
983 AI->eraseFromParent();
984 ++NumGlobals;
985 Changed = true;
986 continue;
987 }
Bob Wilson69743022011-01-13 20:59:44 +0000988
Chris Lattner7809ecd2009-02-03 01:30:09 +0000989 // Check to see if we can perform the core SROA transformation. We cannot
990 // transform the allocation instruction if it is an array allocation
991 // (allocations OF arrays are ok though), and an allocation of a scalar
992 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000993 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000994
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000995 // Do not promote [0 x %struct].
996 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +0000997
Chris Lattner31d80102010-04-15 21:59:20 +0000998 // Do not promote any struct whose size is too big.
999 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001000
Bob Wilson3992feb2010-02-03 17:23:56 +00001001 // If the alloca looks like a good candidate for scalar replacement, and if
1002 // all its users can be transformed, then split up the aggregate into its
1003 // separate elements.
1004 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1005 DoScalarReplacement(AI, WorkList);
1006 Changed = true;
1007 continue;
1008 }
1009
Chris Lattner6e733d32009-01-28 20:16:43 +00001010 // If we can turn this aggregate value (potentially with casts) into a
1011 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001012 // IsNotTrivial tracks whether this is something that mem2reg could have
1013 // promoted itself. If so, we don't want to transform it needlessly. Note
1014 // that we can't just check based on the type: the alloca may be of an i32
1015 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001016 if (AllocaInst *NewAI =
1017 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001018 NewAI->takeName(AI);
1019 AI->eraseFromParent();
1020 ++NumConverted;
1021 Changed = true;
1022 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001023 }
1024
Chris Lattner7809ecd2009-02-03 01:30:09 +00001025 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001026 }
1027
1028 return Changed;
1029}
Chris Lattner5e062a12003-05-30 04:15:41 +00001030
Chris Lattnera10b29b2007-04-25 05:02:56 +00001031/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1032/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001033void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001034 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001035 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001036 SmallVector<AllocaInst*, 32> ElementAllocas;
1037 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1038 ElementAllocas.reserve(ST->getNumContainedTypes());
1039 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001040 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001041 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001042 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001043 ElementAllocas.push_back(NA);
1044 WorkList.push_back(NA); // Add to worklist for recursive processing
1045 }
1046 } else {
1047 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1048 ElementAllocas.reserve(AT->getNumElements());
1049 const Type *ElTy = AT->getElementType();
1050 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001051 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001052 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001053 ElementAllocas.push_back(NA);
1054 WorkList.push_back(NA); // Add to worklist for recursive processing
1055 }
1056 }
1057
Bob Wilsonb742def2009-12-18 20:14:40 +00001058 // Now that we have created the new alloca instructions, rewrite all the
1059 // uses of the old alloca.
1060 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001061
Bob Wilsonb742def2009-12-18 20:14:40 +00001062 // Now erase any instructions that were made dead while rewriting the alloca.
1063 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001064 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001065
Dan Gohmanfe601042010-06-22 15:08:57 +00001066 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001067}
Chris Lattnera59adc42009-12-14 05:11:02 +00001068
Bob Wilsonb742def2009-12-18 20:14:40 +00001069/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1070/// recursively including all their operands that become trivially dead.
1071void SROA::DeleteDeadInstructions() {
1072 while (!DeadInsts.empty()) {
1073 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001074
Bob Wilsonb742def2009-12-18 20:14:40 +00001075 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1076 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1077 // Zero out the operand and see if it becomes trivially dead.
1078 // (But, don't add allocas to the dead instruction list -- they are
1079 // already on the worklist and will be deleted separately.)
1080 *OI = 0;
1081 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1082 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001083 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001084
1085 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001086 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001087}
Bob Wilson69743022011-01-13 20:59:44 +00001088
Bob Wilsonb742def2009-12-18 20:14:40 +00001089/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1090/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001091/// the Info parameter. Offset indicates the position within AI that is
1092/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +00001093void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001094 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001095 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1096 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001097
Bob Wilsonb742def2009-12-18 20:14:40 +00001098 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001099 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001100 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001101 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001102 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001103 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001104 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001105 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001106 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1107 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001108 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001109 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001110 else
1111 MarkUnsafe(Info);
1112 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1113 if (!LI->isVolatile()) {
1114 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001115 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001116 LIType, false, Info);
Chris Lattner7e9b4272011-01-16 06:18:28 +00001117 Info.hasALoadOrStore = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001118 } else
1119 MarkUnsafe(Info);
1120 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1121 // Store is ok if storing INTO the pointer, not storing the pointer
1122 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1123 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001124 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001125 SIType, true, Info);
Chris Lattner7e9b4272011-01-16 06:18:28 +00001126 Info.hasALoadOrStore = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001127 } else
1128 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001129 } else {
1130 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1131 MarkUnsafe(Info);
1132 }
1133 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001134 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001135}
Bob Wilson39c88a62009-12-17 18:34:24 +00001136
Bob Wilsonb742def2009-12-18 20:14:40 +00001137/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1138/// replacement. It is safe when all the indices are constant, in-bounds
1139/// references, and when the resulting offset corresponds to an element within
1140/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001141/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001142void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001143 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001144 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1145 if (GEPIt == E)
1146 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001147
Chris Lattner88e6dc82008-08-23 05:21:06 +00001148 // Walk through the GEP type indices, checking the types that this indexes
1149 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001150 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001151 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001152 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001153 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001154
Bob Wilsonb742def2009-12-18 20:14:40 +00001155 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1156 if (!IdxVal)
1157 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001158 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001159
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001160 // Compute the offset due to this GEP and check if the alloca has a
1161 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001162 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1163 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1164 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001165 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1166 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001167}
1168
Bob Wilson704d1342011-01-13 17:45:11 +00001169/// isHomogeneousAggregate - Check if type T is a struct or array containing
1170/// elements of the same type (which is always true for arrays). If so,
1171/// return true with NumElts and EltTy set to the number of elements and the
1172/// element type, respectively.
1173static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1174 const Type *&EltTy) {
1175 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1176 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001177 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001178 return true;
1179 }
1180 if (const StructType *ST = dyn_cast<StructType>(T)) {
1181 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001182 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001183 for (unsigned n = 1; n < NumElts; ++n) {
1184 if (ST->getContainedType(n) != EltTy)
1185 return false;
1186 }
1187 return true;
1188 }
1189 return false;
1190}
1191
1192/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1193/// "homogeneous" aggregates with the same element type and number of elements.
1194static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1195 if (T1 == T2)
1196 return true;
1197
1198 unsigned NumElts1, NumElts2;
1199 const Type *EltTy1, *EltTy2;
1200 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1201 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1202 NumElts1 == NumElts2 &&
1203 EltTy1 == EltTy2)
1204 return true;
1205
1206 return false;
1207}
1208
Bob Wilsonb742def2009-12-18 20:14:40 +00001209/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1210/// alloca or has an offset and size that corresponds to a component element
1211/// within it. The offset checked here may have been formed from a GEP with a
1212/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001213void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001214 const Type *MemOpType, bool isStore,
1215 AllocaInfo &Info) {
1216 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001217 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001218 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1219 // loads/stores (which are essentially the same as the MemIntrinsics with
1220 // regard to copying padding between elements). But, if an alloca is
1221 // flagged as both a source and destination of such operations, we'll need
1222 // to check later for padding between elements.
1223 if (!MemOpType || MemOpType->isIntegerTy()) {
1224 if (isStore)
1225 Info.isMemCpyDst = true;
1226 else
1227 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001228 return;
1229 }
Bob Wilson704d1342011-01-13 17:45:11 +00001230 // This is also safe for references using a type that is compatible with
1231 // the type of the alloca, so that loads/stores can be rewritten using
1232 // insertvalue/extractvalue.
Chris Lattner7e9b4272011-01-16 06:18:28 +00001233 if (isCompatibleAggregate(MemOpType, AI->getAllocatedType())) {
1234 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001235 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001236 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001237 }
1238 // Check if the offset/size correspond to a component within the alloca type.
1239 const Type *T = AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001240 if (TypeHasComponent(T, Offset, MemSize)) {
1241 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001242 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001243 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001244
1245 return MarkUnsafe(Info);
1246}
1247
1248/// TypeHasComponent - Return true if T has a component type with the
1249/// specified offset and size. If Size is zero, do not check the size.
1250bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1251 const Type *EltTy;
1252 uint64_t EltSize;
1253 if (const StructType *ST = dyn_cast<StructType>(T)) {
1254 const StructLayout *Layout = TD->getStructLayout(ST);
1255 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1256 EltTy = ST->getContainedType(EltIdx);
1257 EltSize = TD->getTypeAllocSize(EltTy);
1258 Offset -= Layout->getElementOffset(EltIdx);
1259 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1260 EltTy = AT->getElementType();
1261 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001262 if (Offset >= AT->getNumElements() * EltSize)
1263 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001264 Offset %= EltSize;
1265 } else {
1266 return false;
1267 }
1268 if (Offset == 0 && (Size == 0 || EltSize == Size))
1269 return true;
1270 // Check if the component spans multiple elements.
1271 if (Offset + Size > EltSize)
1272 return false;
1273 return TypeHasComponent(EltTy, Offset, Size);
1274}
1275
1276/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1277/// the instruction I, which references it, to use the separate elements.
1278/// Offset indicates the position within AI that is referenced by this
1279/// instruction.
1280void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1281 SmallVector<AllocaInst*, 32> &NewElts) {
1282 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1283 Instruction *User = cast<Instruction>(*UI);
1284
1285 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1286 RewriteBitCast(BC, AI, Offset, NewElts);
1287 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1288 RewriteGEP(GEPI, AI, Offset, NewElts);
1289 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1290 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1291 uint64_t MemSize = Length->getZExtValue();
1292 if (Offset == 0 &&
1293 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1294 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001295 // Otherwise the intrinsic can only touch a single element and the
1296 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001297 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1298 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001299
Bob Wilson704d1342011-01-13 17:45:11 +00001300 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001301 // Replace:
1302 // %res = load { i32, i32 }* %alloc
1303 // with:
1304 // %load.0 = load i32* %alloc.0
1305 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1306 // %load.1 = load i32* %alloc.1
1307 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1308 // (Also works for arrays instead of structs)
1309 Value *Insert = UndefValue::get(LIType);
1310 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1311 Value *Load = new LoadInst(NewElts[i], "load", LI);
1312 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1313 }
1314 LI->replaceAllUsesWith(Insert);
1315 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001316 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001317 TD->getTypeAllocSize(LIType) ==
1318 TD->getTypeAllocSize(AI->getAllocatedType())) {
1319 // If this is a load of the entire alloca to an integer, rewrite it.
1320 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1321 }
1322 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1323 Value *Val = SI->getOperand(0);
1324 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001325 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001326 // Replace:
1327 // store { i32, i32 } %val, { i32, i32 }* %alloc
1328 // with:
1329 // %val.0 = extractvalue { i32, i32 } %val, 0
1330 // store i32 %val.0, i32* %alloc.0
1331 // %val.1 = extractvalue { i32, i32 } %val, 1
1332 // store i32 %val.1, i32* %alloc.1
1333 // (Also works for arrays instead of structs)
1334 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1335 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1336 new StoreInst(Extract, NewElts[i], SI);
1337 }
1338 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001339 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001340 TD->getTypeAllocSize(SIType) ==
1341 TD->getTypeAllocSize(AI->getAllocatedType())) {
1342 // If this is a store of the entire alloca from an integer, rewrite it.
1343 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1344 }
1345 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001346 }
1347}
1348
Bob Wilsonb742def2009-12-18 20:14:40 +00001349/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1350/// and recursively continue updating all of its uses.
1351void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1352 SmallVector<AllocaInst*, 32> &NewElts) {
1353 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1354 if (BC->getOperand(0) != AI)
1355 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001356
Bob Wilsonb742def2009-12-18 20:14:40 +00001357 // The bitcast references the original alloca. Replace its uses with
1358 // references to the first new element alloca.
1359 Instruction *Val = NewElts[0];
1360 if (Val->getType() != BC->getDestTy()) {
1361 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1362 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001363 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001364 BC->replaceAllUsesWith(Val);
1365 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001366}
1367
Bob Wilsonb742def2009-12-18 20:14:40 +00001368/// FindElementAndOffset - Return the index of the element containing Offset
1369/// within the specified type, which must be either a struct or an array.
1370/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001371/// element. IdxTy is set to the type of the index result to be used in a
1372/// GEP instruction.
1373uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1374 const Type *&IdxTy) {
1375 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001376 if (const StructType *ST = dyn_cast<StructType>(T)) {
1377 const StructLayout *Layout = TD->getStructLayout(ST);
1378 Idx = Layout->getElementContainingOffset(Offset);
1379 T = ST->getContainedType(Idx);
1380 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001381 IdxTy = Type::getInt32Ty(T->getContext());
1382 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001383 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001384 const ArrayType *AT = cast<ArrayType>(T);
1385 T = AT->getElementType();
1386 uint64_t EltSize = TD->getTypeAllocSize(T);
1387 Idx = Offset / EltSize;
1388 Offset -= Idx * EltSize;
1389 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001390 return Idx;
1391}
1392
1393/// RewriteGEP - Check if this GEP instruction moves the pointer across
1394/// elements of the alloca that are being split apart, and if so, rewrite
1395/// the GEP to be relative to the new element.
1396void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1397 SmallVector<AllocaInst*, 32> &NewElts) {
1398 uint64_t OldOffset = Offset;
1399 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1400 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1401 &Indices[0], Indices.size());
1402
1403 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1404
1405 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001406 const Type *IdxTy;
1407 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001408 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001409 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001410
1411 T = AI->getAllocatedType();
1412 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001413 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001414
1415 // If this GEP does not move the pointer across elements of the alloca
1416 // being split, then it does not needs to be rewritten.
1417 if (Idx == OldIdx)
1418 return;
1419
1420 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1421 SmallVector<Value*, 8> NewArgs;
1422 NewArgs.push_back(Constant::getNullValue(i32Ty));
1423 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001424 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1425 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001426 }
1427 Instruction *Val = NewElts[Idx];
1428 if (NewArgs.size() > 1) {
1429 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1430 NewArgs.end(), "", GEPI);
1431 Val->takeName(GEPI);
1432 }
1433 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001434 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001435 GEPI->replaceAllUsesWith(Val);
1436 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001437}
1438
1439/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1440/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001441void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001442 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001443 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001444 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001445 // appropriate type. The "Other" pointer is the pointer that goes to memory
1446 // that doesn't have anything to do with the alloca that we are promoting. For
1447 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001448 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001449 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001450 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001451 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001452 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001453 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001454 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001455 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001456 }
1457 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001458
Chris Lattnerd93afec2009-01-07 07:18:45 +00001459 // If there is an other pointer, we want to convert it to the same pointer
1460 // type as AI has, so we can GEP through it safely.
1461 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001462 unsigned AddrSpace =
1463 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001464
1465 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1466 // optimization, but it's also required to detect the corner case where
1467 // both pointer operands are referencing the same memory, and where
1468 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1469 // function is only called for mem intrinsics that access the whole
1470 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001471 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00001472
Bob Wilsona756b1d2010-01-19 04:32:48 +00001473 // Copying the alloca to itself is a no-op: just delete it.
1474 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1475 // This code will run twice for a no-op memcpy -- once for each operand.
1476 // Put only one reference to MI on the DeadInsts list.
1477 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1478 E = DeadInsts.end(); I != E; ++I)
1479 if (*I == MI) return;
1480 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001481 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001482 }
Bob Wilson69743022011-01-13 20:59:44 +00001483
Chris Lattnerd93afec2009-01-07 07:18:45 +00001484 // If the pointer is not the right type, insert a bitcast to the right
1485 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001486 const Type *NewTy =
1487 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00001488
Chris Lattner0238f8c2010-07-08 00:27:05 +00001489 if (OtherPtr->getType() != NewTy)
1490 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001491 }
Bob Wilson69743022011-01-13 20:59:44 +00001492
Chris Lattnerd93afec2009-01-07 07:18:45 +00001493 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00001494 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00001495
Owen Anderson1d0be152009-08-13 21:58:54 +00001496 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001497
1498 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1499 // If this is a memcpy/memmove, emit a GEP of the other element address.
1500 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001501 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00001502
Bob Wilsona756b1d2010-01-19 04:32:48 +00001503 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001504 Value *Idx[2] = { Zero,
1505 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001506 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001507 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001508 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001509 uint64_t EltOffset;
1510 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001511 const Type *OtherTy = OtherPtrTy->getElementType();
1512 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001513 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1514 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001515 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001516 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001517 }
Bob Wilson69743022011-01-13 20:59:44 +00001518
Chris Lattner1541e0f2009-03-04 19:20:50 +00001519 // The alignment of the other pointer is the guaranteed alignment of the
1520 // element, which is affected by both the known alignment of the whole
1521 // mem intrinsic and the alignment of the element. If the alignment of
1522 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1523 // known alignment is just 4 bytes.
1524 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001525 }
Bob Wilson69743022011-01-13 20:59:44 +00001526
Chris Lattnerd93afec2009-01-07 07:18:45 +00001527 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001528 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00001529
Chris Lattnerd93afec2009-01-07 07:18:45 +00001530 // If we got down to a scalar, insert a load or store as appropriate.
1531 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001532 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001533 if (SROADest) {
1534 // From Other to Alloca.
1535 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1536 new StoreInst(Elt, EltPtr, MI);
1537 } else {
1538 // From Alloca to Other.
1539 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1540 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1541 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001542 continue;
1543 }
1544 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00001545
Chris Lattnerd93afec2009-01-07 07:18:45 +00001546 // If the stored element is zero (common case), just store a null
1547 // constant.
1548 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001549 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001550 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001551 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001552 } else {
1553 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001554 const Type *ValTy = EltTy->getScalarType();
1555
Chris Lattnerd93afec2009-01-07 07:18:45 +00001556 // Construct an integer with the right value.
1557 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1558 APInt OneVal(EltSize, CI->getZExtValue());
1559 APInt TotalVal(OneVal);
1560 // Set each byte.
1561 for (unsigned i = 0; 8*i < EltSize; ++i) {
1562 TotalVal = TotalVal.shl(8);
1563 TotalVal |= OneVal;
1564 }
Bob Wilson69743022011-01-13 20:59:44 +00001565
Chris Lattnerd93afec2009-01-07 07:18:45 +00001566 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001567 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001568 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001569 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001570 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001571 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001572 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00001573
Chris Lattnerd93afec2009-01-07 07:18:45 +00001574 // If the requested value was a vector constant, create it.
1575 if (EltTy != ValTy) {
1576 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1577 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001578 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001579 }
1580 }
1581 new StoreInst(StoreVal, EltPtr, MI);
1582 continue;
1583 }
1584 // Otherwise, if we're storing a byte variable, use a memset call for
1585 // this element.
1586 }
Bob Wilson69743022011-01-13 20:59:44 +00001587
Duncan Sands777d2302009-05-09 07:06:46 +00001588 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001589
Chris Lattner61db1f52010-12-26 22:57:41 +00001590 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00001591
Chris Lattnerd93afec2009-01-07 07:18:45 +00001592 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00001593 if (isa<MemSetInst>(MI)) {
1594 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1595 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001596 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00001597 assert(isa<MemTransferInst>(MI));
1598 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
1599 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00001600
Chris Lattner61db1f52010-12-26 22:57:41 +00001601 if (isa<MemCpyInst>(MI))
1602 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1603 else
1604 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001605 }
Chris Lattner372dda82007-03-05 07:52:57 +00001606 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001607 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001608}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001609
Bob Wilson39fdd692009-12-04 21:57:37 +00001610/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001611/// overwrites the entire allocation. Extract out the pieces of the stored
1612/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001613void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001614 SmallVector<AllocaInst*, 32> &NewElts){
1615 // Extract each element out of the integer according to its structure offset
1616 // and store the element value to the individual alloca.
1617 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001618 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001619 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001620
Chris Lattner70728532011-01-16 05:58:24 +00001621 IRBuilder<> Builder(SI);
1622
Eli Friedman41b33f42009-06-01 09:14:32 +00001623 // Handle tail padding by extending the operand
1624 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001625 SrcVal = Builder.CreateZExt(SrcVal,
1626 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001627
David Greene504c7d82010-01-05 01:27:09 +00001628 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001629 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001630
1631 // There are two forms here: AI could be an array or struct. Both cases
1632 // have different ways to compute the element offset.
1633 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1634 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00001635
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001636 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1637 // Get the number of bits to shift SrcVal to get the value.
1638 const Type *FieldTy = EltSTy->getElementType(i);
1639 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00001640
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001641 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001642 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001643
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001644 Value *EltVal = SrcVal;
1645 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001646 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001647 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001648 }
Bob Wilson69743022011-01-13 20:59:44 +00001649
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001650 // Truncate down to an integer of the right size.
1651 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001652
Chris Lattner583dd602009-01-09 18:18:43 +00001653 // Ignore zero sized fields like {}, they obviously contain no data.
1654 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001655
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001656 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001657 EltVal = Builder.CreateTrunc(EltVal,
1658 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001659 Value *DestField = NewElts[i];
1660 if (EltVal->getType() == FieldTy) {
1661 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001662 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001663 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00001664 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001665 } else {
1666 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00001667 DestField = Builder.CreateBitCast(DestField,
1668 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001669 }
1670 new StoreInst(EltVal, DestField, SI);
1671 }
Bob Wilson69743022011-01-13 20:59:44 +00001672
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001673 } else {
1674 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1675 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001676 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001677 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1678
1679 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00001680
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001681 if (TD->isBigEndian())
1682 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001683 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001684 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00001685
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001686 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001687 // Ignore zero sized fields like {}, they obviously contain no data.
1688 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001689
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001690 Value *EltVal = SrcVal;
1691 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001692 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001693 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001694 }
Bob Wilson69743022011-01-13 20:59:44 +00001695
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001696 // Truncate down to an integer of the right size.
1697 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001698 EltVal = Builder.CreateTrunc(EltVal,
1699 IntegerType::get(SI->getContext(),
1700 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001701 Value *DestField = NewElts[i];
1702 if (EltVal->getType() == ArrayEltTy) {
1703 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001704 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001705 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001706 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00001707 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001708 } else {
1709 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00001710 DestField = Builder.CreateBitCast(DestField,
1711 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001712 }
1713 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00001714
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001715 if (TD->isBigEndian())
1716 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001717 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001718 Shift += ElementOffset;
1719 }
1720 }
Bob Wilson69743022011-01-13 20:59:44 +00001721
Bob Wilsonb742def2009-12-18 20:14:40 +00001722 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001723}
1724
Bob Wilson39fdd692009-12-04 21:57:37 +00001725/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001726/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001727void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001728 SmallVector<AllocaInst*, 32> &NewElts) {
1729 // Extract each element out of the NewElts according to its structure offset
1730 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001731 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001732 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001733
David Greene504c7d82010-01-05 01:27:09 +00001734 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001735 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00001736
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001737 // There are two forms here: AI could be an array or struct. Both cases
1738 // have different ways to compute the element offset.
1739 const StructLayout *Layout = 0;
1740 uint64_t ArrayEltBitOffset = 0;
1741 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1742 Layout = TD->getStructLayout(EltSTy);
1743 } else {
1744 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001745 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001746 }
1747
1748 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001749 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00001750
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001751 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1752 // Load the value from the alloca. If the NewElt is an aggregate, cast
1753 // the pointer to an integer of the same size before doing the load.
1754 Value *SrcField = NewElts[i];
1755 const Type *FieldTy =
1756 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001757 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001758
Chris Lattner583dd602009-01-09 18:18:43 +00001759 // Ignore zero sized fields like {}, they obviously contain no data.
1760 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001761
1762 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00001763 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001764 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1765 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001766 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001767 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001768 "", LI);
1769 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1770
1771 // If SrcField is a fp or vector of the right size but that isn't an
1772 // integer type, bitcast to an integer so we can shift it.
1773 if (SrcField->getType() != FieldIntTy)
1774 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1775
1776 // Zero extend the field to be the same size as the final alloca so that
1777 // we can shift and insert it.
1778 if (SrcField->getType() != ResultVal->getType())
1779 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00001780
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001781 // Determine the number of bits to shift SrcField.
1782 uint64_t Shift;
1783 if (Layout) // Struct case.
1784 Shift = Layout->getElementOffsetInBits(i);
1785 else // Array case.
1786 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001787
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001788 if (TD->isBigEndian())
1789 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00001790
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001791 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001792 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001793 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1794 }
1795
Chris Lattner14952472010-06-27 07:58:26 +00001796 // Don't create an 'or x, 0' on the first iteration.
1797 if (!isa<Constant>(ResultVal) ||
1798 !cast<Constant>(ResultVal)->isNullValue())
1799 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1800 else
1801 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001802 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001803
1804 // Handle tail padding by truncating the result
1805 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1806 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1807
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001808 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001809 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001810}
1811
Duncan Sands3cb36502007-11-04 14:43:57 +00001812/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00001813/// alignment padding in between the elements that would be split apart
1814/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001815static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00001816 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1817 Ty = ATy->getElementType();
1818 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001819 }
Bob Wilson694a10e2011-01-13 17:45:08 +00001820
1821 // SROA currently handles only Arrays and Structs.
1822 const StructType *STy = cast<StructType>(Ty);
1823 const StructLayout *SL = TD.getStructLayout(STy);
1824 unsigned PrevFieldBitOffset = 0;
1825 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1826 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1827
1828 // Check to see if there is any padding between this element and the
1829 // previous one.
1830 if (i) {
1831 unsigned PrevFieldEnd =
1832 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1833 if (PrevFieldEnd < FieldBitOffset)
1834 return true;
1835 }
1836 PrevFieldBitOffset = FieldBitOffset;
1837 }
1838 // Check for tail padding.
1839 if (unsigned EltCount = STy->getNumElements()) {
1840 unsigned PrevFieldEnd = PrevFieldBitOffset +
1841 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1842 if (PrevFieldEnd < SL->getSizeInBits())
1843 return true;
1844 }
1845 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00001846}
Chris Lattner372dda82007-03-05 07:52:57 +00001847
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001848/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1849/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1850/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001851bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001852 // Loop over the use list of the alloca. We can only transform it if all of
1853 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001854 AllocaInfo Info;
Bob Wilson69743022011-01-13 20:59:44 +00001855
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001856 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001857 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001858 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001859 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001860 }
Bob Wilson69743022011-01-13 20:59:44 +00001861
Chris Lattner39a1c042007-05-30 06:11:23 +00001862 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1863 // source and destination, we have to be careful. In particular, the memcpy
1864 // could be moving around elements that live in structure padding of the LLVM
1865 // types, but may actually be used. In these cases, we refuse to promote the
1866 // struct.
1867 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001868 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001869 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001870
Chris Lattner396a0562011-01-16 17:46:19 +00001871 // If the alloca never has an access to just *part* of it, but is accessed
1872 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00001873 // the alloca instead of promoting each piece at a time and inserting fission
1874 // and fusion code.
1875 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
1876 // If the struct/array just has one element, use basic SRoA.
1877 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1878 if (ST->getNumElements() > 1) return false;
1879 } else {
1880 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
1881 return false;
1882 }
1883 }
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001884 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001885}
Chris Lattnera1888942005-12-12 07:19:13 +00001886
Chris Lattner800de312008-02-29 07:03:13 +00001887
Chris Lattner79b3bd32007-04-25 06:40:51 +00001888
1889/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1890/// some part of a constant global variable. This intentionally only accepts
1891/// constant expressions because we don't can't rewrite arbitrary instructions.
1892static bool PointsToConstantGlobal(Value *V) {
1893 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1894 return GV->isConstant();
1895 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00001896 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00001897 CE->getOpcode() == Instruction::GetElementPtr)
1898 return PointsToConstantGlobal(CE->getOperand(0));
1899 return false;
1900}
1901
1902/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1903/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1904/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1905/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1906/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00001907/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00001908/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001909static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001910 bool isOffset) {
1911 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001912 User *U = cast<Instruction>(*UI);
1913
Chris Lattner2e618492010-11-18 06:20:47 +00001914 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001915 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00001916 if (LI->isVolatile()) return false;
1917 continue;
1918 }
Bob Wilson69743022011-01-13 20:59:44 +00001919
Gabor Greif8a8a4352010-04-06 19:32:30 +00001920 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001921 // If uses of the bitcast are ok, we are ok.
1922 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1923 return false;
1924 continue;
1925 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001926 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001927 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1928 // doesn't, it does.
1929 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1930 isOffset || !GEP->hasAllZeroIndices()))
1931 return false;
1932 continue;
1933 }
Bob Wilson69743022011-01-13 20:59:44 +00001934
Chris Lattner62480652010-11-18 06:41:51 +00001935 if (CallSite CS = U) {
1936 // If this is a readonly/readnone call site, then we know it is just a
1937 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00001938 if (CS.onlyReadsMemory())
1939 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00001940
1941 // If this is the function being called then we treat it like a load and
1942 // ignore it.
1943 if (CS.isCallee(UI))
1944 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001945
Chris Lattner62480652010-11-18 06:41:51 +00001946 // If this is being passed as a byval argument, the caller is making a
1947 // copy, so it is only a read of the alloca.
1948 unsigned ArgNo = CS.getArgumentNo(UI);
1949 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
1950 continue;
1951 }
Bob Wilson69743022011-01-13 20:59:44 +00001952
Chris Lattner79b3bd32007-04-25 06:40:51 +00001953 // If this is isn't our memcpy/memmove, reject it as something we can't
1954 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001955 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1956 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001957 return false;
Bob Wilson69743022011-01-13 20:59:44 +00001958
Chris Lattner2e618492010-11-18 06:20:47 +00001959 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00001960 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00001961 if (UI.getOperandNo() == 1) {
1962 if (MI->isVolatile()) return false;
1963 continue;
1964 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00001965
1966 // If we already have seen a copy, reject the second one.
1967 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00001968
Chris Lattner79b3bd32007-04-25 06:40:51 +00001969 // If the pointer has been offset from the start of the alloca, we can't
1970 // safely handle this.
1971 if (isOffset) return false;
1972
1973 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001974 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00001975
Chris Lattner79b3bd32007-04-25 06:40:51 +00001976 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001977 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001978 return false;
Bob Wilson69743022011-01-13 20:59:44 +00001979
Chris Lattner79b3bd32007-04-25 06:40:51 +00001980 // Otherwise, the transform is safe. Remember the copy instruction.
1981 TheCopy = MI;
1982 }
1983 return true;
1984}
1985
1986/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1987/// modified by a copy from a constant global. If we can prove this, we can
1988/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001989MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1990 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001991 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1992 return TheCopy;
1993 return 0;
1994}