blob: 6f4f17e20fb4481554b49cd22fbab42e433a93d3 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000033#include "llvm/Analysis/Dominators.h"
34#include "llvm/Target/TargetData.h"
35#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000036#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000037#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000038#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000039#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000040#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000041#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000042#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000043#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000044#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumReplaced, "Number of allocas broken up");
48STATISTIC(NumPromoted, "Number of allocas promoted");
49STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000050STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000051
Chris Lattner0e5f4992006-12-19 21:40:18 +000052namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000053 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000054 static char ID; // Pass identification, replacement for typeid
Owen Anderson90c579d2010-08-06 18:33:48 +000055 explicit SROA(signed T = -1) : FunctionPass(ID) {
Owen Anderson081c34b2010-10-19 17:21:58 +000056 initializeSROAPass(*PassRegistry::getPassRegistry());
Devang Patelff366852007-07-09 21:19:23 +000057 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000058 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000059 else
60 SRThreshold = T;
61 }
Devang Patel794fd752007-05-01 21:15:47 +000062
Chris Lattnered7b41e2003-05-27 15:45:27 +000063 bool runOnFunction(Function &F);
64
Chris Lattner38aec322003-09-11 16:45:55 +000065 bool performScalarRepl(Function &F);
66 bool performPromotion(Function &F);
67
Chris Lattnera15854c2003-08-31 00:45:13 +000068 // getAnalysisUsage - This pass does not require any passes, but we know it
69 // will not alter the CFG, so say so.
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000071 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000072 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000073 AU.setPreservesCFG();
74 }
75
Chris Lattnered7b41e2003-05-27 15:45:27 +000076 private:
Chris Lattner56c38522009-01-07 06:34:28 +000077 TargetData *TD;
78
Bob Wilsonb742def2009-12-18 20:14:40 +000079 /// DeadInsts - Keep track of instructions we have made dead, so that
80 /// we can remove them after we are done working.
81 SmallVector<Value*, 32> DeadInsts;
82
Chris Lattner39a1c042007-05-30 06:11:23 +000083 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
84 /// information about the uses. All these fields are initialized to false
85 /// and set to true when something is learned.
86 struct AllocaInfo {
87 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
88 bool isUnsafe : 1;
89
Chris Lattner39a1c042007-05-30 06:11:23 +000090 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 bool isMemCpySrc : 1;
92
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000093 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000094 bool isMemCpyDst : 1;
95
96 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +000097 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +000098 };
99
Devang Patelff366852007-07-09 21:19:23 +0000100 unsigned SRThreshold;
101
Chris Lattner39a1c042007-05-30 06:11:23 +0000102 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
103
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000104 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000105
Bob Wilsonb742def2009-12-18 20:14:40 +0000106 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000107 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000108 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000109 AllocaInfo &Info);
110 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
111 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000112 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000113 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
114 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000115
Victor Hernandez7b929da2009-10-23 21:09:37 +0000116 void DoScalarReplacement(AllocaInst *AI,
117 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000118 void DeleteDeadInstructions();
Chris Lattner3126f1c2010-08-18 02:37:06 +0000119
Bob Wilsonb742def2009-12-18 20:14:40 +0000120 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
121 SmallVector<AllocaInst*, 32> &NewElts);
122 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
123 SmallVector<AllocaInst*, 32> &NewElts);
124 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
125 SmallVector<AllocaInst*, 32> &NewElts);
126 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000127 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000128 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000129 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000130 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000131 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000132 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000133
Chris Lattner31d80102010-04-15 21:59:20 +0000134 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000135 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000136}
137
Dan Gohman844731a2008-05-13 00:00:25 +0000138char SROA::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000139INITIALIZE_PASS_BEGIN(SROA, "scalarrepl",
140 "Scalar Replacement of Aggregates", false, false)
141INITIALIZE_PASS_DEPENDENCY(DominatorTree)
142INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
143INITIALIZE_PASS_END(SROA, "scalarrepl",
Owen Andersonce665bd2010-10-07 22:25:06 +0000144 "Scalar Replacement of Aggregates", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000145
Brian Gaeked0fde302003-11-11 22:41:34 +0000146// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000147FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
148 return new SROA(Threshold);
149}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000150
151
Chris Lattner4cc576b2010-04-16 00:24:57 +0000152//===----------------------------------------------------------------------===//
153// Convert To Scalar Optimization.
154//===----------------------------------------------------------------------===//
155
156namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000157/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
158/// optimization, which scans the uses of an alloca and determines if it can
159/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000160class ConvertToScalarInfo {
161 /// AllocaSize - The size of the alloca being considered.
162 unsigned AllocaSize;
163 const TargetData &TD;
164
Chris Lattnera0bada72010-04-16 02:32:17 +0000165 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000166 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000167 bool IsNotTrivial;
Chris Lattnera001b662010-04-16 00:38:19 +0000168
169 /// VectorTy - This tracks the type that we should promote the vector to if
170 /// it is possible to turn it into a vector. This starts out null, and if it
171 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000172 const Type *VectorTy;
Chris Lattnera001b662010-04-16 00:38:19 +0000173
174 /// HadAVector - True if there is at least one vector access to the alloca.
175 /// We don't want to turn random arrays into vectors and use vector element
176 /// insert/extract, but if there are element accesses to something that is
177 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000178 bool HadAVector;
179
180public:
181 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
182 : AllocaSize(Size), TD(td) {
183 IsNotTrivial = false;
184 VectorTy = 0;
185 HadAVector = false;
186 }
187
Chris Lattnera001b662010-04-16 00:38:19 +0000188 AllocaInst *TryConvert(AllocaInst *AI);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000189
190private:
191 bool CanConvertToScalar(Value *V, uint64_t Offset);
192 void MergeInType(const Type *In, uint64_t Offset);
193 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
194
195 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
196 uint64_t Offset, IRBuilder<> &Builder);
197 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
198 uint64_t Offset, IRBuilder<> &Builder);
199};
200} // end anonymous namespace.
201
Chris Lattner91abace2010-09-01 05:14:33 +0000202
203/// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
204/// allowed to form. We do this to avoid MMX types, which is a complete hack,
205/// but is required until the backend is fixed.
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000206static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
207 StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
208 if (!Triple.startswith("i386") &&
209 !Triple.startswith("x86_64"))
210 return false;
211
Chris Lattner91abace2010-09-01 05:14:33 +0000212 // Reject all the MMX vector types.
213 switch (VTy->getNumElements()) {
214 default: return false;
215 case 1: return VTy->getElementType()->isIntegerTy(64);
216 case 2: return VTy->getElementType()->isIntegerTy(32);
217 case 4: return VTy->getElementType()->isIntegerTy(16);
218 case 8: return VTy->getElementType()->isIntegerTy(8);
219 }
220}
221
222
Chris Lattnera001b662010-04-16 00:38:19 +0000223/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
224/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
225/// alloca if possible or null if not.
226AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
227 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
228 // out.
229 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
230 return 0;
231
232 // If we were able to find a vector type that can handle this with
233 // insert/extract elements, and if there was at least one use that had
234 // a vector type, promote this to a vector. We don't want to promote
235 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
236 // we just get a lot of insert/extracts. If at least one vector is
237 // involved, then we probably really do have a union of vector/array.
238 const Type *NewTy;
Chris Lattner91abace2010-09-01 05:14:33 +0000239 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
Chris Lattner72eaa0e2010-09-01 23:09:27 +0000240 !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000241 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
242 << *VectorTy << '\n');
243 NewTy = VectorTy; // Use the vector type.
244 } else {
245 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
246 // Create and insert the integer alloca.
247 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
248 }
249 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
250 ConvertUsesToScalar(AI, NewAI, 0);
251 return NewAI;
252}
253
254/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
255/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000256///
257/// There are two cases we handle here:
258/// 1) A union of vector types of the same size and potentially its elements.
259/// Here we turn element accesses into insert/extract element operations.
260/// This promotes a <4 x float> with a store of float to the third element
261/// into a <4 x float> that uses insert element.
262/// 2) A fully general blob of memory, which we turn into some (potentially
263/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000264/// and stores would mutate the memory. We mark this by setting VectorTy
265/// to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000266void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000267 // If we already decided to turn this into a blob of integer memory, there is
268 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000269 if (VectorTy && VectorTy->isVoidTy())
270 return;
271
272 // If this could be contributing to a vector, analyze it.
273
274 // If the In type is a vector that is the same size as the alloca, see if it
275 // matches the existing VecTy.
276 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000277 // Remember if we saw a vector type.
278 HadAVector = true;
279
Chris Lattner4cc576b2010-04-16 00:24:57 +0000280 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
281 // If we're storing/loading a vector of the right size, allow it as a
282 // vector. If this the first vector we see, remember the type so that
Chris Lattnera001b662010-04-16 00:38:19 +0000283 // we know the element size. If this is a subsequent access, ignore it
284 // even if it is a differing type but the same size. Worst case we can
285 // bitcast the resultant vectors.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000286 if (VectorTy == 0)
287 VectorTy = VInTy;
288 return;
289 }
290 } else if (In->isFloatTy() || In->isDoubleTy() ||
291 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
292 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
293 // If we're accessing something that could be an element of a vector, see
294 // if the implied vector agrees with what we already have and if Offset is
295 // compatible with it.
296 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
297 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
298 (VectorTy == 0 ||
299 cast<VectorType>(VectorTy)->getElementType()
300 ->getPrimitiveSizeInBits()/8 == EltSize)) {
301 if (VectorTy == 0)
302 VectorTy = VectorType::get(In, AllocaSize/EltSize);
303 return;
304 }
305 }
306
307 // Otherwise, we have a case that we can't handle with an optimized vector
308 // form. We can still turn this into a large integer.
309 VectorTy = Type::getVoidTy(In->getContext());
310}
311
312/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
313/// its accesses to a single vector type, return true and set VecTy to
314/// the new type. If we could convert the alloca into a single promotable
315/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
316/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
317/// is the current offset from the base of the alloca being analyzed.
318///
319/// If we see at least one access to the value that is as a vector type, set the
320/// SawVec flag.
321bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
322 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
323 Instruction *User = cast<Instruction>(*UI);
324
325 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
326 // Don't break volatile loads.
327 if (LI->isVolatile())
328 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000329 // Don't touch MMX operations.
330 if (LI->getType()->isX86_MMXTy())
331 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000332 MergeInType(LI->getType(), Offset);
333 continue;
334 }
335
336 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
337 // Storing the pointer, not into the value?
338 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000339 // Don't touch MMX operations.
340 if (SI->getOperand(0)->getType()->isX86_MMXTy())
341 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000342 MergeInType(SI->getOperand(0)->getType(), Offset);
343 continue;
344 }
345
346 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000347 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000348 if (!CanConvertToScalar(BCI, Offset))
349 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000350 continue;
351 }
352
353 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
354 // If this is a GEP with a variable indices, we can't handle it.
355 if (!GEP->hasAllConstantIndices())
356 return false;
357
358 // Compute the offset that this GEP adds to the pointer.
359 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
360 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
361 &Indices[0], Indices.size());
362 // See if all uses can be converted.
363 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
364 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000365 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000366 continue;
367 }
368
369 // If this is a constant sized memset of a constant value (e.g. 0) we can
370 // handle it.
371 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
372 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000373 if (!isa<ConstantInt>(MSI->getValue()) ||
374 !isa<ConstantInt>(MSI->getLength()))
375 return false;
376 IsNotTrivial = true; // Can't be mem2reg'd.
377 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000378 }
379
380 // If this is a memcpy or memmove into or out of the whole allocation, we
381 // can handle it like a load or store of the scalar type.
382 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000383 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
384 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
385 return false;
386
387 IsNotTrivial = true; // Can't be mem2reg'd.
388 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000389 }
390
391 // Otherwise, we cannot handle this!
392 return false;
393 }
394
395 return true;
396}
397
398/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
399/// directly. This happens when we are converting an "integer union" to a
400/// single integer scalar, or when we are converting a "vector union" to a
401/// vector with insert/extractelement instructions.
402///
403/// Offset is an offset from the original alloca, in bits that need to be
404/// shifted to the right. By the end of this, there should be no uses of Ptr.
405void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
406 uint64_t Offset) {
407 while (!Ptr->use_empty()) {
408 Instruction *User = cast<Instruction>(Ptr->use_back());
409
410 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
411 ConvertUsesToScalar(CI, NewAI, Offset);
412 CI->eraseFromParent();
413 continue;
414 }
415
416 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
417 // Compute the offset that this GEP adds to the pointer.
418 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
419 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
420 &Indices[0], Indices.size());
421 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
422 GEP->eraseFromParent();
423 continue;
424 }
425
426 IRBuilder<> Builder(User->getParent(), User);
427
428 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
429 // The load is a bit extract from NewAI shifted right by Offset bits.
430 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
431 Value *NewLoadVal
432 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
433 LI->replaceAllUsesWith(NewLoadVal);
434 LI->eraseFromParent();
435 continue;
436 }
437
438 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
439 assert(SI->getOperand(0) != Ptr && "Consistency error!");
440 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
441 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
442 Builder);
443 Builder.CreateStore(New, NewAI);
444 SI->eraseFromParent();
445
446 // If the load we just inserted is now dead, then the inserted store
447 // overwrote the entire thing.
448 if (Old->use_empty())
449 Old->eraseFromParent();
450 continue;
451 }
452
453 // If this is a constant sized memset of a constant value (e.g. 0) we can
454 // transform it into a store of the expanded constant value.
455 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
456 assert(MSI->getRawDest() == Ptr && "Consistency error!");
457 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
458 if (NumBytes != 0) {
459 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
460
461 // Compute the value replicated the right number of times.
462 APInt APVal(NumBytes*8, Val);
463
464 // Splat the value if non-zero.
465 if (Val)
466 for (unsigned i = 1; i != NumBytes; ++i)
467 APVal |= APVal << 8;
468
469 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
470 Value *New = ConvertScalar_InsertValue(
471 ConstantInt::get(User->getContext(), APVal),
472 Old, Offset, Builder);
473 Builder.CreateStore(New, NewAI);
474
475 // If the load we just inserted is now dead, then the memset overwrote
476 // the entire thing.
477 if (Old->use_empty())
478 Old->eraseFromParent();
479 }
480 MSI->eraseFromParent();
481 continue;
482 }
483
484 // If this is a memcpy or memmove into or out of the whole allocation, we
485 // can handle it like a load or store of the scalar type.
486 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
487 assert(Offset == 0 && "must be store to start of alloca");
488
489 // If the source and destination are both to the same alloca, then this is
490 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
491 // as appropriate.
492 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
493
494 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
495 // Dest must be OrigAI, change this to be a load from the original
496 // pointer (bitcasted), then a store to our new alloca.
497 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
498 Value *SrcPtr = MTI->getSource();
499 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
500
501 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
502 SrcVal->setAlignment(MTI->getAlignment());
503 Builder.CreateStore(SrcVal, NewAI);
504 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
505 // Src must be OrigAI, change this to be a load from NewAI then a store
506 // through the original dest pointer (bitcasted).
507 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
508 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
509
510 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
511 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
512 NewStore->setAlignment(MTI->getAlignment());
513 } else {
514 // Noop transfer. Src == Dst
515 }
516
517 MTI->eraseFromParent();
518 continue;
519 }
520
521 llvm_unreachable("Unsupported operation!");
522 }
523}
524
525/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
526/// or vector value FromVal, extracting the bits from the offset specified by
527/// Offset. This returns the value, which is of type ToType.
528///
529/// This happens when we are converting an "integer union" to a single
530/// integer scalar, or when we are converting a "vector union" to a vector with
531/// insert/extractelement instructions.
532///
533/// Offset is an offset from the original alloca, in bits that need to be
534/// shifted to the right.
535Value *ConvertToScalarInfo::
536ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
537 uint64_t Offset, IRBuilder<> &Builder) {
538 // If the load is of the whole new alloca, no conversion is needed.
539 if (FromVal->getType() == ToType && Offset == 0)
540 return FromVal;
541
542 // If the result alloca is a vector type, this is either an element
543 // access or a bitcast to another vector type of the same size.
544 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
545 if (ToType->isVectorTy())
546 return Builder.CreateBitCast(FromVal, ToType, "tmp");
547
548 // Otherwise it must be an element access.
549 unsigned Elt = 0;
550 if (Offset) {
551 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
552 Elt = Offset/EltSize;
553 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
554 }
555 // Return the element extracted out of it.
556 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
557 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
558 if (V->getType() != ToType)
559 V = Builder.CreateBitCast(V, ToType, "tmp");
560 return V;
561 }
562
563 // If ToType is a first class aggregate, extract out each of the pieces and
564 // use insertvalue's to form the FCA.
565 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
566 const StructLayout &Layout = *TD.getStructLayout(ST);
567 Value *Res = UndefValue::get(ST);
568 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
569 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
570 Offset+Layout.getElementOffsetInBits(i),
571 Builder);
572 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
573 }
574 return Res;
575 }
576
577 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
578 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
579 Value *Res = UndefValue::get(AT);
580 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
581 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
582 Offset+i*EltSize, Builder);
583 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
584 }
585 return Res;
586 }
587
588 // Otherwise, this must be a union that was converted to an integer value.
589 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
590
591 // If this is a big-endian system and the load is narrower than the
592 // full alloca type, we need to do a shift to get the right bits.
593 int ShAmt = 0;
594 if (TD.isBigEndian()) {
595 // On big-endian machines, the lowest bit is stored at the bit offset
596 // from the pointer given by getTypeStoreSizeInBits. This matters for
597 // integers with a bitwidth that is not a multiple of 8.
598 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
599 TD.getTypeStoreSizeInBits(ToType) - Offset;
600 } else {
601 ShAmt = Offset;
602 }
603
604 // Note: we support negative bitwidths (with shl) which are not defined.
605 // We do this to support (f.e.) loads off the end of a structure where
606 // only some bits are used.
607 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
608 FromVal = Builder.CreateLShr(FromVal,
609 ConstantInt::get(FromVal->getType(),
610 ShAmt), "tmp");
611 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
612 FromVal = Builder.CreateShl(FromVal,
613 ConstantInt::get(FromVal->getType(),
614 -ShAmt), "tmp");
615
616 // Finally, unconditionally truncate the integer to the right width.
617 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
618 if (LIBitWidth < NTy->getBitWidth())
619 FromVal =
620 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
621 LIBitWidth), "tmp");
622 else if (LIBitWidth > NTy->getBitWidth())
623 FromVal =
624 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
625 LIBitWidth), "tmp");
626
627 // If the result is an integer, this is a trunc or bitcast.
628 if (ToType->isIntegerTy()) {
629 // Should be done.
630 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
631 // Just do a bitcast, we know the sizes match up.
632 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
633 } else {
634 // Otherwise must be a pointer.
635 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
636 }
637 assert(FromVal->getType() == ToType && "Didn't convert right?");
638 return FromVal;
639}
640
641/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
642/// or vector value "Old" at the offset specified by Offset.
643///
644/// This happens when we are converting an "integer union" to a
645/// single integer scalar, or when we are converting a "vector union" to a
646/// vector with insert/extractelement instructions.
647///
648/// Offset is an offset from the original alloca, in bits that need to be
649/// shifted to the right.
650Value *ConvertToScalarInfo::
651ConvertScalar_InsertValue(Value *SV, Value *Old,
652 uint64_t Offset, IRBuilder<> &Builder) {
653 // Convert the stored type to the actual type, shift it left to insert
654 // then 'or' into place.
655 const Type *AllocaType = Old->getType();
656 LLVMContext &Context = Old->getContext();
657
658 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
659 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
660 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
661
662 // Changing the whole vector with memset or with an access of a different
663 // vector type?
664 if (ValSize == VecSize)
665 return Builder.CreateBitCast(SV, AllocaType, "tmp");
666
667 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
668
669 // Must be an element insertion.
670 unsigned Elt = Offset/EltSize;
671
672 if (SV->getType() != VTy->getElementType())
673 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
674
675 SV = Builder.CreateInsertElement(Old, SV,
676 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
677 "tmp");
678 return SV;
679 }
680
681 // If SV is a first-class aggregate value, insert each value recursively.
682 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
683 const StructLayout &Layout = *TD.getStructLayout(ST);
684 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
685 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
686 Old = ConvertScalar_InsertValue(Elt, Old,
687 Offset+Layout.getElementOffsetInBits(i),
688 Builder);
689 }
690 return Old;
691 }
692
693 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
694 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
695 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
696 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
697 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
698 }
699 return Old;
700 }
701
702 // If SV is a float, convert it to the appropriate integer type.
703 // If it is a pointer, do the same.
704 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
705 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
706 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
707 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
708 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
709 SV = Builder.CreateBitCast(SV,
710 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
711 else if (SV->getType()->isPointerTy())
712 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
713
714 // Zero extend or truncate the value if needed.
715 if (SV->getType() != AllocaType) {
716 if (SV->getType()->getPrimitiveSizeInBits() <
717 AllocaType->getPrimitiveSizeInBits())
718 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
719 else {
720 // Truncation may be needed if storing more than the alloca can hold
721 // (undefined behavior).
722 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
723 SrcWidth = DestWidth;
724 SrcStoreWidth = DestStoreWidth;
725 }
726 }
727
728 // If this is a big-endian system and the store is narrower than the
729 // full alloca type, we need to do a shift to get the right bits.
730 int ShAmt = 0;
731 if (TD.isBigEndian()) {
732 // On big-endian machines, the lowest bit is stored at the bit offset
733 // from the pointer given by getTypeStoreSizeInBits. This matters for
734 // integers with a bitwidth that is not a multiple of 8.
735 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
736 } else {
737 ShAmt = Offset;
738 }
739
740 // Note: we support negative bitwidths (with shr) which are not defined.
741 // We do this to support (f.e.) stores off the end of a structure where
742 // only some bits in the structure are set.
743 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
744 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
745 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
746 ShAmt), "tmp");
747 Mask <<= ShAmt;
748 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
749 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
750 -ShAmt), "tmp");
751 Mask = Mask.lshr(-ShAmt);
752 }
753
754 // Mask out the bits we are about to insert from the old value, and or
755 // in the new bits.
756 if (SrcWidth != DestWidth) {
757 assert(DestWidth > SrcWidth);
758 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
759 SV = Builder.CreateOr(Old, SV, "ins");
760 }
761 return SV;
762}
763
764
765//===----------------------------------------------------------------------===//
766// SRoA Driver
767//===----------------------------------------------------------------------===//
768
769
Chris Lattnered7b41e2003-05-27 15:45:27 +0000770bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000771 TD = getAnalysisIfAvailable<TargetData>();
772
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000773 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000774
775 // FIXME: ScalarRepl currently depends on TargetData more than it
776 // theoretically needs to. It should be refactored in order to support
777 // target-independent IR. Until this is done, just skip the actual
778 // scalar-replacement portion of this pass.
779 if (!TD) return Changed;
780
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000781 while (1) {
782 bool LocalChange = performScalarRepl(F);
783 if (!LocalChange) break; // No need to repromote if no scalarrepl
784 Changed = true;
785 LocalChange = performPromotion(F);
786 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
787 }
Chris Lattner38aec322003-09-11 16:45:55 +0000788
789 return Changed;
790}
791
792
793bool SROA::performPromotion(Function &F) {
794 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000795 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000796 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000797
Chris Lattner02a3be02003-09-20 14:39:18 +0000798 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000799
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000800 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000801
Chris Lattner38aec322003-09-11 16:45:55 +0000802 while (1) {
803 Allocas.clear();
804
805 // Find allocas that are safe to promote, by looking at all instructions in
806 // the entry node
807 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
808 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000809 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000810 Allocas.push_back(AI);
811
812 if (Allocas.empty()) break;
813
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000814 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000815 NumPromoted += Allocas.size();
816 Changed = true;
817 }
818
819 return Changed;
820}
821
Chris Lattner4cc576b2010-04-16 00:24:57 +0000822
Bob Wilson3992feb2010-02-03 17:23:56 +0000823/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
824/// SROA. It must be a struct or array type with a small number of elements.
825static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
826 const Type *T = AI->getAllocatedType();
827 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000828 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000829 return ST->getNumElements() <= 32;
830 // Arrays are much less likely to be safe for SROA; only consider
831 // them if they are very small.
832 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
833 return AT->getNumElements() <= 8;
834 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000835}
836
Chris Lattnerc4472072010-04-15 23:50:26 +0000837
Chris Lattner38aec322003-09-11 16:45:55 +0000838// performScalarRepl - This algorithm is a simple worklist driven algorithm,
839// which runs on all of the malloc/alloca instructions in the function, removing
840// them if they are only used by getelementptr instructions.
841//
842bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000843 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000844
Chris Lattner31d80102010-04-15 21:59:20 +0000845 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000846 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000847 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000848 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000849 WorkList.push_back(A);
850
851 // Process the worklist
852 bool Changed = false;
853 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000854 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000855 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000856
Chris Lattneradd2bd72006-12-22 23:14:42 +0000857 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
858 // with unused elements.
859 if (AI->use_empty()) {
860 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000861 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000862 continue;
863 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000864
865 // If this alloca is impossible for us to promote, reject it early.
866 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
867 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000868
869 // Check to see if this allocation is only modified by a memcpy/memmove from
870 // a constant global. If this is the case, we can change all users to use
871 // the constant global instead. This is commonly produced by the CFE by
872 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
873 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000874 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000875 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
876 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000877 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000878 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000879 TheCopy->eraseFromParent(); // Don't mutate the global.
880 AI->eraseFromParent();
881 ++NumGlobals;
882 Changed = true;
883 continue;
884 }
Chris Lattner15c82772009-02-02 20:44:45 +0000885
Chris Lattner7809ecd2009-02-03 01:30:09 +0000886 // Check to see if we can perform the core SROA transformation. We cannot
887 // transform the allocation instruction if it is an array allocation
888 // (allocations OF arrays are ok though), and an allocation of a scalar
889 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000890 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000891
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000892 // Do not promote [0 x %struct].
893 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000894
895 // Do not promote any struct whose size is too big.
896 if (AllocaSize > SRThreshold) continue;
897
Bob Wilson3992feb2010-02-03 17:23:56 +0000898 // If the alloca looks like a good candidate for scalar replacement, and if
899 // all its users can be transformed, then split up the aggregate into its
900 // separate elements.
901 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
902 DoScalarReplacement(AI, WorkList);
903 Changed = true;
904 continue;
905 }
906
Chris Lattner6e733d32009-01-28 20:16:43 +0000907 // If we can turn this aggregate value (potentially with casts) into a
908 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000909 // IsNotTrivial tracks whether this is something that mem2reg could have
910 // promoted itself. If so, we don't want to transform it needlessly. Note
911 // that we can't just check based on the type: the alloca may be of an i32
912 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000913 if (AllocaInst *NewAI =
914 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000915 NewAI->takeName(AI);
916 AI->eraseFromParent();
917 ++NumConverted;
918 Changed = true;
919 continue;
Chris Lattner593375d2010-04-16 00:20:00 +0000920 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000921
Chris Lattner7809ecd2009-02-03 01:30:09 +0000922 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000923 }
924
925 return Changed;
926}
Chris Lattner5e062a12003-05-30 04:15:41 +0000927
Chris Lattnera10b29b2007-04-25 05:02:56 +0000928/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
929/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000930void SROA::DoScalarReplacement(AllocaInst *AI,
931 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000932 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000933 SmallVector<AllocaInst*, 32> ElementAllocas;
934 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
935 ElementAllocas.reserve(ST->getNumContainedTypes());
936 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000937 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000938 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000939 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000940 ElementAllocas.push_back(NA);
941 WorkList.push_back(NA); // Add to worklist for recursive processing
942 }
943 } else {
944 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
945 ElementAllocas.reserve(AT->getNumElements());
946 const Type *ElTy = AT->getElementType();
947 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000948 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000949 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000950 ElementAllocas.push_back(NA);
951 WorkList.push_back(NA); // Add to worklist for recursive processing
952 }
953 }
954
Bob Wilsonb742def2009-12-18 20:14:40 +0000955 // Now that we have created the new alloca instructions, rewrite all the
956 // uses of the old alloca.
957 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000958
Bob Wilsonb742def2009-12-18 20:14:40 +0000959 // Now erase any instructions that were made dead while rewriting the alloca.
960 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000961 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000962
Dan Gohmanfe601042010-06-22 15:08:57 +0000963 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000964}
Chris Lattnera59adc42009-12-14 05:11:02 +0000965
Bob Wilsonb742def2009-12-18 20:14:40 +0000966/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
967/// recursively including all their operands that become trivially dead.
968void SROA::DeleteDeadInstructions() {
969 while (!DeadInsts.empty()) {
970 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000971
Bob Wilsonb742def2009-12-18 20:14:40 +0000972 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
973 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
974 // Zero out the operand and see if it becomes trivially dead.
975 // (But, don't add allocas to the dead instruction list -- they are
976 // already on the worklist and will be deleted separately.)
977 *OI = 0;
978 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
979 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000980 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000981
982 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000983 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000984}
Bob Wilsonb742def2009-12-18 20:14:40 +0000985
Bob Wilsonb742def2009-12-18 20:14:40 +0000986/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
987/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000988/// the Info parameter. Offset indicates the position within AI that is
989/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000990void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000991 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000992 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
993 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000994
Bob Wilsonb742def2009-12-18 20:14:40 +0000995 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000996 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000997 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000998 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000999 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001000 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001001 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001002 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001003 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1004 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001005 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001006 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001007 else
1008 MarkUnsafe(Info);
1009 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1010 if (!LI->isVolatile()) {
1011 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001012 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001013 LIType, false, Info);
1014 } else
1015 MarkUnsafe(Info);
1016 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1017 // Store is ok if storing INTO the pointer, not storing the pointer
1018 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1019 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001020 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +00001021 SIType, true, Info);
1022 } else
1023 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001024 } else {
1025 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1026 MarkUnsafe(Info);
1027 }
1028 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001029 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001030}
Bob Wilson39c88a62009-12-17 18:34:24 +00001031
Bob Wilsonb742def2009-12-18 20:14:40 +00001032/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1033/// replacement. It is safe when all the indices are constant, in-bounds
1034/// references, and when the resulting offset corresponds to an element within
1035/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001036/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +00001037void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001038 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001039 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1040 if (GEPIt == E)
1041 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001042
Chris Lattner88e6dc82008-08-23 05:21:06 +00001043 // Walk through the GEP type indices, checking the types that this indexes
1044 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001045 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001046 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001047 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001048 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001049
Bob Wilsonb742def2009-12-18 20:14:40 +00001050 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1051 if (!IdxVal)
1052 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001053 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001054
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001055 // Compute the offset due to this GEP and check if the alloca has a
1056 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001057 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1058 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1059 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +00001060 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1061 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +00001062}
1063
Bob Wilsonb742def2009-12-18 20:14:40 +00001064/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1065/// alloca or has an offset and size that corresponds to a component element
1066/// within it. The offset checked here may have been formed from a GEP with a
1067/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001068void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001069 const Type *MemOpType, bool isStore,
1070 AllocaInfo &Info) {
1071 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001072 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001073 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1074 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1075 // (which are essentially the same as the MemIntrinsics, especially with
1076 // regard to copying padding between elements), or references using the
1077 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +00001078 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001079 if (!UsesAggregateType) {
1080 if (isStore)
1081 Info.isMemCpyDst = true;
1082 else
1083 Info.isMemCpySrc = true;
1084 }
1085 return;
1086 }
1087 }
1088 // Check if the offset/size correspond to a component within the alloca type.
1089 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001090 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +00001091 return;
1092
1093 return MarkUnsafe(Info);
1094}
1095
1096/// TypeHasComponent - Return true if T has a component type with the
1097/// specified offset and size. If Size is zero, do not check the size.
1098bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1099 const Type *EltTy;
1100 uint64_t EltSize;
1101 if (const StructType *ST = dyn_cast<StructType>(T)) {
1102 const StructLayout *Layout = TD->getStructLayout(ST);
1103 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1104 EltTy = ST->getContainedType(EltIdx);
1105 EltSize = TD->getTypeAllocSize(EltTy);
1106 Offset -= Layout->getElementOffset(EltIdx);
1107 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1108 EltTy = AT->getElementType();
1109 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001110 if (Offset >= AT->getNumElements() * EltSize)
1111 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001112 Offset %= EltSize;
1113 } else {
1114 return false;
1115 }
1116 if (Offset == 0 && (Size == 0 || EltSize == Size))
1117 return true;
1118 // Check if the component spans multiple elements.
1119 if (Offset + Size > EltSize)
1120 return false;
1121 return TypeHasComponent(EltTy, Offset, Size);
1122}
1123
1124/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1125/// the instruction I, which references it, to use the separate elements.
1126/// Offset indicates the position within AI that is referenced by this
1127/// instruction.
1128void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1129 SmallVector<AllocaInst*, 32> &NewElts) {
1130 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1131 Instruction *User = cast<Instruction>(*UI);
1132
1133 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1134 RewriteBitCast(BC, AI, Offset, NewElts);
1135 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1136 RewriteGEP(GEPI, AI, Offset, NewElts);
1137 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1138 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1139 uint64_t MemSize = Length->getZExtValue();
1140 if (Offset == 0 &&
1141 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1142 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001143 // Otherwise the intrinsic can only touch a single element and the
1144 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +00001145 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1146 const Type *LIType = LI->getType();
1147 if (LIType == AI->getAllocatedType()) {
1148 // Replace:
1149 // %res = load { i32, i32 }* %alloc
1150 // with:
1151 // %load.0 = load i32* %alloc.0
1152 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1153 // %load.1 = load i32* %alloc.1
1154 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1155 // (Also works for arrays instead of structs)
1156 Value *Insert = UndefValue::get(LIType);
1157 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1158 Value *Load = new LoadInst(NewElts[i], "load", LI);
1159 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1160 }
1161 LI->replaceAllUsesWith(Insert);
1162 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001163 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001164 TD->getTypeAllocSize(LIType) ==
1165 TD->getTypeAllocSize(AI->getAllocatedType())) {
1166 // If this is a load of the entire alloca to an integer, rewrite it.
1167 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1168 }
1169 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1170 Value *Val = SI->getOperand(0);
1171 const Type *SIType = Val->getType();
1172 if (SIType == AI->getAllocatedType()) {
1173 // Replace:
1174 // store { i32, i32 } %val, { i32, i32 }* %alloc
1175 // with:
1176 // %val.0 = extractvalue { i32, i32 } %val, 0
1177 // store i32 %val.0, i32* %alloc.0
1178 // %val.1 = extractvalue { i32, i32 } %val, 1
1179 // store i32 %val.1, i32* %alloc.1
1180 // (Also works for arrays instead of structs)
1181 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1182 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1183 new StoreInst(Extract, NewElts[i], SI);
1184 }
1185 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001186 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001187 TD->getTypeAllocSize(SIType) ==
1188 TD->getTypeAllocSize(AI->getAllocatedType())) {
1189 // If this is a store of the entire alloca from an integer, rewrite it.
1190 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1191 }
1192 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001193 }
1194}
1195
Bob Wilsonb742def2009-12-18 20:14:40 +00001196/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1197/// and recursively continue updating all of its uses.
1198void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1199 SmallVector<AllocaInst*, 32> &NewElts) {
1200 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1201 if (BC->getOperand(0) != AI)
1202 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001203
Bob Wilsonb742def2009-12-18 20:14:40 +00001204 // The bitcast references the original alloca. Replace its uses with
1205 // references to the first new element alloca.
1206 Instruction *Val = NewElts[0];
1207 if (Val->getType() != BC->getDestTy()) {
1208 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1209 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001210 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001211 BC->replaceAllUsesWith(Val);
1212 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001213}
1214
Bob Wilsonb742def2009-12-18 20:14:40 +00001215/// FindElementAndOffset - Return the index of the element containing Offset
1216/// within the specified type, which must be either a struct or an array.
1217/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001218/// element. IdxTy is set to the type of the index result to be used in a
1219/// GEP instruction.
1220uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1221 const Type *&IdxTy) {
1222 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001223 if (const StructType *ST = dyn_cast<StructType>(T)) {
1224 const StructLayout *Layout = TD->getStructLayout(ST);
1225 Idx = Layout->getElementContainingOffset(Offset);
1226 T = ST->getContainedType(Idx);
1227 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001228 IdxTy = Type::getInt32Ty(T->getContext());
1229 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001230 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001231 const ArrayType *AT = cast<ArrayType>(T);
1232 T = AT->getElementType();
1233 uint64_t EltSize = TD->getTypeAllocSize(T);
1234 Idx = Offset / EltSize;
1235 Offset -= Idx * EltSize;
1236 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001237 return Idx;
1238}
1239
1240/// RewriteGEP - Check if this GEP instruction moves the pointer across
1241/// elements of the alloca that are being split apart, and if so, rewrite
1242/// the GEP to be relative to the new element.
1243void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1244 SmallVector<AllocaInst*, 32> &NewElts) {
1245 uint64_t OldOffset = Offset;
1246 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1247 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1248 &Indices[0], Indices.size());
1249
1250 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1251
1252 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001253 const Type *IdxTy;
1254 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001255 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001256 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001257
1258 T = AI->getAllocatedType();
1259 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001260 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001261
1262 // If this GEP does not move the pointer across elements of the alloca
1263 // being split, then it does not needs to be rewritten.
1264 if (Idx == OldIdx)
1265 return;
1266
1267 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1268 SmallVector<Value*, 8> NewArgs;
1269 NewArgs.push_back(Constant::getNullValue(i32Ty));
1270 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001271 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1272 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001273 }
1274 Instruction *Val = NewElts[Idx];
1275 if (NewArgs.size() > 1) {
1276 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1277 NewArgs.end(), "", GEPI);
1278 Val->takeName(GEPI);
1279 }
1280 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001281 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001282 GEPI->replaceAllUsesWith(Val);
1283 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001284}
1285
1286/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1287/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001288void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001289 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001290 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001291 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001292 // appropriate type. The "Other" pointer is the pointer that goes to memory
1293 // that doesn't have anything to do with the alloca that we are promoting. For
1294 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001295 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001296 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001297 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001298 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001299 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001300 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001301 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001302 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001303 }
1304 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001305
Chris Lattnerd93afec2009-01-07 07:18:45 +00001306 // If there is an other pointer, we want to convert it to the same pointer
1307 // type as AI has, so we can GEP through it safely.
1308 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001309 unsigned AddrSpace =
1310 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001311
1312 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1313 // optimization, but it's also required to detect the corner case where
1314 // both pointer operands are referencing the same memory, and where
1315 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1316 // function is only called for mem intrinsics that access the whole
1317 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001318 OtherPtr = OtherPtr->stripPointerCasts();
1319
Bob Wilsona756b1d2010-01-19 04:32:48 +00001320 // Copying the alloca to itself is a no-op: just delete it.
1321 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1322 // This code will run twice for a no-op memcpy -- once for each operand.
1323 // Put only one reference to MI on the DeadInsts list.
1324 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1325 E = DeadInsts.end(); I != E; ++I)
1326 if (*I == MI) return;
1327 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001328 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001329 }
Chris Lattner372dda82007-03-05 07:52:57 +00001330
Chris Lattnerd93afec2009-01-07 07:18:45 +00001331 // If the pointer is not the right type, insert a bitcast to the right
1332 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001333 const Type *NewTy =
1334 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1335
1336 if (OtherPtr->getType() != NewTy)
1337 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001338 }
1339
1340 // Process each element of the aggregate.
Gabor Greifa9b23132010-04-20 13:13:04 +00001341 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001342 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +00001343 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +00001344
Owen Anderson1d0be152009-08-13 21:58:54 +00001345 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001346
1347 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1348 // If this is a memcpy/memmove, emit a GEP of the other element address.
1349 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001350 unsigned OtherEltAlign = MemAlignment;
1351
Bob Wilsona756b1d2010-01-19 04:32:48 +00001352 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001353 Value *Idx[2] = { Zero,
1354 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001355 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001356 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001357 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001358 uint64_t EltOffset;
1359 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001360 const Type *OtherTy = OtherPtrTy->getElementType();
1361 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001362 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1363 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001364 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001365 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001366 }
1367
1368 // The alignment of the other pointer is the guaranteed alignment of the
1369 // element, which is affected by both the known alignment of the whole
1370 // mem intrinsic and the alignment of the element. If the alignment of
1371 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1372 // known alignment is just 4 bytes.
1373 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00001374 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001375
1376 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00001377 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001378
1379 // If we got down to a scalar, insert a load or store as appropriate.
1380 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001381 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001382 if (SROADest) {
1383 // From Other to Alloca.
1384 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1385 new StoreInst(Elt, EltPtr, MI);
1386 } else {
1387 // From Alloca to Other.
1388 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1389 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1390 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001391 continue;
1392 }
1393 assert(isa<MemSetInst>(MI));
1394
1395 // If the stored element is zero (common case), just store a null
1396 // constant.
1397 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001398 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001399 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001400 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00001401 } else {
1402 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00001403 const Type *ValTy = EltTy->getScalarType();
1404
Chris Lattnerd93afec2009-01-07 07:18:45 +00001405 // Construct an integer with the right value.
1406 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1407 APInt OneVal(EltSize, CI->getZExtValue());
1408 APInt TotalVal(OneVal);
1409 // Set each byte.
1410 for (unsigned i = 0; 8*i < EltSize; ++i) {
1411 TotalVal = TotalVal.shl(8);
1412 TotalVal |= OneVal;
1413 }
1414
1415 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001416 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001417 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001418 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001419 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001420 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001421 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1422
1423 // If the requested value was a vector constant, create it.
1424 if (EltTy != ValTy) {
1425 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1426 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +00001427 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001428 }
1429 }
1430 new StoreInst(StoreVal, EltPtr, MI);
1431 continue;
1432 }
1433 // Otherwise, if we're storing a byte variable, use a memset call for
1434 // this element.
1435 }
1436
1437 // Cast the element pointer to BytePtrTy.
1438 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001439 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001440
1441 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +00001442 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1443 // Preserve address space of OtherElt
1444 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1445 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1446 if (OtherPTy->getElementType() != PTy->getElementType()) {
1447 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1448 OtherPTy->getAddressSpace());
1449 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
Benjamin Krameraf812352010-10-16 11:28:23 +00001450 OtherElt->getName(), MI);
Mon P Wang20adc9d2010-04-04 03:10:48 +00001451 }
1452 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00001453
Duncan Sands777d2302009-05-09 07:06:46 +00001454 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001455
1456 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001457 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001458 Value *Ops[] = {
1459 SROADest ? EltPtr : OtherElt, // Dest ptr
1460 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001461 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +00001462 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +00001463 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1464 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +00001465 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001466 // In case we fold the address space overloaded memcpy of A to B
1467 // with memcpy of B to C, change the function to be a memcpy of A to C.
1468 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1469 Ops[2]->getType() };
1470 Module *M = MI->getParent()->getParent()->getParent();
1471 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1472 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001473 } else {
1474 assert(isa<MemSetInst>(MI));
1475 Value *Ops[] = {
Gabor Greif6f14c8c2010-06-30 09:16:16 +00001476 EltPtr, MI->getArgOperand(1), // Dest, Value,
1477 ConstantInt::get(MI->getArgOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +00001478 Zero, // Align
1479 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +00001480 };
Mon P Wang20adc9d2010-04-04 03:10:48 +00001481 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1482 Module *M = MI->getParent()->getParent()->getParent();
1483 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1484 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001485 }
Chris Lattner372dda82007-03-05 07:52:57 +00001486 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001487 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00001488}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001489
Bob Wilson39fdd692009-12-04 21:57:37 +00001490/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001491/// overwrites the entire allocation. Extract out the pieces of the stored
1492/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001493void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001494 SmallVector<AllocaInst*, 32> &NewElts){
1495 // Extract each element out of the integer according to its structure offset
1496 // and store the element value to the individual alloca.
1497 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00001498 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001499 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001500
Eli Friedman41b33f42009-06-01 09:14:32 +00001501 // Handle tail padding by extending the operand
1502 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001503 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001504 IntegerType::get(SI->getContext(), AllocaSizeBits),
1505 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001506
David Greene504c7d82010-01-05 01:27:09 +00001507 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00001508 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001509
1510 // There are two forms here: AI could be an array or struct. Both cases
1511 // have different ways to compute the element offset.
1512 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1513 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1514
1515 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1516 // Get the number of bits to shift SrcVal to get the value.
1517 const Type *FieldTy = EltSTy->getElementType(i);
1518 uint64_t Shift = Layout->getElementOffsetInBits(i);
1519
1520 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00001521 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001522
1523 Value *EltVal = SrcVal;
1524 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001525 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001526 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1527 "sroa.store.elt", SI);
1528 }
1529
1530 // Truncate down to an integer of the right size.
1531 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +00001532
1533 // Ignore zero sized fields like {}, they obviously contain no data.
1534 if (FieldSizeBits == 0) continue;
1535
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001536 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001537 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001538 IntegerType::get(SI->getContext(), FieldSizeBits),
1539 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001540 Value *DestField = NewElts[i];
1541 if (EltVal->getType() == FieldTy) {
1542 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00001543 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001544 // Bitcast to the right element type (for fp/vector values).
1545 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1546 } else {
1547 // Otherwise, bitcast the dest pointer (for aggregates).
1548 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001549 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001550 "", SI);
1551 }
1552 new StoreInst(EltVal, DestField, SI);
1553 }
1554
1555 } else {
1556 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1557 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001558 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001559 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1560
1561 uint64_t Shift;
1562
1563 if (TD->isBigEndian())
1564 Shift = AllocaSizeBits-ElementOffset;
1565 else
1566 Shift = 0;
1567
1568 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001569 // Ignore zero sized fields like {}, they obviously contain no data.
1570 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001571
1572 Value *EltVal = SrcVal;
1573 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001574 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001575 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1576 "sroa.store.elt", SI);
1577 }
1578
1579 // Truncate down to an integer of the right size.
1580 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001581 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001582 IntegerType::get(SI->getContext(),
1583 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001584 Value *DestField = NewElts[i];
1585 if (EltVal->getType() == ArrayEltTy) {
1586 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001587 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001588 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001589 // Bitcast to the right element type (for fp/vector values).
1590 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1591 } else {
1592 // Otherwise, bitcast the dest pointer (for aggregates).
1593 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001594 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001595 "", SI);
1596 }
1597 new StoreInst(EltVal, DestField, SI);
1598
1599 if (TD->isBigEndian())
1600 Shift -= ElementOffset;
1601 else
1602 Shift += ElementOffset;
1603 }
1604 }
1605
Bob Wilsonb742def2009-12-18 20:14:40 +00001606 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001607}
1608
Bob Wilson39fdd692009-12-04 21:57:37 +00001609/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001610/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001611void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001612 SmallVector<AllocaInst*, 32> &NewElts) {
1613 // Extract each element out of the NewElts according to its structure offset
1614 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001615 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001616 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001617
David Greene504c7d82010-01-05 01:27:09 +00001618 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001619 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001620
1621 // There are two forms here: AI could be an array or struct. Both cases
1622 // have different ways to compute the element offset.
1623 const StructLayout *Layout = 0;
1624 uint64_t ArrayEltBitOffset = 0;
1625 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1626 Layout = TD->getStructLayout(EltSTy);
1627 } else {
1628 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001629 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001630 }
Owen Andersone922c022009-07-22 00:24:57 +00001631
Owen Andersone922c022009-07-22 00:24:57 +00001632 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001633 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001634
1635 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1636 // Load the value from the alloca. If the NewElt is an aggregate, cast
1637 // the pointer to an integer of the same size before doing the load.
1638 Value *SrcField = NewElts[i];
1639 const Type *FieldTy =
1640 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001641 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1642
1643 // Ignore zero sized fields like {}, they obviously contain no data.
1644 if (FieldSizeBits == 0) continue;
1645
Owen Anderson1d0be152009-08-13 21:58:54 +00001646 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1647 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001648 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1649 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001650 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001651 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001652 "", LI);
1653 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1654
1655 // If SrcField is a fp or vector of the right size but that isn't an
1656 // integer type, bitcast to an integer so we can shift it.
1657 if (SrcField->getType() != FieldIntTy)
1658 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1659
1660 // Zero extend the field to be the same size as the final alloca so that
1661 // we can shift and insert it.
1662 if (SrcField->getType() != ResultVal->getType())
1663 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1664
1665 // Determine the number of bits to shift SrcField.
1666 uint64_t Shift;
1667 if (Layout) // Struct case.
1668 Shift = Layout->getElementOffsetInBits(i);
1669 else // Array case.
1670 Shift = i*ArrayEltBitOffset;
1671
1672 if (TD->isBigEndian())
1673 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1674
1675 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001676 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001677 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1678 }
1679
Chris Lattner14952472010-06-27 07:58:26 +00001680 // Don't create an 'or x, 0' on the first iteration.
1681 if (!isa<Constant>(ResultVal) ||
1682 !cast<Constant>(ResultVal)->isNullValue())
1683 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1684 else
1685 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001686 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001687
1688 // Handle tail padding by truncating the result
1689 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1690 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1691
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001692 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001693 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001694}
1695
Duncan Sands3cb36502007-11-04 14:43:57 +00001696/// HasPadding - Return true if the specified type has any structure or
1697/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001698static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner91abace2010-09-01 05:14:33 +00001699 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty))
1700 return HasPadding(ATy->getElementType(), TD);
1701
1702 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
1703 return HasPadding(VTy->getElementType(), TD);
1704
Chris Lattner39a1c042007-05-30 06:11:23 +00001705 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1706 const StructLayout *SL = TD.getStructLayout(STy);
1707 unsigned PrevFieldBitOffset = 0;
1708 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001709 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1710
Chris Lattner39a1c042007-05-30 06:11:23 +00001711 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001712 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001713 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001714
Chris Lattner39a1c042007-05-30 06:11:23 +00001715 // Check to see if there is any padding between this element and the
1716 // previous one.
1717 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001718 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001719 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1720 if (PrevFieldEnd < FieldBitOffset)
1721 return true;
1722 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001723
Chris Lattner39a1c042007-05-30 06:11:23 +00001724 PrevFieldBitOffset = FieldBitOffset;
1725 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001726
Chris Lattner39a1c042007-05-30 06:11:23 +00001727 // Check for tail padding.
1728 if (unsigned EltCount = STy->getNumElements()) {
1729 unsigned PrevFieldEnd = PrevFieldBitOffset +
1730 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001731 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001732 return true;
1733 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001734 }
Chris Lattner91abace2010-09-01 05:14:33 +00001735
Duncan Sands777d2302009-05-09 07:06:46 +00001736 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001737}
Chris Lattner372dda82007-03-05 07:52:57 +00001738
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001739/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1740/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1741/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001742bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001743 // Loop over the use list of the alloca. We can only transform it if all of
1744 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001745 AllocaInfo Info;
1746
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001747 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001748 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001749 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001750 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001751 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001752
1753 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1754 // source and destination, we have to be careful. In particular, the memcpy
1755 // could be moving around elements that live in structure padding of the LLVM
1756 // types, but may actually be used. In these cases, we refuse to promote the
1757 // struct.
1758 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001759 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001760 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001761
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001762 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001763}
Chris Lattnera1888942005-12-12 07:19:13 +00001764
Chris Lattner800de312008-02-29 07:03:13 +00001765
Chris Lattner79b3bd32007-04-25 06:40:51 +00001766
1767/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1768/// some part of a constant global variable. This intentionally only accepts
1769/// constant expressions because we don't can't rewrite arbitrary instructions.
1770static bool PointsToConstantGlobal(Value *V) {
1771 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1772 return GV->isConstant();
1773 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1774 if (CE->getOpcode() == Instruction::BitCast ||
1775 CE->getOpcode() == Instruction::GetElementPtr)
1776 return PointsToConstantGlobal(CE->getOperand(0));
1777 return false;
1778}
1779
1780/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1781/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1782/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1783/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1784/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1785/// the alloca, and if the source pointer is a pointer to a constant global, we
1786/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001787static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001788 bool isOffset) {
1789 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001790 User *U = cast<Instruction>(*UI);
1791
Chris Lattner2e618492010-11-18 06:20:47 +00001792 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001793 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00001794 if (LI->isVolatile()) return false;
1795 continue;
1796 }
Chris Lattner6e733d32009-01-28 20:16:43 +00001797
Gabor Greif8a8a4352010-04-06 19:32:30 +00001798 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001799 // If uses of the bitcast are ok, we are ok.
1800 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1801 return false;
1802 continue;
1803 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001804 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001805 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1806 // doesn't, it does.
1807 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1808 isOffset || !GEP->hasAllZeroIndices()))
1809 return false;
1810 continue;
1811 }
1812
1813 // If this is isn't our memcpy/memmove, reject it as something we can't
1814 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001815 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1816 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001817 return false;
Chris Lattner2e618492010-11-18 06:20:47 +00001818
1819 // If the transfer is using the alloca as a source of the transfer, then
1820 // it (unless the transfer is volatile).
1821 if (UI.getOperandNo() == 1) {
1822 if (MI->isVolatile()) return false;
1823 continue;
1824 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00001825
1826 // If we already have seen a copy, reject the second one.
1827 if (TheCopy) return false;
1828
1829 // If the pointer has been offset from the start of the alloca, we can't
1830 // safely handle this.
1831 if (isOffset) return false;
1832
1833 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00001834 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001835
Chris Lattner79b3bd32007-04-25 06:40:51 +00001836 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001837 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001838 return false;
1839
1840 // Otherwise, the transform is safe. Remember the copy instruction.
1841 TheCopy = MI;
1842 }
1843 return true;
1844}
1845
1846/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1847/// modified by a copy from a constant global. If we can prove this, we can
1848/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001849MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1850 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001851 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1852 return TheCopy;
1853 return 0;
1854}