blob: 182fd3cca437f07933b2b11c2c3f278d9d5ffd2a [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//
Chad Rosierc9f27ee2012-04-11 19:21:58 +000016// This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
Chris Lattner38aec322003-09-11 16:45:55 +000017// 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"
Peter Collingbourne9012c572012-05-19 22:52:10 +000032#include "llvm/Operator.h"
Chris Lattner372dda82007-03-05 07:52:57 +000033#include "llvm/Pass.h"
Devang Patel4fd3c592011-07-06 22:06:11 +000034#include "llvm/Analysis/DebugInfo.h"
Cameron Zwarichc8279392011-05-24 03:10:43 +000035#include "llvm/Analysis/DIBuilder.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000036#include "llvm/Analysis/Dominators.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000037#include "llvm/Analysis/Loads.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000038#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000041#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000042#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000043#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000044#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000045#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000046#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000047#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000048#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000049#include "llvm/Support/raw_ostream.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000050#include "llvm/ADT/SetVector.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000051#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000053using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000054
Chris Lattner0e5f4992006-12-19 21:40:18 +000055STATISTIC(NumReplaced, "Number of allocas broken up");
56STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnerc87c50a2011-01-23 22:04:55 +000057STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner0e5f4992006-12-19 21:40:18 +000058STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000059STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000060
Chris Lattner0e5f4992006-12-19 21:40:18 +000061namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000062 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000063 SROA(int T, bool hasDT, char &ID)
64 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000065 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000066 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000067 else
68 SRThreshold = T;
69 }
Devang Patel794fd752007-05-01 21:15:47 +000070
Chris Lattnered7b41e2003-05-27 15:45:27 +000071 bool runOnFunction(Function &F);
72
Chris Lattner38aec322003-09-11 16:45:55 +000073 bool performScalarRepl(Function &F);
74 bool performPromotion(Function &F);
75
Chris Lattnered7b41e2003-05-27 15:45:27 +000076 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000077 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000078 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000079
Bob Wilsonb742def2009-12-18 20:14:40 +000080 /// DeadInsts - Keep track of instructions we have made dead, so that
81 /// we can remove them after we are done working.
82 SmallVector<Value*, 32> DeadInsts;
83
Chris Lattner39a1c042007-05-30 06:11:23 +000084 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
85 /// information about the uses. All these fields are initialized to false
86 /// and set to true when something is learned.
87 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000088 /// The alloca to promote.
89 AllocaInst *AI;
90
Chris Lattner145c5322011-01-23 08:27:54 +000091 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
92 /// looping and avoid redundant work.
93 SmallPtrSet<PHINode*, 8> CheckedPHIs;
94
Chris Lattner39a1c042007-05-30 06:11:23 +000095 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
96 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000097
Chris Lattner39a1c042007-05-30 06:11:23 +000098 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
99 bool isMemCpySrc : 1;
100
Zhou Sheng33b0b8d2007-07-06 06:01:16 +0000101 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +0000102 bool isMemCpyDst : 1;
103
Chris Lattner7e9b4272011-01-16 06:18:28 +0000104 /// hasSubelementAccess - This is true if a subelement of the alloca is
105 /// ever accessed, or false if the alloca is only accessed with mem
106 /// intrinsics or load/store that only access the entire alloca at once.
107 bool hasSubelementAccess : 1;
108
109 /// hasALoadOrStore - This is true if there are any loads or stores to it.
110 /// The alloca may just be accessed with memcpy, for example, which would
111 /// not set this.
112 bool hasALoadOrStore : 1;
113
Chris Lattner6c95d242011-01-23 07:29:29 +0000114 explicit AllocaInfo(AllocaInst *ai)
115 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000116 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000117 };
Bob Wilson69743022011-01-13 20:59:44 +0000118
Devang Patelff366852007-07-09 21:19:23 +0000119 unsigned SRThreshold;
120
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000121 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
122 I.isUnsafe = true;
123 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
124 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000125
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000126 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000127
Chris Lattner6c95d242011-01-23 07:29:29 +0000128 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000129 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
130 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000131 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
132 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000133 Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000134 Instruction *TheAccess, bool AllowWholeAccess);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000135 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
136 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
137 Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000138
139 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000140 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000141 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000142
Bob Wilsonb742def2009-12-18 20:14:40 +0000143 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
144 SmallVector<AllocaInst*, 32> &NewElts);
145 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
146 SmallVector<AllocaInst*, 32> &NewElts);
147 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
148 SmallVector<AllocaInst*, 32> &NewElts);
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000149 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
150 uint64_t Offset,
151 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilsonb742def2009-12-18 20:14:40 +0000152 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000153 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000154 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000155 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000156 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000157 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000158 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000159
Nick Lewycky9174d5c2011-06-27 05:40:02 +0000160 static MemTransferInst *isOnlyCopiedFromConstantGlobal(
161 AllocaInst *AI, SmallVector<Instruction*, 4> &ToDelete);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000162 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000163
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000164 // SROA_DT - SROA that uses DominatorTree.
165 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000166 static char ID;
167 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000168 SROA_DT(int T = -1) : SROA(T, true, ID) {
169 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000170 }
171
172 // getAnalysisUsage - This pass does not require any passes, but we know it
173 // will not alter the CFG, so say so.
174 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
175 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000176 AU.setPreservesCFG();
177 }
178 };
179
180 // SROA_SSAUp - SROA that uses SSAUpdater.
181 struct SROA_SSAUp : public SROA {
182 static char ID;
183 public:
184 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
185 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
186 }
187
188 // getAnalysisUsage - This pass does not require any passes, but we know it
189 // will not alter the CFG, so say so.
190 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
191 AU.setPreservesCFG();
192 }
193 };
194
Chris Lattnered7b41e2003-05-27 15:45:27 +0000195}
196
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000197char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000198char SROA_SSAUp::ID = 0;
199
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000200INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
201 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000202INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000203INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
204 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000205
206INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
207 "Scalar Replacement of Aggregates (SSAUp)", false, false)
208INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
209 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000210
Brian Gaeked0fde302003-11-11 22:41:34 +0000211// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000212FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000213 bool UseDomTree) {
214 if (UseDomTree)
215 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000216 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000217}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000218
219
Chris Lattner4cc576b2010-04-16 00:24:57 +0000220//===----------------------------------------------------------------------===//
221// Convert To Scalar Optimization.
222//===----------------------------------------------------------------------===//
223
224namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000225/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
226/// optimization, which scans the uses of an alloca and determines if it can
227/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000228class ConvertToScalarInfo {
Cameron Zwarichd4c9c3e2011-03-16 00:13:35 +0000229 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000230 unsigned AllocaSize;
231 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000232
Chris Lattnera0bada72010-04-16 02:32:17 +0000233 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000234 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000235 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000236
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000237 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
238 /// computed based on the uses of the alloca rather than the LLVM type system.
239 enum {
240 Unknown,
Cameron Zwarich51797822011-06-13 21:44:40 +0000241
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000242 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich51797822011-06-13 21:44:40 +0000243 // type. This will not be converted into a vector unless there is a later
244 // access using an actual vector type.
245 ImplicitVector,
246
Cameron Zwarich15cd80c2011-06-13 23:39:23 +0000247 // Accesses via vector operations and GEPs that are consistent with the
248 // layout of a vector type.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000249 Vector,
Cameron Zwarich51797822011-06-13 21:44:40 +0000250
251 // An integer bag-of-bits with bitwise operations for insertion and
252 // extraction. Any combination of types can be converted into this kind
253 // of scalar.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000254 Integer
255 } ScalarKind;
256
Chris Lattnera001b662010-04-16 00:38:19 +0000257 /// VectorTy - This tracks the type that we should promote the vector to if
258 /// it is possible to turn it into a vector. This starts out null, and if it
259 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000260 VectorType *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000261
Cameron Zwarich1bcdb6f2011-03-16 08:13:42 +0000262 /// HadNonMemTransferAccess - True if there is at least one access to the
263 /// alloca that is not a MemTransferInst. We don't want to turn structs into
264 /// large integers unless there is some potential for optimization.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000265 bool HadNonMemTransferAccess;
266
Pete Cooper80f020a2012-06-17 03:58:26 +0000267 /// HadDynamicAccess - True if some element of this alloca was dynamic.
268 /// We don't yet have support for turning a dynamic access into a large
269 /// integer.
270 bool HadDynamicAccess;
271
Chris Lattner4cc576b2010-04-16 00:24:57 +0000272public:
273 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000274 : AllocaSize(Size), TD(td), IsNotTrivial(false), ScalarKind(Unknown),
Pete Cooper80f020a2012-06-17 03:58:26 +0000275 VectorTy(0), HadNonMemTransferAccess(false), HadDynamicAccess(false) { }
Bob Wilson69743022011-01-13 20:59:44 +0000276
Chris Lattnera001b662010-04-16 00:38:19 +0000277 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000278
Chris Lattner4cc576b2010-04-16 00:24:57 +0000279private:
Pete Cooper80f020a2012-06-17 03:58:26 +0000280 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000281 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
282 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
Pete Cooper80f020a2012-06-17 03:58:26 +0000283 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
284 Value *NonConstantIdx);
Bob Wilson69743022011-01-13 20:59:44 +0000285
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000286 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
Pete Cooper80f020a2012-06-17 03:58:26 +0000287 uint64_t Offset, Value* NonConstantIdx,
288 IRBuilder<> &Builder);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000289 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Pete Cooper80f020a2012-06-17 03:58:26 +0000290 uint64_t Offset, Value* NonConstantIdx,
291 IRBuilder<> &Builder);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000292};
293} // end anonymous namespace.
294
Chris Lattner91abace2010-09-01 05:14:33 +0000295
Chris Lattnera001b662010-04-16 00:38:19 +0000296/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
297/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
298/// alloca if possible or null if not.
299AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
300 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
301 // out.
Pete Cooper80f020a2012-06-17 03:58:26 +0000302 if (!CanConvertToScalar(AI, 0, 0) || !IsNotTrivial)
Chris Lattnera001b662010-04-16 00:38:19 +0000303 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000304
Cameron Zwarich51797822011-06-13 21:44:40 +0000305 // If an alloca has only memset / memcpy uses, it may still have an Unknown
306 // ScalarKind. Treat it as an Integer below.
307 if (ScalarKind == Unknown)
308 ScalarKind = Integer;
309
Cameron Zwarich3ebb05d2011-06-18 06:17:51 +0000310 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
311 ScalarKind = Integer;
312
Chris Lattnera001b662010-04-16 00:38:19 +0000313 // If we were able to find a vector type that can handle this with
314 // insert/extract elements, and if there was at least one use that had
315 // a vector type, promote this to a vector. We don't want to promote
316 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
317 // we just get a lot of insert/extracts. If at least one vector is
318 // involved, then we probably really do have a union of vector/array.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000319 Type *NewTy;
Cameron Zwarich5b93d3c2011-06-14 06:33:51 +0000320 if (ScalarKind == Vector) {
321 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnera001b662010-04-16 00:38:19 +0000322 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
323 << *VectorTy << '\n');
324 NewTy = VectorTy; // Use the vector type.
325 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000326 unsigned BitWidth = AllocaSize * 8;
Cameron Zwarich51797822011-06-13 21:44:40 +0000327 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
328 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth))
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000329 return 0;
Pete Cooper80f020a2012-06-17 03:58:26 +0000330 // Dynamic accesses on integers aren't yet supported. They need us to shift
331 // by a dynamic amount which could be difficult to work out as we might not
332 // know whether to use a left or right shift.
333 if (ScalarKind == Integer && HadDynamicAccess)
334 return 0;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000335
Chris Lattnera001b662010-04-16 00:38:19 +0000336 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
337 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000338 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000339 }
340 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Pete Cooper80f020a2012-06-17 03:58:26 +0000341 ConvertUsesToScalar(AI, NewAI, 0, 0);
Chris Lattnera001b662010-04-16 00:38:19 +0000342 return NewAI;
343}
344
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000345/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
346/// (VectorTy) so far at the offset specified by Offset (which is specified in
347/// bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000348///
Cameron Zwarich446d9522011-10-11 06:10:30 +0000349/// There are two cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000350/// 1) A union of vector types of the same size and potentially its elements.
351/// Here we turn element accesses into insert/extract element operations.
352/// This promotes a <4 x float> with a store of float to the third element
353/// into a <4 x float> that uses insert element.
Cameron Zwarich446d9522011-10-11 06:10:30 +0000354/// 2) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000355/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000356/// and stores would mutate the memory. We mark this by setting VectorTy
357/// to VoidTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000358void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000359 uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000360 // If we already decided to turn this into a blob of integer memory, there is
361 // nothing to be done.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000362 if (ScalarKind == Integer)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000363 return;
Bob Wilson69743022011-01-13 20:59:44 +0000364
Chris Lattner4cc576b2010-04-16 00:24:57 +0000365 // If this could be contributing to a vector, analyze it.
366
367 // If the In type is a vector that is the same size as the alloca, see if it
368 // matches the existing VecTy.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000369 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000370 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000371 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000372 } else if (In->isFloatTy() || In->isDoubleTy() ||
373 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
374 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000375 // Full width accesses can be ignored, because they can always be turned
376 // into bitcasts.
377 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarichdd689122011-06-13 21:44:31 +0000378 if (EltSize == AllocaSize)
Cameron Zwarich9827b782011-03-29 05:19:52 +0000379 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000380
Chris Lattner4cc576b2010-04-16 00:24:57 +0000381 // If we're accessing something that could be an element of a vector, see
382 // if the implied vector agrees with what we already have and if Offset is
383 // compatible with it.
Cameron Zwarich96cc1d02011-06-09 01:45:33 +0000384 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarich446d9522011-10-11 06:10:30 +0000385 (!VectorTy || EltSize == VectorTy->getElementType()
386 ->getPrimitiveSizeInBits()/8)) {
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000387 if (!VectorTy) {
Cameron Zwarich51797822011-06-13 21:44:40 +0000388 ScalarKind = ImplicitVector;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000389 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000390 }
Cameron Zwarich446d9522011-10-11 06:10:30 +0000391 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000392 }
393 }
Bob Wilson69743022011-01-13 20:59:44 +0000394
Chris Lattner4cc576b2010-04-16 00:24:57 +0000395 // Otherwise, we have a case that we can't handle with an optimized vector
396 // form. We can still turn this into a large integer.
Cameron Zwarichdeb74f22011-06-13 21:44:35 +0000397 ScalarKind = Integer;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000398}
399
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000400/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
401/// returning true if the type was successfully merged and false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000402bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000403 uint64_t Offset) {
Cameron Zwarich446d9522011-10-11 06:10:30 +0000404 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
405 // If we're storing/loading a vector of the right size, allow it as a
406 // vector. If this the first vector we see, remember the type so that
407 // we know the element size. If this is a subsequent access, ignore it
408 // even if it is a differing type but the same size. Worst case we can
409 // bitcast the resultant vectors.
410 if (!VectorTy)
411 VectorTy = VInTy;
Cameron Zwarich51797822011-06-13 21:44:40 +0000412 ScalarKind = Vector;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000413 return true;
Cameron Zwarich51797822011-06-13 21:44:40 +0000414 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000415
Cameron Zwarich446d9522011-10-11 06:10:30 +0000416 return false;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000417}
418
Chris Lattner4cc576b2010-04-16 00:24:57 +0000419/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
420/// its accesses to a single vector type, return true and set VecTy to
421/// the new type. If we could convert the alloca into a single promotable
422/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
423/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
424/// is the current offset from the base of the alloca being analyzed.
425///
426/// If we see at least one access to the value that is as a vector type, set the
427/// SawVec flag.
Pete Cooper80f020a2012-06-17 03:58:26 +0000428bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
429 Value* NonConstantIdx) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000430 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
431 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000432
Chris Lattner4cc576b2010-04-16 00:24:57 +0000433 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
434 // Don't break volatile loads.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000435 if (!LI->isSimple())
Chris Lattner4cc576b2010-04-16 00:24:57 +0000436 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000437 // Don't touch MMX operations.
438 if (LI->getType()->isX86_MMXTy())
439 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000440 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000441 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000442 continue;
443 }
Bob Wilson69743022011-01-13 20:59:44 +0000444
Chris Lattner4cc576b2010-04-16 00:24:57 +0000445 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
446 // Storing the pointer, not into the value?
Eli Friedman2bc3d522011-09-12 20:23:13 +0000447 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000448 // Don't touch MMX operations.
449 if (SI->getOperand(0)->getType()->isX86_MMXTy())
450 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000451 HadNonMemTransferAccess = true;
Cameron Zwarichc0e26072011-06-13 21:44:43 +0000452 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000453 continue;
454 }
Bob Wilson69743022011-01-13 20:59:44 +0000455
Chris Lattner4cc576b2010-04-16 00:24:57 +0000456 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000457 if (!onlyUsedByLifetimeMarkers(BCI))
458 IsNotTrivial = true; // Can't be mem2reg'd.
Pete Cooper80f020a2012-06-17 03:58:26 +0000459 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000460 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000461 continue;
462 }
463
464 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
465 // If this is a GEP with a variable indices, we can't handle it.
Pete Cooper80f020a2012-06-17 03:58:26 +0000466 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
467 if (!PtrTy)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000468 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000469
Chris Lattner4cc576b2010-04-16 00:24:57 +0000470 // Compute the offset that this GEP adds to the pointer.
471 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Pete Cooper80f020a2012-06-17 03:58:26 +0000472 Value *GEPNonConstantIdx = 0;
473 if (!GEP->hasAllConstantIndices()) {
474 if (!isa<VectorType>(PtrTy->getElementType()))
475 return false;
476 if (NonConstantIdx)
477 return false;
478 GEPNonConstantIdx = Indices.pop_back_val();
479 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
480 return false;
481 HadDynamicAccess = true;
482 } else
483 GEPNonConstantIdx = NonConstantIdx;
484 uint64_t GEPOffset = TD.getIndexedOffset(PtrTy,
Jay Foad8fbbb392011-07-19 14:01:37 +0000485 Indices);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000486 // See if all uses can be converted.
Pete Cooper80f020a2012-06-17 03:58:26 +0000487 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000488 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000489 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000490 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000491 continue;
492 }
493
494 // If this is a constant sized memset of a constant value (e.g. 0) we can
495 // handle it.
496 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
Pete Cooper80f020a2012-06-17 03:58:26 +0000497 // Store to dynamic index.
498 if (NonConstantIdx)
499 return false;
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000500 // Store of constant value.
501 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnera001b662010-04-16 00:38:19 +0000502 return false;
Cameron Zwarich6be41eb2011-06-18 05:47:49 +0000503
504 // Store of constant size.
505 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
506 if (!Len)
507 return false;
508
509 // If the size differs from the alloca, we can only convert the alloca to
510 // an integer bag-of-bits.
511 // FIXME: This should handle all of the cases that are currently accepted
512 // as vector element insertions.
513 if (Len->getZExtValue() != AllocaSize || Offset != 0)
514 ScalarKind = Integer;
515
Chris Lattnera001b662010-04-16 00:38:19 +0000516 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000517 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000518 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000519 }
520
521 // If this is a memcpy or memmove into or out of the whole allocation, we
522 // can handle it like a load or store of the scalar type.
523 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Pete Cooper80f020a2012-06-17 03:58:26 +0000524 // Store to dynamic index.
525 if (NonConstantIdx)
526 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000527 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
528 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
529 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000530
Chris Lattnera001b662010-04-16 00:38:19 +0000531 IsNotTrivial = true; // Can't be mem2reg'd.
532 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000533 }
Bob Wilson69743022011-01-13 20:59:44 +0000534
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000535 // If this is a lifetime intrinsic, we can handle it.
536 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
537 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
538 II->getIntrinsicID() == Intrinsic::lifetime_end) {
539 continue;
540 }
541 }
542
Chris Lattner4cc576b2010-04-16 00:24:57 +0000543 // Otherwise, we cannot handle this!
544 return false;
545 }
Bob Wilson69743022011-01-13 20:59:44 +0000546
Chris Lattner4cc576b2010-04-16 00:24:57 +0000547 return true;
548}
549
550/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
551/// directly. This happens when we are converting an "integer union" to a
552/// single integer scalar, or when we are converting a "vector union" to a
553/// vector with insert/extractelement instructions.
554///
555/// Offset is an offset from the original alloca, in bits that need to be
556/// shifted to the right. By the end of this, there should be no uses of Ptr.
557void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
Pete Cooper80f020a2012-06-17 03:58:26 +0000558 uint64_t Offset,
559 Value* NonConstantIdx) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000560 while (!Ptr->use_empty()) {
561 Instruction *User = cast<Instruction>(Ptr->use_back());
562
563 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Pete Cooper80f020a2012-06-17 03:58:26 +0000564 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000565 CI->eraseFromParent();
566 continue;
567 }
568
569 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
570 // Compute the offset that this GEP adds to the pointer.
571 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Pete Cooper80f020a2012-06-17 03:58:26 +0000572 if (!GEP->hasAllConstantIndices())
573 NonConstantIdx = Indices.pop_back_val();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000574 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foad8fbbb392011-07-19 14:01:37 +0000575 Indices);
Pete Cooper80f020a2012-06-17 03:58:26 +0000576 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, NonConstantIdx);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000577 GEP->eraseFromParent();
578 continue;
579 }
Bob Wilson69743022011-01-13 20:59:44 +0000580
Chris Lattner61db1f52010-12-26 22:57:41 +0000581 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000582
Chris Lattner4cc576b2010-04-16 00:24:57 +0000583 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
584 // The load is a bit extract from NewAI shifted right by Offset bits.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000585 Value *LoadedVal = Builder.CreateLoad(NewAI);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000586 Value *NewLoadVal
Pete Cooper80f020a2012-06-17 03:58:26 +0000587 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
588 NonConstantIdx, Builder);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000589 LI->replaceAllUsesWith(NewLoadVal);
590 LI->eraseFromParent();
591 continue;
592 }
Bob Wilson69743022011-01-13 20:59:44 +0000593
Chris Lattner4cc576b2010-04-16 00:24:57 +0000594 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
595 assert(SI->getOperand(0) != Ptr && "Consistency error!");
596 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
597 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
Pete Cooper80f020a2012-06-17 03:58:26 +0000598 NonConstantIdx, Builder);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000599 Builder.CreateStore(New, NewAI);
600 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000601
Chris Lattner4cc576b2010-04-16 00:24:57 +0000602 // If the load we just inserted is now dead, then the inserted store
603 // overwrote the entire thing.
604 if (Old->use_empty())
605 Old->eraseFromParent();
606 continue;
607 }
Bob Wilson69743022011-01-13 20:59:44 +0000608
Chris Lattner4cc576b2010-04-16 00:24:57 +0000609 // If this is a constant sized memset of a constant value (e.g. 0) we can
610 // transform it into a store of the expanded constant value.
611 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
612 assert(MSI->getRawDest() == Ptr && "Consistency error!");
Pete Cooper80f020a2012-06-17 03:58:26 +0000613 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
Duncan Sands01b305f2012-03-23 08:29:04 +0000614 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
Chris Lattner1fe6bfc2012-03-22 03:46:58 +0000615 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
Aaron Ballman7e2fa312012-03-15 00:05:31 +0000616 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000617 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000618
Chris Lattner4cc576b2010-04-16 00:24:57 +0000619 // Compute the value replicated the right number of times.
620 APInt APVal(NumBytes*8, Val);
621
622 // Splat the value if non-zero.
623 if (Val)
624 for (unsigned i = 1; i != NumBytes; ++i)
625 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000626
Chris Lattner4cc576b2010-04-16 00:24:57 +0000627 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
628 Value *New = ConvertScalar_InsertValue(
629 ConstantInt::get(User->getContext(), APVal),
Pete Cooper80f020a2012-06-17 03:58:26 +0000630 Old, Offset, 0, Builder);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000631 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000632
Chris Lattner4cc576b2010-04-16 00:24:57 +0000633 // If the load we just inserted is now dead, then the memset overwrote
634 // the entire thing.
635 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000636 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000637 }
638 MSI->eraseFromParent();
639 continue;
640 }
641
642 // If this is a memcpy or memmove into or out of the whole allocation, we
643 // can handle it like a load or store of the scalar type.
644 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
645 assert(Offset == 0 && "must be store to start of alloca");
Pete Cooper80f020a2012-06-17 03:58:26 +0000646 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
Bob Wilson69743022011-01-13 20:59:44 +0000647
Chris Lattner4cc576b2010-04-16 00:24:57 +0000648 // If the source and destination are both to the same alloca, then this is
649 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
650 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000651 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000652
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000653 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000654 // Dest must be OrigAI, change this to be a load from the original
655 // pointer (bitcasted), then a store to our new alloca.
656 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
657 Value *SrcPtr = MTI->getSource();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000658 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
659 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000660 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
661 AIPTy = PointerType::get(AIPTy->getElementType(),
662 SPTy->getAddressSpace());
663 }
664 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
665
Chris Lattner4cc576b2010-04-16 00:24:57 +0000666 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
667 SrcVal->setAlignment(MTI->getAlignment());
668 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000669 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000670 // Src must be OrigAI, change this to be a load from NewAI then a store
671 // through the original dest pointer (bitcasted).
672 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
673 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
674
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000675 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
676 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wange90a6332010-12-23 01:41:32 +0000677 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
678 AIPTy = PointerType::get(AIPTy->getElementType(),
679 DPTy->getAddressSpace());
680 }
681 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
682
Chris Lattner4cc576b2010-04-16 00:24:57 +0000683 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
684 NewStore->setAlignment(MTI->getAlignment());
685 } else {
686 // Noop transfer. Src == Dst
687 }
688
689 MTI->eraseFromParent();
690 continue;
691 }
Bob Wilson69743022011-01-13 20:59:44 +0000692
Nick Lewycky5a1cb642011-07-25 23:14:22 +0000693 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
694 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
695 II->getIntrinsicID() == Intrinsic::lifetime_end) {
696 // There's no need to preserve these, as the resulting alloca will be
697 // converted to a register anyways.
698 II->eraseFromParent();
699 continue;
700 }
701 }
702
Chris Lattner4cc576b2010-04-16 00:24:57 +0000703 llvm_unreachable("Unsupported operation!");
704 }
705}
706
707/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
708/// or vector value FromVal, extracting the bits from the offset specified by
709/// Offset. This returns the value, which is of type ToType.
710///
711/// This happens when we are converting an "integer union" to a single
712/// integer scalar, or when we are converting a "vector union" to a vector with
713/// insert/extractelement instructions.
714///
715/// Offset is an offset from the original alloca, in bits that need to be
716/// shifted to the right.
717Value *ConvertToScalarInfo::
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000718ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Pete Cooper80f020a2012-06-17 03:58:26 +0000719 uint64_t Offset, Value* NonConstantIdx,
720 IRBuilder<> &Builder) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000721 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000722 Type *FromType = FromVal->getType();
Mon P Wangbe0761c2011-04-13 21:40:02 +0000723 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000724 return FromVal;
725
726 // If the result alloca is a vector type, this is either an element
727 // access or a bitcast to another vector type of the same size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000728 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich0398d612011-06-08 22:08:31 +0000729 unsigned FromTypeSize = TD.getTypeAllocSize(FromType);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000730 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Cameron Zwarich446d9522011-10-11 06:10:30 +0000731 if (FromTypeSize == ToTypeSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000732 return Builder.CreateBitCast(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000733
734 // Otherwise it must be an element access.
735 unsigned Elt = 0;
736 if (Offset) {
737 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
738 Elt = Offset/EltSize;
739 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
740 }
741 // Return the element extracted out of it.
Pete Cooper80f020a2012-06-17 03:58:26 +0000742 Value *Idx;
743 if (NonConstantIdx) {
744 if (Elt)
745 Idx = Builder.CreateAdd(NonConstantIdx,
746 Builder.getInt32(Elt),
747 "dyn.offset");
748 else
749 Idx = NonConstantIdx;
750 } else
751 Idx = Builder.getInt32(Elt);
752 Value *V = Builder.CreateExtractElement(FromVal, Idx);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000753 if (V->getType() != ToType)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000754 V = Builder.CreateBitCast(V, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000755 return V;
756 }
Bob Wilson69743022011-01-13 20:59:44 +0000757
Chris Lattner4cc576b2010-04-16 00:24:57 +0000758 // If ToType is a first class aggregate, extract out each of the pieces and
759 // use insertvalue's to form the FCA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000760 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Pete Cooper80f020a2012-06-17 03:58:26 +0000761 assert(!NonConstantIdx &&
762 "Dynamic indexing into struct types not supported");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000763 const StructLayout &Layout = *TD.getStructLayout(ST);
764 Value *Res = UndefValue::get(ST);
765 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
766 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
767 Offset+Layout.getElementOffsetInBits(i),
Pete Cooper80f020a2012-06-17 03:58:26 +0000768 0, Builder);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000769 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000770 }
771 return Res;
772 }
Bob Wilson69743022011-01-13 20:59:44 +0000773
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000774 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Pete Cooper80f020a2012-06-17 03:58:26 +0000775 assert(!NonConstantIdx &&
776 "Dynamic indexing into array types not supported");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000777 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
778 Value *Res = UndefValue::get(AT);
779 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
780 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
Pete Cooper80f020a2012-06-17 03:58:26 +0000781 Offset+i*EltSize, 0, Builder);
Benjamin Kramera9390a42011-09-27 20:39:19 +0000782 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000783 }
784 return Res;
785 }
786
787 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000788 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner4cc576b2010-04-16 00:24:57 +0000789
790 // If this is a big-endian system and the load is narrower than the
791 // full alloca type, we need to do a shift to get the right bits.
792 int ShAmt = 0;
793 if (TD.isBigEndian()) {
794 // On big-endian machines, the lowest bit is stored at the bit offset
795 // from the pointer given by getTypeStoreSizeInBits. This matters for
796 // integers with a bitwidth that is not a multiple of 8.
797 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
798 TD.getTypeStoreSizeInBits(ToType) - Offset;
799 } else {
800 ShAmt = Offset;
801 }
802
803 // Note: we support negative bitwidths (with shl) which are not defined.
804 // We do this to support (f.e.) loads off the end of a structure where
805 // only some bits are used.
806 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
807 FromVal = Builder.CreateLShr(FromVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +0000808 ConstantInt::get(FromVal->getType(), ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000809 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000810 FromVal = Builder.CreateShl(FromVal,
Benjamin Kramera9390a42011-09-27 20:39:19 +0000811 ConstantInt::get(FromVal->getType(), -ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000812
813 // Finally, unconditionally truncate the integer to the right width.
814 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
815 if (LIBitWidth < NTy->getBitWidth())
816 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000817 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000818 LIBitWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000819 else if (LIBitWidth > NTy->getBitWidth())
820 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000821 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000822 LIBitWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000823
824 // If the result is an integer, this is a trunc or bitcast.
825 if (ToType->isIntegerTy()) {
826 // Should be done.
827 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
828 // Just do a bitcast, we know the sizes match up.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000829 FromVal = Builder.CreateBitCast(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000830 } else {
831 // Otherwise must be a pointer.
Benjamin Kramera9390a42011-09-27 20:39:19 +0000832 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000833 }
834 assert(FromVal->getType() == ToType && "Didn't convert right?");
835 return FromVal;
836}
837
838/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
839/// or vector value "Old" at the offset specified by Offset.
840///
841/// This happens when we are converting an "integer union" to a
842/// single integer scalar, or when we are converting a "vector union" to a
843/// vector with insert/extractelement instructions.
844///
845/// Offset is an offset from the original alloca, in bits that need to be
846/// shifted to the right.
Pete Cooper80f020a2012-06-17 03:58:26 +0000847///
848/// NonConstantIdx is an index value if there was a GEP with a non-constant
849/// index value. If this is 0 then all GEPs used to find this insert address
850/// are constant.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000851Value *ConvertToScalarInfo::
852ConvertScalar_InsertValue(Value *SV, Value *Old,
Pete Cooper80f020a2012-06-17 03:58:26 +0000853 uint64_t Offset, Value* NonConstantIdx,
854 IRBuilder<> &Builder) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000855 // Convert the stored type to the actual type, shift it left to insert
856 // then 'or' into place.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000857 Type *AllocaType = Old->getType();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000858 LLVMContext &Context = Old->getContext();
859
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000860 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000861 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
862 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000863
Chris Lattner4cc576b2010-04-16 00:24:57 +0000864 // Changing the whole vector with memset or with an access of a different
865 // vector type?
Cameron Zwarich446d9522011-10-11 06:10:30 +0000866 if (ValSize == VecSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000867 return Builder.CreateBitCast(SV, AllocaType);
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000868
Chris Lattner4cc576b2010-04-16 00:24:57 +0000869 // Must be an element insertion.
Cameron Zwarich90747e32011-10-23 07:02:10 +0000870 Type *EltTy = VTy->getElementType();
871 if (SV->getType() != EltTy)
872 SV = Builder.CreateBitCast(SV, EltTy);
873 uint64_t EltSize = TD.getTypeAllocSizeInBits(EltTy);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000874 unsigned Elt = Offset/EltSize;
Pete Cooper80f020a2012-06-17 03:58:26 +0000875 Value *Idx;
876 if (NonConstantIdx) {
877 if (Elt)
878 Idx = Builder.CreateAdd(NonConstantIdx,
879 Builder.getInt32(Elt),
880 "dyn.offset");
881 else
882 Idx = NonConstantIdx;
883 } else
884 Idx = Builder.getInt32(Elt);
885 return Builder.CreateInsertElement(Old, SV, Idx);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000886 }
Bob Wilson69743022011-01-13 20:59:44 +0000887
Chris Lattner4cc576b2010-04-16 00:24:57 +0000888 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000889 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Pete Cooper80f020a2012-06-17 03:58:26 +0000890 assert(!NonConstantIdx &&
891 "Dynamic indexing into struct types not supported");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000892 const StructLayout &Layout = *TD.getStructLayout(ST);
893 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000894 Value *Elt = Builder.CreateExtractValue(SV, i);
Bob Wilson69743022011-01-13 20:59:44 +0000895 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000896 Offset+Layout.getElementOffsetInBits(i),
Pete Cooper80f020a2012-06-17 03:58:26 +0000897 0, Builder);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000898 }
899 return Old;
900 }
Bob Wilson69743022011-01-13 20:59:44 +0000901
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000902 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Pete Cooper80f020a2012-06-17 03:58:26 +0000903 assert(!NonConstantIdx &&
904 "Dynamic indexing into array types not supported");
Chris Lattner4cc576b2010-04-16 00:24:57 +0000905 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
906 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000907 Value *Elt = Builder.CreateExtractValue(SV, i);
Pete Cooper80f020a2012-06-17 03:58:26 +0000908 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, 0, Builder);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000909 }
910 return Old;
911 }
912
913 // If SV is a float, convert it to the appropriate integer type.
914 // If it is a pointer, do the same.
915 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
916 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
917 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
918 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
919 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000920 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000921 else if (SV->getType()->isPointerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000922 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000923
924 // Zero extend or truncate the value if needed.
925 if (SV->getType() != AllocaType) {
926 if (SV->getType()->getPrimitiveSizeInBits() <
927 AllocaType->getPrimitiveSizeInBits())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000928 SV = Builder.CreateZExt(SV, AllocaType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000929 else {
930 // Truncation may be needed if storing more than the alloca can hold
931 // (undefined behavior).
Benjamin Kramera9390a42011-09-27 20:39:19 +0000932 SV = Builder.CreateTrunc(SV, AllocaType);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000933 SrcWidth = DestWidth;
934 SrcStoreWidth = DestStoreWidth;
935 }
936 }
937
938 // If this is a big-endian system and the store is narrower than the
939 // full alloca type, we need to do a shift to get the right bits.
940 int ShAmt = 0;
941 if (TD.isBigEndian()) {
942 // On big-endian machines, the lowest bit is stored at the bit offset
943 // from the pointer given by getTypeStoreSizeInBits. This matters for
944 // integers with a bitwidth that is not a multiple of 8.
945 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
946 } else {
947 ShAmt = Offset;
948 }
949
950 // Note: we support negative bitwidths (with shr) which are not defined.
951 // We do this to support (f.e.) stores off the end of a structure where
952 // only some bits in the structure are set.
953 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
954 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000955 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000956 Mask <<= ShAmt;
957 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000958 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
Chris Lattner4cc576b2010-04-16 00:24:57 +0000959 Mask = Mask.lshr(-ShAmt);
960 }
961
962 // Mask out the bits we are about to insert from the old value, and or
963 // in the new bits.
964 if (SrcWidth != DestWidth) {
965 assert(DestWidth > SrcWidth);
966 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
967 SV = Builder.CreateOr(Old, SV, "ins");
968 }
969 return SV;
970}
971
972
973//===----------------------------------------------------------------------===//
974// SRoA Driver
975//===----------------------------------------------------------------------===//
976
977
Chris Lattnered7b41e2003-05-27 15:45:27 +0000978bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000979 TD = getAnalysisIfAvailable<TargetData>();
980
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000981 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000982
983 // FIXME: ScalarRepl currently depends on TargetData more than it
984 // theoretically needs to. It should be refactored in order to support
985 // target-independent IR. Until this is done, just skip the actual
986 // scalar-replacement portion of this pass.
987 if (!TD) return Changed;
988
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000989 while (1) {
990 bool LocalChange = performScalarRepl(F);
991 if (!LocalChange) break; // No need to repromote if no scalarrepl
992 Changed = true;
993 LocalChange = performPromotion(F);
994 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
995 }
Chris Lattner38aec322003-09-11 16:45:55 +0000996
997 return Changed;
998}
999
Chris Lattnerd0f56132011-01-14 19:50:47 +00001000namespace {
1001class AllocaPromoter : public LoadAndStorePromoter {
1002 AllocaInst *AI;
Devang Patel231a5ab2011-07-06 21:09:55 +00001003 DIBuilder *DIB;
Devang Patel4fd3c592011-07-06 22:06:11 +00001004 SmallVector<DbgDeclareInst *, 4> DDIs;
1005 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerd0f56132011-01-14 19:50:47 +00001006public:
Cameron Zwarichc8279392011-05-24 03:10:43 +00001007 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
Devang Patel231a5ab2011-07-06 21:09:55 +00001008 DIBuilder *DB)
Devang Patel4fd3c592011-07-06 22:06:11 +00001009 : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +00001010
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001011 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +00001012 // Remember which alloca we're promoting (for isInstInList).
1013 this->AI = AI;
Rafael Espindola125ef762011-12-26 23:12:42 +00001014 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
Devang Patel4fd3c592011-07-06 22:06:11 +00001015 for (Value::use_iterator UI = DebugNode->use_begin(),
1016 E = DebugNode->use_end(); UI != E; ++UI)
1017 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1018 DDIs.push_back(DDI);
1019 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1020 DVIs.push_back(DVI);
Rafael Espindola125ef762011-12-26 23:12:42 +00001021 }
Devang Patel4fd3c592011-07-06 22:06:11 +00001022
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001023 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +00001024 AI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +00001025 for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(),
1026 E = DDIs.end(); I != E; ++I) {
1027 DbgDeclareInst *DDI = *I;
Devang Patel231a5ab2011-07-06 21:09:55 +00001028 DDI->eraseFromParent();
Devang Patel4fd3c592011-07-06 22:06:11 +00001029 }
1030 for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(),
1031 E = DVIs.end(); I != E; ++I) {
1032 DbgValueInst *DVI = *I;
1033 DVI->eraseFromParent();
1034 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001035 }
1036
Chris Lattnerd0f56132011-01-14 19:50:47 +00001037 virtual bool isInstInList(Instruction *I,
1038 const SmallVectorImpl<Instruction*> &Insts) const {
1039 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1040 return LI->getOperand(0) == AI;
1041 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001042 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001043
Devang Patel4fd3c592011-07-06 22:06:11 +00001044 virtual void updateDebugInfo(Instruction *Inst) const {
1045 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1046 E = DDIs.end(); I != E; ++I) {
1047 DbgDeclareInst *DDI = *I;
1048 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1049 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1050 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1051 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1052 }
1053 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1054 E = DVIs.end(); I != E; ++I) {
1055 DbgValueInst *DVI = *I;
Benjamin Kramer6a1c7792012-02-23 17:42:19 +00001056 Value *Arg = NULL;
Devang Patel4fd3c592011-07-06 22:06:11 +00001057 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Devang Patel4fd3c592011-07-06 22:06:11 +00001058 // If an argument is zero extended then use argument directly. The ZExt
1059 // may be zapped by an optimization pass in future.
Devang Patel4fd3c592011-07-06 22:06:11 +00001060 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
Benjamin Kramer6a1c7792012-02-23 17:42:19 +00001061 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Devang Patel4fd3c592011-07-06 22:06:11 +00001062 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Benjamin Kramer6a1c7792012-02-23 17:42:19 +00001063 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1064 if (!Arg)
1065 Arg = SI->getOperand(0);
Devang Patel4fd3c592011-07-06 22:06:11 +00001066 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Benjamin Kramer6a1c7792012-02-23 17:42:19 +00001067 Arg = LI->getOperand(0);
1068 } else {
1069 continue;
Devang Patel4fd3c592011-07-06 22:06:11 +00001070 }
Benjamin Kramer6a1c7792012-02-23 17:42:19 +00001071 Instruction *DbgVal =
1072 DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1073 Inst);
1074 DbgVal->setDebugLoc(DVI->getDebugLoc());
Devang Patel4fd3c592011-07-06 22:06:11 +00001075 }
Devang Patel231a5ab2011-07-06 21:09:55 +00001076 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001077};
1078} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001079
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001080/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1081/// subsequently loaded can be rewritten to load both input pointers and then
1082/// select between the result, allowing the load of the alloca to be promoted.
1083/// From this:
1084/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1085/// %V = load i32* %P2
1086/// to:
1087/// %V1 = load i32* %Alloca -> will be mem2reg'd
1088/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001089/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001090///
1091/// We can do this to a select if its only uses are loads and if the operand to
1092/// the select can be loaded unconditionally.
1093static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1094 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1095 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1096
1097 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1098 UI != UE; ++UI) {
1099 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman2bc3d522011-09-12 20:23:13 +00001100 if (LI == 0 || !LI->isSimple()) return false;
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001101
Chris Lattnere3357862011-01-24 01:07:11 +00001102 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001103 // (e.g. allocas) or at this point because we can see other accesses to it.
1104 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1105 LI->getAlignment(), TD))
1106 return false;
1107 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1108 LI->getAlignment(), TD))
1109 return false;
1110 }
1111
1112 return true;
1113}
1114
Chris Lattnere3357862011-01-24 01:07:11 +00001115/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1116/// subsequently loaded can be rewritten to load both input pointers in the pred
1117/// blocks and then PHI the results, allowing the load of the alloca to be
1118/// promoted.
1119/// From this:
1120/// %P2 = phi [i32* %Alloca, i32* %Other]
1121/// %V = load i32* %P2
1122/// to:
1123/// %V1 = load i32* %Alloca -> will be mem2reg'd
1124/// ...
1125/// %V2 = load i32* %Other
1126/// ...
1127/// %V = phi [i32 %V1, i32 %V2]
1128///
1129/// We can do this to a select if its only uses are loads and if the operand to
1130/// the select can be loaded unconditionally.
1131static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1132 // For now, we can only do this promotion if the load is in the same block as
1133 // the PHI, and if there are no stores between the phi and load.
1134 // TODO: Allow recursive phi users.
1135 // TODO: Allow stores.
1136 BasicBlock *BB = PN->getParent();
1137 unsigned MaxAlign = 0;
1138 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1139 UI != UE; ++UI) {
1140 LoadInst *LI = dyn_cast<LoadInst>(*UI);
Eli Friedman2bc3d522011-09-12 20:23:13 +00001141 if (LI == 0 || !LI->isSimple()) return false;
Chris Lattnere3357862011-01-24 01:07:11 +00001142
1143 // For now we only allow loads in the same block as the PHI. This is a
1144 // common case that happens when instcombine merges two loads through a PHI.
1145 if (LI->getParent() != BB) return false;
1146
1147 // Ensure that there are no instructions between the PHI and the load that
1148 // could store.
1149 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1150 if (BBI->mayWriteToMemory())
1151 return false;
1152
1153 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1154 }
1155
1156 // Okay, we know that we have one or more loads in the same block as the PHI.
1157 // We can transform this if it is safe to push the loads into the predecessor
1158 // blocks. The only thing to watch out for is that we can't put a possibly
1159 // trapping load in the predecessor if it is a critical edge.
1160 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1161 BasicBlock *Pred = PN->getIncomingBlock(i);
Eli Friedmand102a032011-09-22 18:56:30 +00001162 Value *InVal = PN->getIncomingValue(i);
1163
1164 // If the terminator of the predecessor has side-effects (an invoke),
1165 // there is no safe place to put a load in the predecessor.
1166 if (Pred->getTerminator()->mayHaveSideEffects())
1167 return false;
1168
1169 // If the value is produced by the terminator of the predecessor
1170 // (an invoke), there is no valid place to put a load in the predecessor.
1171 if (Pred->getTerminator() == InVal)
1172 return false;
Chris Lattnere3357862011-01-24 01:07:11 +00001173
1174 // If the predecessor has a single successor, then the edge isn't critical.
1175 if (Pred->getTerminator()->getNumSuccessors() == 1)
1176 continue;
Chris Lattnere3357862011-01-24 01:07:11 +00001177
1178 // If this pointer is always safe to load, or if we can prove that there is
1179 // already a load in the block, then we can move the load to the pred block.
1180 if (InVal->isDereferenceablePointer() ||
1181 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1182 continue;
1183
1184 return false;
1185 }
1186
1187 return true;
1188}
1189
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001190
1191/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1192/// direct (non-volatile) loads and stores to it. If the alloca is close but
1193/// not quite there, this will transform the code to allow promotion. As such,
1194/// it is a non-pure predicate.
1195static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1196 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1197 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1198
1199 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1200 UI != UE; ++UI) {
1201 User *U = *UI;
1202 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001203 if (!LI->isSimple())
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001204 return false;
1205 continue;
1206 }
1207
1208 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001209 if (SI->getOperand(0) == AI || !SI->isSimple())
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001210 return false; // Don't allow a store OF the AI, only INTO the AI.
1211 continue;
1212 }
1213
1214 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1215 // If the condition being selected on is a constant, fold the select, yes
1216 // this does (rarely) happen early on.
1217 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1218 Value *Result = SI->getOperand(1+CI->isZero());
1219 SI->replaceAllUsesWith(Result);
1220 SI->eraseFromParent();
1221
1222 // This is very rare and we just scrambled the use list of AI, start
1223 // over completely.
1224 return tryToMakeAllocaBePromotable(AI, TD);
1225 }
1226
1227 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1228 // loads, then we can transform this by rewriting the select.
1229 if (!isSafeSelectToSpeculate(SI, TD))
1230 return false;
1231
1232 InstsToRewrite.insert(SI);
1233 continue;
1234 }
1235
Chris Lattnere3357862011-01-24 01:07:11 +00001236 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1237 if (PN->use_empty()) { // Dead PHIs can be stripped.
1238 InstsToRewrite.insert(PN);
1239 continue;
1240 }
1241
1242 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1243 // in the pred blocks, then we can transform this by rewriting the PHI.
1244 if (!isSafePHIToSpeculate(PN, TD))
1245 return false;
1246
1247 InstsToRewrite.insert(PN);
1248 continue;
1249 }
1250
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001251 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1252 if (onlyUsedByLifetimeMarkers(BCI)) {
1253 InstsToRewrite.insert(BCI);
1254 continue;
1255 }
1256 }
1257
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001258 return false;
1259 }
1260
1261 // If there are no instructions to rewrite, then all uses are load/stores and
1262 // we're done!
1263 if (InstsToRewrite.empty())
1264 return true;
1265
1266 // If we have instructions that need to be rewritten for this to be promotable
1267 // take care of it now.
1268 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001269 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1270 // This could only be a bitcast used by nothing but lifetime intrinsics.
1271 for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end();
1272 I != E;) {
1273 Use &U = I.getUse();
1274 ++I;
1275 cast<Instruction>(U.getUser())->eraseFromParent();
1276 }
1277 BCI->eraseFromParent();
1278 continue;
1279 }
1280
Chris Lattnere3357862011-01-24 01:07:11 +00001281 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1282 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1283 // loads with a new select.
1284 while (!SI->use_empty()) {
1285 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001286
Chris Lattnere3357862011-01-24 01:07:11 +00001287 IRBuilder<> Builder(LI);
1288 LoadInst *TrueLoad =
1289 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1290 LoadInst *FalseLoad =
Nick Lewycky394d1f12011-07-01 06:27:03 +00001291 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Chris Lattnere3357862011-01-24 01:07:11 +00001292
1293 // Transfer alignment and TBAA info if present.
1294 TrueLoad->setAlignment(LI->getAlignment());
1295 FalseLoad->setAlignment(LI->getAlignment());
1296 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1297 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1298 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1299 }
1300
1301 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1302 V->takeName(LI);
1303 LI->replaceAllUsesWith(V);
1304 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001305 }
Chris Lattnere3357862011-01-24 01:07:11 +00001306
1307 // Now that all the loads are gone, the select is gone too.
1308 SI->eraseFromParent();
1309 continue;
1310 }
1311
1312 // Otherwise, we have a PHI node which allows us to push the loads into the
1313 // predecessors.
1314 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1315 if (PN->use_empty()) {
1316 PN->eraseFromParent();
1317 continue;
1318 }
1319
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001320 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001321 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1322 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001323
1324 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1325 // matter which one we get and if any differ, it doesn't matter.
1326 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1327 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1328 unsigned Align = SomeLoad->getAlignment();
1329
1330 // Rewrite all loads of the PN to use the new PHI.
1331 while (!PN->use_empty()) {
1332 LoadInst *LI = cast<LoadInst>(PN->use_back());
1333 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001334 LI->eraseFromParent();
1335 }
1336
Chris Lattnere3357862011-01-24 01:07:11 +00001337 // Inject loads into all of the pred blocks. Keep track of which blocks we
1338 // insert them into in case we have multiple edges from the same block.
1339 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1340
1341 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1342 BasicBlock *Pred = PN->getIncomingBlock(i);
1343 LoadInst *&Load = InsertedLoads[Pred];
1344 if (Load == 0) {
1345 Load = new LoadInst(PN->getIncomingValue(i),
1346 PN->getName() + "." + Pred->getName(),
1347 Pred->getTerminator());
1348 Load->setAlignment(Align);
1349 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1350 }
1351
1352 NewPN->addIncoming(Load, Pred);
1353 }
1354
1355 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001356 }
1357
1358 ++NumAdjusted;
1359 return true;
1360}
1361
Chris Lattner38aec322003-09-11 16:45:55 +00001362bool SROA::performPromotion(Function &F) {
1363 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001364 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001365 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001366 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001367
Chris Lattner02a3be02003-09-20 14:39:18 +00001368 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Devang Patel231a5ab2011-07-06 21:09:55 +00001369 DIBuilder DIB(*F.getParent());
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001370 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001371 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001372 while (1) {
1373 Allocas.clear();
1374
1375 // Find allocas that are safe to promote, by looking at all instructions in
1376 // the entry node
1377 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1378 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001379 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001380 Allocas.push_back(AI);
1381
1382 if (Allocas.empty()) break;
1383
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001384 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001385 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001386 else {
1387 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001388 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1389 AllocaInst *AI = Allocas[i];
1390
1391 // Build list of instructions to promote.
1392 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1393 UI != E; ++UI)
1394 Insts.push_back(cast<Instruction>(*UI));
Devang Patel231a5ab2011-07-06 21:09:55 +00001395 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001396 Insts.clear();
1397 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001398 }
Chris Lattner38aec322003-09-11 16:45:55 +00001399 NumPromoted += Allocas.size();
1400 Changed = true;
1401 }
1402
1403 return Changed;
1404}
1405
Chris Lattner4cc576b2010-04-16 00:24:57 +00001406
Bob Wilson3992feb2010-02-03 17:23:56 +00001407/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1408/// SROA. It must be a struct or array type with a small number of elements.
1409static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001410 Type *T = AI->getAllocatedType();
Bob Wilson3992feb2010-02-03 17:23:56 +00001411 // Do not promote any struct into more than 32 separate vars.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001412 if (StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001413 return ST->getNumElements() <= 32;
1414 // Arrays are much less likely to be safe for SROA; only consider
1415 // them if they are very small.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001416 if (ArrayType *AT = dyn_cast<ArrayType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001417 return AT->getNumElements() <= 8;
1418 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001419}
1420
Peter Collingbourne9012c572012-05-19 22:52:10 +00001421/// getPointeeAlignment - Compute the minimum alignment of the value pointed
1422/// to by the given pointer.
1423static unsigned getPointeeAlignment(Value *V, const TargetData &TD) {
1424 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1425 if (CE->getOpcode() == Instruction::BitCast ||
1426 (CE->getOpcode() == Instruction::GetElementPtr &&
1427 cast<GEPOperator>(CE)->hasAllZeroIndices()))
1428 return getPointeeAlignment(CE->getOperand(0), TD);
1429
1430 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1431 if (!GV->isDeclaration())
1432 return TD.getPreferredAlignment(GV);
1433
1434 if (PointerType *PT = dyn_cast<PointerType>(V->getType()))
1435 return TD.getABITypeAlignment(PT->getElementType());
1436
1437 return 0;
1438}
1439
Chris Lattnerc4472072010-04-15 23:50:26 +00001440
Chris Lattner38aec322003-09-11 16:45:55 +00001441// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001442// which runs on all of the alloca instructions in the function, removing them
1443// if they are only used by getelementptr instructions.
Chris Lattner38aec322003-09-11 16:45:55 +00001444//
1445bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001446 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001447
Chris Lattner31d80102010-04-15 21:59:20 +00001448 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001449 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001450 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001451 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001452 WorkList.push_back(A);
1453
1454 // Process the worklist
1455 bool Changed = false;
1456 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001457 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001458 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001459
Chris Lattneradd2bd72006-12-22 23:14:42 +00001460 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1461 // with unused elements.
1462 if (AI->use_empty()) {
1463 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001464 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001465 continue;
1466 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001467
1468 // If this alloca is impossible for us to promote, reject it early.
1469 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1470 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001471
Chris Lattner79b3bd32007-04-25 06:40:51 +00001472 // Check to see if this allocation is only modified by a memcpy/memmove from
Peter Collingbourne9012c572012-05-19 22:52:10 +00001473 // a constant global whose alignment is equal to or exceeds that of the
1474 // allocation. If this is the case, we can change all users to use
Chris Lattner79b3bd32007-04-25 06:40:51 +00001475 // the constant global instead. This is commonly produced by the CFE by
1476 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1477 // is only subsequently read.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00001478 SmallVector<Instruction *, 4> ToDelete;
1479 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(AI, ToDelete)) {
Peter Collingbourne9012c572012-05-19 22:52:10 +00001480 if (AI->getAlignment() <= getPointeeAlignment(Copy->getSource(), *TD)) {
1481 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1482 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
1483 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
1484 ToDelete[i]->eraseFromParent();
1485 Constant *TheSrc = cast<Constant>(Copy->getSource());
1486 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1487 Copy->eraseFromParent(); // Don't mutate the global.
1488 AI->eraseFromParent();
1489 ++NumGlobals;
1490 Changed = true;
1491 continue;
1492 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00001493 }
Bob Wilson69743022011-01-13 20:59:44 +00001494
Chris Lattner7809ecd2009-02-03 01:30:09 +00001495 // Check to see if we can perform the core SROA transformation. We cannot
1496 // transform the allocation instruction if it is an array allocation
1497 // (allocations OF arrays are ok though), and an allocation of a scalar
1498 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001499 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001500
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001501 // Do not promote [0 x %struct].
1502 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001503
Chris Lattner31d80102010-04-15 21:59:20 +00001504 // Do not promote any struct whose size is too big.
1505 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001506
Bob Wilson3992feb2010-02-03 17:23:56 +00001507 // If the alloca looks like a good candidate for scalar replacement, and if
1508 // all its users can be transformed, then split up the aggregate into its
1509 // separate elements.
1510 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1511 DoScalarReplacement(AI, WorkList);
1512 Changed = true;
1513 continue;
1514 }
1515
Chris Lattner6e733d32009-01-28 20:16:43 +00001516 // If we can turn this aggregate value (potentially with casts) into a
1517 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001518 // IsNotTrivial tracks whether this is something that mem2reg could have
1519 // promoted itself. If so, we don't want to transform it needlessly. Note
1520 // that we can't just check based on the type: the alloca may be of an i32
1521 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001522 if (AllocaInst *NewAI =
1523 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001524 NewAI->takeName(AI);
1525 AI->eraseFromParent();
1526 ++NumConverted;
1527 Changed = true;
1528 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001529 }
1530
Chris Lattner7809ecd2009-02-03 01:30:09 +00001531 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001532 }
1533
1534 return Changed;
1535}
Chris Lattner5e062a12003-05-30 04:15:41 +00001536
Chris Lattnera10b29b2007-04-25 05:02:56 +00001537/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1538/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001539void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001540 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001541 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001542 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001543 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattnera10b29b2007-04-25 05:02:56 +00001544 ElementAllocas.reserve(ST->getNumContainedTypes());
1545 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001546 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001547 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001548 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001549 ElementAllocas.push_back(NA);
1550 WorkList.push_back(NA); // Add to worklist for recursive processing
1551 }
1552 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001553 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnera10b29b2007-04-25 05:02:56 +00001554 ElementAllocas.reserve(AT->getNumElements());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001555 Type *ElTy = AT->getElementType();
Chris Lattnera10b29b2007-04-25 05:02:56 +00001556 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001557 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001558 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001559 ElementAllocas.push_back(NA);
1560 WorkList.push_back(NA); // Add to worklist for recursive processing
1561 }
1562 }
1563
Bob Wilsonb742def2009-12-18 20:14:40 +00001564 // Now that we have created the new alloca instructions, rewrite all the
1565 // uses of the old alloca.
1566 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001567
Bob Wilsonb742def2009-12-18 20:14:40 +00001568 // Now erase any instructions that were made dead while rewriting the alloca.
1569 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001570 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001571
Dan Gohmanfe601042010-06-22 15:08:57 +00001572 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001573}
Chris Lattnera59adc42009-12-14 05:11:02 +00001574
Bob Wilsonb742def2009-12-18 20:14:40 +00001575/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1576/// recursively including all their operands that become trivially dead.
1577void SROA::DeleteDeadInstructions() {
1578 while (!DeadInsts.empty()) {
1579 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001580
Bob Wilsonb742def2009-12-18 20:14:40 +00001581 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1582 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1583 // Zero out the operand and see if it becomes trivially dead.
1584 // (But, don't add allocas to the dead instruction list -- they are
1585 // already on the worklist and will be deleted separately.)
1586 *OI = 0;
1587 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1588 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001589 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001590
1591 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001592 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001593}
Bob Wilson69743022011-01-13 20:59:44 +00001594
Bob Wilsonb742def2009-12-18 20:14:40 +00001595/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1596/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001597/// the Info parameter. Offset indicates the position within AI that is
1598/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001599void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001600 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001601 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1602 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001603
Bob Wilsonb742def2009-12-18 20:14:40 +00001604 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001605 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001606 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001607 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001608 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001609 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001610 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001611 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001612 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001613 if (Length == 0)
1614 return MarkUnsafe(Info, User);
Aaron Ballman7e2fa312012-03-15 00:05:31 +00001615 if (Length->isNegative())
1616 return MarkUnsafe(Info, User);
1617
Chris Lattner6c95d242011-01-23 07:29:29 +00001618 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001619 UI.getOperandNo() == 0, Info, MI,
1620 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001621 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001622 if (!LI->isSimple())
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001623 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001624 Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001625 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001626 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001627 Info.hasALoadOrStore = true;
1628
Bob Wilsonb742def2009-12-18 20:14:40 +00001629 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1630 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman2bc3d522011-09-12 20:23:13 +00001631 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001632 return MarkUnsafe(Info, User);
1633
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001634 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001635 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001636 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001637 Info.hasALoadOrStore = true;
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001638 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1639 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1640 II->getIntrinsicID() != Intrinsic::lifetime_end)
1641 return MarkUnsafe(Info, User);
Chris Lattner145c5322011-01-23 08:27:54 +00001642 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1643 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1644 } else {
1645 return MarkUnsafe(Info, User);
1646 }
1647 if (Info.isUnsafe) return;
1648 }
1649}
1650
1651
1652/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1653/// derived from the alloca, we can often still split the alloca into elements.
1654/// This is useful if we have a large alloca where one element is phi'd
1655/// together somewhere: we can SRoA and promote all the other elements even if
1656/// we end up not being able to promote this one.
1657///
1658/// All we require is that the uses of the PHI do not index into other parts of
1659/// the alloca. The most important use case for this is single load and stores
1660/// that are PHI'd together, which can happen due to code sinking.
1661void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1662 AllocaInfo &Info) {
1663 // If we've already checked this PHI, don't do it again.
1664 if (PHINode *PN = dyn_cast<PHINode>(I))
1665 if (!Info.CheckedPHIs.insert(PN))
1666 return;
1667
1668 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1669 Instruction *User = cast<Instruction>(*UI);
1670
1671 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1672 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1673 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1674 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1675 // but would have to prove that we're staying inside of an element being
1676 // promoted.
1677 if (!GEPI->hasAllZeroIndices())
1678 return MarkUnsafe(Info, User);
1679 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1680 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman2bc3d522011-09-12 20:23:13 +00001681 if (!LI->isSimple())
Chris Lattner145c5322011-01-23 08:27:54 +00001682 return MarkUnsafe(Info, User);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001683 Type *LIType = LI->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001684 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1685 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1686 Info.hasALoadOrStore = true;
1687
1688 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1689 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman2bc3d522011-09-12 20:23:13 +00001690 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner145c5322011-01-23 08:27:54 +00001691 return MarkUnsafe(Info, User);
1692
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001693 Type *SIType = SI->getOperand(0)->getType();
Chris Lattner145c5322011-01-23 08:27:54 +00001694 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1695 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1696 Info.hasALoadOrStore = true;
1697 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1698 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001699 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001700 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001701 }
1702 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001703 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001704}
Bob Wilson39c88a62009-12-17 18:34:24 +00001705
Bob Wilsonb742def2009-12-18 20:14:40 +00001706/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1707/// replacement. It is safe when all the indices are constant, in-bounds
1708/// references, and when the resulting offset corresponds to an element within
1709/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001710/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001711void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001712 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001713 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1714 if (GEPIt == E)
1715 return;
Pete Coopercbf73902012-06-15 18:07:29 +00001716 bool NonConstant = false;
1717 unsigned NonConstantIdxSize = 0;
Bob Wilson39c88a62009-12-17 18:34:24 +00001718
Chris Lattner88e6dc82008-08-23 05:21:06 +00001719 // Walk through the GEP type indices, checking the types that this indexes
1720 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001721 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001722 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001723 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001724 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001725
Bob Wilsonb742def2009-12-18 20:14:40 +00001726 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
Pete Coopercbf73902012-06-15 18:07:29 +00001727 if (!IdxVal) {
1728 // Non constant GEPs are only a problem on arrays, structs, and pointers
1729 // Vectors can be dynamically indexed.
1730 // FIXME: Add support for dynamic indexing on arrays. This should be
1731 // ok on any subarrays of the alloca array, eg, a[0][i] is ok, but a[i][0]
1732 // isn't.
1733 if (!(*GEPIt)->isVectorTy())
1734 return MarkUnsafe(Info, GEPI);
1735 NonConstant = true;
1736 NonConstantIdxSize = TD->getTypeAllocSize(*GEPIt);
1737 }
Chris Lattner88e6dc82008-08-23 05:21:06 +00001738 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001739
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001740 // Compute the offset due to this GEP and check if the alloca has a
1741 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001742 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Pete Coopercbf73902012-06-15 18:07:29 +00001743 // If this GEP is non constant then the last operand must have been a
1744 // dynamic index into a vector. Pop this now as it has no impact on the
1745 // constant part of the offset.
1746 if (NonConstant)
1747 Indices.pop_back();
Jay Foad8fbbb392011-07-19 14:01:37 +00001748 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Pete Coopercbf73902012-06-15 18:07:29 +00001749 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
1750 NonConstantIdxSize))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001751 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001752}
1753
Bob Wilson704d1342011-01-13 17:45:11 +00001754/// isHomogeneousAggregate - Check if type T is a struct or array containing
1755/// elements of the same type (which is always true for arrays). If so,
1756/// return true with NumElts and EltTy set to the number of elements and the
1757/// element type, respectively.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001758static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1759 Type *&EltTy) {
1760 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001761 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001762 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001763 return true;
1764 }
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001765 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson704d1342011-01-13 17:45:11 +00001766 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001767 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001768 for (unsigned n = 1; n < NumElts; ++n) {
1769 if (ST->getContainedType(n) != EltTy)
1770 return false;
1771 }
1772 return true;
1773 }
1774 return false;
1775}
1776
1777/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1778/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001779static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson704d1342011-01-13 17:45:11 +00001780 if (T1 == T2)
1781 return true;
1782
1783 unsigned NumElts1, NumElts2;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001784 Type *EltTy1, *EltTy2;
Bob Wilson704d1342011-01-13 17:45:11 +00001785 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1786 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1787 NumElts1 == NumElts2 &&
1788 EltTy1 == EltTy2)
1789 return true;
1790
1791 return false;
1792}
1793
Bob Wilsonb742def2009-12-18 20:14:40 +00001794/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1795/// alloca or has an offset and size that corresponds to a component element
1796/// within it. The offset checked here may have been formed from a GEP with a
1797/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001798///
1799/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1800/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001801void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001802 Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001803 AllocaInfo &Info, Instruction *TheAccess,
1804 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001805 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001806 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001807 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001808 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1809 // loads/stores (which are essentially the same as the MemIntrinsics with
1810 // regard to copying padding between elements). But, if an alloca is
1811 // flagged as both a source and destination of such operations, we'll need
1812 // to check later for padding between elements.
1813 if (!MemOpType || MemOpType->isIntegerTy()) {
1814 if (isStore)
1815 Info.isMemCpyDst = true;
1816 else
1817 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001818 return;
1819 }
Bob Wilson704d1342011-01-13 17:45:11 +00001820 // This is also safe for references using a type that is compatible with
1821 // the type of the alloca, so that loads/stores can be rewritten using
1822 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001823 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001824 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001825 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001826 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001827 }
1828 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001829 Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001830 if (TypeHasComponent(T, Offset, MemSize)) {
1831 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001832 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001833 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001834
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001835 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001836}
1837
1838/// TypeHasComponent - Return true if T has a component type with the
1839/// specified offset and size. If Size is zero, do not check the size.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001840bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1841 Type *EltTy;
Bob Wilsonb742def2009-12-18 20:14:40 +00001842 uint64_t EltSize;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001843 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001844 const StructLayout *Layout = TD->getStructLayout(ST);
1845 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1846 EltTy = ST->getContainedType(EltIdx);
1847 EltSize = TD->getTypeAllocSize(EltTy);
1848 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001849 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001850 EltTy = AT->getElementType();
1851 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001852 if (Offset >= AT->getNumElements() * EltSize)
1853 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001854 Offset %= EltSize;
Pete Cooper6399b7c2012-06-14 23:53:53 +00001855 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1856 EltTy = VT->getElementType();
1857 EltSize = TD->getTypeAllocSize(EltTy);
1858 if (Offset >= VT->getNumElements() * EltSize)
1859 return false;
1860 Offset %= EltSize;
Bob Wilsonb742def2009-12-18 20:14:40 +00001861 } else {
1862 return false;
1863 }
1864 if (Offset == 0 && (Size == 0 || EltSize == Size))
1865 return true;
1866 // Check if the component spans multiple elements.
1867 if (Offset + Size > EltSize)
1868 return false;
1869 return TypeHasComponent(EltTy, Offset, Size);
1870}
1871
1872/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1873/// the instruction I, which references it, to use the separate elements.
1874/// Offset indicates the position within AI that is referenced by this
1875/// instruction.
1876void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1877 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001878 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1879 Use &TheUse = UI.getUse();
1880 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001881
1882 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1883 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001884 continue;
1885 }
1886
1887 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001888 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001889 continue;
1890 }
1891
1892 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001893 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1894 uint64_t MemSize = Length->getZExtValue();
1895 if (Offset == 0 &&
1896 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1897 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001898 // Otherwise the intrinsic can only touch a single element and the
1899 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001900 continue;
1901 }
Nick Lewycky5a1cb642011-07-25 23:14:22 +00001902
1903 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1904 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1905 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1906 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1907 }
1908 continue;
1909 }
Chris Lattner145c5322011-01-23 08:27:54 +00001910
1911 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001912 Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001913
Bob Wilson704d1342011-01-13 17:45:11 +00001914 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001915 // Replace:
1916 // %res = load { i32, i32 }* %alloc
1917 // with:
1918 // %load.0 = load i32* %alloc.0
1919 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1920 // %load.1 = load i32* %alloc.1
1921 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1922 // (Also works for arrays instead of structs)
1923 Value *Insert = UndefValue::get(LIType);
Devang Patelabb25122011-06-03 19:46:19 +00001924 IRBuilder<> Builder(LI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001925 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001926 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1927 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilsonb742def2009-12-18 20:14:40 +00001928 }
1929 LI->replaceAllUsesWith(Insert);
1930 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001931 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001932 TD->getTypeAllocSize(LIType) ==
1933 TD->getTypeAllocSize(AI->getAllocatedType())) {
1934 // If this is a load of the entire alloca to an integer, rewrite it.
1935 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1936 }
Chris Lattner145c5322011-01-23 08:27:54 +00001937 continue;
1938 }
1939
1940 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001941 Value *Val = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001942 Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001943 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001944 // Replace:
1945 // store { i32, i32 } %val, { i32, i32 }* %alloc
1946 // with:
1947 // %val.0 = extractvalue { i32, i32 } %val, 0
1948 // store i32 %val.0, i32* %alloc.0
1949 // %val.1 = extractvalue { i32, i32 } %val, 1
1950 // store i32 %val.1, i32* %alloc.1
1951 // (Also works for arrays instead of structs)
Devang Patelabb25122011-06-03 19:46:19 +00001952 IRBuilder<> Builder(SI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001953 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patelabb25122011-06-03 19:46:19 +00001954 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1955 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilsonb742def2009-12-18 20:14:40 +00001956 }
1957 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001958 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001959 TD->getTypeAllocSize(SIType) ==
1960 TD->getTypeAllocSize(AI->getAllocatedType())) {
1961 // If this is a store of the entire alloca from an integer, rewrite it.
1962 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1963 }
Chris Lattner145c5322011-01-23 08:27:54 +00001964 continue;
1965 }
1966
1967 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1968 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1969 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1970 // the new pointer.
1971 if (!isa<AllocaInst>(I)) continue;
1972
1973 assert(Offset == 0 && NewElts[0] &&
1974 "Direct alloca use should have a zero offset");
1975
1976 // If we have a use of the alloca, we know the derived uses will be
1977 // utilizing just the first element of the scalarized result. Insert a
1978 // bitcast of the first alloca before the user as required.
1979 AllocaInst *NewAI = NewElts[0];
1980 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1981 NewAI->moveBefore(BCI);
1982 TheUse = BCI;
1983 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001984 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001985 }
1986}
1987
Bob Wilsonb742def2009-12-18 20:14:40 +00001988/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1989/// and recursively continue updating all of its uses.
1990void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1991 SmallVector<AllocaInst*, 32> &NewElts) {
1992 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1993 if (BC->getOperand(0) != AI)
1994 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001995
Bob Wilsonb742def2009-12-18 20:14:40 +00001996 // The bitcast references the original alloca. Replace its uses with
Eli Friedman75f69e32011-11-12 02:07:50 +00001997 // references to the alloca containing offset zero (which is normally at
1998 // index zero, but might not be in cases involving structs with elements
1999 // of size zero).
2000 Type *T = AI->getAllocatedType();
2001 uint64_t EltOffset = 0;
2002 Type *IdxTy;
2003 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2004 Instruction *Val = NewElts[Idx];
Bob Wilsonb742def2009-12-18 20:14:40 +00002005 if (Val->getType() != BC->getDestTy()) {
2006 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2007 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00002008 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002009 BC->replaceAllUsesWith(Val);
2010 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00002011}
2012
Bob Wilsonb742def2009-12-18 20:14:40 +00002013/// FindElementAndOffset - Return the index of the element containing Offset
2014/// within the specified type, which must be either a struct or an array.
2015/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00002016/// element. IdxTy is set to the type of the index result to be used in a
2017/// GEP instruction.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002018uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2019 Type *&IdxTy) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002020 uint64_t Idx = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002021 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00002022 const StructLayout *Layout = TD->getStructLayout(ST);
2023 Idx = Layout->getElementContainingOffset(Offset);
2024 T = ST->getContainedType(Idx);
2025 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00002026 IdxTy = Type::getInt32Ty(T->getContext());
2027 return Idx;
Pete Cooper6399b7c2012-06-14 23:53:53 +00002028 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2029 T = AT->getElementType();
2030 uint64_t EltSize = TD->getTypeAllocSize(T);
2031 Idx = Offset / EltSize;
2032 Offset -= Idx * EltSize;
2033 IdxTy = Type::getInt64Ty(T->getContext());
2034 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00002035 }
Pete Cooper6399b7c2012-06-14 23:53:53 +00002036 VectorType *VT = cast<VectorType>(T);
2037 T = VT->getElementType();
Bob Wilsone88728d2009-12-19 06:53:17 +00002038 uint64_t EltSize = TD->getTypeAllocSize(T);
2039 Idx = Offset / EltSize;
2040 Offset -= Idx * EltSize;
2041 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00002042 return Idx;
2043}
2044
2045/// RewriteGEP - Check if this GEP instruction moves the pointer across
2046/// elements of the alloca that are being split apart, and if so, rewrite
2047/// the GEP to be relative to the new element.
2048void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2049 SmallVector<AllocaInst*, 32> &NewElts) {
2050 uint64_t OldOffset = Offset;
2051 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Pete Coopercbf73902012-06-15 18:07:29 +00002052 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2053 // In this case, it must be the last GEP operand which is dynamic so keep that
2054 // aside until we've found the constant GEP offset then add it back in at the
2055 // end.
2056 Value* NonConstantIdx = 0;
2057 if (!GEPI->hasAllConstantIndices())
2058 NonConstantIdx = Indices.pop_back_val();
Jay Foad8fbbb392011-07-19 14:01:37 +00002059 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilsonb742def2009-12-18 20:14:40 +00002060
2061 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2062
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002063 Type *T = AI->getAllocatedType();
2064 Type *IdxTy;
Bob Wilsone88728d2009-12-19 06:53:17 +00002065 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002066 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00002067 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00002068
2069 T = AI->getAllocatedType();
2070 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00002071 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00002072
2073 // If this GEP does not move the pointer across elements of the alloca
2074 // being split, then it does not needs to be rewritten.
2075 if (Idx == OldIdx)
2076 return;
2077
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002078 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00002079 SmallVector<Value*, 8> NewArgs;
2080 NewArgs.push_back(Constant::getNullValue(i32Ty));
2081 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00002082 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2083 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00002084 }
Pete Cooper06e6c382012-06-16 01:43:26 +00002085 if (NonConstantIdx) {
2086 Type* GepTy = T;
2087 // This GEP has a dynamic index. We need to add "i32 0" to index through
2088 // any structs or arrays in the original type until we get to the vector
2089 // to index.
2090 while (!isa<VectorType>(GepTy)) {
2091 NewArgs.push_back(Constant::getNullValue(i32Ty));
2092 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2093 }
Pete Coopercbf73902012-06-15 18:07:29 +00002094 NewArgs.push_back(NonConstantIdx);
Pete Cooper06e6c382012-06-16 01:43:26 +00002095 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002096 Instruction *Val = NewElts[Idx];
2097 if (NewArgs.size() > 1) {
Jay Foada9203102011-07-25 09:48:08 +00002098 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002099 Val->takeName(GEPI);
2100 }
2101 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002102 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002103 GEPI->replaceAllUsesWith(Val);
2104 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002105}
2106
Nick Lewycky5a1cb642011-07-25 23:14:22 +00002107/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2108/// to mark the lifetime of the scalarized memory.
2109void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2110 uint64_t Offset,
2111 SmallVector<AllocaInst*, 32> &NewElts) {
2112 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2113 // Put matching lifetime markers on everything from Offset up to
2114 // Offset+OldSize.
2115 Type *AIType = AI->getAllocatedType();
2116 uint64_t NewOffset = Offset;
2117 Type *IdxTy;
2118 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2119
2120 IRBuilder<> Builder(II);
2121 uint64_t Size = OldSize->getLimitedValue();
2122
2123 if (NewOffset) {
2124 // Splice the first element and index 'NewOffset' bytes in. SROA will
2125 // split the alloca again later.
2126 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy());
2127 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2128
2129 IdxTy = NewElts[Idx]->getAllocatedType();
2130 uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset;
2131 if (EltSize > Size) {
2132 EltSize = Size;
2133 Size = 0;
2134 } else {
2135 Size -= EltSize;
2136 }
2137 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2138 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2139 else
2140 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2141 ++Idx;
2142 }
2143
2144 for (; Idx != NewElts.size() && Size; ++Idx) {
2145 IdxTy = NewElts[Idx]->getAllocatedType();
2146 uint64_t EltSize = TD->getTypeAllocSize(IdxTy);
2147 if (EltSize > Size) {
2148 EltSize = Size;
2149 Size = 0;
2150 } else {
2151 Size -= EltSize;
2152 }
2153 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2154 Builder.CreateLifetimeStart(NewElts[Idx],
2155 Builder.getInt64(EltSize));
2156 else
2157 Builder.CreateLifetimeEnd(NewElts[Idx],
2158 Builder.getInt64(EltSize));
2159 }
2160 DeadInsts.push_back(II);
2161}
2162
Chris Lattnerd93afec2009-01-07 07:18:45 +00002163/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2164/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00002165void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00002166 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00002167 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002168 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00002169 // appropriate type. The "Other" pointer is the pointer that goes to memory
2170 // that doesn't have anything to do with the alloca that we are promoting. For
2171 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00002172 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00002173 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00002174 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00002175 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00002176 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002177 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00002178 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00002179 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00002180 }
2181 }
Bob Wilson78c50b82009-12-08 18:22:03 +00002182
Chris Lattnerd93afec2009-01-07 07:18:45 +00002183 // If there is an other pointer, we want to convert it to the same pointer
2184 // type as AI has, so we can GEP through it safely.
2185 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002186 unsigned AddrSpace =
2187 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002188
2189 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2190 // optimization, but it's also required to detect the corner case where
2191 // both pointer operands are referencing the same memory, and where
2192 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2193 // function is only called for mem intrinsics that access the whole
2194 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002195 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002196
Bob Wilsona756b1d2010-01-19 04:32:48 +00002197 // Copying the alloca to itself is a no-op: just delete it.
2198 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2199 // This code will run twice for a no-op memcpy -- once for each operand.
2200 // Put only one reference to MI on the DeadInsts list.
2201 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2202 E = DeadInsts.end(); I != E; ++I)
2203 if (*I == MI) return;
2204 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002205 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002206 }
Bob Wilson69743022011-01-13 20:59:44 +00002207
Chris Lattnerd93afec2009-01-07 07:18:45 +00002208 // If the pointer is not the right type, insert a bitcast to the right
2209 // type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002210 Type *NewTy =
Chris Lattner0238f8c2010-07-08 00:27:05 +00002211 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002212
Chris Lattner0238f8c2010-07-08 00:27:05 +00002213 if (OtherPtr->getType() != NewTy)
2214 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002215 }
Bob Wilson69743022011-01-13 20:59:44 +00002216
Chris Lattnerd93afec2009-01-07 07:18:45 +00002217 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002218 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002219
Owen Anderson1d0be152009-08-13 21:58:54 +00002220 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002221
2222 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2223 // If this is a memcpy/memmove, emit a GEP of the other element address.
2224 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002225 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002226
Bob Wilsona756b1d2010-01-19 04:32:48 +00002227 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002228 Value *Idx[2] = { Zero,
2229 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Jay Foada9203102011-07-25 09:48:08 +00002230 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002231 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002232 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002233 uint64_t EltOffset;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002234 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2235 Type *OtherTy = OtherPtrTy->getElementType();
2236 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002237 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2238 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002239 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002240 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002241 }
Bob Wilson69743022011-01-13 20:59:44 +00002242
Chris Lattner1541e0f2009-03-04 19:20:50 +00002243 // The alignment of the other pointer is the guaranteed alignment of the
2244 // element, which is affected by both the known alignment of the whole
2245 // mem intrinsic and the alignment of the element. If the alignment of
2246 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2247 // known alignment is just 4 bytes.
2248 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002249 }
Bob Wilson69743022011-01-13 20:59:44 +00002250
Chris Lattnerd93afec2009-01-07 07:18:45 +00002251 Value *EltPtr = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002252 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002253
Chris Lattnerd93afec2009-01-07 07:18:45 +00002254 // If we got down to a scalar, insert a load or store as appropriate.
2255 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002256 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002257 if (SROADest) {
2258 // From Other to Alloca.
2259 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2260 new StoreInst(Elt, EltPtr, MI);
2261 } else {
2262 // From Alloca to Other.
2263 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2264 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2265 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002266 continue;
2267 }
2268 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002269
Chris Lattnerd93afec2009-01-07 07:18:45 +00002270 // If the stored element is zero (common case), just store a null
2271 // constant.
2272 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002273 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002274 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002275 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002276 } else {
2277 // If EltTy is a vector type, get the element type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002278 Type *ValTy = EltTy->getScalarType();
Dan Gohman44118f02009-06-16 00:20:26 +00002279
Chris Lattnerd93afec2009-01-07 07:18:45 +00002280 // Construct an integer with the right value.
2281 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2282 APInt OneVal(EltSize, CI->getZExtValue());
2283 APInt TotalVal(OneVal);
2284 // Set each byte.
2285 for (unsigned i = 0; 8*i < EltSize; ++i) {
2286 TotalVal = TotalVal.shl(8);
2287 TotalVal |= OneVal;
2288 }
Bob Wilson69743022011-01-13 20:59:44 +00002289
Chris Lattnerd93afec2009-01-07 07:18:45 +00002290 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002291 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002292 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002293 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002294 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002295 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002296 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002297
Chris Lattnerd93afec2009-01-07 07:18:45 +00002298 // If the requested value was a vector constant, create it.
Cameron Zwarichc055a872011-10-11 21:26:40 +00002299 if (EltTy->isVectorTy()) {
2300 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
Chris Lattner4ca829e2012-01-25 06:02:56 +00002301 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002302 }
2303 }
2304 new StoreInst(StoreVal, EltPtr, MI);
2305 continue;
2306 }
2307 // Otherwise, if we're storing a byte variable, use a memset call for
2308 // this element.
2309 }
Bob Wilson69743022011-01-13 20:59:44 +00002310
Duncan Sands777d2302009-05-09 07:06:46 +00002311 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Eli Friedman75f69e32011-11-12 02:07:50 +00002312 if (!EltSize)
2313 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002314
Chris Lattner61db1f52010-12-26 22:57:41 +00002315 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002316
Chris Lattnerd93afec2009-01-07 07:18:45 +00002317 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002318 if (isa<MemSetInst>(MI)) {
2319 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2320 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002321 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002322 assert(isa<MemTransferInst>(MI));
2323 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2324 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002325
Chris Lattner61db1f52010-12-26 22:57:41 +00002326 if (isa<MemCpyInst>(MI))
2327 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2328 else
2329 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002330 }
Chris Lattner372dda82007-03-05 07:52:57 +00002331 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002332 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002333}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002334
Bob Wilson39fdd692009-12-04 21:57:37 +00002335/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002336/// overwrites the entire allocation. Extract out the pieces of the stored
2337/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002338void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002339 SmallVector<AllocaInst*, 32> &NewElts){
2340 // Extract each element out of the integer according to its structure offset
2341 // and store the element value to the individual alloca.
2342 Value *SrcVal = SI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002343 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002344 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002345
Chris Lattner70728532011-01-16 05:58:24 +00002346 IRBuilder<> Builder(SI);
2347
Eli Friedman41b33f42009-06-01 09:14:32 +00002348 // Handle tail padding by extending the operand
2349 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002350 SrcVal = Builder.CreateZExt(SrcVal,
2351 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002352
David Greene504c7d82010-01-05 01:27:09 +00002353 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002354 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002355
2356 // There are two forms here: AI could be an array or struct. Both cases
2357 // have different ways to compute the element offset.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002358 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002359 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002360
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002361 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2362 // Get the number of bits to shift SrcVal to get the value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002363 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002364 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002365
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002366 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002367 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002368
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002369 Value *EltVal = SrcVal;
2370 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002371 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002372 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002373 }
Bob Wilson69743022011-01-13 20:59:44 +00002374
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002375 // Truncate down to an integer of the right size.
2376 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002377
Chris Lattner583dd602009-01-09 18:18:43 +00002378 // Ignore zero sized fields like {}, they obviously contain no data.
2379 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002380
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002381 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002382 EltVal = Builder.CreateTrunc(EltVal,
2383 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002384 Value *DestField = NewElts[i];
2385 if (EltVal->getType() == FieldTy) {
2386 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002387 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002388 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002389 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002390 } else {
2391 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002392 DestField = Builder.CreateBitCast(DestField,
2393 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002394 }
2395 new StoreInst(EltVal, DestField, SI);
2396 }
Bob Wilson69743022011-01-13 20:59:44 +00002397
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002398 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002399 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2400 Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002401 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002402 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2403
2404 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002405
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002406 if (TD->isBigEndian())
2407 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002408 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002409 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002410
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002411 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002412 // Ignore zero sized fields like {}, they obviously contain no data.
2413 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002414
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002415 Value *EltVal = SrcVal;
2416 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002417 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002418 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002419 }
Bob Wilson69743022011-01-13 20:59:44 +00002420
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002421 // Truncate down to an integer of the right size.
2422 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002423 EltVal = Builder.CreateTrunc(EltVal,
2424 IntegerType::get(SI->getContext(),
2425 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002426 Value *DestField = NewElts[i];
2427 if (EltVal->getType() == ArrayEltTy) {
2428 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002429 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002430 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002431 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002432 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002433 } else {
2434 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002435 DestField = Builder.CreateBitCast(DestField,
2436 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002437 }
2438 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002439
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002440 if (TD->isBigEndian())
2441 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002442 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002443 Shift += ElementOffset;
2444 }
2445 }
Bob Wilson69743022011-01-13 20:59:44 +00002446
Bob Wilsonb742def2009-12-18 20:14:40 +00002447 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002448}
2449
Bob Wilson39fdd692009-12-04 21:57:37 +00002450/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002451/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002452void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002453 SmallVector<AllocaInst*, 32> &NewElts) {
2454 // Extract each element out of the NewElts according to its structure offset
2455 // and form the result value.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002456 Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002457 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002458
David Greene504c7d82010-01-05 01:27:09 +00002459 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002460 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002461
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002462 // There are two forms here: AI could be an array or struct. Both cases
2463 // have different ways to compute the element offset.
2464 const StructLayout *Layout = 0;
2465 uint64_t ArrayEltBitOffset = 0;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002466 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002467 Layout = TD->getStructLayout(EltSTy);
2468 } else {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002469 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002470 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002471 }
2472
2473 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002474 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002475
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002476 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2477 // Load the value from the alloca. If the NewElt is an aggregate, cast
2478 // the pointer to an integer of the same size before doing the load.
2479 Value *SrcField = NewElts[i];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002480 Type *FieldTy =
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002481 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002482 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002483
Chris Lattner583dd602009-01-09 18:18:43 +00002484 // Ignore zero sized fields like {}, they obviously contain no data.
2485 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002486
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002487 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002488 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002489 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2490 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002491 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002492 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002493 "", LI);
2494 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2495
2496 // If SrcField is a fp or vector of the right size but that isn't an
2497 // integer type, bitcast to an integer so we can shift it.
2498 if (SrcField->getType() != FieldIntTy)
2499 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2500
2501 // Zero extend the field to be the same size as the final alloca so that
2502 // we can shift and insert it.
2503 if (SrcField->getType() != ResultVal->getType())
2504 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002505
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002506 // Determine the number of bits to shift SrcField.
2507 uint64_t Shift;
2508 if (Layout) // Struct case.
2509 Shift = Layout->getElementOffsetInBits(i);
2510 else // Array case.
2511 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002512
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002513 if (TD->isBigEndian())
2514 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002515
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002516 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002517 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002518 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2519 }
2520
Chris Lattner14952472010-06-27 07:58:26 +00002521 // Don't create an 'or x, 0' on the first iteration.
2522 if (!isa<Constant>(ResultVal) ||
2523 !cast<Constant>(ResultVal)->isNullValue())
2524 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2525 else
2526 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002527 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002528
2529 // Handle tail padding by truncating the result
2530 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2531 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2532
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002533 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002534 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002535}
2536
Duncan Sands3cb36502007-11-04 14:43:57 +00002537/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002538/// alignment padding in between the elements that would be split apart
2539/// by SROA; return false otherwise.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002540static bool HasPadding(Type *Ty, const TargetData &TD) {
2541 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002542 Ty = ATy->getElementType();
2543 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002544 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002545
2546 // SROA currently handles only Arrays and Structs.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002547 StructType *STy = cast<StructType>(Ty);
Bob Wilson694a10e2011-01-13 17:45:08 +00002548 const StructLayout *SL = TD.getStructLayout(STy);
2549 unsigned PrevFieldBitOffset = 0;
2550 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2551 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2552
2553 // Check to see if there is any padding between this element and the
2554 // previous one.
2555 if (i) {
2556 unsigned PrevFieldEnd =
2557 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2558 if (PrevFieldEnd < FieldBitOffset)
2559 return true;
2560 }
2561 PrevFieldBitOffset = FieldBitOffset;
2562 }
2563 // Check for tail padding.
2564 if (unsigned EltCount = STy->getNumElements()) {
2565 unsigned PrevFieldEnd = PrevFieldBitOffset +
2566 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2567 if (PrevFieldEnd < SL->getSizeInBits())
2568 return true;
2569 }
2570 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002571}
Chris Lattner372dda82007-03-05 07:52:57 +00002572
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002573/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2574/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2575/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002576bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002577 // Loop over the use list of the alloca. We can only transform it if all of
2578 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002579 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002580
Chris Lattner6c95d242011-01-23 07:29:29 +00002581 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002582 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002583 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002584 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002585 }
Bob Wilson69743022011-01-13 20:59:44 +00002586
Chris Lattner39a1c042007-05-30 06:11:23 +00002587 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2588 // source and destination, we have to be careful. In particular, the memcpy
2589 // could be moving around elements that live in structure padding of the LLVM
2590 // types, but may actually be used. In these cases, we refuse to promote the
2591 // struct.
2592 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002593 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002594 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002595
Chris Lattner396a0562011-01-16 17:46:19 +00002596 // If the alloca never has an access to just *part* of it, but is accessed
2597 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002598 // the alloca instead of promoting each piece at a time and inserting fission
2599 // and fusion code.
2600 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2601 // If the struct/array just has one element, use basic SRoA.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002602 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00002603 if (ST->getNumElements() > 1) return false;
2604 } else {
2605 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2606 return false;
2607 }
2608 }
Chris Lattner145c5322011-01-23 08:27:54 +00002609
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002610 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002611}
Chris Lattnera1888942005-12-12 07:19:13 +00002612
Chris Lattner800de312008-02-29 07:03:13 +00002613
Chris Lattner79b3bd32007-04-25 06:40:51 +00002614
2615/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2616/// some part of a constant global variable. This intentionally only accepts
2617/// constant expressions because we don't can't rewrite arbitrary instructions.
2618static bool PointsToConstantGlobal(Value *V) {
2619 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2620 return GV->isConstant();
2621 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002622 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002623 CE->getOpcode() == Instruction::GetElementPtr)
2624 return PointsToConstantGlobal(CE->getOperand(0));
2625 return false;
2626}
2627
2628/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2629/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2630/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2631/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2632/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002633/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002634/// can optimize this.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002635static bool
2636isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2637 bool isOffset,
2638 SmallVector<Instruction *, 4> &LifetimeMarkers) {
2639 // We track lifetime intrinsics as we encounter them. If we decide to go
2640 // ahead and replace the value with the global, this lets the caller quickly
2641 // eliminate the markers.
2642
Chris Lattner79b3bd32007-04-25 06:40:51 +00002643 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002644 User *U = cast<Instruction>(*UI);
2645
Chris Lattner2e618492010-11-18 06:20:47 +00002646 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002647 // Ignore non-volatile loads, they are always ok.
Eli Friedman2bc3d522011-09-12 20:23:13 +00002648 if (!LI->isSimple()) return false;
Chris Lattner2e618492010-11-18 06:20:47 +00002649 continue;
2650 }
Bob Wilson69743022011-01-13 20:59:44 +00002651
Gabor Greif8a8a4352010-04-06 19:32:30 +00002652 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002653 // If uses of the bitcast are ok, we are ok.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002654 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset,
2655 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002656 return false;
2657 continue;
2658 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002659 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002660 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2661 // doesn't, it does.
2662 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002663 isOffset || !GEP->hasAllZeroIndices(),
2664 LifetimeMarkers))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002665 return false;
2666 continue;
2667 }
Bob Wilson69743022011-01-13 20:59:44 +00002668
Chris Lattner62480652010-11-18 06:41:51 +00002669 if (CallSite CS = U) {
Nick Lewycky081f8002010-11-24 22:04:20 +00002670 // If this is the function being called then we treat it like a load and
2671 // ignore it.
2672 if (CS.isCallee(UI))
2673 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002674
Duncan Sands53892102011-05-06 10:30:37 +00002675 // If this is a readonly/readnone call site, then we know it is just a
2676 // load (but one that potentially returns the value itself), so we can
2677 // ignore it if we know that the value isn't captured.
2678 unsigned ArgNo = CS.getArgumentNo(UI);
2679 if (CS.onlyReadsMemory() &&
Nick Lewycky173862e2011-11-20 19:09:04 +00002680 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
Duncan Sands53892102011-05-06 10:30:37 +00002681 continue;
2682
Chris Lattner62480652010-11-18 06:41:51 +00002683 // If this is being passed as a byval argument, the caller is making a
2684 // copy, so it is only a read of the alloca.
Nick Lewycky173862e2011-11-20 19:09:04 +00002685 if (CS.isByValArgument(ArgNo))
Chris Lattner62480652010-11-18 06:41:51 +00002686 continue;
2687 }
Bob Wilson69743022011-01-13 20:59:44 +00002688
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002689 // Lifetime intrinsics can be handled by the caller.
2690 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
2691 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2692 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2693 assert(II->use_empty() && "Lifetime markers have no result to use!");
2694 LifetimeMarkers.push_back(II);
2695 continue;
2696 }
2697 }
2698
Chris Lattner79b3bd32007-04-25 06:40:51 +00002699 // If this is isn't our memcpy/memmove, reject it as something we can't
2700 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002701 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2702 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002703 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002704
Chris Lattner2e618492010-11-18 06:20:47 +00002705 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002706 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002707 if (UI.getOperandNo() == 1) {
2708 if (MI->isVolatile()) return false;
2709 continue;
2710 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002711
2712 // If we already have seen a copy, reject the second one.
2713 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002714
Chris Lattner79b3bd32007-04-25 06:40:51 +00002715 // If the pointer has been offset from the start of the alloca, we can't
2716 // safely handle this.
2717 if (isOffset) return false;
2718
2719 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002720 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002721
Chris Lattner79b3bd32007-04-25 06:40:51 +00002722 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002723 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002724 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002725
Chris Lattner79b3bd32007-04-25 06:40:51 +00002726 // Otherwise, the transform is safe. Remember the copy instruction.
2727 TheCopy = MI;
2728 }
2729 return true;
2730}
2731
2732/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2733/// modified by a copy from a constant global. If we can prove this, we can
2734/// replace any uses of the alloca with uses of the global directly.
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002735MemTransferInst *
2736SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
2737 SmallVector<Instruction*, 4> &ToDelete) {
Chris Lattner31d80102010-04-15 21:59:20 +00002738 MemTransferInst *TheCopy = 0;
Nick Lewycky9174d5c2011-06-27 05:40:02 +00002739 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false, ToDelete))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002740 return TheCopy;
2741 return 0;
2742}