blob: 86c4e59a97dd4302d814a37215b380df293e8bfd [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 {
82 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
83 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000084
Chris Lattner39a1c042007-05-30 06:11:23 +000085 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
86 bool isMemCpySrc : 1;
87
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000088 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000089 bool isMemCpyDst : 1;
90
Chris Lattner7e9b4272011-01-16 06:18:28 +000091 /// hasSubelementAccess - This is true if a subelement of the alloca is
92 /// ever accessed, or false if the alloca is only accessed with mem
93 /// intrinsics or load/store that only access the entire alloca at once.
94 bool hasSubelementAccess : 1;
95
96 /// hasALoadOrStore - This is true if there are any loads or stores to it.
97 /// The alloca may just be accessed with memcpy, for example, which would
98 /// not set this.
99 bool hasALoadOrStore : 1;
100
Chris Lattner39a1c042007-05-30 06:11:23 +0000101 AllocaInfo()
Chris Lattner7e9b4272011-01-16 06:18:28 +0000102 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
103 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000104 };
Bob Wilson69743022011-01-13 20:59:44 +0000105
Devang Patelff366852007-07-09 21:19:23 +0000106 unsigned SRThreshold;
107
Chris Lattner39a1c042007-05-30 06:11:23 +0000108 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
109
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000110 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000111
Bob Wilsonb742def2009-12-18 20:14:40 +0000112 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000113 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000114 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000115 AllocaInfo &Info);
116 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
117 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000118 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000119 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
120 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000121
122 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000123 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000124 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000125
Bob Wilsonb742def2009-12-18 20:14:40 +0000126 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
127 SmallVector<AllocaInst*, 32> &NewElts);
128 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
129 SmallVector<AllocaInst*, 32> &NewElts);
130 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
131 SmallVector<AllocaInst*, 32> &NewElts);
132 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000133 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000134 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000135 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000136 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000137 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000138 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000139
Chris Lattner31d80102010-04-15 21:59:20 +0000140 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000141 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000142
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000143 // SROA_DT - SROA that uses DominatorTree.
144 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000145 static char ID;
146 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000147 SROA_DT(int T = -1) : SROA(T, true, ID) {
148 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000149 }
150
151 // getAnalysisUsage - This pass does not require any passes, but we know it
152 // will not alter the CFG, so say so.
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000155 AU.setPreservesCFG();
156 }
157 };
158
159 // SROA_SSAUp - SROA that uses SSAUpdater.
160 struct SROA_SSAUp : public SROA {
161 static char ID;
162 public:
163 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
164 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
165 }
166
167 // getAnalysisUsage - This pass does not require any passes, but we know it
168 // will not alter the CFG, so say so.
169 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
170 AU.setPreservesCFG();
171 }
172 };
173
Chris Lattnered7b41e2003-05-27 15:45:27 +0000174}
175
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000176char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000177char SROA_SSAUp::ID = 0;
178
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000179INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
180 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000181INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000182INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
183 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000184
185INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
186 "Scalar Replacement of Aggregates (SSAUp)", false, false)
187INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
188 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000189
Brian Gaeked0fde302003-11-11 22:41:34 +0000190// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000191FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000192 bool UseDomTree) {
193 if (UseDomTree)
194 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000195 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000196}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000197
198
Chris Lattner4cc576b2010-04-16 00:24:57 +0000199//===----------------------------------------------------------------------===//
200// Convert To Scalar Optimization.
201//===----------------------------------------------------------------------===//
202
203namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000204/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
205/// optimization, which scans the uses of an alloca and determines if it can
206/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000207class ConvertToScalarInfo {
208 /// AllocaSize - The size of the alloca being considered.
209 unsigned AllocaSize;
210 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000211
Chris Lattnera0bada72010-04-16 02:32:17 +0000212 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000213 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000214 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000215
Chris Lattnera001b662010-04-16 00:38:19 +0000216 /// VectorTy - This tracks the type that we should promote the vector to if
217 /// it is possible to turn it into a vector. This starts out null, and if it
218 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000219 const Type *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000220
Chris Lattnera001b662010-04-16 00:38:19 +0000221 /// HadAVector - True if there is at least one vector access to the alloca.
222 /// We don't want to turn random arrays into vectors and use vector element
223 /// insert/extract, but if there are element accesses to something that is
224 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000225 bool HadAVector;
226
227public:
228 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
229 : AllocaSize(Size), TD(td) {
230 IsNotTrivial = false;
231 VectorTy = 0;
232 HadAVector = false;
233 }
Bob Wilson69743022011-01-13 20:59:44 +0000234
Chris Lattnera001b662010-04-16 00:38:19 +0000235 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000236
Chris Lattner4cc576b2010-04-16 00:24:57 +0000237private:
238 bool CanConvertToScalar(Value *V, uint64_t Offset);
239 void MergeInType(const Type *In, uint64_t Offset);
240 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000241
Chris Lattner4cc576b2010-04-16 00:24:57 +0000242 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
243 uint64_t Offset, IRBuilder<> &Builder);
244 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
245 uint64_t Offset, IRBuilder<> &Builder);
246};
247} // end anonymous namespace.
248
Chris Lattner91abace2010-09-01 05:14:33 +0000249
250/// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
251/// allowed to form. We do this to avoid MMX types, which is a complete hack,
252/// but is required until the backend is fixed.
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000253static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
254 StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
255 if (!Triple.startswith("i386") &&
256 !Triple.startswith("x86_64"))
257 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000258
Chris Lattner91abace2010-09-01 05:14:33 +0000259 // Reject all the MMX vector types.
260 switch (VTy->getNumElements()) {
261 default: return false;
262 case 1: return VTy->getElementType()->isIntegerTy(64);
263 case 2: return VTy->getElementType()->isIntegerTy(32);
264 case 4: return VTy->getElementType()->isIntegerTy(16);
265 case 8: return VTy->getElementType()->isIntegerTy(8);
266 }
267}
268
269
Chris Lattnera001b662010-04-16 00:38:19 +0000270/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
271/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
272/// alloca if possible or null if not.
273AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
274 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
275 // out.
276 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
277 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000278
Chris Lattnera001b662010-04-16 00:38:19 +0000279 // If we were able to find a vector type that can handle this with
280 // insert/extract elements, and if there was at least one use that had
281 // a vector type, promote this to a vector. We don't want to promote
282 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
283 // we just get a lot of insert/extracts. If at least one vector is
284 // involved, then we probably really do have a union of vector/array.
285 const Type *NewTy;
Chris Lattner91abace2010-09-01 05:14:33 +0000286 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000287 !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000288 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
289 << *VectorTy << '\n');
290 NewTy = VectorTy; // Use the vector type.
291 } else {
292 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
293 // Create and insert the integer alloca.
294 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
295 }
296 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
297 ConvertUsesToScalar(AI, NewAI, 0);
298 return NewAI;
299}
300
301/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
302/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000303///
304/// There are two cases we handle here:
305/// 1) A union of vector types of the same size and potentially its elements.
306/// Here we turn element accesses into insert/extract element operations.
307/// This promotes a <4 x float> with a store of float to the third element
308/// into a <4 x float> that uses insert element.
309/// 2) A fully general blob of memory, which we turn into some (potentially
310/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000311/// and stores would mutate the memory. We mark this by setting VectorTy
312/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000313void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000314 // If we already decided to turn this into a blob of integer memory, there is
315 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000316 if (VectorTy && VectorTy->isVoidTy())
317 return;
Bob Wilson69743022011-01-13 20:59:44 +0000318
Chris Lattner4cc576b2010-04-16 00:24:57 +0000319 // If this could be contributing to a vector, analyze it.
320
321 // If the In type is a vector that is the same size as the alloca, see if it
322 // matches the existing VecTy.
323 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000324 // Remember if we saw a vector type.
325 HadAVector = true;
Bob Wilson69743022011-01-13 20:59:44 +0000326
Chris Lattner4cc576b2010-04-16 00:24:57 +0000327 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
328 // If we're storing/loading a vector of the right size, allow it as a
329 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000330 // we know the element size. If this is a subsequent access, ignore it
331 // even if it is a differing type but the same size. Worst case we can
332 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000333 if (VectorTy == 0)
334 VectorTy = VInTy;
335 return;
336 }
337 } else if (In->isFloatTy() || In->isDoubleTy() ||
338 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
339 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
340 // If we're accessing something that could be an element of a vector, see
341 // if the implied vector agrees with what we already have and if Offset is
342 // compatible with it.
343 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
344 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Bob Wilson69743022011-01-13 20:59:44 +0000345 (VectorTy == 0 ||
Chris Lattner4cc576b2010-04-16 00:24:57 +0000346 cast<VectorType>(VectorTy)->getElementType()
347 ->getPrimitiveSizeInBits()/8 == EltSize)) {
348 if (VectorTy == 0)
349 VectorTy = VectorType::get(In, AllocaSize/EltSize);
350 return;
351 }
352 }
Bob Wilson69743022011-01-13 20:59:44 +0000353
Chris Lattner4cc576b2010-04-16 00:24:57 +0000354 // Otherwise, we have a case that we can't handle with an optimized vector
355 // form. We can still turn this into a large integer.
356 VectorTy = Type::getVoidTy(In->getContext());
357}
358
359/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
360/// its accesses to a single vector type, return true and set VecTy to
361/// the new type. If we could convert the alloca into a single promotable
362/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
363/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
364/// is the current offset from the base of the alloca being analyzed.
365///
366/// If we see at least one access to the value that is as a vector type, set the
367/// SawVec flag.
368bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
369 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
370 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000371
Chris Lattner4cc576b2010-04-16 00:24:57 +0000372 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
373 // Don't break volatile loads.
374 if (LI->isVolatile())
375 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000376 // Don't touch MMX operations.
377 if (LI->getType()->isX86_MMXTy())
378 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000379 MergeInType(LI->getType(), Offset);
380 continue;
381 }
Bob Wilson69743022011-01-13 20:59:44 +0000382
Chris Lattner4cc576b2010-04-16 00:24:57 +0000383 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
384 // Storing the pointer, not into the value?
385 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000386 // Don't touch MMX operations.
387 if (SI->getOperand(0)->getType()->isX86_MMXTy())
388 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000389 MergeInType(SI->getOperand(0)->getType(), Offset);
390 continue;
391 }
Bob Wilson69743022011-01-13 20:59:44 +0000392
Chris Lattner4cc576b2010-04-16 00:24:57 +0000393 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000394 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000395 if (!CanConvertToScalar(BCI, Offset))
396 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000397 continue;
398 }
399
400 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
401 // If this is a GEP with a variable indices, we can't handle it.
402 if (!GEP->hasAllConstantIndices())
403 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000404
Chris Lattner4cc576b2010-04-16 00:24:57 +0000405 // Compute the offset that this GEP adds to the pointer.
406 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
407 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
408 &Indices[0], Indices.size());
409 // See if all uses can be converted.
410 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
411 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000412 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000413 continue;
414 }
415
416 // If this is a constant sized memset of a constant value (e.g. 0) we can
417 // handle it.
418 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
419 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000420 if (!isa<ConstantInt>(MSI->getValue()) ||
421 !isa<ConstantInt>(MSI->getLength()))
422 return false;
423 IsNotTrivial = true; // Can't be mem2reg'd.
424 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000425 }
426
427 // If this is a memcpy or memmove into or out of the whole allocation, we
428 // can handle it like a load or store of the scalar type.
429 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000430 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
431 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
432 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000433
Chris Lattnera001b662010-04-16 00:38:19 +0000434 IsNotTrivial = true; // Can't be mem2reg'd.
435 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000436 }
Bob Wilson69743022011-01-13 20:59:44 +0000437
Chris Lattner4cc576b2010-04-16 00:24:57 +0000438 // Otherwise, we cannot handle this!
439 return false;
440 }
Bob Wilson69743022011-01-13 20:59:44 +0000441
Chris Lattner4cc576b2010-04-16 00:24:57 +0000442 return true;
443}
444
445/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
446/// directly. This happens when we are converting an "integer union" to a
447/// single integer scalar, or when we are converting a "vector union" to a
448/// vector with insert/extractelement instructions.
449///
450/// Offset is an offset from the original alloca, in bits that need to be
451/// shifted to the right. By the end of this, there should be no uses of Ptr.
452void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
453 uint64_t Offset) {
454 while (!Ptr->use_empty()) {
455 Instruction *User = cast<Instruction>(Ptr->use_back());
456
457 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
458 ConvertUsesToScalar(CI, NewAI, Offset);
459 CI->eraseFromParent();
460 continue;
461 }
462
463 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
464 // Compute the offset that this GEP adds to the pointer.
465 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
466 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
467 &Indices[0], Indices.size());
468 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
469 GEP->eraseFromParent();
470 continue;
471 }
Bob Wilson69743022011-01-13 20:59:44 +0000472
Chris Lattner61db1f52010-12-26 22:57:41 +0000473 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000474
Chris Lattner4cc576b2010-04-16 00:24:57 +0000475 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
476 // The load is a bit extract from NewAI shifted right by Offset bits.
477 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
478 Value *NewLoadVal
479 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
480 LI->replaceAllUsesWith(NewLoadVal);
481 LI->eraseFromParent();
482 continue;
483 }
Bob Wilson69743022011-01-13 20:59:44 +0000484
Chris Lattner4cc576b2010-04-16 00:24:57 +0000485 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
486 assert(SI->getOperand(0) != Ptr && "Consistency error!");
487 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
488 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
489 Builder);
490 Builder.CreateStore(New, NewAI);
491 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000492
Chris Lattner4cc576b2010-04-16 00:24:57 +0000493 // If the load we just inserted is now dead, then the inserted store
494 // overwrote the entire thing.
495 if (Old->use_empty())
496 Old->eraseFromParent();
497 continue;
498 }
Bob Wilson69743022011-01-13 20:59:44 +0000499
Chris Lattner4cc576b2010-04-16 00:24:57 +0000500 // If this is a constant sized memset of a constant value (e.g. 0) we can
501 // transform it into a store of the expanded constant value.
502 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
503 assert(MSI->getRawDest() == Ptr && "Consistency error!");
504 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
505 if (NumBytes != 0) {
506 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000507
Chris Lattner4cc576b2010-04-16 00:24:57 +0000508 // Compute the value replicated the right number of times.
509 APInt APVal(NumBytes*8, Val);
510
511 // Splat the value if non-zero.
512 if (Val)
513 for (unsigned i = 1; i != NumBytes; ++i)
514 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000515
Chris Lattner4cc576b2010-04-16 00:24:57 +0000516 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
517 Value *New = ConvertScalar_InsertValue(
518 ConstantInt::get(User->getContext(), APVal),
519 Old, Offset, Builder);
520 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000521
Chris Lattner4cc576b2010-04-16 00:24:57 +0000522 // If the load we just inserted is now dead, then the memset overwrote
523 // the entire thing.
524 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000525 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000526 }
527 MSI->eraseFromParent();
528 continue;
529 }
530
531 // If this is a memcpy or memmove into or out of the whole allocation, we
532 // can handle it like a load or store of the scalar type.
533 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
534 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000535
Chris Lattner4cc576b2010-04-16 00:24:57 +0000536 // If the source and destination are both to the same alloca, then this is
537 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
538 // as appropriate.
Dan Gohman5034dd32010-12-15 20:02:24 +0000539 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000540
Dan Gohman5034dd32010-12-15 20:02:24 +0000541 if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000542 // Dest must be OrigAI, change this to be a load from the original
543 // pointer (bitcasted), then a store to our new alloca.
544 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
545 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000546 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
547 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
548 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
549 AIPTy = PointerType::get(AIPTy->getElementType(),
550 SPTy->getAddressSpace());
551 }
552 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
553
Chris Lattner4cc576b2010-04-16 00:24:57 +0000554 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
555 SrcVal->setAlignment(MTI->getAlignment());
556 Builder.CreateStore(SrcVal, NewAI);
Dan Gohman5034dd32010-12-15 20:02:24 +0000557 } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000558 // Src must be OrigAI, change this to be a load from NewAI then a store
559 // through the original dest pointer (bitcasted).
560 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
561 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
562
Mon P Wange90a6332010-12-23 01:41:32 +0000563 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
564 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
565 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
566 AIPTy = PointerType::get(AIPTy->getElementType(),
567 DPTy->getAddressSpace());
568 }
569 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
570
Chris Lattner4cc576b2010-04-16 00:24:57 +0000571 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
572 NewStore->setAlignment(MTI->getAlignment());
573 } else {
574 // Noop transfer. Src == Dst
575 }
576
577 MTI->eraseFromParent();
578 continue;
579 }
Bob Wilson69743022011-01-13 20:59:44 +0000580
Chris Lattner4cc576b2010-04-16 00:24:57 +0000581 llvm_unreachable("Unsupported operation!");
582 }
583}
584
585/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
586/// or vector value FromVal, extracting the bits from the offset specified by
587/// Offset. This returns the value, which is of type ToType.
588///
589/// This happens when we are converting an "integer union" to a single
590/// integer scalar, or when we are converting a "vector union" to a vector with
591/// insert/extractelement instructions.
592///
593/// Offset is an offset from the original alloca, in bits that need to be
594/// shifted to the right.
595Value *ConvertToScalarInfo::
596ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
597 uint64_t Offset, IRBuilder<> &Builder) {
598 // If the load is of the whole new alloca, no conversion is needed.
599 if (FromVal->getType() == ToType && Offset == 0)
600 return FromVal;
601
602 // If the result alloca is a vector type, this is either an element
603 // access or a bitcast to another vector type of the same size.
604 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
605 if (ToType->isVectorTy())
606 return Builder.CreateBitCast(FromVal, ToType, "tmp");
607
608 // Otherwise it must be an element access.
609 unsigned Elt = 0;
610 if (Offset) {
611 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
612 Elt = Offset/EltSize;
613 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
614 }
615 // Return the element extracted out of it.
616 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
617 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
618 if (V->getType() != ToType)
619 V = Builder.CreateBitCast(V, ToType, "tmp");
620 return V;
621 }
Bob Wilson69743022011-01-13 20:59:44 +0000622
Chris Lattner4cc576b2010-04-16 00:24:57 +0000623 // If ToType is a first class aggregate, extract out each of the pieces and
624 // use insertvalue's to form the FCA.
625 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
626 const StructLayout &Layout = *TD.getStructLayout(ST);
627 Value *Res = UndefValue::get(ST);
628 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
629 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
630 Offset+Layout.getElementOffsetInBits(i),
631 Builder);
632 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
633 }
634 return Res;
635 }
Bob Wilson69743022011-01-13 20:59:44 +0000636
Chris Lattner4cc576b2010-04-16 00:24:57 +0000637 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
638 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
639 Value *Res = UndefValue::get(AT);
640 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
641 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
642 Offset+i*EltSize, Builder);
643 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
644 }
645 return Res;
646 }
647
648 // Otherwise, this must be a union that was converted to an integer value.
649 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
650
651 // If this is a big-endian system and the load is narrower than the
652 // full alloca type, we need to do a shift to get the right bits.
653 int ShAmt = 0;
654 if (TD.isBigEndian()) {
655 // On big-endian machines, the lowest bit is stored at the bit offset
656 // from the pointer given by getTypeStoreSizeInBits. This matters for
657 // integers with a bitwidth that is not a multiple of 8.
658 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
659 TD.getTypeStoreSizeInBits(ToType) - Offset;
660 } else {
661 ShAmt = Offset;
662 }
663
664 // Note: we support negative bitwidths (with shl) which are not defined.
665 // We do this to support (f.e.) loads off the end of a structure where
666 // only some bits are used.
667 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
668 FromVal = Builder.CreateLShr(FromVal,
669 ConstantInt::get(FromVal->getType(),
670 ShAmt), "tmp");
671 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000672 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000673 ConstantInt::get(FromVal->getType(),
674 -ShAmt), "tmp");
675
676 // Finally, unconditionally truncate the integer to the right width.
677 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
678 if (LIBitWidth < NTy->getBitWidth())
679 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000680 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000681 LIBitWidth), "tmp");
682 else if (LIBitWidth > NTy->getBitWidth())
683 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000684 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000685 LIBitWidth), "tmp");
686
687 // If the result is an integer, this is a trunc or bitcast.
688 if (ToType->isIntegerTy()) {
689 // Should be done.
690 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
691 // Just do a bitcast, we know the sizes match up.
692 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
693 } else {
694 // Otherwise must be a pointer.
695 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
696 }
697 assert(FromVal->getType() == ToType && "Didn't convert right?");
698 return FromVal;
699}
700
701/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
702/// or vector value "Old" at the offset specified by Offset.
703///
704/// This happens when we are converting an "integer union" to a
705/// single integer scalar, or when we are converting a "vector union" to a
706/// vector with insert/extractelement instructions.
707///
708/// Offset is an offset from the original alloca, in bits that need to be
709/// shifted to the right.
710Value *ConvertToScalarInfo::
711ConvertScalar_InsertValue(Value *SV, Value *Old,
712 uint64_t Offset, IRBuilder<> &Builder) {
713 // Convert the stored type to the actual type, shift it left to insert
714 // then 'or' into place.
715 const Type *AllocaType = Old->getType();
716 LLVMContext &Context = Old->getContext();
717
718 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
719 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
720 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000721
Chris Lattner4cc576b2010-04-16 00:24:57 +0000722 // Changing the whole vector with memset or with an access of a different
723 // vector type?
724 if (ValSize == VecSize)
725 return Builder.CreateBitCast(SV, AllocaType, "tmp");
726
727 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
728
729 // Must be an element insertion.
730 unsigned Elt = Offset/EltSize;
Bob Wilson69743022011-01-13 20:59:44 +0000731
Chris Lattner4cc576b2010-04-16 00:24:57 +0000732 if (SV->getType() != VTy->getElementType())
733 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000734
735 SV = Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000736 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
737 "tmp");
738 return SV;
739 }
Bob Wilson69743022011-01-13 20:59:44 +0000740
Chris Lattner4cc576b2010-04-16 00:24:57 +0000741 // If SV is a first-class aggregate value, insert each value recursively.
742 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
743 const StructLayout &Layout = *TD.getStructLayout(ST);
744 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
745 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000746 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000747 Offset+Layout.getElementOffsetInBits(i),
748 Builder);
749 }
750 return Old;
751 }
Bob Wilson69743022011-01-13 20:59:44 +0000752
Chris Lattner4cc576b2010-04-16 00:24:57 +0000753 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
754 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
755 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
756 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
757 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
758 }
759 return Old;
760 }
761
762 // If SV is a float, convert it to the appropriate integer type.
763 // If it is a pointer, do the same.
764 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
765 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
766 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
767 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
768 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
769 SV = Builder.CreateBitCast(SV,
770 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
771 else if (SV->getType()->isPointerTy())
772 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
773
774 // Zero extend or truncate the value if needed.
775 if (SV->getType() != AllocaType) {
776 if (SV->getType()->getPrimitiveSizeInBits() <
777 AllocaType->getPrimitiveSizeInBits())
778 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
779 else {
780 // Truncation may be needed if storing more than the alloca can hold
781 // (undefined behavior).
782 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
783 SrcWidth = DestWidth;
784 SrcStoreWidth = DestStoreWidth;
785 }
786 }
787
788 // If this is a big-endian system and the store is narrower than the
789 // full alloca type, we need to do a shift to get the right bits.
790 int ShAmt = 0;
791 if (TD.isBigEndian()) {
792 // On big-endian machines, the lowest bit is stored at the bit offset
793 // from the pointer given by getTypeStoreSizeInBits. This matters for
794 // integers with a bitwidth that is not a multiple of 8.
795 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
796 } else {
797 ShAmt = Offset;
798 }
799
800 // Note: we support negative bitwidths (with shr) which are not defined.
801 // We do this to support (f.e.) stores off the end of a structure where
802 // only some bits in the structure are set.
803 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
804 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
805 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
806 ShAmt), "tmp");
807 Mask <<= ShAmt;
808 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
809 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
810 -ShAmt), "tmp");
811 Mask = Mask.lshr(-ShAmt);
812 }
813
814 // Mask out the bits we are about to insert from the old value, and or
815 // in the new bits.
816 if (SrcWidth != DestWidth) {
817 assert(DestWidth > SrcWidth);
818 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
819 SV = Builder.CreateOr(Old, SV, "ins");
820 }
821 return SV;
822}
823
824
825//===----------------------------------------------------------------------===//
826// SRoA Driver
827//===----------------------------------------------------------------------===//
828
829
Chris Lattnered7b41e2003-05-27 15:45:27 +0000830bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000831 TD = getAnalysisIfAvailable<TargetData>();
832
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000833 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000834
835 // FIXME: ScalarRepl currently depends on TargetData more than it
836 // theoretically needs to. It should be refactored in order to support
837 // target-independent IR. Until this is done, just skip the actual
838 // scalar-replacement portion of this pass.
839 if (!TD) return Changed;
840
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000841 while (1) {
842 bool LocalChange = performScalarRepl(F);
843 if (!LocalChange) break; // No need to repromote if no scalarrepl
844 Changed = true;
845 LocalChange = performPromotion(F);
846 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
847 }
Chris Lattner38aec322003-09-11 16:45:55 +0000848
849 return Changed;
850}
851
Chris Lattnerd0f56132011-01-14 19:50:47 +0000852namespace {
853class AllocaPromoter : public LoadAndStorePromoter {
854 AllocaInst *AI;
855public:
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000856 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
857 : LoadAndStorePromoter(Insts, S), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +0000858
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000859 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +0000860 // Remember which alloca we're promoting (for isInstInList).
861 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000862 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +0000863 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000864 }
865
Chris Lattnerd0f56132011-01-14 19:50:47 +0000866 virtual bool isInstInList(Instruction *I,
867 const SmallVectorImpl<Instruction*> &Insts) const {
868 if (LoadInst *LI = dyn_cast<LoadInst>(I))
869 return LI->getOperand(0) == AI;
870 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000871 }
Chris Lattnerd0f56132011-01-14 19:50:47 +0000872};
873} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +0000874
875bool SROA::performPromotion(Function &F) {
876 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000877 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000878 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000879 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +0000880
Chris Lattner02a3be02003-09-20 14:39:18 +0000881 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000882
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000883 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000884 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +0000885 while (1) {
886 Allocas.clear();
887
888 // Find allocas that are safe to promote, by looking at all instructions in
889 // the entry node
890 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
891 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000892 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000893 Allocas.push_back(AI);
894
895 if (Allocas.empty()) break;
896
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000897 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +0000898 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000899 else {
900 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000901 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
902 AllocaInst *AI = Allocas[i];
903
904 // Build list of instructions to promote.
905 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
906 UI != E; ++UI)
907 Insts.push_back(cast<Instruction>(*UI));
908
909 AllocaPromoter(Insts, SSA).run(AI, Insts);
910 Insts.clear();
911 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000912 }
Chris Lattner38aec322003-09-11 16:45:55 +0000913 NumPromoted += Allocas.size();
914 Changed = true;
915 }
916
917 return Changed;
918}
919
Chris Lattner4cc576b2010-04-16 00:24:57 +0000920
Bob Wilson3992feb2010-02-03 17:23:56 +0000921/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
922/// SROA. It must be a struct or array type with a small number of elements.
923static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
924 const Type *T = AI->getAllocatedType();
925 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000926 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000927 return ST->getNumElements() <= 32;
928 // Arrays are much less likely to be safe for SROA; only consider
929 // them if they are very small.
930 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
931 return AT->getNumElements() <= 8;
932 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000933}
934
Chris Lattnerc4472072010-04-15 23:50:26 +0000935
Chris Lattner38aec322003-09-11 16:45:55 +0000936// performScalarRepl - This algorithm is a simple worklist driven algorithm,
937// which runs on all of the malloc/alloca instructions in the function, removing
938// them if they are only used by getelementptr instructions.
939//
940bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000941 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000942
Chris Lattner31d80102010-04-15 21:59:20 +0000943 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000944 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000945 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000946 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000947 WorkList.push_back(A);
948
949 // Process the worklist
950 bool Changed = false;
951 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000952 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000953 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +0000954
Chris Lattneradd2bd72006-12-22 23:14:42 +0000955 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
956 // with unused elements.
957 if (AI->use_empty()) {
958 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000959 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000960 continue;
961 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000962
963 // If this alloca is impossible for us to promote, reject it early.
964 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
965 continue;
Bob Wilson69743022011-01-13 20:59:44 +0000966
Chris Lattner79b3bd32007-04-25 06:40:51 +0000967 // Check to see if this allocation is only modified by a memcpy/memmove from
968 // a constant global. If this is the case, we can change all users to use
969 // the constant global instead. This is commonly produced by the CFE by
970 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
971 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000972 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000973 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
974 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000975 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000976 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000977 TheCopy->eraseFromParent(); // Don't mutate the global.
978 AI->eraseFromParent();
979 ++NumGlobals;
980 Changed = true;
981 continue;
982 }
Bob Wilson69743022011-01-13 20:59:44 +0000983
Chris Lattner7809ecd2009-02-03 01:30:09 +0000984 // Check to see if we can perform the core SROA transformation. We cannot
985 // transform the allocation instruction if it is an array allocation
986 // (allocations OF arrays are ok though), and an allocation of a scalar
987 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000988 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000989
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000990 // Do not promote [0 x %struct].
991 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +0000992
Chris Lattner31d80102010-04-15 21:59:20 +0000993 // Do not promote any struct whose size is too big.
994 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +0000995
Bob Wilson3992feb2010-02-03 17:23:56 +0000996 // If the alloca looks like a good candidate for scalar replacement, and if
997 // all its users can be transformed, then split up the aggregate into its
998 // separate elements.
999 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1000 DoScalarReplacement(AI, WorkList);
1001 Changed = true;
1002 continue;
1003 }
1004
Chris Lattner6e733d32009-01-28 20:16:43 +00001005 // If we can turn this aggregate value (potentially with casts) into a
1006 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001007 // IsNotTrivial tracks whether this is something that mem2reg could have
1008 // promoted itself. If so, we don't want to transform it needlessly. Note
1009 // that we can't just check based on the type: the alloca may be of an i32
1010 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001011 if (AllocaInst *NewAI =
1012 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001013 NewAI->takeName(AI);
1014 AI->eraseFromParent();
1015 ++NumConverted;
1016 Changed = true;
1017 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001018 }
1019
Chris Lattner7809ecd2009-02-03 01:30:09 +00001020 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001021 }
1022
1023 return Changed;
1024}
Chris Lattner5e062a12003-05-30 04:15:41 +00001025
Chris Lattnera10b29b2007-04-25 05:02:56 +00001026/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1027/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001028void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001029 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001030 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001031 SmallVector<AllocaInst*, 32> ElementAllocas;
1032 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1033 ElementAllocas.reserve(ST->getNumContainedTypes());
1034 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001035 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001036 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 } else {
1042 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1043 ElementAllocas.reserve(AT->getNumElements());
1044 const Type *ElTy = AT->getElementType();
1045 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001046 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001047 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001048 ElementAllocas.push_back(NA);
1049 WorkList.push_back(NA); // Add to worklist for recursive processing
1050 }
1051 }
1052
Bob Wilsonb742def2009-12-18 20:14:40 +00001053 // Now that we have created the new alloca instructions, rewrite all the
1054 // uses of the old alloca.
1055 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001056
Bob Wilsonb742def2009-12-18 20:14:40 +00001057 // Now erase any instructions that were made dead while rewriting the alloca.
1058 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001059 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001060
Dan Gohmanfe601042010-06-22 15:08:57 +00001061 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001062}
Chris Lattnera59adc42009-12-14 05:11:02 +00001063
Bob Wilsonb742def2009-12-18 20:14:40 +00001064/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1065/// recursively including all their operands that become trivially dead.
1066void SROA::DeleteDeadInstructions() {
1067 while (!DeadInsts.empty()) {
1068 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001069
Bob Wilsonb742def2009-12-18 20:14:40 +00001070 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1071 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1072 // Zero out the operand and see if it becomes trivially dead.
1073 // (But, don't add allocas to the dead instruction list -- they are
1074 // already on the worklist and will be deleted separately.)
1075 *OI = 0;
1076 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1077 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001078 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001079
1080 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001081 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001082}
Bob Wilson69743022011-01-13 20:59:44 +00001083
Bob Wilsonb742def2009-12-18 20:14:40 +00001084/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1085/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001086/// the Info parameter. Offset indicates the position within AI that is
1087/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +00001088void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001089 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001090 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1091 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001092
Bob Wilsonb742def2009-12-18 20:14:40 +00001093 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001094 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001095 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001096 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001097 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001098 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001099 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001100 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001101 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1102 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001103 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001104 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001105 else
1106 MarkUnsafe(Info);
1107 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1108 if (!LI->isVolatile()) {
1109 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001110 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001111 LIType, false, Info);
Chris Lattner7e9b4272011-01-16 06:18:28 +00001112 Info.hasALoadOrStore = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001113 } else
1114 MarkUnsafe(Info);
1115 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1116 // Store is ok if storing INTO the pointer, not storing the pointer
1117 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1118 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001119 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001120 SIType, true, Info);
Chris Lattner7e9b4272011-01-16 06:18:28 +00001121 Info.hasALoadOrStore = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001122 } else
1123 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001124 } else {
1125 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1126 MarkUnsafe(Info);
1127 }
1128 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001129 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001130}
Bob Wilson39c88a62009-12-17 18:34:24 +00001131
Bob Wilsonb742def2009-12-18 20:14:40 +00001132/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1133/// replacement. It is safe when all the indices are constant, in-bounds
1134/// references, and when the resulting offset corresponds to an element within
1135/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001136/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001137void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001138 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001139 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1140 if (GEPIt == E)
1141 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001142
Chris Lattner88e6dc82008-08-23 05:21:06 +00001143 // Walk through the GEP type indices, checking the types that this indexes
1144 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001145 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001146 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001147 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001148 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001149
Bob Wilsonb742def2009-12-18 20:14:40 +00001150 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1151 if (!IdxVal)
1152 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001153 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001154
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001155 // Compute the offset due to this GEP and check if the alloca has a
1156 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001157 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1158 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1159 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001160 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1161 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001162}
1163
Bob Wilson704d1342011-01-13 17:45:11 +00001164/// isHomogeneousAggregate - Check if type T is a struct or array containing
1165/// elements of the same type (which is always true for arrays). If so,
1166/// return true with NumElts and EltTy set to the number of elements and the
1167/// element type, respectively.
1168static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1169 const Type *&EltTy) {
1170 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1171 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001172 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001173 return true;
1174 }
1175 if (const StructType *ST = dyn_cast<StructType>(T)) {
1176 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001177 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001178 for (unsigned n = 1; n < NumElts; ++n) {
1179 if (ST->getContainedType(n) != EltTy)
1180 return false;
1181 }
1182 return true;
1183 }
1184 return false;
1185}
1186
1187/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1188/// "homogeneous" aggregates with the same element type and number of elements.
1189static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1190 if (T1 == T2)
1191 return true;
1192
1193 unsigned NumElts1, NumElts2;
1194 const Type *EltTy1, *EltTy2;
1195 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1196 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1197 NumElts1 == NumElts2 &&
1198 EltTy1 == EltTy2)
1199 return true;
1200
1201 return false;
1202}
1203
Bob Wilsonb742def2009-12-18 20:14:40 +00001204/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1205/// alloca or has an offset and size that corresponds to a component element
1206/// within it. The offset checked here may have been formed from a GEP with a
1207/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001208void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001209 const Type *MemOpType, bool isStore,
1210 AllocaInfo &Info) {
1211 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001212 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001213 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1214 // loads/stores (which are essentially the same as the MemIntrinsics with
1215 // regard to copying padding between elements). But, if an alloca is
1216 // flagged as both a source and destination of such operations, we'll need
1217 // to check later for padding between elements.
1218 if (!MemOpType || MemOpType->isIntegerTy()) {
1219 if (isStore)
1220 Info.isMemCpyDst = true;
1221 else
1222 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001223 return;
1224 }
Bob Wilson704d1342011-01-13 17:45:11 +00001225 // This is also safe for references using a type that is compatible with
1226 // the type of the alloca, so that loads/stores can be rewritten using
1227 // insertvalue/extractvalue.
Chris Lattner7e9b4272011-01-16 06:18:28 +00001228 if (isCompatibleAggregate(MemOpType, AI->getAllocatedType())) {
1229 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001230 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001231 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001232 }
1233 // Check if the offset/size correspond to a component within the alloca type.
1234 const Type *T = AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001235 if (TypeHasComponent(T, Offset, MemSize)) {
1236 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001237 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001238 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001239
1240 return MarkUnsafe(Info);
1241}
1242
1243/// TypeHasComponent - Return true if T has a component type with the
1244/// specified offset and size. If Size is zero, do not check the size.
1245bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1246 const Type *EltTy;
1247 uint64_t EltSize;
1248 if (const StructType *ST = dyn_cast<StructType>(T)) {
1249 const StructLayout *Layout = TD->getStructLayout(ST);
1250 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1251 EltTy = ST->getContainedType(EltIdx);
1252 EltSize = TD->getTypeAllocSize(EltTy);
1253 Offset -= Layout->getElementOffset(EltIdx);
1254 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1255 EltTy = AT->getElementType();
1256 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001257 if (Offset >= AT->getNumElements() * EltSize)
1258 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001259 Offset %= EltSize;
1260 } else {
1261 return false;
1262 }
1263 if (Offset == 0 && (Size == 0 || EltSize == Size))
1264 return true;
1265 // Check if the component spans multiple elements.
1266 if (Offset + Size > EltSize)
1267 return false;
1268 return TypeHasComponent(EltTy, Offset, Size);
1269}
1270
1271/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1272/// the instruction I, which references it, to use the separate elements.
1273/// Offset indicates the position within AI that is referenced by this
1274/// instruction.
1275void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1276 SmallVector<AllocaInst*, 32> &NewElts) {
1277 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1278 Instruction *User = cast<Instruction>(*UI);
1279
1280 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1281 RewriteBitCast(BC, AI, Offset, NewElts);
1282 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1283 RewriteGEP(GEPI, AI, Offset, NewElts);
1284 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1285 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1286 uint64_t MemSize = Length->getZExtValue();
1287 if (Offset == 0 &&
1288 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1289 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001290 // Otherwise the intrinsic can only touch a single element and the
1291 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001292 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1293 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001294
Bob Wilson704d1342011-01-13 17:45:11 +00001295 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001296 // Replace:
1297 // %res = load { i32, i32 }* %alloc
1298 // with:
1299 // %load.0 = load i32* %alloc.0
1300 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1301 // %load.1 = load i32* %alloc.1
1302 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1303 // (Also works for arrays instead of structs)
1304 Value *Insert = UndefValue::get(LIType);
1305 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1306 Value *Load = new LoadInst(NewElts[i], "load", LI);
1307 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1308 }
1309 LI->replaceAllUsesWith(Insert);
1310 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001311 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001312 TD->getTypeAllocSize(LIType) ==
1313 TD->getTypeAllocSize(AI->getAllocatedType())) {
1314 // If this is a load of the entire alloca to an integer, rewrite it.
1315 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1316 }
1317 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1318 Value *Val = SI->getOperand(0);
1319 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001320 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001321 // Replace:
1322 // store { i32, i32 } %val, { i32, i32 }* %alloc
1323 // with:
1324 // %val.0 = extractvalue { i32, i32 } %val, 0
1325 // store i32 %val.0, i32* %alloc.0
1326 // %val.1 = extractvalue { i32, i32 } %val, 1
1327 // store i32 %val.1, i32* %alloc.1
1328 // (Also works for arrays instead of structs)
1329 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1330 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1331 new StoreInst(Extract, NewElts[i], SI);
1332 }
1333 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001334 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001335 TD->getTypeAllocSize(SIType) ==
1336 TD->getTypeAllocSize(AI->getAllocatedType())) {
1337 // If this is a store of the entire alloca from an integer, rewrite it.
1338 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1339 }
1340 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001341 }
1342}
1343
Bob Wilsonb742def2009-12-18 20:14:40 +00001344/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1345/// and recursively continue updating all of its uses.
1346void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1347 SmallVector<AllocaInst*, 32> &NewElts) {
1348 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1349 if (BC->getOperand(0) != AI)
1350 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001351
Bob Wilsonb742def2009-12-18 20:14:40 +00001352 // The bitcast references the original alloca. Replace its uses with
1353 // references to the first new element alloca.
1354 Instruction *Val = NewElts[0];
1355 if (Val->getType() != BC->getDestTy()) {
1356 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1357 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001358 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001359 BC->replaceAllUsesWith(Val);
1360 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001361}
1362
Bob Wilsonb742def2009-12-18 20:14:40 +00001363/// FindElementAndOffset - Return the index of the element containing Offset
1364/// within the specified type, which must be either a struct or an array.
1365/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001366/// element. IdxTy is set to the type of the index result to be used in a
1367/// GEP instruction.
1368uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1369 const Type *&IdxTy) {
1370 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001371 if (const StructType *ST = dyn_cast<StructType>(T)) {
1372 const StructLayout *Layout = TD->getStructLayout(ST);
1373 Idx = Layout->getElementContainingOffset(Offset);
1374 T = ST->getContainedType(Idx);
1375 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001376 IdxTy = Type::getInt32Ty(T->getContext());
1377 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001378 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001379 const ArrayType *AT = cast<ArrayType>(T);
1380 T = AT->getElementType();
1381 uint64_t EltSize = TD->getTypeAllocSize(T);
1382 Idx = Offset / EltSize;
1383 Offset -= Idx * EltSize;
1384 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001385 return Idx;
1386}
1387
1388/// RewriteGEP - Check if this GEP instruction moves the pointer across
1389/// elements of the alloca that are being split apart, and if so, rewrite
1390/// the GEP to be relative to the new element.
1391void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1392 SmallVector<AllocaInst*, 32> &NewElts) {
1393 uint64_t OldOffset = Offset;
1394 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1395 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1396 &Indices[0], Indices.size());
1397
1398 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1399
1400 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001401 const Type *IdxTy;
1402 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001403 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001404 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001405
1406 T = AI->getAllocatedType();
1407 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001408 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001409
1410 // If this GEP does not move the pointer across elements of the alloca
1411 // being split, then it does not needs to be rewritten.
1412 if (Idx == OldIdx)
1413 return;
1414
1415 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1416 SmallVector<Value*, 8> NewArgs;
1417 NewArgs.push_back(Constant::getNullValue(i32Ty));
1418 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001419 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1420 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001421 }
1422 Instruction *Val = NewElts[Idx];
1423 if (NewArgs.size() > 1) {
1424 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1425 NewArgs.end(), "", GEPI);
1426 Val->takeName(GEPI);
1427 }
1428 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001429 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001430 GEPI->replaceAllUsesWith(Val);
1431 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001432}
1433
1434/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1435/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001436void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001437 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001438 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001439 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001440 // appropriate type. The "Other" pointer is the pointer that goes to memory
1441 // that doesn't have anything to do with the alloca that we are promoting. For
1442 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001443 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001444 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001445 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001446 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001447 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001448 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001449 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001450 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001451 }
1452 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001453
Chris Lattnerd93afec2009-01-07 07:18:45 +00001454 // If there is an other pointer, we want to convert it to the same pointer
1455 // type as AI has, so we can GEP through it safely.
1456 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001457 unsigned AddrSpace =
1458 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001459
1460 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1461 // optimization, but it's also required to detect the corner case where
1462 // both pointer operands are referencing the same memory, and where
1463 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1464 // function is only called for mem intrinsics that access the whole
1465 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001466 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00001467
Bob Wilsona756b1d2010-01-19 04:32:48 +00001468 // Copying the alloca to itself is a no-op: just delete it.
1469 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1470 // This code will run twice for a no-op memcpy -- once for each operand.
1471 // Put only one reference to MI on the DeadInsts list.
1472 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1473 E = DeadInsts.end(); I != E; ++I)
1474 if (*I == MI) return;
1475 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001476 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001477 }
Bob Wilson69743022011-01-13 20:59:44 +00001478
Chris Lattnerd93afec2009-01-07 07:18:45 +00001479 // If the pointer is not the right type, insert a bitcast to the right
1480 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001481 const Type *NewTy =
1482 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00001483
Chris Lattner0238f8c2010-07-08 00:27:05 +00001484 if (OtherPtr->getType() != NewTy)
1485 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001486 }
Bob Wilson69743022011-01-13 20:59:44 +00001487
Chris Lattnerd93afec2009-01-07 07:18:45 +00001488 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00001489 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00001490
Owen Anderson1d0be152009-08-13 21:58:54 +00001491 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001492
1493 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1494 // If this is a memcpy/memmove, emit a GEP of the other element address.
1495 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001496 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00001497
Bob Wilsona756b1d2010-01-19 04:32:48 +00001498 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001499 Value *Idx[2] = { Zero,
1500 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001501 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001502 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001503 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001504 uint64_t EltOffset;
1505 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001506 const Type *OtherTy = OtherPtrTy->getElementType();
1507 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001508 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1509 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001510 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001511 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001512 }
Bob Wilson69743022011-01-13 20:59:44 +00001513
Chris Lattner1541e0f2009-03-04 19:20:50 +00001514 // The alignment of the other pointer is the guaranteed alignment of the
1515 // element, which is affected by both the known alignment of the whole
1516 // mem intrinsic and the alignment of the element. If the alignment of
1517 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1518 // known alignment is just 4 bytes.
1519 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001520 }
Bob Wilson69743022011-01-13 20:59:44 +00001521
Chris Lattnerd93afec2009-01-07 07:18:45 +00001522 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001523 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00001524
Chris Lattnerd93afec2009-01-07 07:18:45 +00001525 // If we got down to a scalar, insert a load or store as appropriate.
1526 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001527 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001528 if (SROADest) {
1529 // From Other to Alloca.
1530 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1531 new StoreInst(Elt, EltPtr, MI);
1532 } else {
1533 // From Alloca to Other.
1534 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1535 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1536 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001537 continue;
1538 }
1539 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00001540
Chris Lattnerd93afec2009-01-07 07:18:45 +00001541 // If the stored element is zero (common case), just store a null
1542 // constant.
1543 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001544 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001545 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001546 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001547 } else {
1548 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001549 const Type *ValTy = EltTy->getScalarType();
1550
Chris Lattnerd93afec2009-01-07 07:18:45 +00001551 // Construct an integer with the right value.
1552 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1553 APInt OneVal(EltSize, CI->getZExtValue());
1554 APInt TotalVal(OneVal);
1555 // Set each byte.
1556 for (unsigned i = 0; 8*i < EltSize; ++i) {
1557 TotalVal = TotalVal.shl(8);
1558 TotalVal |= OneVal;
1559 }
Bob Wilson69743022011-01-13 20:59:44 +00001560
Chris Lattnerd93afec2009-01-07 07:18:45 +00001561 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001562 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001563 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001564 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001565 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001566 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001567 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00001568
Chris Lattnerd93afec2009-01-07 07:18:45 +00001569 // If the requested value was a vector constant, create it.
1570 if (EltTy != ValTy) {
1571 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1572 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001573 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001574 }
1575 }
1576 new StoreInst(StoreVal, EltPtr, MI);
1577 continue;
1578 }
1579 // Otherwise, if we're storing a byte variable, use a memset call for
1580 // this element.
1581 }
Bob Wilson69743022011-01-13 20:59:44 +00001582
Duncan Sands777d2302009-05-09 07:06:46 +00001583 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001584
Chris Lattner61db1f52010-12-26 22:57:41 +00001585 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00001586
Chris Lattnerd93afec2009-01-07 07:18:45 +00001587 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00001588 if (isa<MemSetInst>(MI)) {
1589 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1590 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001591 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00001592 assert(isa<MemTransferInst>(MI));
1593 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
1594 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00001595
Chris Lattner61db1f52010-12-26 22:57:41 +00001596 if (isa<MemCpyInst>(MI))
1597 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1598 else
1599 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00001600 }
Chris Lattner372dda82007-03-05 07:52:57 +00001601 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001602 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001603}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001604
Bob Wilson39fdd692009-12-04 21:57:37 +00001605/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001606/// overwrites the entire allocation. Extract out the pieces of the stored
1607/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001608void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001609 SmallVector<AllocaInst*, 32> &NewElts){
1610 // Extract each element out of the integer according to its structure offset
1611 // and store the element value to the individual alloca.
1612 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001613 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001614 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001615
Chris Lattner70728532011-01-16 05:58:24 +00001616 IRBuilder<> Builder(SI);
1617
Eli Friedman41b33f42009-06-01 09:14:32 +00001618 // Handle tail padding by extending the operand
1619 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001620 SrcVal = Builder.CreateZExt(SrcVal,
1621 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001622
David Greene504c7d82010-01-05 01:27:09 +00001623 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001624 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001625
1626 // There are two forms here: AI could be an array or struct. Both cases
1627 // have different ways to compute the element offset.
1628 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1629 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00001630
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001631 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1632 // Get the number of bits to shift SrcVal to get the value.
1633 const Type *FieldTy = EltSTy->getElementType(i);
1634 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00001635
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001636 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001637 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001638
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001639 Value *EltVal = SrcVal;
1640 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001641 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001642 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001643 }
Bob Wilson69743022011-01-13 20:59:44 +00001644
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001645 // Truncate down to an integer of the right size.
1646 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001647
Chris Lattner583dd602009-01-09 18:18:43 +00001648 // Ignore zero sized fields like {}, they obviously contain no data.
1649 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001650
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001651 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001652 EltVal = Builder.CreateTrunc(EltVal,
1653 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001654 Value *DestField = NewElts[i];
1655 if (EltVal->getType() == FieldTy) {
1656 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001657 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001658 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00001659 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001660 } else {
1661 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00001662 DestField = Builder.CreateBitCast(DestField,
1663 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001664 }
1665 new StoreInst(EltVal, DestField, SI);
1666 }
Bob Wilson69743022011-01-13 20:59:44 +00001667
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001668 } else {
1669 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1670 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001671 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001672 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1673
1674 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00001675
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001676 if (TD->isBigEndian())
1677 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001678 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001679 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00001680
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001681 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001682 // Ignore zero sized fields like {}, they obviously contain no data.
1683 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001684
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001685 Value *EltVal = SrcVal;
1686 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001687 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00001688 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001689 }
Bob Wilson69743022011-01-13 20:59:44 +00001690
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001691 // Truncate down to an integer of the right size.
1692 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00001693 EltVal = Builder.CreateTrunc(EltVal,
1694 IntegerType::get(SI->getContext(),
1695 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001696 Value *DestField = NewElts[i];
1697 if (EltVal->getType() == ArrayEltTy) {
1698 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001699 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001700 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001701 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00001702 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001703 } else {
1704 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00001705 DestField = Builder.CreateBitCast(DestField,
1706 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001707 }
1708 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00001709
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001710 if (TD->isBigEndian())
1711 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001712 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001713 Shift += ElementOffset;
1714 }
1715 }
Bob Wilson69743022011-01-13 20:59:44 +00001716
Bob Wilsonb742def2009-12-18 20:14:40 +00001717 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001718}
1719
Bob Wilson39fdd692009-12-04 21:57:37 +00001720/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001721/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001722void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001723 SmallVector<AllocaInst*, 32> &NewElts) {
1724 // Extract each element out of the NewElts according to its structure offset
1725 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001726 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001727 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001728
David Greene504c7d82010-01-05 01:27:09 +00001729 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001730 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00001731
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001732 // There are two forms here: AI could be an array or struct. Both cases
1733 // have different ways to compute the element offset.
1734 const StructLayout *Layout = 0;
1735 uint64_t ArrayEltBitOffset = 0;
1736 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1737 Layout = TD->getStructLayout(EltSTy);
1738 } else {
1739 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001740 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00001741 }
1742
1743 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001744 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00001745
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001746 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1747 // Load the value from the alloca. If the NewElt is an aggregate, cast
1748 // the pointer to an integer of the same size before doing the load.
1749 Value *SrcField = NewElts[i];
1750 const Type *FieldTy =
1751 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001752 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00001753
Chris Lattner583dd602009-01-09 18:18:43 +00001754 // Ignore zero sized fields like {}, they obviously contain no data.
1755 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001756
1757 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00001758 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001759 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1760 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001761 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001762 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001763 "", LI);
1764 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1765
1766 // If SrcField is a fp or vector of the right size but that isn't an
1767 // integer type, bitcast to an integer so we can shift it.
1768 if (SrcField->getType() != FieldIntTy)
1769 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1770
1771 // Zero extend the field to be the same size as the final alloca so that
1772 // we can shift and insert it.
1773 if (SrcField->getType() != ResultVal->getType())
1774 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00001775
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001776 // Determine the number of bits to shift SrcField.
1777 uint64_t Shift;
1778 if (Layout) // Struct case.
1779 Shift = Layout->getElementOffsetInBits(i);
1780 else // Array case.
1781 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00001782
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001783 if (TD->isBigEndian())
1784 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00001785
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001786 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001787 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001788 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1789 }
1790
Chris Lattner14952472010-06-27 07:58:26 +00001791 // Don't create an 'or x, 0' on the first iteration.
1792 if (!isa<Constant>(ResultVal) ||
1793 !cast<Constant>(ResultVal)->isNullValue())
1794 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1795 else
1796 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001797 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001798
1799 // Handle tail padding by truncating the result
1800 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1801 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1802
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001803 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001804 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001805}
1806
Duncan Sands3cb36502007-11-04 14:43:57 +00001807/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00001808/// alignment padding in between the elements that would be split apart
1809/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001810static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00001811 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1812 Ty = ATy->getElementType();
1813 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001814 }
Bob Wilson694a10e2011-01-13 17:45:08 +00001815
1816 // SROA currently handles only Arrays and Structs.
1817 const StructType *STy = cast<StructType>(Ty);
1818 const StructLayout *SL = TD.getStructLayout(STy);
1819 unsigned PrevFieldBitOffset = 0;
1820 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1821 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1822
1823 // Check to see if there is any padding between this element and the
1824 // previous one.
1825 if (i) {
1826 unsigned PrevFieldEnd =
1827 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1828 if (PrevFieldEnd < FieldBitOffset)
1829 return true;
1830 }
1831 PrevFieldBitOffset = FieldBitOffset;
1832 }
1833 // Check for tail padding.
1834 if (unsigned EltCount = STy->getNumElements()) {
1835 unsigned PrevFieldEnd = PrevFieldBitOffset +
1836 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1837 if (PrevFieldEnd < SL->getSizeInBits())
1838 return true;
1839 }
1840 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00001841}
Chris Lattner372dda82007-03-05 07:52:57 +00001842
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001843/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1844/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1845/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001846bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001847 // Loop over the use list of the alloca. We can only transform it if all of
1848 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001849 AllocaInfo Info;
Bob Wilson69743022011-01-13 20:59:44 +00001850
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001851 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001852 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001853 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001854 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001855 }
Bob Wilson69743022011-01-13 20:59:44 +00001856
Chris Lattner39a1c042007-05-30 06:11:23 +00001857 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1858 // source and destination, we have to be careful. In particular, the memcpy
1859 // could be moving around elements that live in structure padding of the LLVM
1860 // types, but may actually be used. In these cases, we refuse to promote the
1861 // struct.
1862 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001863 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001864 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001865
Chris Lattner396a0562011-01-16 17:46:19 +00001866 // If the alloca never has an access to just *part* of it, but is accessed
1867 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00001868 // the alloca instead of promoting each piece at a time and inserting fission
1869 // and fusion code.
1870 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
1871 // If the struct/array just has one element, use basic SRoA.
1872 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1873 if (ST->getNumElements() > 1) return false;
1874 } else {
1875 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
1876 return false;
1877 }
1878 }
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001879 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001880}
Chris Lattnera1888942005-12-12 07:19:13 +00001881
Chris Lattner800de312008-02-29 07:03:13 +00001882
Chris Lattner79b3bd32007-04-25 06:40:51 +00001883
1884/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1885/// some part of a constant global variable. This intentionally only accepts
1886/// constant expressions because we don't can't rewrite arbitrary instructions.
1887static bool PointsToConstantGlobal(Value *V) {
1888 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1889 return GV->isConstant();
1890 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00001891 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00001892 CE->getOpcode() == Instruction::GetElementPtr)
1893 return PointsToConstantGlobal(CE->getOperand(0));
1894 return false;
1895}
1896
1897/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1898/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1899/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1900/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1901/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00001902/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00001903/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001904static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001905 bool isOffset) {
1906 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001907 User *U = cast<Instruction>(*UI);
1908
Chris Lattner2e618492010-11-18 06:20:47 +00001909 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001910 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00001911 if (LI->isVolatile()) return false;
1912 continue;
1913 }
Bob Wilson69743022011-01-13 20:59:44 +00001914
Gabor Greif8a8a4352010-04-06 19:32:30 +00001915 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001916 // If uses of the bitcast are ok, we are ok.
1917 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1918 return false;
1919 continue;
1920 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001921 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001922 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1923 // doesn't, it does.
1924 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1925 isOffset || !GEP->hasAllZeroIndices()))
1926 return false;
1927 continue;
1928 }
Bob Wilson69743022011-01-13 20:59:44 +00001929
Chris Lattner62480652010-11-18 06:41:51 +00001930 if (CallSite CS = U) {
1931 // If this is a readonly/readnone call site, then we know it is just a
1932 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00001933 if (CS.onlyReadsMemory())
1934 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00001935
1936 // If this is the function being called then we treat it like a load and
1937 // ignore it.
1938 if (CS.isCallee(UI))
1939 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001940
Chris Lattner62480652010-11-18 06:41:51 +00001941 // If this is being passed as a byval argument, the caller is making a
1942 // copy, so it is only a read of the alloca.
1943 unsigned ArgNo = CS.getArgumentNo(UI);
1944 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
1945 continue;
1946 }
Bob Wilson69743022011-01-13 20:59:44 +00001947
Chris Lattner79b3bd32007-04-25 06:40:51 +00001948 // If this is isn't our memcpy/memmove, reject it as something we can't
1949 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001950 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1951 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001952 return false;
Bob Wilson69743022011-01-13 20:59:44 +00001953
Chris Lattner2e618492010-11-18 06:20:47 +00001954 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00001955 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00001956 if (UI.getOperandNo() == 1) {
1957 if (MI->isVolatile()) return false;
1958 continue;
1959 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00001960
1961 // If we already have seen a copy, reject the second one.
1962 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00001963
Chris Lattner79b3bd32007-04-25 06:40:51 +00001964 // If the pointer has been offset from the start of the alloca, we can't
1965 // safely handle this.
1966 if (isOffset) return false;
1967
1968 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001969 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00001970
Chris Lattner79b3bd32007-04-25 06:40:51 +00001971 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001972 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001973 return false;
Bob Wilson69743022011-01-13 20:59:44 +00001974
Chris Lattner79b3bd32007-04-25 06:40:51 +00001975 // Otherwise, the transform is safe. Remember the copy instruction.
1976 TheCopy = MI;
1977 }
1978 return true;
1979}
1980
1981/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1982/// modified by a copy from a constant global. If we can prove this, we can
1983/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001984MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1985 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001986 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1987 return TheCopy;
1988 return 0;
1989}