blob: 6b79695d6f3ff39ab915cdb90d6d2ac9d9d66c01 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000033#include "llvm/Analysis/Dominators.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000034#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000035#include "llvm/Target/TargetData.h"
36#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000037#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000038#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000039#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000040#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000043#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000044#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000045#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000046#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000047#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Chris Lattner0e5f4992006-12-19 21:40:18 +000050STATISTIC(NumReplaced, "Number of allocas broken up");
51STATISTIC(NumPromoted, "Number of allocas promoted");
52STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000053STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000054
Chris Lattner0e5f4992006-12-19 21:40:18 +000055namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000056 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000057 SROA(int T, bool hasDT, char &ID)
58 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000059 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000060 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000061 else
62 SRThreshold = T;
63 }
Devang Patel794fd752007-05-01 21:15:47 +000064
Chris Lattnered7b41e2003-05-27 15:45:27 +000065 bool runOnFunction(Function &F);
66
Chris Lattner38aec322003-09-11 16:45:55 +000067 bool performScalarRepl(Function &F);
68 bool performPromotion(Function &F);
69
Chris Lattnered7b41e2003-05-27 15:45:27 +000070 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000071 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000072 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000073
Bob Wilsonb742def2009-12-18 20:14:40 +000074 /// DeadInsts - Keep track of instructions we have made dead, so that
75 /// we can remove them after we are done working.
76 SmallVector<Value*, 32> DeadInsts;
77
Chris Lattner39a1c042007-05-30 06:11:23 +000078 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
79 /// information about the uses. All these fields are initialized to false
80 /// and set to true when something is learned.
81 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000082 /// The alloca to promote.
83 AllocaInst *AI;
84
Chris Lattner145c5322011-01-23 08:27:54 +000085 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
86 /// looping and avoid redundant work.
87 SmallPtrSet<PHINode*, 8> CheckedPHIs;
88
Chris Lattner39a1c042007-05-30 06:11:23 +000089 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
90 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000091
Chris Lattner39a1c042007-05-30 06:11:23 +000092 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
93 bool isMemCpySrc : 1;
94
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000095 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000096 bool isMemCpyDst : 1;
97
Chris Lattner7e9b4272011-01-16 06:18:28 +000098 /// hasSubelementAccess - This is true if a subelement of the alloca is
99 /// ever accessed, or false if the alloca is only accessed with mem
100 /// intrinsics or load/store that only access the entire alloca at once.
101 bool hasSubelementAccess : 1;
102
103 /// hasALoadOrStore - This is true if there are any loads or stores to it.
104 /// The alloca may just be accessed with memcpy, for example, which would
105 /// not set this.
106 bool hasALoadOrStore : 1;
107
Chris Lattner6c95d242011-01-23 07:29:29 +0000108 explicit AllocaInfo(AllocaInst *ai)
109 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000110 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000111 };
Bob Wilson69743022011-01-13 20:59:44 +0000112
Devang Patelff366852007-07-09 21:19:23 +0000113 unsigned SRThreshold;
114
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000115 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
116 I.isUnsafe = true;
117 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
118 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000119
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000120 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000121
Chris Lattner6c95d242011-01-23 07:29:29 +0000122 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000123 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
124 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000125 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
126 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000127 const Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000128 Instruction *TheAccess, bool AllowWholeAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +0000129 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000130 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
131 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000132
133 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000134 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000135 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000136
Bob Wilsonb742def2009-12-18 20:14:40 +0000137 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
138 SmallVector<AllocaInst*, 32> &NewElts);
139 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
140 SmallVector<AllocaInst*, 32> &NewElts);
141 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
142 SmallVector<AllocaInst*, 32> &NewElts);
143 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000144 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000145 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000146 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000147 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000148 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000149 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000150
Chris Lattner31d80102010-04-15 21:59:20 +0000151 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000152 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000153
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000154 // SROA_DT - SROA that uses DominatorTree.
155 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000156 static char ID;
157 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000158 SROA_DT(int T = -1) : SROA(T, true, ID) {
159 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000160 }
161
162 // getAnalysisUsage - This pass does not require any passes, but we know it
163 // will not alter the CFG, so say so.
164 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
165 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000166 AU.setPreservesCFG();
167 }
168 };
169
170 // SROA_SSAUp - SROA that uses SSAUpdater.
171 struct SROA_SSAUp : public SROA {
172 static char ID;
173 public:
174 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
175 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
176 }
177
178 // getAnalysisUsage - This pass does not require any passes, but we know it
179 // will not alter the CFG, so say so.
180 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
181 AU.setPreservesCFG();
182 }
183 };
184
Chris Lattnered7b41e2003-05-27 15:45:27 +0000185}
186
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000187char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000188char SROA_SSAUp::ID = 0;
189
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000190INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
191 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000192INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000193INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
194 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000195
196INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
197 "Scalar Replacement of Aggregates (SSAUp)", false, false)
198INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
199 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000200
Brian Gaeked0fde302003-11-11 22:41:34 +0000201// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000202FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000203 bool UseDomTree) {
204 if (UseDomTree)
205 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000206 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000207}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000208
209
Chris Lattner4cc576b2010-04-16 00:24:57 +0000210//===----------------------------------------------------------------------===//
211// Convert To Scalar Optimization.
212//===----------------------------------------------------------------------===//
213
214namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000215/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
216/// optimization, which scans the uses of an alloca and determines if it can
217/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000218class ConvertToScalarInfo {
219 /// AllocaSize - The size of the alloca being considered.
220 unsigned AllocaSize;
221 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000222
Chris Lattnera0bada72010-04-16 02:32:17 +0000223 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000224 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000225 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000226
Chris Lattnera001b662010-04-16 00:38:19 +0000227 /// VectorTy - This tracks the type that we should promote the vector to if
228 /// it is possible to turn it into a vector. This starts out null, and if it
229 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000230 const Type *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000231
Chris Lattnera001b662010-04-16 00:38:19 +0000232 /// HadAVector - True if there is at least one vector access to the alloca.
233 /// We don't want to turn random arrays into vectors and use vector element
234 /// insert/extract, but if there are element accesses to something that is
235 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000236 bool HadAVector;
237
238public:
239 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
240 : AllocaSize(Size), TD(td) {
241 IsNotTrivial = false;
242 VectorTy = 0;
243 HadAVector = false;
244 }
Bob Wilson69743022011-01-13 20:59:44 +0000245
Chris Lattnera001b662010-04-16 00:38:19 +0000246 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000247
Chris Lattner4cc576b2010-04-16 00:24:57 +0000248private:
249 bool CanConvertToScalar(Value *V, uint64_t Offset);
250 void MergeInType(const Type *In, uint64_t Offset);
251 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000252
Chris Lattner4cc576b2010-04-16 00:24:57 +0000253 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
254 uint64_t Offset, IRBuilder<> &Builder);
255 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
256 uint64_t Offset, IRBuilder<> &Builder);
257};
258} // end anonymous namespace.
259
Chris Lattner91abace2010-09-01 05:14:33 +0000260
Chris Lattnera001b662010-04-16 00:38:19 +0000261/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
262/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
263/// alloca if possible or null if not.
264AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
265 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
266 // out.
267 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
268 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000269
Chris Lattnera001b662010-04-16 00:38:19 +0000270 // If we were able to find a vector type that can handle this with
271 // insert/extract elements, and if there was at least one use that had
272 // a vector type, promote this to a vector. We don't want to promote
273 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
274 // we just get a lot of insert/extracts. If at least one vector is
275 // involved, then we probably really do have a union of vector/array.
276 const Type *NewTy;
Chris Lattner85a7c692011-01-23 06:40:33 +0000277 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
Chris Lattnera001b662010-04-16 00:38:19 +0000278 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
279 << *VectorTy << '\n');
280 NewTy = VectorTy; // Use the vector type.
281 } else {
282 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
283 // Create and insert the integer alloca.
284 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
285 }
286 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
287 ConvertUsesToScalar(AI, NewAI, 0);
288 return NewAI;
289}
290
291/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
292/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000293///
294/// There are two cases we handle here:
295/// 1) A union of vector types of the same size and potentially its elements.
296/// Here we turn element accesses into insert/extract element operations.
297/// This promotes a <4 x float> with a store of float to the third element
298/// into a <4 x float> that uses insert element.
299/// 2) A fully general blob of memory, which we turn into some (potentially
300/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000301/// and stores would mutate the memory. We mark this by setting VectorTy
302/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000303void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000304 // If we already decided to turn this into a blob of integer memory, there is
305 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000306 if (VectorTy && VectorTy->isVoidTy())
307 return;
Bob Wilson69743022011-01-13 20:59:44 +0000308
Chris Lattner4cc576b2010-04-16 00:24:57 +0000309 // If this could be contributing to a vector, analyze it.
310
311 // If the In type is a vector that is the same size as the alloca, see if it
312 // matches the existing VecTy.
313 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000314 // Remember if we saw a vector type.
315 HadAVector = true;
Bob Wilson69743022011-01-13 20:59:44 +0000316
Chris Lattner4cc576b2010-04-16 00:24:57 +0000317 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
318 // If we're storing/loading a vector of the right size, allow it as a
319 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000320 // we know the element size. If this is a subsequent access, ignore it
321 // even if it is a differing type but the same size. Worst case we can
322 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000323 if (VectorTy == 0)
324 VectorTy = VInTy;
325 return;
326 }
327 } else if (In->isFloatTy() || In->isDoubleTy() ||
328 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
329 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
330 // If we're accessing something that could be an element of a vector, see
331 // if the implied vector agrees with what we already have and if Offset is
332 // compatible with it.
333 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
334 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Bob Wilson69743022011-01-13 20:59:44 +0000335 (VectorTy == 0 ||
Chris Lattner4cc576b2010-04-16 00:24:57 +0000336 cast<VectorType>(VectorTy)->getElementType()
337 ->getPrimitiveSizeInBits()/8 == EltSize)) {
338 if (VectorTy == 0)
339 VectorTy = VectorType::get(In, AllocaSize/EltSize);
340 return;
341 }
342 }
Bob Wilson69743022011-01-13 20:59:44 +0000343
Chris Lattner4cc576b2010-04-16 00:24:57 +0000344 // Otherwise, we have a case that we can't handle with an optimized vector
345 // form. We can still turn this into a large integer.
346 VectorTy = Type::getVoidTy(In->getContext());
347}
348
349/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
350/// its accesses to a single vector type, return true and set VecTy to
351/// the new type. If we could convert the alloca into a single promotable
352/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
353/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
354/// is the current offset from the base of the alloca being analyzed.
355///
356/// If we see at least one access to the value that is as a vector type, set the
357/// SawVec flag.
358bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
359 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
360 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000361
Chris Lattner4cc576b2010-04-16 00:24:57 +0000362 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
363 // Don't break volatile loads.
364 if (LI->isVolatile())
365 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000366 // Don't touch MMX operations.
367 if (LI->getType()->isX86_MMXTy())
368 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000369 MergeInType(LI->getType(), Offset);
370 continue;
371 }
Bob Wilson69743022011-01-13 20:59:44 +0000372
Chris Lattner4cc576b2010-04-16 00:24:57 +0000373 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
374 // Storing the pointer, not into the value?
375 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000376 // Don't touch MMX operations.
377 if (SI->getOperand(0)->getType()->isX86_MMXTy())
378 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000379 MergeInType(SI->getOperand(0)->getType(), Offset);
380 continue;
381 }
Bob Wilson69743022011-01-13 20:59:44 +0000382
Chris Lattner4cc576b2010-04-16 00:24:57 +0000383 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000384 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000385 if (!CanConvertToScalar(BCI, Offset))
386 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000387 continue;
388 }
389
390 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
391 // If this is a GEP with a variable indices, we can't handle it.
392 if (!GEP->hasAllConstantIndices())
393 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000394
Chris Lattner4cc576b2010-04-16 00:24:57 +0000395 // Compute the offset that this GEP adds to the pointer.
396 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
397 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
398 &Indices[0], Indices.size());
399 // See if all uses can be converted.
400 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
401 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000402 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000403 continue;
404 }
405
406 // If this is a constant sized memset of a constant value (e.g. 0) we can
407 // handle it.
408 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
409 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000410 if (!isa<ConstantInt>(MSI->getValue()) ||
411 !isa<ConstantInt>(MSI->getLength()))
412 return false;
413 IsNotTrivial = true; // Can't be mem2reg'd.
414 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000415 }
416
417 // If this is a memcpy or memmove into or out of the whole allocation, we
418 // can handle it like a load or store of the scalar type.
419 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000420 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
421 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
422 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000423
Chris Lattnera001b662010-04-16 00:38:19 +0000424 IsNotTrivial = true; // Can't be mem2reg'd.
425 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000426 }
Bob Wilson69743022011-01-13 20:59:44 +0000427
Chris Lattner4cc576b2010-04-16 00:24:57 +0000428 // Otherwise, we cannot handle this!
429 return false;
430 }
Bob Wilson69743022011-01-13 20:59:44 +0000431
Chris Lattner4cc576b2010-04-16 00:24:57 +0000432 return true;
433}
434
435/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
436/// directly. This happens when we are converting an "integer union" to a
437/// single integer scalar, or when we are converting a "vector union" to a
438/// vector with insert/extractelement instructions.
439///
440/// Offset is an offset from the original alloca, in bits that need to be
441/// shifted to the right. By the end of this, there should be no uses of Ptr.
442void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
443 uint64_t Offset) {
444 while (!Ptr->use_empty()) {
445 Instruction *User = cast<Instruction>(Ptr->use_back());
446
447 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
448 ConvertUsesToScalar(CI, NewAI, Offset);
449 CI->eraseFromParent();
450 continue;
451 }
452
453 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
454 // Compute the offset that this GEP adds to the pointer.
455 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
456 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
457 &Indices[0], Indices.size());
458 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
459 GEP->eraseFromParent();
460 continue;
461 }
Bob Wilson69743022011-01-13 20:59:44 +0000462
Chris Lattner61db1f52010-12-26 22:57:41 +0000463 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000464
Chris Lattner4cc576b2010-04-16 00:24:57 +0000465 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
466 // The load is a bit extract from NewAI shifted right by Offset bits.
467 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
468 Value *NewLoadVal
469 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
470 LI->replaceAllUsesWith(NewLoadVal);
471 LI->eraseFromParent();
472 continue;
473 }
Bob Wilson69743022011-01-13 20:59:44 +0000474
Chris Lattner4cc576b2010-04-16 00:24:57 +0000475 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
476 assert(SI->getOperand(0) != Ptr && "Consistency error!");
477 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
478 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
479 Builder);
480 Builder.CreateStore(New, NewAI);
481 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000482
Chris Lattner4cc576b2010-04-16 00:24:57 +0000483 // If the load we just inserted is now dead, then the inserted store
484 // overwrote the entire thing.
485 if (Old->use_empty())
486 Old->eraseFromParent();
487 continue;
488 }
Bob Wilson69743022011-01-13 20:59:44 +0000489
Chris Lattner4cc576b2010-04-16 00:24:57 +0000490 // If this is a constant sized memset of a constant value (e.g. 0) we can
491 // transform it into a store of the expanded constant value.
492 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
493 assert(MSI->getRawDest() == Ptr && "Consistency error!");
494 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
495 if (NumBytes != 0) {
496 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000497
Chris Lattner4cc576b2010-04-16 00:24:57 +0000498 // Compute the value replicated the right number of times.
499 APInt APVal(NumBytes*8, Val);
500
501 // Splat the value if non-zero.
502 if (Val)
503 for (unsigned i = 1; i != NumBytes; ++i)
504 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000505
Chris Lattner4cc576b2010-04-16 00:24:57 +0000506 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
507 Value *New = ConvertScalar_InsertValue(
508 ConstantInt::get(User->getContext(), APVal),
509 Old, Offset, Builder);
510 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000511
Chris Lattner4cc576b2010-04-16 00:24:57 +0000512 // If the load we just inserted is now dead, then the memset overwrote
513 // the entire thing.
514 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000515 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000516 }
517 MSI->eraseFromParent();
518 continue;
519 }
520
521 // If this is a memcpy or memmove into or out of the whole allocation, we
522 // can handle it like a load or store of the scalar type.
523 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
524 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000525
Chris Lattner4cc576b2010-04-16 00:24:57 +0000526 // If the source and destination are both to the same alloca, then this is
527 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
528 // as appropriate.
Dan Gohman5034dd32010-12-15 20:02:24 +0000529 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000530
Dan Gohman5034dd32010-12-15 20:02:24 +0000531 if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000532 // Dest must be OrigAI, change this to be a load from the original
533 // pointer (bitcasted), then a store to our new alloca.
534 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
535 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000536 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
537 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
538 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
539 AIPTy = PointerType::get(AIPTy->getElementType(),
540 SPTy->getAddressSpace());
541 }
542 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
543
Chris Lattner4cc576b2010-04-16 00:24:57 +0000544 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
545 SrcVal->setAlignment(MTI->getAlignment());
546 Builder.CreateStore(SrcVal, NewAI);
Dan Gohman5034dd32010-12-15 20:02:24 +0000547 } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000548 // Src must be OrigAI, change this to be a load from NewAI then a store
549 // through the original dest pointer (bitcasted).
550 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
551 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
552
Mon P Wange90a6332010-12-23 01:41:32 +0000553 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
554 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
555 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
556 AIPTy = PointerType::get(AIPTy->getElementType(),
557 DPTy->getAddressSpace());
558 }
559 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
560
Chris Lattner4cc576b2010-04-16 00:24:57 +0000561 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
562 NewStore->setAlignment(MTI->getAlignment());
563 } else {
564 // Noop transfer. Src == Dst
565 }
566
567 MTI->eraseFromParent();
568 continue;
569 }
Bob Wilson69743022011-01-13 20:59:44 +0000570
Chris Lattner4cc576b2010-04-16 00:24:57 +0000571 llvm_unreachable("Unsupported operation!");
572 }
573}
574
575/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
576/// or vector value FromVal, extracting the bits from the offset specified by
577/// Offset. This returns the value, which is of type ToType.
578///
579/// This happens when we are converting an "integer union" to a single
580/// integer scalar, or when we are converting a "vector union" to a vector with
581/// insert/extractelement instructions.
582///
583/// Offset is an offset from the original alloca, in bits that need to be
584/// shifted to the right.
585Value *ConvertToScalarInfo::
586ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
587 uint64_t Offset, IRBuilder<> &Builder) {
588 // If the load is of the whole new alloca, no conversion is needed.
589 if (FromVal->getType() == ToType && Offset == 0)
590 return FromVal;
591
592 // If the result alloca is a vector type, this is either an element
593 // access or a bitcast to another vector type of the same size.
594 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
595 if (ToType->isVectorTy())
596 return Builder.CreateBitCast(FromVal, ToType, "tmp");
597
598 // Otherwise it must be an element access.
599 unsigned Elt = 0;
600 if (Offset) {
601 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
602 Elt = Offset/EltSize;
603 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
604 }
605 // Return the element extracted out of it.
606 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
607 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
608 if (V->getType() != ToType)
609 V = Builder.CreateBitCast(V, ToType, "tmp");
610 return V;
611 }
Bob Wilson69743022011-01-13 20:59:44 +0000612
Chris Lattner4cc576b2010-04-16 00:24:57 +0000613 // If ToType is a first class aggregate, extract out each of the pieces and
614 // use insertvalue's to form the FCA.
615 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
616 const StructLayout &Layout = *TD.getStructLayout(ST);
617 Value *Res = UndefValue::get(ST);
618 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
619 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
620 Offset+Layout.getElementOffsetInBits(i),
621 Builder);
622 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
623 }
624 return Res;
625 }
Bob Wilson69743022011-01-13 20:59:44 +0000626
Chris Lattner4cc576b2010-04-16 00:24:57 +0000627 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
628 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
629 Value *Res = UndefValue::get(AT);
630 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
631 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
632 Offset+i*EltSize, Builder);
633 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
634 }
635 return Res;
636 }
637
638 // Otherwise, this must be a union that was converted to an integer value.
639 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
640
641 // If this is a big-endian system and the load is narrower than the
642 // full alloca type, we need to do a shift to get the right bits.
643 int ShAmt = 0;
644 if (TD.isBigEndian()) {
645 // On big-endian machines, the lowest bit is stored at the bit offset
646 // from the pointer given by getTypeStoreSizeInBits. This matters for
647 // integers with a bitwidth that is not a multiple of 8.
648 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
649 TD.getTypeStoreSizeInBits(ToType) - Offset;
650 } else {
651 ShAmt = Offset;
652 }
653
654 // Note: we support negative bitwidths (with shl) which are not defined.
655 // We do this to support (f.e.) loads off the end of a structure where
656 // only some bits are used.
657 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
658 FromVal = Builder.CreateLShr(FromVal,
659 ConstantInt::get(FromVal->getType(),
660 ShAmt), "tmp");
661 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000662 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000663 ConstantInt::get(FromVal->getType(),
664 -ShAmt), "tmp");
665
666 // Finally, unconditionally truncate the integer to the right width.
667 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
668 if (LIBitWidth < NTy->getBitWidth())
669 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000670 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000671 LIBitWidth), "tmp");
672 else if (LIBitWidth > NTy->getBitWidth())
673 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000674 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000675 LIBitWidth), "tmp");
676
677 // If the result is an integer, this is a trunc or bitcast.
678 if (ToType->isIntegerTy()) {
679 // Should be done.
680 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
681 // Just do a bitcast, we know the sizes match up.
682 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
683 } else {
684 // Otherwise must be a pointer.
685 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
686 }
687 assert(FromVal->getType() == ToType && "Didn't convert right?");
688 return FromVal;
689}
690
691/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
692/// or vector value "Old" at the offset specified by Offset.
693///
694/// This happens when we are converting an "integer union" to a
695/// single integer scalar, or when we are converting a "vector union" to a
696/// vector with insert/extractelement instructions.
697///
698/// Offset is an offset from the original alloca, in bits that need to be
699/// shifted to the right.
700Value *ConvertToScalarInfo::
701ConvertScalar_InsertValue(Value *SV, Value *Old,
702 uint64_t Offset, IRBuilder<> &Builder) {
703 // Convert the stored type to the actual type, shift it left to insert
704 // then 'or' into place.
705 const Type *AllocaType = Old->getType();
706 LLVMContext &Context = Old->getContext();
707
708 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
709 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
710 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000711
Chris Lattner4cc576b2010-04-16 00:24:57 +0000712 // Changing the whole vector with memset or with an access of a different
713 // vector type?
714 if (ValSize == VecSize)
715 return Builder.CreateBitCast(SV, AllocaType, "tmp");
716
717 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
718
719 // Must be an element insertion.
720 unsigned Elt = Offset/EltSize;
Bob Wilson69743022011-01-13 20:59:44 +0000721
Chris Lattner4cc576b2010-04-16 00:24:57 +0000722 if (SV->getType() != VTy->getElementType())
723 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000724
725 SV = Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000726 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
727 "tmp");
728 return SV;
729 }
Bob Wilson69743022011-01-13 20:59:44 +0000730
Chris Lattner4cc576b2010-04-16 00:24:57 +0000731 // If SV is a first-class aggregate value, insert each value recursively.
732 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
733 const StructLayout &Layout = *TD.getStructLayout(ST);
734 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
735 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000736 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000737 Offset+Layout.getElementOffsetInBits(i),
738 Builder);
739 }
740 return Old;
741 }
Bob Wilson69743022011-01-13 20:59:44 +0000742
Chris Lattner4cc576b2010-04-16 00:24:57 +0000743 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
744 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
745 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
746 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
747 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
748 }
749 return Old;
750 }
751
752 // If SV is a float, convert it to the appropriate integer type.
753 // If it is a pointer, do the same.
754 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
755 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
756 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
757 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
758 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
759 SV = Builder.CreateBitCast(SV,
760 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
761 else if (SV->getType()->isPointerTy())
762 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
763
764 // Zero extend or truncate the value if needed.
765 if (SV->getType() != AllocaType) {
766 if (SV->getType()->getPrimitiveSizeInBits() <
767 AllocaType->getPrimitiveSizeInBits())
768 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
769 else {
770 // Truncation may be needed if storing more than the alloca can hold
771 // (undefined behavior).
772 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
773 SrcWidth = DestWidth;
774 SrcStoreWidth = DestStoreWidth;
775 }
776 }
777
778 // If this is a big-endian system and the store is narrower than the
779 // full alloca type, we need to do a shift to get the right bits.
780 int ShAmt = 0;
781 if (TD.isBigEndian()) {
782 // On big-endian machines, the lowest bit is stored at the bit offset
783 // from the pointer given by getTypeStoreSizeInBits. This matters for
784 // integers with a bitwidth that is not a multiple of 8.
785 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
786 } else {
787 ShAmt = Offset;
788 }
789
790 // Note: we support negative bitwidths (with shr) which are not defined.
791 // We do this to support (f.e.) stores off the end of a structure where
792 // only some bits in the structure are set.
793 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
794 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
795 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
796 ShAmt), "tmp");
797 Mask <<= ShAmt;
798 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
799 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
800 -ShAmt), "tmp");
801 Mask = Mask.lshr(-ShAmt);
802 }
803
804 // Mask out the bits we are about to insert from the old value, and or
805 // in the new bits.
806 if (SrcWidth != DestWidth) {
807 assert(DestWidth > SrcWidth);
808 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
809 SV = Builder.CreateOr(Old, SV, "ins");
810 }
811 return SV;
812}
813
814
815//===----------------------------------------------------------------------===//
816// SRoA Driver
817//===----------------------------------------------------------------------===//
818
819
Chris Lattnered7b41e2003-05-27 15:45:27 +0000820bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000821 TD = getAnalysisIfAvailable<TargetData>();
822
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000823 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000824
825 // FIXME: ScalarRepl currently depends on TargetData more than it
826 // theoretically needs to. It should be refactored in order to support
827 // target-independent IR. Until this is done, just skip the actual
828 // scalar-replacement portion of this pass.
829 if (!TD) return Changed;
830
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000831 while (1) {
832 bool LocalChange = performScalarRepl(F);
833 if (!LocalChange) break; // No need to repromote if no scalarrepl
834 Changed = true;
835 LocalChange = performPromotion(F);
836 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
837 }
Chris Lattner38aec322003-09-11 16:45:55 +0000838
839 return Changed;
840}
841
Chris Lattnerd0f56132011-01-14 19:50:47 +0000842namespace {
843class AllocaPromoter : public LoadAndStorePromoter {
844 AllocaInst *AI;
845public:
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000846 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
847 : LoadAndStorePromoter(Insts, S), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +0000848
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000849 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +0000850 // Remember which alloca we're promoting (for isInstInList).
851 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000852 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +0000853 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000854 }
855
Chris Lattnerd0f56132011-01-14 19:50:47 +0000856 virtual bool isInstInList(Instruction *I,
857 const SmallVectorImpl<Instruction*> &Insts) const {
858 if (LoadInst *LI = dyn_cast<LoadInst>(I))
859 return LI->getOperand(0) == AI;
860 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000861 }
Chris Lattnerd0f56132011-01-14 19:50:47 +0000862};
863} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +0000864
865bool SROA::performPromotion(Function &F) {
866 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000867 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000868 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000869 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +0000870
Chris Lattner02a3be02003-09-20 14:39:18 +0000871 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000872
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000873 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000874 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +0000875 while (1) {
876 Allocas.clear();
877
878 // Find allocas that are safe to promote, by looking at all instructions in
879 // the entry node
880 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
881 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000882 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000883 Allocas.push_back(AI);
884
885 if (Allocas.empty()) break;
886
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000887 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +0000888 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000889 else {
890 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000891 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
892 AllocaInst *AI = Allocas[i];
893
894 // Build list of instructions to promote.
895 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
896 UI != E; ++UI)
897 Insts.push_back(cast<Instruction>(*UI));
898
899 AllocaPromoter(Insts, SSA).run(AI, Insts);
900 Insts.clear();
901 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000902 }
Chris Lattner38aec322003-09-11 16:45:55 +0000903 NumPromoted += Allocas.size();
904 Changed = true;
905 }
906
907 return Changed;
908}
909
Chris Lattner4cc576b2010-04-16 00:24:57 +0000910
Bob Wilson3992feb2010-02-03 17:23:56 +0000911/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
912/// SROA. It must be a struct or array type with a small number of elements.
913static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
914 const Type *T = AI->getAllocatedType();
915 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000916 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000917 return ST->getNumElements() <= 32;
918 // Arrays are much less likely to be safe for SROA; only consider
919 // them if they are very small.
920 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
921 return AT->getNumElements() <= 8;
922 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000923}
924
Chris Lattnerc4472072010-04-15 23:50:26 +0000925
Chris Lattner38aec322003-09-11 16:45:55 +0000926// performScalarRepl - This algorithm is a simple worklist driven algorithm,
927// which runs on all of the malloc/alloca instructions in the function, removing
928// them if they are only used by getelementptr instructions.
929//
930bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000931 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000932
Chris Lattner31d80102010-04-15 21:59:20 +0000933 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000934 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000935 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000936 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000937 WorkList.push_back(A);
938
939 // Process the worklist
940 bool Changed = false;
941 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000942 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000943 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +0000944
Chris Lattneradd2bd72006-12-22 23:14:42 +0000945 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
946 // with unused elements.
947 if (AI->use_empty()) {
948 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000949 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000950 continue;
951 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000952
953 // If this alloca is impossible for us to promote, reject it early.
954 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
955 continue;
Bob Wilson69743022011-01-13 20:59:44 +0000956
Chris Lattner79b3bd32007-04-25 06:40:51 +0000957 // Check to see if this allocation is only modified by a memcpy/memmove from
958 // a constant global. If this is the case, we can change all users to use
959 // the constant global instead. This is commonly produced by the CFE by
960 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
961 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000962 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000963 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
964 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000965 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000966 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000967 TheCopy->eraseFromParent(); // Don't mutate the global.
968 AI->eraseFromParent();
969 ++NumGlobals;
970 Changed = true;
971 continue;
972 }
Bob Wilson69743022011-01-13 20:59:44 +0000973
Chris Lattner7809ecd2009-02-03 01:30:09 +0000974 // Check to see if we can perform the core SROA transformation. We cannot
975 // transform the allocation instruction if it is an array allocation
976 // (allocations OF arrays are ok though), and an allocation of a scalar
977 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000978 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000979
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000980 // Do not promote [0 x %struct].
981 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +0000982
Chris Lattner31d80102010-04-15 21:59:20 +0000983 // Do not promote any struct whose size is too big.
984 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +0000985
Bob Wilson3992feb2010-02-03 17:23:56 +0000986 // If the alloca looks like a good candidate for scalar replacement, and if
987 // all its users can be transformed, then split up the aggregate into its
988 // separate elements.
989 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
990 DoScalarReplacement(AI, WorkList);
991 Changed = true;
992 continue;
993 }
994
Chris Lattner6e733d32009-01-28 20:16:43 +0000995 // If we can turn this aggregate value (potentially with casts) into a
996 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000997 // IsNotTrivial tracks whether this is something that mem2reg could have
998 // promoted itself. If so, we don't want to transform it needlessly. Note
999 // that we can't just check based on the type: the alloca may be of an i32
1000 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001001 if (AllocaInst *NewAI =
1002 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001003 NewAI->takeName(AI);
1004 AI->eraseFromParent();
1005 ++NumConverted;
1006 Changed = true;
1007 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001008 }
1009
Chris Lattner7809ecd2009-02-03 01:30:09 +00001010 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001011 }
1012
1013 return Changed;
1014}
Chris Lattner5e062a12003-05-30 04:15:41 +00001015
Chris Lattnera10b29b2007-04-25 05:02:56 +00001016/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1017/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001018void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001019 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001020 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001021 SmallVector<AllocaInst*, 32> ElementAllocas;
1022 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1023 ElementAllocas.reserve(ST->getNumContainedTypes());
1024 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001025 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001026 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001027 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001028 ElementAllocas.push_back(NA);
1029 WorkList.push_back(NA); // Add to worklist for recursive processing
1030 }
1031 } else {
1032 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1033 ElementAllocas.reserve(AT->getNumElements());
1034 const Type *ElTy = AT->getElementType();
1035 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001036 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001037 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001038 ElementAllocas.push_back(NA);
1039 WorkList.push_back(NA); // Add to worklist for recursive processing
1040 }
1041 }
1042
Bob Wilsonb742def2009-12-18 20:14:40 +00001043 // Now that we have created the new alloca instructions, rewrite all the
1044 // uses of the old alloca.
1045 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001046
Bob Wilsonb742def2009-12-18 20:14:40 +00001047 // Now erase any instructions that were made dead while rewriting the alloca.
1048 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001049 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001050
Dan Gohmanfe601042010-06-22 15:08:57 +00001051 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001052}
Chris Lattnera59adc42009-12-14 05:11:02 +00001053
Bob Wilsonb742def2009-12-18 20:14:40 +00001054/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1055/// recursively including all their operands that become trivially dead.
1056void SROA::DeleteDeadInstructions() {
1057 while (!DeadInsts.empty()) {
1058 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001059
Bob Wilsonb742def2009-12-18 20:14:40 +00001060 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1061 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1062 // Zero out the operand and see if it becomes trivially dead.
1063 // (But, don't add allocas to the dead instruction list -- they are
1064 // already on the worklist and will be deleted separately.)
1065 *OI = 0;
1066 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1067 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001068 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001069
1070 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001071 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001072}
Bob Wilson69743022011-01-13 20:59:44 +00001073
Bob Wilsonb742def2009-12-18 20:14:40 +00001074/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1075/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001076/// the Info parameter. Offset indicates the position within AI that is
1077/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001078void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001079 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001080 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1081 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001082
Bob Wilsonb742def2009-12-18 20:14:40 +00001083 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001084 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001085 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001086 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001087 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001088 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001089 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001090 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001091 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001092 if (Length == 0)
1093 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001094 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001095 UI.getOperandNo() == 0, Info, MI,
1096 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001097 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001098 if (LI->isVolatile())
1099 return MarkUnsafe(Info, User);
1100 const Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001101 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001102 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001103 Info.hasALoadOrStore = true;
1104
Bob Wilsonb742def2009-12-18 20:14:40 +00001105 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1106 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001107 if (SI->isVolatile() || SI->getOperand(0) == I)
1108 return MarkUnsafe(Info, User);
1109
1110 const Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001111 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001112 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001113 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001114 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1115 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1116 } else {
1117 return MarkUnsafe(Info, User);
1118 }
1119 if (Info.isUnsafe) return;
1120 }
1121}
1122
1123
1124/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1125/// derived from the alloca, we can often still split the alloca into elements.
1126/// This is useful if we have a large alloca where one element is phi'd
1127/// together somewhere: we can SRoA and promote all the other elements even if
1128/// we end up not being able to promote this one.
1129///
1130/// All we require is that the uses of the PHI do not index into other parts of
1131/// the alloca. The most important use case for this is single load and stores
1132/// that are PHI'd together, which can happen due to code sinking.
1133void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1134 AllocaInfo &Info) {
1135 // If we've already checked this PHI, don't do it again.
1136 if (PHINode *PN = dyn_cast<PHINode>(I))
1137 if (!Info.CheckedPHIs.insert(PN))
1138 return;
1139
1140 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1141 Instruction *User = cast<Instruction>(*UI);
1142
1143 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1144 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1145 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1146 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1147 // but would have to prove that we're staying inside of an element being
1148 // promoted.
1149 if (!GEPI->hasAllZeroIndices())
1150 return MarkUnsafe(Info, User);
1151 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1152 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1153 if (LI->isVolatile())
1154 return MarkUnsafe(Info, User);
1155 const Type *LIType = LI->getType();
1156 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1157 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1158 Info.hasALoadOrStore = true;
1159
1160 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1161 // Store is ok if storing INTO the pointer, not storing the pointer
1162 if (SI->isVolatile() || SI->getOperand(0) == I)
1163 return MarkUnsafe(Info, User);
1164
1165 const Type *SIType = SI->getOperand(0)->getType();
1166 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1167 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1168 Info.hasALoadOrStore = true;
1169 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1170 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001171 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001172 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001173 }
1174 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001175 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001176}
Bob Wilson39c88a62009-12-17 18:34:24 +00001177
Bob Wilsonb742def2009-12-18 20:14:40 +00001178/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1179/// replacement. It is safe when all the indices are constant, in-bounds
1180/// references, and when the resulting offset corresponds to an element within
1181/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001182/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001183void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001184 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001185 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1186 if (GEPIt == E)
1187 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001188
Chris Lattner88e6dc82008-08-23 05:21:06 +00001189 // Walk through the GEP type indices, checking the types that this indexes
1190 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001191 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001192 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001193 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001194 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001195
Bob Wilsonb742def2009-12-18 20:14:40 +00001196 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1197 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001198 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001199 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001200
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001201 // Compute the offset due to this GEP and check if the alloca has a
1202 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001203 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1204 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1205 &Indices[0], Indices.size());
Chris Lattner6c95d242011-01-23 07:29:29 +00001206 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001207 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001208}
1209
Bob Wilson704d1342011-01-13 17:45:11 +00001210/// isHomogeneousAggregate - Check if type T is a struct or array containing
1211/// elements of the same type (which is always true for arrays). If so,
1212/// return true with NumElts and EltTy set to the number of elements and the
1213/// element type, respectively.
1214static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1215 const Type *&EltTy) {
1216 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1217 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001218 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001219 return true;
1220 }
1221 if (const StructType *ST = dyn_cast<StructType>(T)) {
1222 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001223 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001224 for (unsigned n = 1; n < NumElts; ++n) {
1225 if (ST->getContainedType(n) != EltTy)
1226 return false;
1227 }
1228 return true;
1229 }
1230 return false;
1231}
1232
1233/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1234/// "homogeneous" aggregates with the same element type and number of elements.
1235static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1236 if (T1 == T2)
1237 return true;
1238
1239 unsigned NumElts1, NumElts2;
1240 const Type *EltTy1, *EltTy2;
1241 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1242 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1243 NumElts1 == NumElts2 &&
1244 EltTy1 == EltTy2)
1245 return true;
1246
1247 return false;
1248}
1249
Bob Wilsonb742def2009-12-18 20:14:40 +00001250/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1251/// alloca or has an offset and size that corresponds to a component element
1252/// within it. The offset checked here may have been formed from a GEP with a
1253/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001254///
1255/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1256/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001257void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001258 const Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001259 AllocaInfo &Info, Instruction *TheAccess,
1260 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001261 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001262 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001263 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001264 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1265 // loads/stores (which are essentially the same as the MemIntrinsics with
1266 // regard to copying padding between elements). But, if an alloca is
1267 // flagged as both a source and destination of such operations, we'll need
1268 // to check later for padding between elements.
1269 if (!MemOpType || MemOpType->isIntegerTy()) {
1270 if (isStore)
1271 Info.isMemCpyDst = true;
1272 else
1273 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001274 return;
1275 }
Bob Wilson704d1342011-01-13 17:45:11 +00001276 // This is also safe for references using a type that is compatible with
1277 // the type of the alloca, so that loads/stores can be rewritten using
1278 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001279 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001280 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001281 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001282 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001283 }
1284 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner6c95d242011-01-23 07:29:29 +00001285 const Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001286 if (TypeHasComponent(T, Offset, MemSize)) {
1287 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001288 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001289 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001290
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001291 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001292}
1293
1294/// TypeHasComponent - Return true if T has a component type with the
1295/// specified offset and size. If Size is zero, do not check the size.
1296bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1297 const Type *EltTy;
1298 uint64_t EltSize;
1299 if (const StructType *ST = dyn_cast<StructType>(T)) {
1300 const StructLayout *Layout = TD->getStructLayout(ST);
1301 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1302 EltTy = ST->getContainedType(EltIdx);
1303 EltSize = TD->getTypeAllocSize(EltTy);
1304 Offset -= Layout->getElementOffset(EltIdx);
1305 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1306 EltTy = AT->getElementType();
1307 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001308 if (Offset >= AT->getNumElements() * EltSize)
1309 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001310 Offset %= EltSize;
1311 } else {
1312 return false;
1313 }
1314 if (Offset == 0 && (Size == 0 || EltSize == Size))
1315 return true;
1316 // Check if the component spans multiple elements.
1317 if (Offset + Size > EltSize)
1318 return false;
1319 return TypeHasComponent(EltTy, Offset, Size);
1320}
1321
1322/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1323/// the instruction I, which references it, to use the separate elements.
1324/// Offset indicates the position within AI that is referenced by this
1325/// instruction.
1326void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1327 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001328 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1329 Use &TheUse = UI.getUse();
1330 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001331
1332 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1333 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001334 continue;
1335 }
1336
1337 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001338 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001339 continue;
1340 }
1341
1342 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001343 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1344 uint64_t MemSize = Length->getZExtValue();
1345 if (Offset == 0 &&
1346 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1347 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001348 // Otherwise the intrinsic can only touch a single element and the
1349 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001350 continue;
1351 }
1352
1353 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001354 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001355
Bob Wilson704d1342011-01-13 17:45:11 +00001356 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001357 // Replace:
1358 // %res = load { i32, i32 }* %alloc
1359 // with:
1360 // %load.0 = load i32* %alloc.0
1361 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1362 // %load.1 = load i32* %alloc.1
1363 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1364 // (Also works for arrays instead of structs)
1365 Value *Insert = UndefValue::get(LIType);
1366 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1367 Value *Load = new LoadInst(NewElts[i], "load", LI);
1368 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1369 }
1370 LI->replaceAllUsesWith(Insert);
1371 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001372 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001373 TD->getTypeAllocSize(LIType) ==
1374 TD->getTypeAllocSize(AI->getAllocatedType())) {
1375 // If this is a load of the entire alloca to an integer, rewrite it.
1376 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1377 }
Chris Lattner145c5322011-01-23 08:27:54 +00001378 continue;
1379 }
1380
1381 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001382 Value *Val = SI->getOperand(0);
1383 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001384 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001385 // Replace:
1386 // store { i32, i32 } %val, { i32, i32 }* %alloc
1387 // with:
1388 // %val.0 = extractvalue { i32, i32 } %val, 0
1389 // store i32 %val.0, i32* %alloc.0
1390 // %val.1 = extractvalue { i32, i32 } %val, 1
1391 // store i32 %val.1, i32* %alloc.1
1392 // (Also works for arrays instead of structs)
1393 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1394 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1395 new StoreInst(Extract, NewElts[i], SI);
1396 }
1397 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001398 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001399 TD->getTypeAllocSize(SIType) ==
1400 TD->getTypeAllocSize(AI->getAllocatedType())) {
1401 // If this is a store of the entire alloca from an integer, rewrite it.
1402 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1403 }
Chris Lattner145c5322011-01-23 08:27:54 +00001404 continue;
1405 }
1406
1407 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1408 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1409 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1410 // the new pointer.
1411 if (!isa<AllocaInst>(I)) continue;
1412
1413 assert(Offset == 0 && NewElts[0] &&
1414 "Direct alloca use should have a zero offset");
1415
1416 // If we have a use of the alloca, we know the derived uses will be
1417 // utilizing just the first element of the scalarized result. Insert a
1418 // bitcast of the first alloca before the user as required.
1419 AllocaInst *NewAI = NewElts[0];
1420 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1421 NewAI->moveBefore(BCI);
1422 TheUse = BCI;
1423 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001424 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001425 }
1426}
1427
Bob Wilsonb742def2009-12-18 20:14:40 +00001428/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1429/// and recursively continue updating all of its uses.
1430void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1431 SmallVector<AllocaInst*, 32> &NewElts) {
1432 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1433 if (BC->getOperand(0) != AI)
1434 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001435
Bob Wilsonb742def2009-12-18 20:14:40 +00001436 // The bitcast references the original alloca. Replace its uses with
1437 // references to the first new element alloca.
1438 Instruction *Val = NewElts[0];
1439 if (Val->getType() != BC->getDestTy()) {
1440 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1441 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001442 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001443 BC->replaceAllUsesWith(Val);
1444 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001445}
1446
Bob Wilsonb742def2009-12-18 20:14:40 +00001447/// FindElementAndOffset - Return the index of the element containing Offset
1448/// within the specified type, which must be either a struct or an array.
1449/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001450/// element. IdxTy is set to the type of the index result to be used in a
1451/// GEP instruction.
1452uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1453 const Type *&IdxTy) {
1454 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001455 if (const StructType *ST = dyn_cast<StructType>(T)) {
1456 const StructLayout *Layout = TD->getStructLayout(ST);
1457 Idx = Layout->getElementContainingOffset(Offset);
1458 T = ST->getContainedType(Idx);
1459 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001460 IdxTy = Type::getInt32Ty(T->getContext());
1461 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001462 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001463 const ArrayType *AT = cast<ArrayType>(T);
1464 T = AT->getElementType();
1465 uint64_t EltSize = TD->getTypeAllocSize(T);
1466 Idx = Offset / EltSize;
1467 Offset -= Idx * EltSize;
1468 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001469 return Idx;
1470}
1471
1472/// RewriteGEP - Check if this GEP instruction moves the pointer across
1473/// elements of the alloca that are being split apart, and if so, rewrite
1474/// the GEP to be relative to the new element.
1475void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1476 SmallVector<AllocaInst*, 32> &NewElts) {
1477 uint64_t OldOffset = Offset;
1478 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1479 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1480 &Indices[0], Indices.size());
1481
1482 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1483
1484 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001485 const Type *IdxTy;
1486 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001487 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001488 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001489
1490 T = AI->getAllocatedType();
1491 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001492 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001493
1494 // If this GEP does not move the pointer across elements of the alloca
1495 // being split, then it does not needs to be rewritten.
1496 if (Idx == OldIdx)
1497 return;
1498
1499 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1500 SmallVector<Value*, 8> NewArgs;
1501 NewArgs.push_back(Constant::getNullValue(i32Ty));
1502 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001503 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1504 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001505 }
1506 Instruction *Val = NewElts[Idx];
1507 if (NewArgs.size() > 1) {
1508 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1509 NewArgs.end(), "", GEPI);
1510 Val->takeName(GEPI);
1511 }
1512 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001513 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001514 GEPI->replaceAllUsesWith(Val);
1515 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001516}
1517
1518/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1519/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001520void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001521 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001522 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001523 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001524 // appropriate type. The "Other" pointer is the pointer that goes to memory
1525 // that doesn't have anything to do with the alloca that we are promoting. For
1526 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001527 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001528 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001529 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001530 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001531 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001532 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001533 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001534 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001535 }
1536 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001537
Chris Lattnerd93afec2009-01-07 07:18:45 +00001538 // If there is an other pointer, we want to convert it to the same pointer
1539 // type as AI has, so we can GEP through it safely.
1540 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001541 unsigned AddrSpace =
1542 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001543
1544 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1545 // optimization, but it's also required to detect the corner case where
1546 // both pointer operands are referencing the same memory, and where
1547 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1548 // function is only called for mem intrinsics that access the whole
1549 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001550 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00001551
Bob Wilsona756b1d2010-01-19 04:32:48 +00001552 // Copying the alloca to itself is a no-op: just delete it.
1553 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1554 // This code will run twice for a no-op memcpy -- once for each operand.
1555 // Put only one reference to MI on the DeadInsts list.
1556 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1557 E = DeadInsts.end(); I != E; ++I)
1558 if (*I == MI) return;
1559 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001560 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001561 }
Bob Wilson69743022011-01-13 20:59:44 +00001562
Chris Lattnerd93afec2009-01-07 07:18:45 +00001563 // If the pointer is not the right type, insert a bitcast to the right
1564 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001565 const Type *NewTy =
1566 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00001567
Chris Lattner0238f8c2010-07-08 00:27:05 +00001568 if (OtherPtr->getType() != NewTy)
1569 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001570 }
Bob Wilson69743022011-01-13 20:59:44 +00001571
Chris Lattnerd93afec2009-01-07 07:18:45 +00001572 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00001573 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00001574
Owen Anderson1d0be152009-08-13 21:58:54 +00001575 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001576
1577 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1578 // If this is a memcpy/memmove, emit a GEP of the other element address.
1579 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001580 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00001581
Bob Wilsona756b1d2010-01-19 04:32:48 +00001582 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001583 Value *Idx[2] = { Zero,
1584 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001585 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001586 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001587 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001588 uint64_t EltOffset;
1589 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001590 const Type *OtherTy = OtherPtrTy->getElementType();
1591 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001592 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1593 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001594 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001595 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001596 }
Bob Wilson69743022011-01-13 20:59:44 +00001597
Chris Lattner1541e0f2009-03-04 19:20:50 +00001598 // The alignment of the other pointer is the guaranteed alignment of the
1599 // element, which is affected by both the known alignment of the whole
1600 // mem intrinsic and the alignment of the element. If the alignment of
1601 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1602 // known alignment is just 4 bytes.
1603 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001604 }
Bob Wilson69743022011-01-13 20:59:44 +00001605
Chris Lattnerd93afec2009-01-07 07:18:45 +00001606 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001607 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00001608
Chris Lattnerd93afec2009-01-07 07:18:45 +00001609 // If we got down to a scalar, insert a load or store as appropriate.
1610 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001611 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001612 if (SROADest) {
1613 // From Other to Alloca.
1614 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1615 new StoreInst(Elt, EltPtr, MI);
1616 } else {
1617 // From Alloca to Other.
1618 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1619 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1620 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001621 continue;
1622 }
1623 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00001624
Chris Lattnerd93afec2009-01-07 07:18:45 +00001625 // If the stored element is zero (common case), just store a null
1626 // constant.
1627 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001628 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001629 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001630 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001631 } else {
1632 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001633 const Type *ValTy = EltTy->getScalarType();
1634
Chris Lattnerd93afec2009-01-07 07:18:45 +00001635 // Construct an integer with the right value.
1636 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1637 APInt OneVal(EltSize, CI->getZExtValue());
1638 APInt TotalVal(OneVal);
1639 // Set each byte.
1640 for (unsigned i = 0; 8*i < EltSize; ++i) {
1641 TotalVal = TotalVal.shl(8);
1642 TotalVal |= OneVal;
1643 }
Bob Wilson69743022011-01-13 20:59:44 +00001644
Chris Lattnerd93afec2009-01-07 07:18:45 +00001645 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001646 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001647 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001648 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001649 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001650 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001651 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00001652
Chris Lattnerd93afec2009-01-07 07:18:45 +00001653 // If the requested value was a vector constant, create it.
1654 if (EltTy != ValTy) {
1655 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1656 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001657 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001658 }
1659 }
1660 new StoreInst(StoreVal, EltPtr, MI);
1661 continue;
1662 }
1663 // Otherwise, if we're storing a byte variable, use a memset call for
1664 // this element.
1665 }
Bob Wilson69743022011-01-13 20:59:44 +00001666
Duncan Sands777d2302009-05-09 07:06:46 +00001667 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001668
Chris Lattner61db1f52010-12-26 22:57:41 +00001669 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00001670
Chris Lattnerd93afec2009-01-07 07:18:45 +00001671 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00001672 if (isa<MemSetInst>(MI)) {
1673 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1674 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001675 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00001676 assert(isa<MemTransferInst>(MI));
1677 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
1678 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00001679
Chris Lattner61db1f52010-12-26 22:57:41 +00001680 if (isa<MemCpyInst>(MI))
1681 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1682 else
1683 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001684 }
Chris Lattner372dda82007-03-05 07:52:57 +00001685 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001686 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001687}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001688
Bob Wilson39fdd692009-12-04 21:57:37 +00001689/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001690/// overwrites the entire allocation. Extract out the pieces of the stored
1691/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001692void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001693 SmallVector<AllocaInst*, 32> &NewElts){
1694 // Extract each element out of the integer according to its structure offset
1695 // and store the element value to the individual alloca.
1696 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001697 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001698 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001699
Chris Lattner70728532011-01-16 05:58:24 +00001700 IRBuilder<> Builder(SI);
1701
Eli Friedman41b33f42009-06-01 09:14:32 +00001702 // Handle tail padding by extending the operand
1703 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001704 SrcVal = Builder.CreateZExt(SrcVal,
1705 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001706
David Greene504c7d82010-01-05 01:27:09 +00001707 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001708 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001709
1710 // There are two forms here: AI could be an array or struct. Both cases
1711 // have different ways to compute the element offset.
1712 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1713 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00001714
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001715 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1716 // Get the number of bits to shift SrcVal to get the value.
1717 const Type *FieldTy = EltSTy->getElementType(i);
1718 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00001719
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001720 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001721 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001722
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001723 Value *EltVal = SrcVal;
1724 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001725 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001726 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001727 }
Bob Wilson69743022011-01-13 20:59:44 +00001728
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001729 // Truncate down to an integer of the right size.
1730 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001731
Chris Lattner583dd602009-01-09 18:18:43 +00001732 // Ignore zero sized fields like {}, they obviously contain no data.
1733 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001734
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001735 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001736 EltVal = Builder.CreateTrunc(EltVal,
1737 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001738 Value *DestField = NewElts[i];
1739 if (EltVal->getType() == FieldTy) {
1740 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001741 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001742 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00001743 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001744 } else {
1745 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00001746 DestField = Builder.CreateBitCast(DestField,
1747 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001748 }
1749 new StoreInst(EltVal, DestField, SI);
1750 }
Bob Wilson69743022011-01-13 20:59:44 +00001751
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001752 } else {
1753 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1754 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001755 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001756 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1757
1758 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00001759
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001760 if (TD->isBigEndian())
1761 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001762 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001763 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00001764
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001765 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001766 // Ignore zero sized fields like {}, they obviously contain no data.
1767 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001768
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001769 Value *EltVal = SrcVal;
1770 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001771 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001772 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001773 }
Bob Wilson69743022011-01-13 20:59:44 +00001774
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001775 // Truncate down to an integer of the right size.
1776 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001777 EltVal = Builder.CreateTrunc(EltVal,
1778 IntegerType::get(SI->getContext(),
1779 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001780 Value *DestField = NewElts[i];
1781 if (EltVal->getType() == ArrayEltTy) {
1782 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001783 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001784 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001785 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00001786 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001787 } else {
1788 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00001789 DestField = Builder.CreateBitCast(DestField,
1790 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001791 }
1792 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00001793
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001794 if (TD->isBigEndian())
1795 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001796 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001797 Shift += ElementOffset;
1798 }
1799 }
Bob Wilson69743022011-01-13 20:59:44 +00001800
Bob Wilsonb742def2009-12-18 20:14:40 +00001801 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001802}
1803
Bob Wilson39fdd692009-12-04 21:57:37 +00001804/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001805/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001806void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001807 SmallVector<AllocaInst*, 32> &NewElts) {
1808 // Extract each element out of the NewElts according to its structure offset
1809 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001810 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001811 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001812
David Greene504c7d82010-01-05 01:27:09 +00001813 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001814 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00001815
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001816 // There are two forms here: AI could be an array or struct. Both cases
1817 // have different ways to compute the element offset.
1818 const StructLayout *Layout = 0;
1819 uint64_t ArrayEltBitOffset = 0;
1820 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1821 Layout = TD->getStructLayout(EltSTy);
1822 } else {
1823 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001824 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001825 }
1826
1827 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001828 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00001829
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001830 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1831 // Load the value from the alloca. If the NewElt is an aggregate, cast
1832 // the pointer to an integer of the same size before doing the load.
1833 Value *SrcField = NewElts[i];
1834 const Type *FieldTy =
1835 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001836 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001837
Chris Lattner583dd602009-01-09 18:18:43 +00001838 // Ignore zero sized fields like {}, they obviously contain no data.
1839 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001840
1841 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00001842 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001843 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1844 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001845 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001846 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001847 "", LI);
1848 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1849
1850 // If SrcField is a fp or vector of the right size but that isn't an
1851 // integer type, bitcast to an integer so we can shift it.
1852 if (SrcField->getType() != FieldIntTy)
1853 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1854
1855 // Zero extend the field to be the same size as the final alloca so that
1856 // we can shift and insert it.
1857 if (SrcField->getType() != ResultVal->getType())
1858 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00001859
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001860 // Determine the number of bits to shift SrcField.
1861 uint64_t Shift;
1862 if (Layout) // Struct case.
1863 Shift = Layout->getElementOffsetInBits(i);
1864 else // Array case.
1865 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001866
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001867 if (TD->isBigEndian())
1868 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00001869
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001870 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001871 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001872 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1873 }
1874
Chris Lattner14952472010-06-27 07:58:26 +00001875 // Don't create an 'or x, 0' on the first iteration.
1876 if (!isa<Constant>(ResultVal) ||
1877 !cast<Constant>(ResultVal)->isNullValue())
1878 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1879 else
1880 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001881 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001882
1883 // Handle tail padding by truncating the result
1884 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1885 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1886
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001887 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001888 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001889}
1890
Duncan Sands3cb36502007-11-04 14:43:57 +00001891/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00001892/// alignment padding in between the elements that would be split apart
1893/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001894static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00001895 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1896 Ty = ATy->getElementType();
1897 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001898 }
Bob Wilson694a10e2011-01-13 17:45:08 +00001899
1900 // SROA currently handles only Arrays and Structs.
1901 const StructType *STy = cast<StructType>(Ty);
1902 const StructLayout *SL = TD.getStructLayout(STy);
1903 unsigned PrevFieldBitOffset = 0;
1904 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1905 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1906
1907 // Check to see if there is any padding between this element and the
1908 // previous one.
1909 if (i) {
1910 unsigned PrevFieldEnd =
1911 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1912 if (PrevFieldEnd < FieldBitOffset)
1913 return true;
1914 }
1915 PrevFieldBitOffset = FieldBitOffset;
1916 }
1917 // Check for tail padding.
1918 if (unsigned EltCount = STy->getNumElements()) {
1919 unsigned PrevFieldEnd = PrevFieldBitOffset +
1920 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1921 if (PrevFieldEnd < SL->getSizeInBits())
1922 return true;
1923 }
1924 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00001925}
Chris Lattner372dda82007-03-05 07:52:57 +00001926
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001927/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1928/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1929/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001930bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001931 // Loop over the use list of the alloca. We can only transform it if all of
1932 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00001933 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00001934
Chris Lattner6c95d242011-01-23 07:29:29 +00001935 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001936 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001937 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001938 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001939 }
Bob Wilson69743022011-01-13 20:59:44 +00001940
Chris Lattner39a1c042007-05-30 06:11:23 +00001941 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1942 // source and destination, we have to be careful. In particular, the memcpy
1943 // could be moving around elements that live in structure padding of the LLVM
1944 // types, but may actually be used. In these cases, we refuse to promote the
1945 // struct.
1946 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001947 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001948 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001949
Chris Lattner396a0562011-01-16 17:46:19 +00001950 // If the alloca never has an access to just *part* of it, but is accessed
1951 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00001952 // the alloca instead of promoting each piece at a time and inserting fission
1953 // and fusion code.
1954 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
1955 // If the struct/array just has one element, use basic SRoA.
1956 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1957 if (ST->getNumElements() > 1) return false;
1958 } else {
1959 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
1960 return false;
1961 }
1962 }
Chris Lattner145c5322011-01-23 08:27:54 +00001963
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001964 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001965}
Chris Lattnera1888942005-12-12 07:19:13 +00001966
Chris Lattner800de312008-02-29 07:03:13 +00001967
Chris Lattner79b3bd32007-04-25 06:40:51 +00001968
1969/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1970/// some part of a constant global variable. This intentionally only accepts
1971/// constant expressions because we don't can't rewrite arbitrary instructions.
1972static bool PointsToConstantGlobal(Value *V) {
1973 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1974 return GV->isConstant();
1975 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00001976 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00001977 CE->getOpcode() == Instruction::GetElementPtr)
1978 return PointsToConstantGlobal(CE->getOperand(0));
1979 return false;
1980}
1981
1982/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1983/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1984/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1985/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1986/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00001987/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00001988/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001989static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001990 bool isOffset) {
1991 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001992 User *U = cast<Instruction>(*UI);
1993
Chris Lattner2e618492010-11-18 06:20:47 +00001994 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001995 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00001996 if (LI->isVolatile()) return false;
1997 continue;
1998 }
Bob Wilson69743022011-01-13 20:59:44 +00001999
Gabor Greif8a8a4352010-04-06 19:32:30 +00002000 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002001 // If uses of the bitcast are ok, we are ok.
2002 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2003 return false;
2004 continue;
2005 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002006 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002007 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2008 // doesn't, it does.
2009 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2010 isOffset || !GEP->hasAllZeroIndices()))
2011 return false;
2012 continue;
2013 }
Bob Wilson69743022011-01-13 20:59:44 +00002014
Chris Lattner62480652010-11-18 06:41:51 +00002015 if (CallSite CS = U) {
2016 // If this is a readonly/readnone call site, then we know it is just a
2017 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00002018 if (CS.onlyReadsMemory())
2019 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00002020
2021 // If this is the function being called then we treat it like a load and
2022 // ignore it.
2023 if (CS.isCallee(UI))
2024 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002025
Chris Lattner62480652010-11-18 06:41:51 +00002026 // If this is being passed as a byval argument, the caller is making a
2027 // copy, so it is only a read of the alloca.
2028 unsigned ArgNo = CS.getArgumentNo(UI);
2029 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2030 continue;
2031 }
Bob Wilson69743022011-01-13 20:59:44 +00002032
Chris Lattner79b3bd32007-04-25 06:40:51 +00002033 // If this is isn't our memcpy/memmove, reject it as something we can't
2034 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002035 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2036 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002037 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002038
Chris Lattner2e618492010-11-18 06:20:47 +00002039 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002040 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002041 if (UI.getOperandNo() == 1) {
2042 if (MI->isVolatile()) return false;
2043 continue;
2044 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002045
2046 // If we already have seen a copy, reject the second one.
2047 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002048
Chris Lattner79b3bd32007-04-25 06:40:51 +00002049 // If the pointer has been offset from the start of the alloca, we can't
2050 // safely handle this.
2051 if (isOffset) return false;
2052
2053 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002054 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002055
Chris Lattner79b3bd32007-04-25 06:40:51 +00002056 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002057 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002058 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002059
Chris Lattner79b3bd32007-04-25 06:40:51 +00002060 // Otherwise, the transform is safe. Remember the copy instruction.
2061 TheCopy = MI;
2062 }
2063 return true;
2064}
2065
2066/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2067/// modified by a copy from a constant global. If we can prove this, we can
2068/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00002069MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2070 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00002071 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2072 return TheCopy;
2073 return 0;
2074}