blob: 5644b0e9096cbd39266c31a24d4c9b65a3380aab [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000033#include "llvm/Analysis/DIBuilder.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000034#include "llvm/Analysis/Dominators.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000035#include "llvm/Analysis/Loads.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000036#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000039#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000040#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000041#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000042#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000043#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000044#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000045#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000046#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000047#include "llvm/Support/raw_ostream.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000048#include "llvm/ADT/SetVector.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000049#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000051using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000052
Chris Lattner0e5f4992006-12-19 21:40:18 +000053STATISTIC(NumReplaced, "Number of allocas broken up");
54STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnerc87c50a2011-01-23 22:04:55 +000055STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner0e5f4992006-12-19 21:40:18 +000056STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000057STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000058
Chris Lattner0e5f4992006-12-19 21:40:18 +000059namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000060 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000061 SROA(int T, bool hasDT, char &ID)
62 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000063 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000064 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000065 else
66 SRThreshold = T;
67 }
Devang Patel794fd752007-05-01 21:15:47 +000068
Chris Lattnered7b41e2003-05-27 15:45:27 +000069 bool runOnFunction(Function &F);
70
Chris Lattner38aec322003-09-11 16:45:55 +000071 bool performScalarRepl(Function &F);
72 bool performPromotion(Function &F);
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000075 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000076 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000077
Bob Wilsonb742def2009-12-18 20:14:40 +000078 /// DeadInsts - Keep track of instructions we have made dead, so that
79 /// we can remove them after we are done working.
80 SmallVector<Value*, 32> DeadInsts;
81
Chris Lattner39a1c042007-05-30 06:11:23 +000082 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
83 /// information about the uses. All these fields are initialized to false
84 /// and set to true when something is learned.
85 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000086 /// The alloca to promote.
87 AllocaInst *AI;
88
Chris Lattner145c5322011-01-23 08:27:54 +000089 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
90 /// looping and avoid redundant work.
91 SmallPtrSet<PHINode*, 8> CheckedPHIs;
92
Chris Lattner39a1c042007-05-30 06:11:23 +000093 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
94 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000095
Chris Lattner39a1c042007-05-30 06:11:23 +000096 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
97 bool isMemCpySrc : 1;
98
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000099 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +0000100 bool isMemCpyDst : 1;
101
Chris Lattner7e9b4272011-01-16 06:18:28 +0000102 /// hasSubelementAccess - This is true if a subelement of the alloca is
103 /// ever accessed, or false if the alloca is only accessed with mem
104 /// intrinsics or load/store that only access the entire alloca at once.
105 bool hasSubelementAccess : 1;
106
107 /// hasALoadOrStore - This is true if there are any loads or stores to it.
108 /// The alloca may just be accessed with memcpy, for example, which would
109 /// not set this.
110 bool hasALoadOrStore : 1;
111
Chris Lattner6c95d242011-01-23 07:29:29 +0000112 explicit AllocaInfo(AllocaInst *ai)
113 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000114 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000115 };
Bob Wilson69743022011-01-13 20:59:44 +0000116
Devang Patelff366852007-07-09 21:19:23 +0000117 unsigned SRThreshold;
118
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000119 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
120 I.isUnsafe = true;
121 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
122 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000123
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000124 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000125
Chris Lattner6c95d242011-01-23 07:29:29 +0000126 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000127 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
128 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000129 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
130 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000131 const Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000132 Instruction *TheAccess, bool AllowWholeAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +0000133 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000134 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
135 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000136
137 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000138 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000139 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000140
Bob Wilsonb742def2009-12-18 20:14:40 +0000141 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
142 SmallVector<AllocaInst*, 32> &NewElts);
143 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
144 SmallVector<AllocaInst*, 32> &NewElts);
145 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
146 SmallVector<AllocaInst*, 32> &NewElts);
147 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000148 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000149 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000150 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000151 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000152 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000153 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000154
Chris Lattner31d80102010-04-15 21:59:20 +0000155 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000156 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000157
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000158 // SROA_DT - SROA that uses DominatorTree.
159 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000160 static char ID;
161 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000162 SROA_DT(int T = -1) : SROA(T, true, ID) {
163 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000164 }
165
166 // getAnalysisUsage - This pass does not require any passes, but we know it
167 // will not alter the CFG, so say so.
168 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
169 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000170 AU.setPreservesCFG();
171 }
172 };
173
174 // SROA_SSAUp - SROA that uses SSAUpdater.
175 struct SROA_SSAUp : public SROA {
176 static char ID;
177 public:
178 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
179 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
180 }
181
182 // getAnalysisUsage - This pass does not require any passes, but we know it
183 // will not alter the CFG, so say so.
184 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
185 AU.setPreservesCFG();
186 }
187 };
188
Chris Lattnered7b41e2003-05-27 15:45:27 +0000189}
190
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000191char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000192char SROA_SSAUp::ID = 0;
193
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000194INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
195 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000196INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000197INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
198 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000199
200INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
201 "Scalar Replacement of Aggregates (SSAUp)", false, false)
202INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
203 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000204
Brian Gaeked0fde302003-11-11 22:41:34 +0000205// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000206FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000207 bool UseDomTree) {
208 if (UseDomTree)
209 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000210 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000211}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000212
213
Chris Lattner4cc576b2010-04-16 00:24:57 +0000214//===----------------------------------------------------------------------===//
215// Convert To Scalar Optimization.
216//===----------------------------------------------------------------------===//
217
218namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000219/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
220/// optimization, which scans the uses of an alloca and determines if it can
221/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000222class ConvertToScalarInfo {
Cameron Zwarichd4c9c3e2011-03-16 00:13:35 +0000223 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000224 unsigned AllocaSize;
225 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000226
Chris Lattnera0bada72010-04-16 02:32:17 +0000227 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000228 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000229 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000230
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000231 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
232 /// computed based on the uses of the alloca rather than the LLVM type system.
233 enum {
234 Unknown,
235 Vector,
236 Integer
237 } ScalarKind;
238
Chris Lattnera001b662010-04-16 00:38:19 +0000239 /// VectorTy - This tracks the type that we should promote the vector to if
240 /// it is possible to turn it into a vector. This starts out null, and if it
241 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000242 const VectorType *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000243
Chris Lattnera001b662010-04-16 00:38:19 +0000244 /// HadAVector - True if there is at least one vector access to the alloca.
245 /// We don't want to turn random arrays into vectors and use vector element
246 /// insert/extract, but if there are element accesses to something that is
247 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000248 bool HadAVector;
249
Cameron Zwarich1bcdb6f2011-03-16 08:13:42 +0000250 /// HadNonMemTransferAccess - True if there is at least one access to the
251 /// alloca that is not a MemTransferInst. We don't want to turn structs into
252 /// large integers unless there is some potential for optimization.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000253 bool HadNonMemTransferAccess;
254
Chris Lattner4cc576b2010-04-16 00:24:57 +0000255public:
256 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000257 : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
258 VectorTy(0), HadAVector(false), HadNonMemTransferAccess(false) { }
Bob Wilson69743022011-01-13 20:59:44 +0000259
Chris Lattnera001b662010-04-16 00:38:19 +0000260 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000261
Chris Lattner4cc576b2010-04-16 00:24:57 +0000262private:
263 bool CanConvertToScalar(Value *V, uint64_t Offset);
Cameron Zwarichdd689122011-06-13 21:44:31 +0000264 void MergeInType(const Type *In, uint64_t Offset);
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000265 bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000266 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000267
Chris Lattner4cc576b2010-04-16 00:24:57 +0000268 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
269 uint64_t Offset, IRBuilder<> &Builder);
270 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
271 uint64_t Offset, IRBuilder<> &Builder);
272};
273} // end anonymous namespace.
274
Chris Lattner91abace2010-09-01 05:14:33 +0000275
Chris Lattnera001b662010-04-16 00:38:19 +0000276/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
277/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
278/// alloca if possible or null if not.
279AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
280 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
281 // out.
282 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
283 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000284
Chris Lattnera001b662010-04-16 00:38:19 +0000285 // If we were able to find a vector type that can handle this with
286 // insert/extract elements, and if there was at least one use that had
287 // a vector type, promote this to a vector. We don't want to promote
288 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
289 // we just get a lot of insert/extracts. If at least one vector is
290 // involved, then we probably really do have a union of vector/array.
291 const Type *NewTy;
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000292 if (ScalarKind != Integer && VectorTy && HadAVector) {
Chris Lattnera001b662010-04-16 00:38:19 +0000293 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
294 << *VectorTy << '\n');
295 NewTy = VectorTy; // Use the vector type.
296 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000297 unsigned BitWidth = AllocaSize * 8;
298 if (!HadAVector && !HadNonMemTransferAccess &&
299 !TD.fitsInLegalInteger(BitWidth))
300 return 0;
301
Chris Lattnera001b662010-04-16 00:38:19 +0000302 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
303 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000304 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000305 }
306 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
307 ConvertUsesToScalar(AI, NewAI, 0);
308 return NewAI;
309}
310
311/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
312/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000313///
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000314/// There are three cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000315/// 1) A union of vector types of the same size and potentially its elements.
316/// Here we turn element accesses into insert/extract element operations.
317/// This promotes a <4 x float> with a store of float to the third element
318/// into a <4 x float> that uses insert element.
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000319/// 2) A union of vector types with power-of-2 size differences, e.g. a float,
320/// <2 x float> and <4 x float>. Here we turn element accesses into insert
321/// and extract element operations, and <2 x float> accesses into a cast to
322/// <2 x double>, an extract, and a cast back to <2 x float>.
323/// 3) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000324/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000325/// and stores would mutate the memory. We mark this by setting VectorTy
326/// to VoidTy.
Cameron Zwarichdd689122011-06-13 21:44:31 +0000327void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000328 // If we already decided to turn this into a blob of integer memory, there is
329 // nothing to be done.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000330 if (ScalarKind == Integer)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000331 return;
Bob Wilson69743022011-01-13 20:59:44 +0000332
Chris Lattner4cc576b2010-04-16 00:24:57 +0000333 // If this could be contributing to a vector, analyze it.
334
335 // If the In type is a vector that is the same size as the alloca, see if it
336 // matches the existing VecTy.
337 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000338 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000339 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000340 } else if (In->isFloatTy() || In->isDoubleTy() ||
341 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
342 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000343 // Full width accesses can be ignored, because they can always be turned
344 // into bitcasts.
345 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000346 if (EltSize == AllocaSize)
Cameron Zwarich9827b782011-03-29 05:19:52 +0000347 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000348
Chris Lattner4cc576b2010-04-16 00:24:57 +0000349 // If we're accessing something that could be an element of a vector, see
350 // if the implied vector agrees with what we already have and if Offset is
351 // compatible with it.
Cameron Zwarich96cc1d02011-06-09 01:45:33 +0000352 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichc4f78202011-06-09 01:52:44 +0000353 (!VectorTy || Offset * 8 < VectorTy->getPrimitiveSizeInBits())) {
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000354 if (!VectorTy) {
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000355 ScalarKind = Vector;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000356 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000357 return;
358 }
359
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000360 unsigned CurrentEltSize = VectorTy->getElementType()
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000361 ->getPrimitiveSizeInBits()/8;
362 if (EltSize == CurrentEltSize)
363 return;
Cameron Zwarich344731c2011-04-20 21:48:38 +0000364
365 if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
366 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000367 }
368 }
Bob Wilson69743022011-01-13 20:59:44 +0000369
Chris Lattner4cc576b2010-04-16 00:24:57 +0000370 // Otherwise, we have a case that we can't handle with an optimized vector
371 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000372 ScalarKind = Integer;
373 VectorTy = 0;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000374}
375
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000376/// MergeInVectorType - Handles the vector case of MergeInType, returning true
377/// if the type was successfully merged and false otherwise.
378bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
379 uint64_t Offset) {
380 // Remember if we saw a vector type.
381 HadAVector = true;
382
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000383 // TODO: Support nonzero offsets?
384 if (Offset != 0)
385 return false;
386
387 // Only allow vectors that are a power-of-2 away from the size of the alloca.
388 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
389 return false;
390
391 // If this the first vector we see, remember the type so that we know the
392 // element size.
393 if (!VectorTy) {
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000394 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000395 VectorTy = VInTy;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000396 return true;
397 }
398
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000399 unsigned BitWidth = VectorTy->getBitWidth();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000400 unsigned InBitWidth = VInTy->getBitWidth();
401
402 // Vectors of the same size can be converted using a simple bitcast.
403 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8))
404 return true;
405
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000406 const Type *ElementTy = VectorTy->getElementType();
407 const Type *InElementTy = VInTy->getElementType();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000408
409 // Do not allow mixed integer and floating-point accesses from vectors of
410 // different sizes.
411 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
412 return false;
413
414 if (ElementTy->isFloatingPointTy()) {
415 // Only allow floating-point vectors of different sizes if they have the
416 // same element type.
417 // TODO: This could be loosened a bit, but would anything benefit?
418 if (ElementTy != InElementTy)
419 return false;
420
421 // There are no arbitrary-precision floating-point types, which limits the
422 // number of legal vector types with larger element types that we can form
423 // to bitcast and extract a subvector.
424 // TODO: We could support some more cases with mixed fp128 and double here.
425 if (!(BitWidth == 64 || BitWidth == 128) ||
426 !(InBitWidth == 64 || InBitWidth == 128))
427 return false;
428 } else {
429 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
430 "or floating-point.");
431 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
432 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
433
434 // Do not allow integer types smaller than a byte or types whose widths are
435 // not a multiple of a byte.
436 if (BitWidth < 8 || InBitWidth < 8 ||
437 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
438 return false;
439 }
440
441 // Pick the largest of the two vector types.
442 if (InBitWidth > BitWidth)
443 VectorTy = VInTy;
444
445 return true;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000446}
447
Chris Lattner4cc576b2010-04-16 00:24:57 +0000448/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
449/// its accesses to a single vector type, return true and set VecTy to
450/// the new type. If we could convert the alloca into a single promotable
451/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
452/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
453/// is the current offset from the base of the alloca being analyzed.
454///
455/// If we see at least one access to the value that is as a vector type, set the
456/// SawVec flag.
457bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
458 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
459 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000460
Chris Lattner4cc576b2010-04-16 00:24:57 +0000461 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
462 // Don't break volatile loads.
463 if (LI->isVolatile())
464 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000465 // Don't touch MMX operations.
466 if (LI->getType()->isX86_MMXTy())
467 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000468 HadNonMemTransferAccess = true;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000469 MergeInType(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000470 continue;
471 }
Bob Wilson69743022011-01-13 20:59:44 +0000472
Chris Lattner4cc576b2010-04-16 00:24:57 +0000473 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
474 // Storing the pointer, not into the value?
475 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000476 // Don't touch MMX operations.
477 if (SI->getOperand(0)->getType()->isX86_MMXTy())
478 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000479 HadNonMemTransferAccess = true;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000480 MergeInType(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000481 continue;
482 }
Bob Wilson69743022011-01-13 20:59:44 +0000483
Chris Lattner4cc576b2010-04-16 00:24:57 +0000484 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000485 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000486 if (!CanConvertToScalar(BCI, Offset))
487 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000488 continue;
489 }
490
491 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
492 // If this is a GEP with a variable indices, we can't handle it.
493 if (!GEP->hasAllConstantIndices())
494 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000495
Chris Lattner4cc576b2010-04-16 00:24:57 +0000496 // Compute the offset that this GEP adds to the pointer.
497 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
498 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
499 &Indices[0], Indices.size());
500 // See if all uses can be converted.
501 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
502 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000503 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000504 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000505 continue;
506 }
507
508 // If this is a constant sized memset of a constant value (e.g. 0) we can
509 // handle it.
510 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
511 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000512 if (!isa<ConstantInt>(MSI->getValue()) ||
513 !isa<ConstantInt>(MSI->getLength()))
514 return false;
515 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000516 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000517 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000518 }
519
520 // If this is a memcpy or memmove into or out of the whole allocation, we
521 // can handle it like a load or store of the scalar type.
522 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000523 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
524 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
525 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000526
Chris Lattnera001b662010-04-16 00:38:19 +0000527 IsNotTrivial = true; // Can't be mem2reg'd.
528 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000529 }
Bob Wilson69743022011-01-13 20:59:44 +0000530
Chris Lattner4cc576b2010-04-16 00:24:57 +0000531 // Otherwise, we cannot handle this!
532 return false;
533 }
Bob Wilson69743022011-01-13 20:59:44 +0000534
Chris Lattner4cc576b2010-04-16 00:24:57 +0000535 return true;
536}
537
538/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
539/// directly. This happens when we are converting an "integer union" to a
540/// single integer scalar, or when we are converting a "vector union" to a
541/// vector with insert/extractelement instructions.
542///
543/// Offset is an offset from the original alloca, in bits that need to be
544/// shifted to the right. By the end of this, there should be no uses of Ptr.
545void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
546 uint64_t Offset) {
547 while (!Ptr->use_empty()) {
548 Instruction *User = cast<Instruction>(Ptr->use_back());
549
550 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
551 ConvertUsesToScalar(CI, NewAI, Offset);
552 CI->eraseFromParent();
553 continue;
554 }
555
556 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
557 // Compute the offset that this GEP adds to the pointer.
558 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
559 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
560 &Indices[0], Indices.size());
561 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
562 GEP->eraseFromParent();
563 continue;
564 }
Bob Wilson69743022011-01-13 20:59:44 +0000565
Chris Lattner61db1f52010-12-26 22:57:41 +0000566 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000567
Chris Lattner4cc576b2010-04-16 00:24:57 +0000568 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
569 // The load is a bit extract from NewAI shifted right by Offset bits.
570 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
571 Value *NewLoadVal
572 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
573 LI->replaceAllUsesWith(NewLoadVal);
574 LI->eraseFromParent();
575 continue;
576 }
Bob Wilson69743022011-01-13 20:59:44 +0000577
Chris Lattner4cc576b2010-04-16 00:24:57 +0000578 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
579 assert(SI->getOperand(0) != Ptr && "Consistency error!");
580 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
581 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
582 Builder);
583 Builder.CreateStore(New, NewAI);
584 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000585
Chris Lattner4cc576b2010-04-16 00:24:57 +0000586 // If the load we just inserted is now dead, then the inserted store
587 // overwrote the entire thing.
588 if (Old->use_empty())
589 Old->eraseFromParent();
590 continue;
591 }
Bob Wilson69743022011-01-13 20:59:44 +0000592
Chris Lattner4cc576b2010-04-16 00:24:57 +0000593 // If this is a constant sized memset of a constant value (e.g. 0) we can
594 // transform it into a store of the expanded constant value.
595 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
596 assert(MSI->getRawDest() == Ptr && "Consistency error!");
597 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
598 if (NumBytes != 0) {
599 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000600
Chris Lattner4cc576b2010-04-16 00:24:57 +0000601 // Compute the value replicated the right number of times.
602 APInt APVal(NumBytes*8, Val);
603
604 // Splat the value if non-zero.
605 if (Val)
606 for (unsigned i = 1; i != NumBytes; ++i)
607 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000608
Chris Lattner4cc576b2010-04-16 00:24:57 +0000609 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
610 Value *New = ConvertScalar_InsertValue(
611 ConstantInt::get(User->getContext(), APVal),
612 Old, Offset, Builder);
613 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000614
Chris Lattner4cc576b2010-04-16 00:24:57 +0000615 // If the load we just inserted is now dead, then the memset overwrote
616 // the entire thing.
617 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000618 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000619 }
620 MSI->eraseFromParent();
621 continue;
622 }
623
624 // If this is a memcpy or memmove into or out of the whole allocation, we
625 // can handle it like a load or store of the scalar type.
626 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
627 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000628
Chris Lattner4cc576b2010-04-16 00:24:57 +0000629 // If the source and destination are both to the same alloca, then this is
630 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
631 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000632 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000633
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000634 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000635 // Dest must be OrigAI, change this to be a load from the original
636 // pointer (bitcasted), then a store to our new alloca.
637 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
638 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000639 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
640 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
641 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
642 AIPTy = PointerType::get(AIPTy->getElementType(),
643 SPTy->getAddressSpace());
644 }
645 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
646
Chris Lattner4cc576b2010-04-16 00:24:57 +0000647 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
648 SrcVal->setAlignment(MTI->getAlignment());
649 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000650 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000651 // Src must be OrigAI, change this to be a load from NewAI then a store
652 // through the original dest pointer (bitcasted).
653 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
654 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
655
Mon P Wange90a6332010-12-23 01:41:32 +0000656 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
657 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
658 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
659 AIPTy = PointerType::get(AIPTy->getElementType(),
660 DPTy->getAddressSpace());
661 }
662 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
663
Chris Lattner4cc576b2010-04-16 00:24:57 +0000664 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
665 NewStore->setAlignment(MTI->getAlignment());
666 } else {
667 // Noop transfer. Src == Dst
668 }
669
670 MTI->eraseFromParent();
671 continue;
672 }
Bob Wilson69743022011-01-13 20:59:44 +0000673
Chris Lattner4cc576b2010-04-16 00:24:57 +0000674 llvm_unreachable("Unsupported operation!");
675 }
676}
677
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000678/// getScaledElementType - Gets a scaled element type for a partial vector
Cameron Zwarich344731c2011-04-20 21:48:38 +0000679/// access of an alloca. The input types must be integer or floating-point
680/// scalar or vector types, and the resulting type is an integer, float or
681/// double.
682static const Type *getScaledElementType(const Type *Ty1, const Type *Ty2,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000683 unsigned NewBitWidth) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000684 bool IsFP1 = Ty1->isFloatingPointTy() ||
685 (Ty1->isVectorTy() &&
686 cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
687 bool IsFP2 = Ty2->isFloatingPointTy() ||
688 (Ty2->isVectorTy() &&
689 cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000690
Cameron Zwarich344731c2011-04-20 21:48:38 +0000691 LLVMContext &Context = Ty1->getContext();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000692
Cameron Zwarich344731c2011-04-20 21:48:38 +0000693 // Prefer floating-point types over integer types, as integer types may have
694 // been created by earlier scalar replacement.
695 if (IsFP1 || IsFP2) {
696 if (NewBitWidth == 32)
697 return Type::getFloatTy(Context);
698 if (NewBitWidth == 64)
699 return Type::getDoubleTy(Context);
700 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000701
Cameron Zwarich344731c2011-04-20 21:48:38 +0000702 return Type::getIntNTy(Context, NewBitWidth);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000703}
704
Mon P Wangddf9abf2011-04-14 08:04:01 +0000705/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
706/// to another vector of the same element type which has the same allocation
707/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
708static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
709 IRBuilder<> &Builder) {
710 const Type *FromType = FromVal->getType();
Mon P Wang481823a2011-04-14 19:20:42 +0000711 const VectorType *FromVTy = cast<VectorType>(FromType);
712 const VectorType *ToVTy = cast<VectorType>(ToType);
713 assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
Mon P Wangddf9abf2011-04-14 08:04:01 +0000714 "Vectors must have the same element type");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000715 Value *UnV = UndefValue::get(FromType);
716 unsigned numEltsFrom = FromVTy->getNumElements();
717 unsigned numEltsTo = ToVTy->getNumElements();
718
719 SmallVector<Constant*, 3> Args;
Mon P Wang481823a2011-04-14 19:20:42 +0000720 const Type* Int32Ty = Builder.getInt32Ty();
Mon P Wangddf9abf2011-04-14 08:04:01 +0000721 unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
722 unsigned i;
723 for (i=0; i != minNumElts; ++i)
Mon P Wang481823a2011-04-14 19:20:42 +0000724 Args.push_back(ConstantInt::get(Int32Ty, i));
Mon P Wangddf9abf2011-04-14 08:04:01 +0000725
726 if (i < numEltsTo) {
Mon P Wang481823a2011-04-14 19:20:42 +0000727 Constant* UnC = UndefValue::get(Int32Ty);
Mon P Wangddf9abf2011-04-14 08:04:01 +0000728 for (; i != numEltsTo; ++i)
729 Args.push_back(UnC);
730 }
731 Constant *Mask = ConstantVector::get(Args);
732 return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
733}
734
Chris Lattner4cc576b2010-04-16 00:24:57 +0000735/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
736/// or vector value FromVal, extracting the bits from the offset specified by
737/// Offset. This returns the value, which is of type ToType.
738///
739/// This happens when we are converting an "integer union" to a single
740/// integer scalar, or when we are converting a "vector union" to a vector with
741/// insert/extractelement instructions.
742///
743/// Offset is an offset from the original alloca, in bits that need to be
744/// shifted to the right.
745Value *ConvertToScalarInfo::
746ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
747 uint64_t Offset, IRBuilder<> &Builder) {
748 // If the load is of the whole new alloca, no conversion is needed.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000749 const Type *FromType = FromVal->getType();
750 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000751 return FromVal;
752
753 // If the result alloca is a vector type, this is either an element
754 // access or a bitcast to another vector type of the same size.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000755 if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000756 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000757 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000758 if (FromTypeSize == ToTypeSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000759 // If the two types have the same primitive size, use a bit cast.
760 // Otherwise, it is two vectors with the same element type that has
761 // the same allocation size but different number of elements so use
762 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000763 if (FromType->getPrimitiveSizeInBits() ==
764 ToType->getPrimitiveSizeInBits())
765 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000766 else
767 return CreateShuffleVectorCast(FromVal, ToType, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000768 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000769
Cameron Zwarich0398d612011-06-08 22:08:31 +0000770 if (isPowerOf2_64(FromTypeSize / ToTypeSize)) {
Cameron Zwarich344731c2011-04-20 21:48:38 +0000771 assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
772 "of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000773
Cameron Zwarich344731c2011-04-20 21:48:38 +0000774 const Type *CastElementTy = getScaledElementType(FromType, ToType,
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000775 ToTypeSize * 8);
Cameron Zwarich0398d612011-06-08 22:08:31 +0000776 unsigned NumCastVectorElements = FromTypeSize / ToTypeSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000777
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000778 LLVMContext &Context = FromVal->getContext();
779 const Type *CastTy = VectorType::get(CastElementTy,
780 NumCastVectorElements);
781 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000782
783 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
784 unsigned Elt = Offset/EltSize;
785 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000786 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000787 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000788 return Builder.CreateBitCast(Extract, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000789 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000790
791 // Otherwise it must be an element access.
792 unsigned Elt = 0;
793 if (Offset) {
794 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
795 Elt = Offset/EltSize;
796 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
797 }
798 // Return the element extracted out of it.
799 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
800 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
801 if (V->getType() != ToType)
802 V = Builder.CreateBitCast(V, ToType, "tmp");
803 return V;
804 }
Bob Wilson69743022011-01-13 20:59:44 +0000805
Chris Lattner4cc576b2010-04-16 00:24:57 +0000806 // If ToType is a first class aggregate, extract out each of the pieces and
807 // use insertvalue's to form the FCA.
808 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
809 const StructLayout &Layout = *TD.getStructLayout(ST);
810 Value *Res = UndefValue::get(ST);
811 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
812 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
813 Offset+Layout.getElementOffsetInBits(i),
814 Builder);
815 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
816 }
817 return Res;
818 }
Bob Wilson69743022011-01-13 20:59:44 +0000819
Chris Lattner4cc576b2010-04-16 00:24:57 +0000820 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
821 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
822 Value *Res = UndefValue::get(AT);
823 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
824 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
825 Offset+i*EltSize, Builder);
826 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
827 }
828 return Res;
829 }
830
831 // Otherwise, this must be a union that was converted to an integer value.
832 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
833
834 // If this is a big-endian system and the load is narrower than the
835 // full alloca type, we need to do a shift to get the right bits.
836 int ShAmt = 0;
837 if (TD.isBigEndian()) {
838 // On big-endian machines, the lowest bit is stored at the bit offset
839 // from the pointer given by getTypeStoreSizeInBits. This matters for
840 // integers with a bitwidth that is not a multiple of 8.
841 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
842 TD.getTypeStoreSizeInBits(ToType) - Offset;
843 } else {
844 ShAmt = Offset;
845 }
846
847 // Note: we support negative bitwidths (with shl) which are not defined.
848 // We do this to support (f.e.) loads off the end of a structure where
849 // only some bits are used.
850 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
851 FromVal = Builder.CreateLShr(FromVal,
852 ConstantInt::get(FromVal->getType(),
853 ShAmt), "tmp");
854 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000855 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000856 ConstantInt::get(FromVal->getType(),
857 -ShAmt), "tmp");
858
859 // Finally, unconditionally truncate the integer to the right width.
860 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
861 if (LIBitWidth < NTy->getBitWidth())
862 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000863 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000864 LIBitWidth), "tmp");
865 else if (LIBitWidth > NTy->getBitWidth())
866 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000867 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000868 LIBitWidth), "tmp");
869
870 // If the result is an integer, this is a trunc or bitcast.
871 if (ToType->isIntegerTy()) {
872 // Should be done.
873 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
874 // Just do a bitcast, we know the sizes match up.
875 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
876 } else {
877 // Otherwise must be a pointer.
878 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
879 }
880 assert(FromVal->getType() == ToType && "Didn't convert right?");
881 return FromVal;
882}
883
884/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
885/// or vector value "Old" at the offset specified by Offset.
886///
887/// This happens when we are converting an "integer union" to a
888/// single integer scalar, or when we are converting a "vector union" to a
889/// vector with insert/extractelement instructions.
890///
891/// Offset is an offset from the original alloca, in bits that need to be
892/// shifted to the right.
893Value *ConvertToScalarInfo::
894ConvertScalar_InsertValue(Value *SV, Value *Old,
895 uint64_t Offset, IRBuilder<> &Builder) {
896 // Convert the stored type to the actual type, shift it left to insert
897 // then 'or' into place.
898 const Type *AllocaType = Old->getType();
899 LLVMContext &Context = Old->getContext();
900
901 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
902 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
903 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000904
Chris Lattner4cc576b2010-04-16 00:24:57 +0000905 // Changing the whole vector with memset or with an access of a different
906 // vector type?
Mon P Wangbe0761c2011-04-13 21:40:02 +0000907 if (ValSize == VecSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000908 // If the two types have the same primitive size, use a bit cast.
909 // Otherwise, it is two vectors with the same element type that has
910 // the same allocation size but different number of elements so use
911 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000912 if (VTy->getPrimitiveSizeInBits() ==
913 SV->getType()->getPrimitiveSizeInBits())
914 return Builder.CreateBitCast(SV, AllocaType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000915 else
916 return CreateShuffleVectorCast(SV, VTy, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000917 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000918
Cameron Zwarich344731c2011-04-20 21:48:38 +0000919 if (isPowerOf2_64(VecSize / ValSize)) {
920 assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
921 "value of a smaller vector type at a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000922
Cameron Zwarich344731c2011-04-20 21:48:38 +0000923 const Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
924 ValSize);
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000925 unsigned NumCastVectorElements = VecSize / ValSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000926
927 LLVMContext &Context = SV->getContext();
928 const Type *OldCastTy = VectorType::get(CastElementTy,
929 NumCastVectorElements);
930 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
931
932 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
Cameron Zwarich344731c2011-04-20 21:48:38 +0000933
934 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
935 unsigned Elt = Offset/EltSize;
936 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000937 Value *Insert =
938 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
Cameron Zwarich344731c2011-04-20 21:48:38 +0000939 Type::getInt32Ty(Context), Elt), "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000940 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
941 }
942
Chris Lattner4cc576b2010-04-16 00:24:57 +0000943 // Must be an element insertion.
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000944 assert(SV->getType() == VTy->getElementType());
945 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000946 unsigned Elt = Offset/EltSize;
Cameron Zwarichc5c43b92011-04-20 21:48:34 +0000947 return Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000948 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
949 "tmp");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000950 }
Bob Wilson69743022011-01-13 20:59:44 +0000951
Chris Lattner4cc576b2010-04-16 00:24:57 +0000952 // If SV is a first-class aggregate value, insert each value recursively.
953 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
954 const StructLayout &Layout = *TD.getStructLayout(ST);
955 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
956 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000957 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000958 Offset+Layout.getElementOffsetInBits(i),
959 Builder);
960 }
961 return Old;
962 }
Bob Wilson69743022011-01-13 20:59:44 +0000963
Chris Lattner4cc576b2010-04-16 00:24:57 +0000964 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
965 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
966 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
967 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
968 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
969 }
970 return Old;
971 }
972
973 // If SV is a float, convert it to the appropriate integer type.
974 // If it is a pointer, do the same.
975 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
976 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
977 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
978 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
979 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
980 SV = Builder.CreateBitCast(SV,
981 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
982 else if (SV->getType()->isPointerTy())
983 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
984
985 // Zero extend or truncate the value if needed.
986 if (SV->getType() != AllocaType) {
987 if (SV->getType()->getPrimitiveSizeInBits() <
988 AllocaType->getPrimitiveSizeInBits())
989 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
990 else {
991 // Truncation may be needed if storing more than the alloca can hold
992 // (undefined behavior).
993 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
994 SrcWidth = DestWidth;
995 SrcStoreWidth = DestStoreWidth;
996 }
997 }
998
999 // If this is a big-endian system and the store is narrower than the
1000 // full alloca type, we need to do a shift to get the right bits.
1001 int ShAmt = 0;
1002 if (TD.isBigEndian()) {
1003 // On big-endian machines, the lowest bit is stored at the bit offset
1004 // from the pointer given by getTypeStoreSizeInBits. This matters for
1005 // integers with a bitwidth that is not a multiple of 8.
1006 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1007 } else {
1008 ShAmt = Offset;
1009 }
1010
1011 // Note: we support negative bitwidths (with shr) which are not defined.
1012 // We do this to support (f.e.) stores off the end of a structure where
1013 // only some bits in the structure are set.
1014 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1015 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1016 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1017 ShAmt), "tmp");
1018 Mask <<= ShAmt;
1019 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1020 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1021 -ShAmt), "tmp");
1022 Mask = Mask.lshr(-ShAmt);
1023 }
1024
1025 // Mask out the bits we are about to insert from the old value, and or
1026 // in the new bits.
1027 if (SrcWidth != DestWidth) {
1028 assert(DestWidth > SrcWidth);
1029 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1030 SV = Builder.CreateOr(Old, SV, "ins");
1031 }
1032 return SV;
1033}
1034
1035
1036//===----------------------------------------------------------------------===//
1037// SRoA Driver
1038//===----------------------------------------------------------------------===//
1039
1040
Chris Lattnered7b41e2003-05-27 15:45:27 +00001041bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001042 TD = getAnalysisIfAvailable<TargetData>();
1043
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001044 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001045
1046 // FIXME: ScalarRepl currently depends on TargetData more than it
1047 // theoretically needs to. It should be refactored in order to support
1048 // target-independent IR. Until this is done, just skip the actual
1049 // scalar-replacement portion of this pass.
1050 if (!TD) return Changed;
1051
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001052 while (1) {
1053 bool LocalChange = performScalarRepl(F);
1054 if (!LocalChange) break; // No need to repromote if no scalarrepl
1055 Changed = true;
1056 LocalChange = performPromotion(F);
1057 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1058 }
Chris Lattner38aec322003-09-11 16:45:55 +00001059
1060 return Changed;
1061}
1062
Chris Lattnerd0f56132011-01-14 19:50:47 +00001063namespace {
1064class AllocaPromoter : public LoadAndStorePromoter {
1065 AllocaInst *AI;
1066public:
Cameron Zwarichc8279392011-05-24 03:10:43 +00001067 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1068 DbgDeclareInst *DD, DIBuilder *&DB)
1069 : LoadAndStorePromoter(Insts, S, DD, DB), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +00001070
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001071 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +00001072 // Remember which alloca we're promoting (for isInstInList).
1073 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001074 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +00001075 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001076 }
1077
Chris Lattnerd0f56132011-01-14 19:50:47 +00001078 virtual bool isInstInList(Instruction *I,
1079 const SmallVectorImpl<Instruction*> &Insts) const {
1080 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1081 return LI->getOperand(0) == AI;
1082 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001083 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001084};
1085} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001086
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001087/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1088/// subsequently loaded can be rewritten to load both input pointers and then
1089/// select between the result, allowing the load of the alloca to be promoted.
1090/// From this:
1091/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1092/// %V = load i32* %P2
1093/// to:
1094/// %V1 = load i32* %Alloca -> will be mem2reg'd
1095/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001096/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001097///
1098/// We can do this to a select if its only uses are loads and if the operand to
1099/// the select can be loaded unconditionally.
1100static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1101 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1102 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1103
1104 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1105 UI != UE; ++UI) {
1106 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1107 if (LI == 0 || LI->isVolatile()) return false;
1108
Chris Lattnere3357862011-01-24 01:07:11 +00001109 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001110 // (e.g. allocas) or at this point because we can see other accesses to it.
1111 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1112 LI->getAlignment(), TD))
1113 return false;
1114 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1115 LI->getAlignment(), TD))
1116 return false;
1117 }
1118
1119 return true;
1120}
1121
Chris Lattnere3357862011-01-24 01:07:11 +00001122/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1123/// subsequently loaded can be rewritten to load both input pointers in the pred
1124/// blocks and then PHI the results, allowing the load of the alloca to be
1125/// promoted.
1126/// From this:
1127/// %P2 = phi [i32* %Alloca, i32* %Other]
1128/// %V = load i32* %P2
1129/// to:
1130/// %V1 = load i32* %Alloca -> will be mem2reg'd
1131/// ...
1132/// %V2 = load i32* %Other
1133/// ...
1134/// %V = phi [i32 %V1, i32 %V2]
1135///
1136/// We can do this to a select if its only uses are loads and if the operand to
1137/// the select can be loaded unconditionally.
1138static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1139 // For now, we can only do this promotion if the load is in the same block as
1140 // the PHI, and if there are no stores between the phi and load.
1141 // TODO: Allow recursive phi users.
1142 // TODO: Allow stores.
1143 BasicBlock *BB = PN->getParent();
1144 unsigned MaxAlign = 0;
1145 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1146 UI != UE; ++UI) {
1147 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1148 if (LI == 0 || LI->isVolatile()) return false;
1149
1150 // For now we only allow loads in the same block as the PHI. This is a
1151 // common case that happens when instcombine merges two loads through a PHI.
1152 if (LI->getParent() != BB) return false;
1153
1154 // Ensure that there are no instructions between the PHI and the load that
1155 // could store.
1156 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1157 if (BBI->mayWriteToMemory())
1158 return false;
1159
1160 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1161 }
1162
1163 // Okay, we know that we have one or more loads in the same block as the PHI.
1164 // We can transform this if it is safe to push the loads into the predecessor
1165 // blocks. The only thing to watch out for is that we can't put a possibly
1166 // trapping load in the predecessor if it is a critical edge.
1167 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1168 BasicBlock *Pred = PN->getIncomingBlock(i);
1169
1170 // If the predecessor has a single successor, then the edge isn't critical.
1171 if (Pred->getTerminator()->getNumSuccessors() == 1)
1172 continue;
1173
1174 Value *InVal = PN->getIncomingValue(i);
1175
1176 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1177 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1178 if (II->getParent() == Pred)
1179 return false;
1180
1181 // If this pointer is always safe to load, or if we can prove that there is
1182 // already a load in the block, then we can move the load to the pred block.
1183 if (InVal->isDereferenceablePointer() ||
1184 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1185 continue;
1186
1187 return false;
1188 }
1189
1190 return true;
1191}
1192
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001193
1194/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1195/// direct (non-volatile) loads and stores to it. If the alloca is close but
1196/// not quite there, this will transform the code to allow promotion. As such,
1197/// it is a non-pure predicate.
1198static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1199 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1200 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1201
1202 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1203 UI != UE; ++UI) {
1204 User *U = *UI;
1205 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1206 if (LI->isVolatile())
1207 return false;
1208 continue;
1209 }
1210
1211 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1212 if (SI->getOperand(0) == AI || SI->isVolatile())
1213 return false; // Don't allow a store OF the AI, only INTO the AI.
1214 continue;
1215 }
1216
1217 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1218 // If the condition being selected on is a constant, fold the select, yes
1219 // this does (rarely) happen early on.
1220 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1221 Value *Result = SI->getOperand(1+CI->isZero());
1222 SI->replaceAllUsesWith(Result);
1223 SI->eraseFromParent();
1224
1225 // This is very rare and we just scrambled the use list of AI, start
1226 // over completely.
1227 return tryToMakeAllocaBePromotable(AI, TD);
1228 }
1229
1230 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1231 // loads, then we can transform this by rewriting the select.
1232 if (!isSafeSelectToSpeculate(SI, TD))
1233 return false;
1234
1235 InstsToRewrite.insert(SI);
1236 continue;
1237 }
1238
Chris Lattnere3357862011-01-24 01:07:11 +00001239 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1240 if (PN->use_empty()) { // Dead PHIs can be stripped.
1241 InstsToRewrite.insert(PN);
1242 continue;
1243 }
1244
1245 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1246 // in the pred blocks, then we can transform this by rewriting the PHI.
1247 if (!isSafePHIToSpeculate(PN, TD))
1248 return false;
1249
1250 InstsToRewrite.insert(PN);
1251 continue;
1252 }
1253
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001254 return false;
1255 }
1256
1257 // If there are no instructions to rewrite, then all uses are load/stores and
1258 // we're done!
1259 if (InstsToRewrite.empty())
1260 return true;
1261
1262 // If we have instructions that need to be rewritten for this to be promotable
1263 // take care of it now.
1264 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Chris Lattnere3357862011-01-24 01:07:11 +00001265 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1266 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1267 // loads with a new select.
1268 while (!SI->use_empty()) {
1269 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001270
Chris Lattnere3357862011-01-24 01:07:11 +00001271 IRBuilder<> Builder(LI);
1272 LoadInst *TrueLoad =
1273 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1274 LoadInst *FalseLoad =
1275 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1276
1277 // Transfer alignment and TBAA info if present.
1278 TrueLoad->setAlignment(LI->getAlignment());
1279 FalseLoad->setAlignment(LI->getAlignment());
1280 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1281 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1282 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1283 }
1284
1285 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1286 V->takeName(LI);
1287 LI->replaceAllUsesWith(V);
1288 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001289 }
Chris Lattnere3357862011-01-24 01:07:11 +00001290
1291 // Now that all the loads are gone, the select is gone too.
1292 SI->eraseFromParent();
1293 continue;
1294 }
1295
1296 // Otherwise, we have a PHI node which allows us to push the loads into the
1297 // predecessors.
1298 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1299 if (PN->use_empty()) {
1300 PN->eraseFromParent();
1301 continue;
1302 }
1303
1304 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001305 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1306 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001307
1308 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1309 // matter which one we get and if any differ, it doesn't matter.
1310 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1311 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1312 unsigned Align = SomeLoad->getAlignment();
1313
1314 // Rewrite all loads of the PN to use the new PHI.
1315 while (!PN->use_empty()) {
1316 LoadInst *LI = cast<LoadInst>(PN->use_back());
1317 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001318 LI->eraseFromParent();
1319 }
1320
Chris Lattnere3357862011-01-24 01:07:11 +00001321 // Inject loads into all of the pred blocks. Keep track of which blocks we
1322 // insert them into in case we have multiple edges from the same block.
1323 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1324
1325 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1326 BasicBlock *Pred = PN->getIncomingBlock(i);
1327 LoadInst *&Load = InsertedLoads[Pred];
1328 if (Load == 0) {
1329 Load = new LoadInst(PN->getIncomingValue(i),
1330 PN->getName() + "." + Pred->getName(),
1331 Pred->getTerminator());
1332 Load->setAlignment(Align);
1333 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1334 }
1335
1336 NewPN->addIncoming(Load, Pred);
1337 }
1338
1339 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001340 }
1341
1342 ++NumAdjusted;
1343 return true;
1344}
1345
Chris Lattner38aec322003-09-11 16:45:55 +00001346bool SROA::performPromotion(Function &F) {
1347 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001348 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001349 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001350 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001351
Chris Lattner02a3be02003-09-20 14:39:18 +00001352 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +00001353
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001354 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001355 SmallVector<Instruction*, 64> Insts;
Cameron Zwarichc8279392011-05-24 03:10:43 +00001356 DIBuilder *DIB = 0;
Chris Lattner38aec322003-09-11 16:45:55 +00001357 while (1) {
1358 Allocas.clear();
1359
1360 // Find allocas that are safe to promote, by looking at all instructions in
1361 // the entry node
1362 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1363 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001364 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001365 Allocas.push_back(AI);
1366
1367 if (Allocas.empty()) break;
1368
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001369 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001370 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001371 else {
1372 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001373 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1374 AllocaInst *AI = Allocas[i];
1375
1376 // Build list of instructions to promote.
1377 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1378 UI != E; ++UI)
1379 Insts.push_back(cast<Instruction>(*UI));
Cameron Zwarichc8279392011-05-24 03:10:43 +00001380
1381 DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
Cameron Zwarich13a16082011-05-24 06:00:08 +00001382 if (DDI && !DIB)
1383 DIB = new DIBuilder(*AI->getParent()->getParent()->getParent());
Cameron Zwarichc8279392011-05-24 03:10:43 +00001384 AllocaPromoter(Insts, SSA, DDI, DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001385 Insts.clear();
1386 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001387 }
Chris Lattner38aec322003-09-11 16:45:55 +00001388 NumPromoted += Allocas.size();
1389 Changed = true;
1390 }
1391
Cameron Zwarichc8279392011-05-24 03:10:43 +00001392 // FIXME: Is there a better way to handle the lazy initialization of DIB
1393 // so that there doesn't need to be an explicit delete?
1394 delete DIB;
1395
Chris Lattner38aec322003-09-11 16:45:55 +00001396 return Changed;
1397}
1398
Chris Lattner4cc576b2010-04-16 00:24:57 +00001399
Bob Wilson3992feb2010-02-03 17:23:56 +00001400/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1401/// SROA. It must be a struct or array type with a small number of elements.
1402static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1403 const Type *T = AI->getAllocatedType();
1404 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +00001405 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001406 return ST->getNumElements() <= 32;
1407 // Arrays are much less likely to be safe for SROA; only consider
1408 // them if they are very small.
1409 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1410 return AT->getNumElements() <= 8;
1411 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001412}
1413
Chris Lattnerc4472072010-04-15 23:50:26 +00001414
Chris Lattner38aec322003-09-11 16:45:55 +00001415// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1416// which runs on all of the malloc/alloca instructions in the function, removing
1417// them if they are only used by getelementptr instructions.
1418//
1419bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001420 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001421
Chris Lattner31d80102010-04-15 21:59:20 +00001422 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001423 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001424 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001425 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001426 WorkList.push_back(A);
1427
1428 // Process the worklist
1429 bool Changed = false;
1430 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001431 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001432 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001433
Chris Lattneradd2bd72006-12-22 23:14:42 +00001434 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1435 // with unused elements.
1436 if (AI->use_empty()) {
1437 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001438 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001439 continue;
1440 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001441
1442 // If this alloca is impossible for us to promote, reject it early.
1443 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1444 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001445
Chris Lattner79b3bd32007-04-25 06:40:51 +00001446 // Check to see if this allocation is only modified by a memcpy/memmove from
1447 // a constant global. If this is the case, we can change all users to use
1448 // the constant global instead. This is commonly produced by the CFE by
1449 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1450 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +00001451 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +00001452 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1453 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +00001454 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001455 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +00001456 TheCopy->eraseFromParent(); // Don't mutate the global.
1457 AI->eraseFromParent();
1458 ++NumGlobals;
1459 Changed = true;
1460 continue;
1461 }
Bob Wilson69743022011-01-13 20:59:44 +00001462
Chris Lattner7809ecd2009-02-03 01:30:09 +00001463 // Check to see if we can perform the core SROA transformation. We cannot
1464 // transform the allocation instruction if it is an array allocation
1465 // (allocations OF arrays are ok though), and an allocation of a scalar
1466 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001467 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001468
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001469 // Do not promote [0 x %struct].
1470 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001471
Chris Lattner31d80102010-04-15 21:59:20 +00001472 // Do not promote any struct whose size is too big.
1473 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001474
Bob Wilson3992feb2010-02-03 17:23:56 +00001475 // If the alloca looks like a good candidate for scalar replacement, and if
1476 // all its users can be transformed, then split up the aggregate into its
1477 // separate elements.
1478 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1479 DoScalarReplacement(AI, WorkList);
1480 Changed = true;
1481 continue;
1482 }
1483
Chris Lattner6e733d32009-01-28 20:16:43 +00001484 // If we can turn this aggregate value (potentially with casts) into a
1485 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001486 // IsNotTrivial tracks whether this is something that mem2reg could have
1487 // promoted itself. If so, we don't want to transform it needlessly. Note
1488 // that we can't just check based on the type: the alloca may be of an i32
1489 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001490 if (AllocaInst *NewAI =
1491 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001492 NewAI->takeName(AI);
1493 AI->eraseFromParent();
1494 ++NumConverted;
1495 Changed = true;
1496 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001497 }
1498
Chris Lattner7809ecd2009-02-03 01:30:09 +00001499 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001500 }
1501
1502 return Changed;
1503}
Chris Lattner5e062a12003-05-30 04:15:41 +00001504
Chris Lattnera10b29b2007-04-25 05:02:56 +00001505/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1506/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001507void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001508 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001509 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001510 SmallVector<AllocaInst*, 32> ElementAllocas;
1511 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1512 ElementAllocas.reserve(ST->getNumContainedTypes());
1513 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001514 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001515 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001516 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001517 ElementAllocas.push_back(NA);
1518 WorkList.push_back(NA); // Add to worklist for recursive processing
1519 }
1520 } else {
1521 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1522 ElementAllocas.reserve(AT->getNumElements());
1523 const Type *ElTy = AT->getElementType();
1524 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001525 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001526 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001527 ElementAllocas.push_back(NA);
1528 WorkList.push_back(NA); // Add to worklist for recursive processing
1529 }
1530 }
1531
Bob Wilsonb742def2009-12-18 20:14:40 +00001532 // Now that we have created the new alloca instructions, rewrite all the
1533 // uses of the old alloca.
1534 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001535
Bob Wilsonb742def2009-12-18 20:14:40 +00001536 // Now erase any instructions that were made dead while rewriting the alloca.
1537 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001538 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001539
Dan Gohmanfe601042010-06-22 15:08:57 +00001540 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001541}
Chris Lattnera59adc42009-12-14 05:11:02 +00001542
Bob Wilsonb742def2009-12-18 20:14:40 +00001543/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1544/// recursively including all their operands that become trivially dead.
1545void SROA::DeleteDeadInstructions() {
1546 while (!DeadInsts.empty()) {
1547 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001548
Bob Wilsonb742def2009-12-18 20:14:40 +00001549 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1550 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1551 // Zero out the operand and see if it becomes trivially dead.
1552 // (But, don't add allocas to the dead instruction list -- they are
1553 // already on the worklist and will be deleted separately.)
1554 *OI = 0;
1555 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1556 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001557 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001558
1559 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001560 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001561}
Bob Wilson69743022011-01-13 20:59:44 +00001562
Bob Wilsonb742def2009-12-18 20:14:40 +00001563/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1564/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001565/// the Info parameter. Offset indicates the position within AI that is
1566/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001567void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001568 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001569 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1570 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001571
Bob Wilsonb742def2009-12-18 20:14:40 +00001572 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001573 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001574 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001575 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001576 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001577 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001578 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001579 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001580 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001581 if (Length == 0)
1582 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001583 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001584 UI.getOperandNo() == 0, Info, MI,
1585 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001586 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001587 if (LI->isVolatile())
1588 return MarkUnsafe(Info, User);
1589 const Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001590 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001591 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001592 Info.hasALoadOrStore = true;
1593
Bob Wilsonb742def2009-12-18 20:14:40 +00001594 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1595 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001596 if (SI->isVolatile() || SI->getOperand(0) == I)
1597 return MarkUnsafe(Info, User);
1598
1599 const Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001600 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001601 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001602 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001603 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1604 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1605 } else {
1606 return MarkUnsafe(Info, User);
1607 }
1608 if (Info.isUnsafe) return;
1609 }
1610}
1611
1612
1613/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1614/// derived from the alloca, we can often still split the alloca into elements.
1615/// This is useful if we have a large alloca where one element is phi'd
1616/// together somewhere: we can SRoA and promote all the other elements even if
1617/// we end up not being able to promote this one.
1618///
1619/// All we require is that the uses of the PHI do not index into other parts of
1620/// the alloca. The most important use case for this is single load and stores
1621/// that are PHI'd together, which can happen due to code sinking.
1622void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1623 AllocaInfo &Info) {
1624 // If we've already checked this PHI, don't do it again.
1625 if (PHINode *PN = dyn_cast<PHINode>(I))
1626 if (!Info.CheckedPHIs.insert(PN))
1627 return;
1628
1629 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1630 Instruction *User = cast<Instruction>(*UI);
1631
1632 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1633 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1634 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1635 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1636 // but would have to prove that we're staying inside of an element being
1637 // promoted.
1638 if (!GEPI->hasAllZeroIndices())
1639 return MarkUnsafe(Info, User);
1640 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1641 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1642 if (LI->isVolatile())
1643 return MarkUnsafe(Info, User);
1644 const Type *LIType = LI->getType();
1645 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1646 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1647 Info.hasALoadOrStore = true;
1648
1649 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1650 // Store is ok if storing INTO the pointer, not storing the pointer
1651 if (SI->isVolatile() || SI->getOperand(0) == I)
1652 return MarkUnsafe(Info, User);
1653
1654 const Type *SIType = SI->getOperand(0)->getType();
1655 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1656 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1657 Info.hasALoadOrStore = true;
1658 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1659 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001660 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001661 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001662 }
1663 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001664 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001665}
Bob Wilson39c88a62009-12-17 18:34:24 +00001666
Bob Wilsonb742def2009-12-18 20:14:40 +00001667/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1668/// replacement. It is safe when all the indices are constant, in-bounds
1669/// references, and when the resulting offset corresponds to an element within
1670/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001671/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001672void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001673 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001674 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1675 if (GEPIt == E)
1676 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001677
Chris Lattner88e6dc82008-08-23 05:21:06 +00001678 // Walk through the GEP type indices, checking the types that this indexes
1679 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001680 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001681 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001682 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001683 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001684
Bob Wilsonb742def2009-12-18 20:14:40 +00001685 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1686 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001687 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001688 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001689
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001690 // Compute the offset due to this GEP and check if the alloca has a
1691 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001692 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1693 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1694 &Indices[0], Indices.size());
Chris Lattner6c95d242011-01-23 07:29:29 +00001695 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001696 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001697}
1698
Bob Wilson704d1342011-01-13 17:45:11 +00001699/// isHomogeneousAggregate - Check if type T is a struct or array containing
1700/// elements of the same type (which is always true for arrays). If so,
1701/// return true with NumElts and EltTy set to the number of elements and the
1702/// element type, respectively.
1703static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1704 const Type *&EltTy) {
1705 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1706 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001707 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001708 return true;
1709 }
1710 if (const StructType *ST = dyn_cast<StructType>(T)) {
1711 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001712 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001713 for (unsigned n = 1; n < NumElts; ++n) {
1714 if (ST->getContainedType(n) != EltTy)
1715 return false;
1716 }
1717 return true;
1718 }
1719 return false;
1720}
1721
1722/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1723/// "homogeneous" aggregates with the same element type and number of elements.
1724static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1725 if (T1 == T2)
1726 return true;
1727
1728 unsigned NumElts1, NumElts2;
1729 const Type *EltTy1, *EltTy2;
1730 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1731 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1732 NumElts1 == NumElts2 &&
1733 EltTy1 == EltTy2)
1734 return true;
1735
1736 return false;
1737}
1738
Bob Wilsonb742def2009-12-18 20:14:40 +00001739/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1740/// alloca or has an offset and size that corresponds to a component element
1741/// within it. The offset checked here may have been formed from a GEP with a
1742/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001743///
1744/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1745/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001746void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001747 const Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001748 AllocaInfo &Info, Instruction *TheAccess,
1749 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001750 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001751 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001752 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001753 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1754 // loads/stores (which are essentially the same as the MemIntrinsics with
1755 // regard to copying padding between elements). But, if an alloca is
1756 // flagged as both a source and destination of such operations, we'll need
1757 // to check later for padding between elements.
1758 if (!MemOpType || MemOpType->isIntegerTy()) {
1759 if (isStore)
1760 Info.isMemCpyDst = true;
1761 else
1762 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001763 return;
1764 }
Bob Wilson704d1342011-01-13 17:45:11 +00001765 // This is also safe for references using a type that is compatible with
1766 // the type of the alloca, so that loads/stores can be rewritten using
1767 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001768 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001769 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001770 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001771 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001772 }
1773 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner6c95d242011-01-23 07:29:29 +00001774 const Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001775 if (TypeHasComponent(T, Offset, MemSize)) {
1776 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001777 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001778 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001779
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001780 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001781}
1782
1783/// TypeHasComponent - Return true if T has a component type with the
1784/// specified offset and size. If Size is zero, do not check the size.
1785bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1786 const Type *EltTy;
1787 uint64_t EltSize;
1788 if (const StructType *ST = dyn_cast<StructType>(T)) {
1789 const StructLayout *Layout = TD->getStructLayout(ST);
1790 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1791 EltTy = ST->getContainedType(EltIdx);
1792 EltSize = TD->getTypeAllocSize(EltTy);
1793 Offset -= Layout->getElementOffset(EltIdx);
1794 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1795 EltTy = AT->getElementType();
1796 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001797 if (Offset >= AT->getNumElements() * EltSize)
1798 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001799 Offset %= EltSize;
1800 } else {
1801 return false;
1802 }
1803 if (Offset == 0 && (Size == 0 || EltSize == Size))
1804 return true;
1805 // Check if the component spans multiple elements.
1806 if (Offset + Size > EltSize)
1807 return false;
1808 return TypeHasComponent(EltTy, Offset, Size);
1809}
1810
1811/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1812/// the instruction I, which references it, to use the separate elements.
1813/// Offset indicates the position within AI that is referenced by this
1814/// instruction.
1815void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1816 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001817 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1818 Use &TheUse = UI.getUse();
1819 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001820
1821 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1822 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001823 continue;
1824 }
1825
1826 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001827 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001828 continue;
1829 }
1830
1831 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001832 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1833 uint64_t MemSize = Length->getZExtValue();
1834 if (Offset == 0 &&
1835 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1836 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001837 // Otherwise the intrinsic can only touch a single element and the
1838 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001839 continue;
1840 }
1841
1842 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001843 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001844
Bob Wilson704d1342011-01-13 17:45:11 +00001845 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001846 // Replace:
1847 // %res = load { i32, i32 }* %alloc
1848 // with:
1849 // %load.0 = load i32* %alloc.0
1850 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1851 // %load.1 = load i32* %alloc.1
1852 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1853 // (Also works for arrays instead of structs)
1854 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00001855 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001856 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001857 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1858 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00001859 }
1860 LI->replaceAllUsesWith(Insert);
1861 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001862 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001863 TD->getTypeAllocSize(LIType) ==
1864 TD->getTypeAllocSize(AI->getAllocatedType())) {
1865 // If this is a load of the entire alloca to an integer, rewrite it.
1866 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1867 }
Chris Lattner145c5322011-01-23 08:27:54 +00001868 continue;
1869 }
1870
1871 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001872 Value *Val = SI->getOperand(0);
1873 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001874 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001875 // Replace:
1876 // store { i32, i32 } %val, { i32, i32 }* %alloc
1877 // with:
1878 // %val.0 = extractvalue { i32, i32 } %val, 0
1879 // store i32 %val.0, i32* %alloc.0
1880 // %val.1 = extractvalue { i32, i32 } %val, 1
1881 // store i32 %val.1, i32* %alloc.1
1882 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00001883 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001884 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001885 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1886 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00001887 }
1888 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001889 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001890 TD->getTypeAllocSize(SIType) ==
1891 TD->getTypeAllocSize(AI->getAllocatedType())) {
1892 // If this is a store of the entire alloca from an integer, rewrite it.
1893 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1894 }
Chris Lattner145c5322011-01-23 08:27:54 +00001895 continue;
1896 }
1897
1898 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1899 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1900 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1901 // the new pointer.
1902 if (!isa<AllocaInst>(I)) continue;
1903
1904 assert(Offset == 0 && NewElts[0] &&
1905 "Direct alloca use should have a zero offset");
1906
1907 // If we have a use of the alloca, we know the derived uses will be
1908 // utilizing just the first element of the scalarized result. Insert a
1909 // bitcast of the first alloca before the user as required.
1910 AllocaInst *NewAI = NewElts[0];
1911 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1912 NewAI->moveBefore(BCI);
1913 TheUse = BCI;
1914 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001915 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001916 }
1917}
1918
Bob Wilsonb742def2009-12-18 20:14:40 +00001919/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1920/// and recursively continue updating all of its uses.
1921void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1922 SmallVector<AllocaInst*, 32> &NewElts) {
1923 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1924 if (BC->getOperand(0) != AI)
1925 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001926
Bob Wilsonb742def2009-12-18 20:14:40 +00001927 // The bitcast references the original alloca. Replace its uses with
1928 // references to the first new element alloca.
1929 Instruction *Val = NewElts[0];
1930 if (Val->getType() != BC->getDestTy()) {
1931 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1932 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001933 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001934 BC->replaceAllUsesWith(Val);
1935 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001936}
1937
Bob Wilsonb742def2009-12-18 20:14:40 +00001938/// FindElementAndOffset - Return the index of the element containing Offset
1939/// within the specified type, which must be either a struct or an array.
1940/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001941/// element. IdxTy is set to the type of the index result to be used in a
1942/// GEP instruction.
1943uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1944 const Type *&IdxTy) {
1945 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001946 if (const StructType *ST = dyn_cast<StructType>(T)) {
1947 const StructLayout *Layout = TD->getStructLayout(ST);
1948 Idx = Layout->getElementContainingOffset(Offset);
1949 T = ST->getContainedType(Idx);
1950 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001951 IdxTy = Type::getInt32Ty(T->getContext());
1952 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001953 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001954 const ArrayType *AT = cast<ArrayType>(T);
1955 T = AT->getElementType();
1956 uint64_t EltSize = TD->getTypeAllocSize(T);
1957 Idx = Offset / EltSize;
1958 Offset -= Idx * EltSize;
1959 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001960 return Idx;
1961}
1962
1963/// RewriteGEP - Check if this GEP instruction moves the pointer across
1964/// elements of the alloca that are being split apart, and if so, rewrite
1965/// the GEP to be relative to the new element.
1966void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1967 SmallVector<AllocaInst*, 32> &NewElts) {
1968 uint64_t OldOffset = Offset;
1969 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1970 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1971 &Indices[0], Indices.size());
1972
1973 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1974
1975 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001976 const Type *IdxTy;
1977 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001978 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001979 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001980
1981 T = AI->getAllocatedType();
1982 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001983 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001984
1985 // If this GEP does not move the pointer across elements of the alloca
1986 // being split, then it does not needs to be rewritten.
1987 if (Idx == OldIdx)
1988 return;
1989
1990 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1991 SmallVector<Value*, 8> NewArgs;
1992 NewArgs.push_back(Constant::getNullValue(i32Ty));
1993 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001994 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1995 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001996 }
1997 Instruction *Val = NewElts[Idx];
1998 if (NewArgs.size() > 1) {
1999 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
2000 NewArgs.end(), "", GEPI);
2001 Val->takeName(GEPI);
2002 }
2003 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002004 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002005 GEPI->replaceAllUsesWith(Val);
2006 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002007}
2008
2009/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2010/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002011void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002012 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002013 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002014 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002015 // appropriate type. The "Other" pointer is the pointer that goes to memory
2016 // that doesn't have anything to do with the alloca that we are promoting. For
2017 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002018 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002019 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002020 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002021 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002022 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002023 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002024 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002025 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002026 }
2027 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002028
Chris Lattnerd93afec2009-01-07 07:18:45 +00002029 // If there is an other pointer, we want to convert it to the same pointer
2030 // type as AI has, so we can GEP through it safely.
2031 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002032 unsigned AddrSpace =
2033 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002034
2035 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2036 // optimization, but it's also required to detect the corner case where
2037 // both pointer operands are referencing the same memory, and where
2038 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2039 // function is only called for mem intrinsics that access the whole
2040 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002041 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002042
Bob Wilsona756b1d2010-01-19 04:32:48 +00002043 // Copying the alloca to itself is a no-op: just delete it.
2044 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2045 // This code will run twice for a no-op memcpy -- once for each operand.
2046 // Put only one reference to MI on the DeadInsts list.
2047 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2048 E = DeadInsts.end(); I != E; ++I)
2049 if (*I == MI) return;
2050 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002051 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002052 }
Bob Wilson69743022011-01-13 20:59:44 +00002053
Chris Lattnerd93afec2009-01-07 07:18:45 +00002054 // If the pointer is not the right type, insert a bitcast to the right
2055 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00002056 const Type *NewTy =
2057 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002058
Chris Lattner0238f8c2010-07-08 00:27:05 +00002059 if (OtherPtr->getType() != NewTy)
2060 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002061 }
Bob Wilson69743022011-01-13 20:59:44 +00002062
Chris Lattnerd93afec2009-01-07 07:18:45 +00002063 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002064 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002065
Owen Anderson1d0be152009-08-13 21:58:54 +00002066 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002067
2068 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2069 // If this is a memcpy/memmove, emit a GEP of the other element address.
2070 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002071 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002072
Bob Wilsona756b1d2010-01-19 04:32:48 +00002073 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002074 Value *Idx[2] = { Zero,
2075 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00002076 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002077 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002078 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002079 uint64_t EltOffset;
2080 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002081 const Type *OtherTy = OtherPtrTy->getElementType();
2082 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002083 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2084 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002085 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002086 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002087 }
Bob Wilson69743022011-01-13 20:59:44 +00002088
Chris Lattner1541e0f2009-03-04 19:20:50 +00002089 // The alignment of the other pointer is the guaranteed alignment of the
2090 // element, which is affected by both the known alignment of the whole
2091 // mem intrinsic and the alignment of the element. If the alignment of
2092 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2093 // known alignment is just 4 bytes.
2094 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002095 }
Bob Wilson69743022011-01-13 20:59:44 +00002096
Chris Lattnerd93afec2009-01-07 07:18:45 +00002097 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00002098 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002099
Chris Lattnerd93afec2009-01-07 07:18:45 +00002100 // If we got down to a scalar, insert a load or store as appropriate.
2101 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002102 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002103 if (SROADest) {
2104 // From Other to Alloca.
2105 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2106 new StoreInst(Elt, EltPtr, MI);
2107 } else {
2108 // From Alloca to Other.
2109 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2110 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2111 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002112 continue;
2113 }
2114 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002115
Chris Lattnerd93afec2009-01-07 07:18:45 +00002116 // If the stored element is zero (common case), just store a null
2117 // constant.
2118 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002119 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002120 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002121 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002122 } else {
2123 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00002124 const Type *ValTy = EltTy->getScalarType();
2125
Chris Lattnerd93afec2009-01-07 07:18:45 +00002126 // Construct an integer with the right value.
2127 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2128 APInt OneVal(EltSize, CI->getZExtValue());
2129 APInt TotalVal(OneVal);
2130 // Set each byte.
2131 for (unsigned i = 0; 8*i < EltSize; ++i) {
2132 TotalVal = TotalVal.shl(8);
2133 TotalVal |= OneVal;
2134 }
Bob Wilson69743022011-01-13 20:59:44 +00002135
Chris Lattnerd93afec2009-01-07 07:18:45 +00002136 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002137 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002138 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002139 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002140 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002141 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002142 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002143
Chris Lattnerd93afec2009-01-07 07:18:45 +00002144 // If the requested value was a vector constant, create it.
2145 if (EltTy != ValTy) {
2146 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2147 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002148 StoreVal = ConstantVector::get(Elts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002149 }
2150 }
2151 new StoreInst(StoreVal, EltPtr, MI);
2152 continue;
2153 }
2154 // Otherwise, if we're storing a byte variable, use a memset call for
2155 // this element.
2156 }
Bob Wilson69743022011-01-13 20:59:44 +00002157
Duncan Sands777d2302009-05-09 07:06:46 +00002158 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002159
Chris Lattner61db1f52010-12-26 22:57:41 +00002160 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002161
Chris Lattnerd93afec2009-01-07 07:18:45 +00002162 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002163 if (isa<MemSetInst>(MI)) {
2164 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2165 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002166 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002167 assert(isa<MemTransferInst>(MI));
2168 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2169 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002170
Chris Lattner61db1f52010-12-26 22:57:41 +00002171 if (isa<MemCpyInst>(MI))
2172 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2173 else
2174 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002175 }
Chris Lattner372dda82007-03-05 07:52:57 +00002176 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002177 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002178}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002179
Bob Wilson39fdd692009-12-04 21:57:37 +00002180/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002181/// overwrites the entire allocation. Extract out the pieces of the stored
2182/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002183void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002184 SmallVector<AllocaInst*, 32> &NewElts){
2185 // Extract each element out of the integer according to its structure offset
2186 // and store the element value to the individual alloca.
2187 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00002188 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002189 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002190
Chris Lattner70728532011-01-16 05:58:24 +00002191 IRBuilder<> Builder(SI);
2192
Eli Friedman41b33f42009-06-01 09:14:32 +00002193 // Handle tail padding by extending the operand
2194 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002195 SrcVal = Builder.CreateZExt(SrcVal,
2196 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002197
David Greene504c7d82010-01-05 01:27:09 +00002198 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002199 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002200
2201 // There are two forms here: AI could be an array or struct. Both cases
2202 // have different ways to compute the element offset.
2203 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2204 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002205
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002206 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2207 // Get the number of bits to shift SrcVal to get the value.
2208 const Type *FieldTy = EltSTy->getElementType(i);
2209 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002210
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002211 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002212 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002213
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002214 Value *EltVal = SrcVal;
2215 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002216 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002217 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002218 }
Bob Wilson69743022011-01-13 20:59:44 +00002219
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002220 // Truncate down to an integer of the right size.
2221 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002222
Chris Lattner583dd602009-01-09 18:18:43 +00002223 // Ignore zero sized fields like {}, they obviously contain no data.
2224 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002225
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002226 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002227 EltVal = Builder.CreateTrunc(EltVal,
2228 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002229 Value *DestField = NewElts[i];
2230 if (EltVal->getType() == FieldTy) {
2231 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002232 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002233 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002234 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002235 } else {
2236 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002237 DestField = Builder.CreateBitCast(DestField,
2238 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002239 }
2240 new StoreInst(EltVal, DestField, SI);
2241 }
Bob Wilson69743022011-01-13 20:59:44 +00002242
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002243 } else {
2244 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2245 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002246 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002247 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2248
2249 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002250
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002251 if (TD->isBigEndian())
2252 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002253 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002254 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002255
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002256 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002257 // Ignore zero sized fields like {}, they obviously contain no data.
2258 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002259
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002260 Value *EltVal = SrcVal;
2261 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002262 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002263 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002264 }
Bob Wilson69743022011-01-13 20:59:44 +00002265
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002266 // Truncate down to an integer of the right size.
2267 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002268 EltVal = Builder.CreateTrunc(EltVal,
2269 IntegerType::get(SI->getContext(),
2270 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002271 Value *DestField = NewElts[i];
2272 if (EltVal->getType() == ArrayEltTy) {
2273 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002274 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002275 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002276 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002277 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002278 } else {
2279 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002280 DestField = Builder.CreateBitCast(DestField,
2281 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002282 }
2283 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002284
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002285 if (TD->isBigEndian())
2286 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002287 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002288 Shift += ElementOffset;
2289 }
2290 }
Bob Wilson69743022011-01-13 20:59:44 +00002291
Bob Wilsonb742def2009-12-18 20:14:40 +00002292 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002293}
2294
Bob Wilson39fdd692009-12-04 21:57:37 +00002295/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002296/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002297void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002298 SmallVector<AllocaInst*, 32> &NewElts) {
2299 // Extract each element out of the NewElts according to its structure offset
2300 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00002301 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002302 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002303
David Greene504c7d82010-01-05 01:27:09 +00002304 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002305 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002306
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002307 // There are two forms here: AI could be an array or struct. Both cases
2308 // have different ways to compute the element offset.
2309 const StructLayout *Layout = 0;
2310 uint64_t ArrayEltBitOffset = 0;
2311 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2312 Layout = TD->getStructLayout(EltSTy);
2313 } else {
2314 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002315 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002316 }
2317
2318 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002319 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002320
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002321 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2322 // Load the value from the alloca. If the NewElt is an aggregate, cast
2323 // the pointer to an integer of the same size before doing the load.
2324 Value *SrcField = NewElts[i];
2325 const Type *FieldTy =
2326 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002327 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002328
Chris Lattner583dd602009-01-09 18:18:43 +00002329 // Ignore zero sized fields like {}, they obviously contain no data.
2330 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002331
2332 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002333 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002334 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2335 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002336 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002337 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002338 "", LI);
2339 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2340
2341 // If SrcField is a fp or vector of the right size but that isn't an
2342 // integer type, bitcast to an integer so we can shift it.
2343 if (SrcField->getType() != FieldIntTy)
2344 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2345
2346 // Zero extend the field to be the same size as the final alloca so that
2347 // we can shift and insert it.
2348 if (SrcField->getType() != ResultVal->getType())
2349 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002350
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002351 // Determine the number of bits to shift SrcField.
2352 uint64_t Shift;
2353 if (Layout) // Struct case.
2354 Shift = Layout->getElementOffsetInBits(i);
2355 else // Array case.
2356 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002357
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002358 if (TD->isBigEndian())
2359 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002360
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002361 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002362 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002363 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2364 }
2365
Chris Lattner14952472010-06-27 07:58:26 +00002366 // Don't create an 'or x, 0' on the first iteration.
2367 if (!isa<Constant>(ResultVal) ||
2368 !cast<Constant>(ResultVal)->isNullValue())
2369 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2370 else
2371 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002372 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002373
2374 // Handle tail padding by truncating the result
2375 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2376 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2377
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002378 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002379 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002380}
2381
Duncan Sands3cb36502007-11-04 14:43:57 +00002382/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002383/// alignment padding in between the elements that would be split apart
2384/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00002385static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002386 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2387 Ty = ATy->getElementType();
2388 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002389 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002390
2391 // SROA currently handles only Arrays and Structs.
2392 const StructType *STy = cast<StructType>(Ty);
2393 const StructLayout *SL = TD.getStructLayout(STy);
2394 unsigned PrevFieldBitOffset = 0;
2395 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2396 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2397
2398 // Check to see if there is any padding between this element and the
2399 // previous one.
2400 if (i) {
2401 unsigned PrevFieldEnd =
2402 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2403 if (PrevFieldEnd < FieldBitOffset)
2404 return true;
2405 }
2406 PrevFieldBitOffset = FieldBitOffset;
2407 }
2408 // Check for tail padding.
2409 if (unsigned EltCount = STy->getNumElements()) {
2410 unsigned PrevFieldEnd = PrevFieldBitOffset +
2411 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2412 if (PrevFieldEnd < SL->getSizeInBits())
2413 return true;
2414 }
2415 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002416}
Chris Lattner372dda82007-03-05 07:52:57 +00002417
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002418/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2419/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2420/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002421bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002422 // Loop over the use list of the alloca. We can only transform it if all of
2423 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002424 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002425
Chris Lattner6c95d242011-01-23 07:29:29 +00002426 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002427 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002428 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002429 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002430 }
Bob Wilson69743022011-01-13 20:59:44 +00002431
Chris Lattner39a1c042007-05-30 06:11:23 +00002432 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2433 // source and destination, we have to be careful. In particular, the memcpy
2434 // could be moving around elements that live in structure padding of the LLVM
2435 // types, but may actually be used. In these cases, we refuse to promote the
2436 // struct.
2437 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002438 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002439 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002440
Chris Lattner396a0562011-01-16 17:46:19 +00002441 // If the alloca never has an access to just *part* of it, but is accessed
2442 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002443 // the alloca instead of promoting each piece at a time and inserting fission
2444 // and fusion code.
2445 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2446 // If the struct/array just has one element, use basic SRoA.
2447 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2448 if (ST->getNumElements() > 1) return false;
2449 } else {
2450 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2451 return false;
2452 }
2453 }
Chris Lattner145c5322011-01-23 08:27:54 +00002454
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002455 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002456}
Chris Lattnera1888942005-12-12 07:19:13 +00002457
Chris Lattner800de312008-02-29 07:03:13 +00002458
Chris Lattner79b3bd32007-04-25 06:40:51 +00002459
2460/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2461/// some part of a constant global variable. This intentionally only accepts
2462/// constant expressions because we don't can't rewrite arbitrary instructions.
2463static bool PointsToConstantGlobal(Value *V) {
2464 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2465 return GV->isConstant();
2466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002467 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002468 CE->getOpcode() == Instruction::GetElementPtr)
2469 return PointsToConstantGlobal(CE->getOperand(0));
2470 return false;
2471}
2472
2473/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2474/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2475/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2476/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2477/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002478/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002479/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00002480static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00002481 bool isOffset) {
2482 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002483 User *U = cast<Instruction>(*UI);
2484
Chris Lattner2e618492010-11-18 06:20:47 +00002485 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002486 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00002487 if (LI->isVolatile()) return false;
2488 continue;
2489 }
Bob Wilson69743022011-01-13 20:59:44 +00002490
Gabor Greif8a8a4352010-04-06 19:32:30 +00002491 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002492 // If uses of the bitcast are ok, we are ok.
2493 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2494 return false;
2495 continue;
2496 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002497 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002498 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2499 // doesn't, it does.
2500 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2501 isOffset || !GEP->hasAllZeroIndices()))
2502 return false;
2503 continue;
2504 }
Bob Wilson69743022011-01-13 20:59:44 +00002505
Chris Lattner62480652010-11-18 06:41:51 +00002506 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002507 // If this is the function being called then we treat it like a load and
2508 // ignore it.
2509 if (CS.isCallee(UI))
2510 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002511
Duncan Sands53892102011-05-06 10:30:37 +00002512 // If this is a readonly/readnone call site, then we know it is just a
2513 // load (but one that potentially returns the value itself), so we can
2514 // ignore it if we know that the value isn't captured.
2515 unsigned ArgNo = CS.getArgumentNo(UI);
2516 if (CS.onlyReadsMemory() &&
2517 (CS.getInstruction()->use_empty() ||
2518 CS.paramHasAttr(ArgNo+1, Attribute::NoCapture)))
2519 continue;
2520
Chris Lattner62480652010-11-18 06:41:51 +00002521 // If this is being passed as a byval argument, the caller is making a
2522 // copy, so it is only a read of the alloca.
Chris Lattner62480652010-11-18 06:41:51 +00002523 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2524 continue;
2525 }
Bob Wilson69743022011-01-13 20:59:44 +00002526
Chris Lattner79b3bd32007-04-25 06:40:51 +00002527 // If this is isn't our memcpy/memmove, reject it as something we can't
2528 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002529 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2530 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002531 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002532
Chris Lattner2e618492010-11-18 06:20:47 +00002533 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002534 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002535 if (UI.getOperandNo() == 1) {
2536 if (MI->isVolatile()) return false;
2537 continue;
2538 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002539
2540 // If we already have seen a copy, reject the second one.
2541 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002542
Chris Lattner79b3bd32007-04-25 06:40:51 +00002543 // If the pointer has been offset from the start of the alloca, we can't
2544 // safely handle this.
2545 if (isOffset) return false;
2546
2547 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002548 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002549
Chris Lattner79b3bd32007-04-25 06:40:51 +00002550 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002551 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002552 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002553
Chris Lattner79b3bd32007-04-25 06:40:51 +00002554 // Otherwise, the transform is safe. Remember the copy instruction.
2555 TheCopy = MI;
2556 }
2557 return true;
2558}
2559
2560/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2561/// modified by a copy from a constant global. If we can prove this, we can
2562/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00002563MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2564 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00002565 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2566 return TheCopy;
2567 return 0;
2568}