blob: 984f5c85d8be2b590a556bcc6adf32fea688a92a [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner72eaa0e2010-09-01 23:09:27 +000031#include "llvm/Module.h"
Chris Lattner372dda82007-03-05 07:52:57 +000032#include "llvm/Pass.h"
Cameron Zwarichb1686c32011-01-18 03:53:26 +000033#include "llvm/Analysis/Dominators.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000034#include "llvm/Analysis/Loads.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000035#include "llvm/Analysis/ValueTracking.h"
Chris Lattner38aec322003-09-11 16:45:55 +000036#include "llvm/Target/TargetData.h"
37#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000038#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere0a1a5b2011-01-14 07:50:47 +000039#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattnera9be1df2010-11-18 06:26:49 +000040#include "llvm/Support/CallSite.h"
Chris Lattner95255282006-06-28 23:17:24 +000041#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000042#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000043#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000044#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000045#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000046#include "llvm/Support/raw_ostream.h"
Chris Lattnerc87c50a2011-01-23 22:04:55 +000047#include "llvm/ADT/SetVector.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000048#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000049#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000050using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000051
Chris Lattner0e5f4992006-12-19 21:40:18 +000052STATISTIC(NumReplaced, "Number of allocas broken up");
53STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnerc87c50a2011-01-23 22:04:55 +000054STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner0e5f4992006-12-19 21:40:18 +000055STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000056STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000057
Chris Lattner0e5f4992006-12-19 21:40:18 +000058namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000059 struct SROA : public FunctionPass {
Cameron Zwarichb1686c32011-01-18 03:53:26 +000060 SROA(int T, bool hasDT, char &ID)
61 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patelff366852007-07-09 21:19:23 +000062 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000063 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000064 else
65 SRThreshold = T;
66 }
Devang Patel794fd752007-05-01 21:15:47 +000067
Chris Lattnered7b41e2003-05-27 15:45:27 +000068 bool runOnFunction(Function &F);
69
Chris Lattner38aec322003-09-11 16:45:55 +000070 bool performScalarRepl(Function &F);
71 bool performPromotion(Function &F);
72
Chris Lattnered7b41e2003-05-27 15:45:27 +000073 private:
Cameron Zwarichb1686c32011-01-18 03:53:26 +000074 bool HasDomTree;
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
Bob Wilson69743022011-01-13 20:59:44 +000076
Bob Wilsonb742def2009-12-18 20:14:40 +000077 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
80
Chris Lattner39a1c042007-05-30 06:11:23 +000081 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
84 struct AllocaInfo {
Chris Lattner6c95d242011-01-23 07:29:29 +000085 /// The alloca to promote.
86 AllocaInst *AI;
87
Chris Lattner145c5322011-01-23 08:27:54 +000088 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
89 /// looping and avoid redundant work.
90 SmallPtrSet<PHINode*, 8> CheckedPHIs;
91
Chris Lattner39a1c042007-05-30 06:11:23 +000092 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
93 bool isUnsafe : 1;
Bob Wilson69743022011-01-13 20:59:44 +000094
Chris Lattner39a1c042007-05-30 06:11:23 +000095 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
96 bool isMemCpySrc : 1;
97
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000098 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000099 bool isMemCpyDst : 1;
100
Chris Lattner7e9b4272011-01-16 06:18:28 +0000101 /// hasSubelementAccess - This is true if a subelement of the alloca is
102 /// ever accessed, or false if the alloca is only accessed with mem
103 /// intrinsics or load/store that only access the entire alloca at once.
104 bool hasSubelementAccess : 1;
105
106 /// hasALoadOrStore - This is true if there are any loads or stores to it.
107 /// The alloca may just be accessed with memcpy, for example, which would
108 /// not set this.
109 bool hasALoadOrStore : 1;
110
Chris Lattner6c95d242011-01-23 07:29:29 +0000111 explicit AllocaInfo(AllocaInst *ai)
112 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner7e9b4272011-01-16 06:18:28 +0000113 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +0000114 };
Bob Wilson69743022011-01-13 20:59:44 +0000115
Devang Patelff366852007-07-09 21:19:23 +0000116 unsigned SRThreshold;
117
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000118 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
119 I.isUnsafe = true;
120 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
121 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000122
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000123 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000124
Chris Lattner6c95d242011-01-23 07:29:29 +0000125 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner145c5322011-01-23 08:27:54 +0000126 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
127 AllocaInfo &Info);
Chris Lattner6c95d242011-01-23 07:29:29 +0000128 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
129 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattnerd01a0da2011-01-23 07:05:44 +0000130 const Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner145c5322011-01-23 08:27:54 +0000131 Instruction *TheAccess, bool AllowWholeAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +0000132 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000133 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
134 const Type *&IdxTy);
Bob Wilson69743022011-01-13 20:59:44 +0000135
136 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000137 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000138 void DeleteDeadInstructions();
Bob Wilson69743022011-01-13 20:59:44 +0000139
Bob Wilsonb742def2009-12-18 20:14:40 +0000140 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
141 SmallVector<AllocaInst*, 32> &NewElts);
142 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
143 SmallVector<AllocaInst*, 32> &NewElts);
144 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
145 SmallVector<AllocaInst*, 32> &NewElts);
146 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000147 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000148 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000149 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000150 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000151 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000152 SmallVector<AllocaInst*, 32> &NewElts);
Bob Wilson69743022011-01-13 20:59:44 +0000153
Chris Lattner31d80102010-04-15 21:59:20 +0000154 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000155 };
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000156
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000157 // SROA_DT - SROA that uses DominatorTree.
158 struct SROA_DT : public SROA {
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000159 static char ID;
160 public:
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000161 SROA_DT(int T = -1) : SROA(T, true, ID) {
162 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000163 }
164
165 // getAnalysisUsage - This pass does not require any passes, but we know it
166 // will not alter the CFG, so say so.
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequired<DominatorTree>();
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000169 AU.setPreservesCFG();
170 }
171 };
172
173 // SROA_SSAUp - SROA that uses SSAUpdater.
174 struct SROA_SSAUp : public SROA {
175 static char ID;
176 public:
177 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
178 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
179 }
180
181 // getAnalysisUsage - This pass does not require any passes, but we know it
182 // will not alter the CFG, so say so.
183 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
184 AU.setPreservesCFG();
185 }
186 };
187
Chris Lattnered7b41e2003-05-27 15:45:27 +0000188}
189
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000190char SROA_DT::ID = 0;
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000191char SROA_SSAUp::ID = 0;
192
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000193INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
194 "Scalar Replacement of Aggregates (DT)", false, false)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000195INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000196INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
197 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000198
199INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
200 "Scalar Replacement of Aggregates (SSAUp)", false, false)
201INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
202 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000203
Brian Gaeked0fde302003-11-11 22:41:34 +0000204// Public interface to the ScalarReplAggregates pass
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000205FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Cameron Zwarichb1686c32011-01-18 03:53:26 +0000206 bool UseDomTree) {
207 if (UseDomTree)
208 return new SROA_DT(Threshold);
Chris Lattnerb352d6e2011-01-14 08:13:00 +0000209 return new SROA_SSAUp(Threshold);
Devang Patelff366852007-07-09 21:19:23 +0000210}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000211
212
Chris Lattner4cc576b2010-04-16 00:24:57 +0000213//===----------------------------------------------------------------------===//
214// Convert To Scalar Optimization.
215//===----------------------------------------------------------------------===//
216
217namespace {
Chris Lattnera001b662010-04-16 00:38:19 +0000218/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
219/// optimization, which scans the uses of an alloca and determines if it can
220/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000221class ConvertToScalarInfo {
Cameron Zwarichd4c9c3e2011-03-16 00:13:35 +0000222 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000223 unsigned AllocaSize;
224 const TargetData &TD;
Bob Wilson69743022011-01-13 20:59:44 +0000225
Chris Lattnera0bada72010-04-16 02:32:17 +0000226 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnera001b662010-04-16 00:38:19 +0000227 /// which means that mem2reg can't promote it.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000228 bool IsNotTrivial;
Bob Wilson69743022011-01-13 20:59:44 +0000229
Chris Lattnera001b662010-04-16 00:38:19 +0000230 /// VectorTy - This tracks the type that we should promote the vector to if
231 /// it is possible to turn it into a vector. This starts out null, and if it
232 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000233 const Type *VectorTy;
Bob Wilson69743022011-01-13 20:59:44 +0000234
Chris Lattnera001b662010-04-16 00:38:19 +0000235 /// HadAVector - True if there is at least one vector access to the alloca.
236 /// We don't want to turn random arrays into vectors and use vector element
237 /// insert/extract, but if there are element accesses to something that is
238 /// also declared as a vector, we do want to promote to a vector.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000239 bool HadAVector;
240
Cameron Zwarich1bcdb6f2011-03-16 08:13:42 +0000241 /// HadNonMemTransferAccess - True if there is at least one access to the
242 /// alloca that is not a MemTransferInst. We don't want to turn structs into
243 /// large integers unless there is some potential for optimization.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000244 bool HadNonMemTransferAccess;
245
Chris Lattner4cc576b2010-04-16 00:24:57 +0000246public:
247 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
Cameron Zwarichdeac2682011-03-16 00:13:37 +0000248 : AllocaSize(Size), TD(td), IsNotTrivial(false), VectorTy(0),
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000249 HadAVector(false), HadNonMemTransferAccess(false) { }
Bob Wilson69743022011-01-13 20:59:44 +0000250
Chris Lattnera001b662010-04-16 00:38:19 +0000251 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson69743022011-01-13 20:59:44 +0000252
Chris Lattner4cc576b2010-04-16 00:24:57 +0000253private:
254 bool CanConvertToScalar(Value *V, uint64_t Offset);
Cameron Zwarich9827b782011-03-29 05:19:52 +0000255 void MergeInType(const Type *In, uint64_t Offset, bool IsLoadOrStore);
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000256 bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000257 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Bob Wilson69743022011-01-13 20:59:44 +0000258
Chris Lattner4cc576b2010-04-16 00:24:57 +0000259 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
260 uint64_t Offset, IRBuilder<> &Builder);
261 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
262 uint64_t Offset, IRBuilder<> &Builder);
263};
264} // end anonymous namespace.
265
Chris Lattner91abace2010-09-01 05:14:33 +0000266
Chris Lattnera001b662010-04-16 00:38:19 +0000267/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
268/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
269/// alloca if possible or null if not.
270AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
271 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
272 // out.
273 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
274 return 0;
Bob Wilson69743022011-01-13 20:59:44 +0000275
Chris Lattnera001b662010-04-16 00:38:19 +0000276 // If we were able to find a vector type that can handle this with
277 // insert/extract elements, and if there was at least one use that had
278 // a vector type, promote this to a vector. We don't want to promote
279 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
280 // we just get a lot of insert/extracts. If at least one vector is
281 // involved, then we probably really do have a union of vector/array.
282 const Type *NewTy;
Chris Lattner85a7c692011-01-23 06:40:33 +0000283 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
Chris Lattnera001b662010-04-16 00:38:19 +0000284 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
285 << *VectorTy << '\n');
286 NewTy = VectorTy; // Use the vector type.
287 } else {
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000288 unsigned BitWidth = AllocaSize * 8;
289 if (!HadAVector && !HadNonMemTransferAccess &&
290 !TD.fitsInLegalInteger(BitWidth))
291 return 0;
292
Chris Lattnera001b662010-04-16 00:38:19 +0000293 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
294 // Create and insert the integer alloca.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000295 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnera001b662010-04-16 00:38:19 +0000296 }
297 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
298 ConvertUsesToScalar(AI, NewAI, 0);
299 return NewAI;
300}
301
302/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
303/// so far at the offset specified by Offset (which is specified in bytes).
Chris Lattner4cc576b2010-04-16 00:24:57 +0000304///
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000305/// There are three cases we handle here:
Chris Lattner4cc576b2010-04-16 00:24:57 +0000306/// 1) A union of vector types of the same size and potentially its elements.
307/// Here we turn element accesses into insert/extract element operations.
308/// This promotes a <4 x float> with a store of float to the third element
309/// into a <4 x float> that uses insert element.
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000310/// 2) A union of vector types with power-of-2 size differences, e.g. a float,
311/// <2 x float> and <4 x float>. Here we turn element accesses into insert
312/// and extract element operations, and <2 x float> accesses into a cast to
313/// <2 x double>, an extract, and a cast back to <2 x float>.
314/// 3) A fully general blob of memory, which we turn into some (potentially
Chris Lattner4cc576b2010-04-16 00:24:57 +0000315/// large) integer type with extract and insert operations where the loads
Chris Lattnera001b662010-04-16 00:38:19 +0000316/// and stores would mutate the memory. We mark this by setting VectorTy
317/// to VoidTy.
Cameron Zwarich9827b782011-03-29 05:19:52 +0000318void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset,
319 bool IsLoadOrStore) {
Chris Lattnera001b662010-04-16 00:38:19 +0000320 // If we already decided to turn this into a blob of integer memory, there is
321 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000322 if (VectorTy && VectorTy->isVoidTy())
323 return;
Bob Wilson69743022011-01-13 20:59:44 +0000324
Chris Lattner4cc576b2010-04-16 00:24:57 +0000325 // If this could be contributing to a vector, analyze it.
326
327 // If the In type is a vector that is the same size as the alloca, see if it
328 // matches the existing VecTy.
329 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000330 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000331 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000332 } else if (In->isFloatTy() || In->isDoubleTy() ||
333 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
334 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000335 // Full width accesses can be ignored, because they can always be turned
336 // into bitcasts.
337 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
338 if (IsLoadOrStore && EltSize == AllocaSize)
339 return;
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000340
Chris Lattner4cc576b2010-04-16 00:24:57 +0000341 // If we're accessing something that could be an element of a vector, see
342 // if the implied vector agrees with what we already have and if Offset is
343 // compatible with it.
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000344 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0) {
345 if (!VectorTy) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000346 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich5fc12822011-04-20 21:48:16 +0000347 return;
348 }
349
350 unsigned CurrentEltSize = cast<VectorType>(VectorTy)->getElementType()
351 ->getPrimitiveSizeInBits()/8;
352 if (EltSize == CurrentEltSize)
353 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000354 }
355 }
Bob Wilson69743022011-01-13 20:59:44 +0000356
Chris Lattner4cc576b2010-04-16 00:24:57 +0000357 // Otherwise, we have a case that we can't handle with an optimized vector
358 // form. We can still turn this into a large integer.
359 VectorTy = Type::getVoidTy(In->getContext());
360}
361
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000362/// MergeInVectorType - Handles the vector case of MergeInType, returning true
363/// if the type was successfully merged and false otherwise.
364bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
365 uint64_t Offset) {
366 // Remember if we saw a vector type.
367 HadAVector = true;
368
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000369 // TODO: Support nonzero offsets?
370 if (Offset != 0)
371 return false;
372
373 // Only allow vectors that are a power-of-2 away from the size of the alloca.
374 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
375 return false;
376
377 // If this the first vector we see, remember the type so that we know the
378 // element size.
379 if (!VectorTy) {
380 VectorTy = VInTy;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000381 return true;
382 }
383
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000384 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
385 unsigned InBitWidth = VInTy->getBitWidth();
386
387 // Vectors of the same size can be converted using a simple bitcast.
388 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8))
389 return true;
390
391 const Type *ElementTy = cast<VectorType>(VectorTy)->getElementType();
Cameron Zwarichc77a10f2011-03-26 04:58:50 +0000392 const Type *InElementTy = cast<VectorType>(VInTy)->getElementType();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000393
394 // Do not allow mixed integer and floating-point accesses from vectors of
395 // different sizes.
396 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
397 return false;
398
399 if (ElementTy->isFloatingPointTy()) {
400 // Only allow floating-point vectors of different sizes if they have the
401 // same element type.
402 // TODO: This could be loosened a bit, but would anything benefit?
403 if (ElementTy != InElementTy)
404 return false;
405
406 // There are no arbitrary-precision floating-point types, which limits the
407 // number of legal vector types with larger element types that we can form
408 // to bitcast and extract a subvector.
409 // TODO: We could support some more cases with mixed fp128 and double here.
410 if (!(BitWidth == 64 || BitWidth == 128) ||
411 !(InBitWidth == 64 || InBitWidth == 128))
412 return false;
413 } else {
414 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
415 "or floating-point.");
416 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
417 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
418
419 // Do not allow integer types smaller than a byte or types whose widths are
420 // not a multiple of a byte.
421 if (BitWidth < 8 || InBitWidth < 8 ||
422 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
423 return false;
424 }
425
426 // Pick the largest of the two vector types.
427 if (InBitWidth > BitWidth)
428 VectorTy = VInTy;
429
430 return true;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000431}
432
Chris Lattner4cc576b2010-04-16 00:24:57 +0000433/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
434/// its accesses to a single vector type, return true and set VecTy to
435/// the new type. If we could convert the alloca into a single promotable
436/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
437/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
438/// is the current offset from the base of the alloca being analyzed.
439///
440/// If we see at least one access to the value that is as a vector type, set the
441/// SawVec flag.
442bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
443 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
444 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000445
Chris Lattner4cc576b2010-04-16 00:24:57 +0000446 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
447 // Don't break volatile loads.
448 if (LI->isVolatile())
449 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000450 // Don't touch MMX operations.
451 if (LI->getType()->isX86_MMXTy())
452 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000453 HadNonMemTransferAccess = true;
Cameron Zwarich9827b782011-03-29 05:19:52 +0000454 MergeInType(LI->getType(), Offset, true);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000455 continue;
456 }
Bob Wilson69743022011-01-13 20:59:44 +0000457
Chris Lattner4cc576b2010-04-16 00:24:57 +0000458 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
459 // Storing the pointer, not into the value?
460 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000461 // Don't touch MMX operations.
462 if (SI->getOperand(0)->getType()->isX86_MMXTy())
463 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000464 HadNonMemTransferAccess = true;
Cameron Zwarich9827b782011-03-29 05:19:52 +0000465 MergeInType(SI->getOperand(0)->getType(), Offset, true);
Chris Lattner4cc576b2010-04-16 00:24:57 +0000466 continue;
467 }
Bob Wilson69743022011-01-13 20:59:44 +0000468
Chris Lattner4cc576b2010-04-16 00:24:57 +0000469 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000470 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000471 if (!CanConvertToScalar(BCI, Offset))
472 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000473 continue;
474 }
475
476 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
477 // If this is a GEP with a variable indices, we can't handle it.
478 if (!GEP->hasAllConstantIndices())
479 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000480
Chris Lattner4cc576b2010-04-16 00:24:57 +0000481 // Compute the offset that this GEP adds to the pointer.
482 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
483 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
484 &Indices[0], Indices.size());
485 // See if all uses can be converted.
486 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
487 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000488 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000489 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000490 continue;
491 }
492
493 // If this is a constant sized memset of a constant value (e.g. 0) we can
494 // handle it.
495 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
496 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000497 if (!isa<ConstantInt>(MSI->getValue()) ||
498 !isa<ConstantInt>(MSI->getLength()))
499 return false;
500 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000501 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000502 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000503 }
504
505 // If this is a memcpy or memmove into or out of the whole allocation, we
506 // can handle it like a load or store of the scalar type.
507 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000508 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
509 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
510 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000511
Chris Lattnera001b662010-04-16 00:38:19 +0000512 IsNotTrivial = true; // Can't be mem2reg'd.
513 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000514 }
Bob Wilson69743022011-01-13 20:59:44 +0000515
Chris Lattner4cc576b2010-04-16 00:24:57 +0000516 // Otherwise, we cannot handle this!
517 return false;
518 }
Bob Wilson69743022011-01-13 20:59:44 +0000519
Chris Lattner4cc576b2010-04-16 00:24:57 +0000520 return true;
521}
522
523/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
524/// directly. This happens when we are converting an "integer union" to a
525/// single integer scalar, or when we are converting a "vector union" to a
526/// vector with insert/extractelement instructions.
527///
528/// Offset is an offset from the original alloca, in bits that need to be
529/// shifted to the right. By the end of this, there should be no uses of Ptr.
530void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
531 uint64_t Offset) {
532 while (!Ptr->use_empty()) {
533 Instruction *User = cast<Instruction>(Ptr->use_back());
534
535 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
536 ConvertUsesToScalar(CI, NewAI, Offset);
537 CI->eraseFromParent();
538 continue;
539 }
540
541 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
542 // Compute the offset that this GEP adds to the pointer.
543 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
544 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
545 &Indices[0], Indices.size());
546 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
547 GEP->eraseFromParent();
548 continue;
549 }
Bob Wilson69743022011-01-13 20:59:44 +0000550
Chris Lattner61db1f52010-12-26 22:57:41 +0000551 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000552
Chris Lattner4cc576b2010-04-16 00:24:57 +0000553 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
554 // The load is a bit extract from NewAI shifted right by Offset bits.
555 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
556 Value *NewLoadVal
557 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
558 LI->replaceAllUsesWith(NewLoadVal);
559 LI->eraseFromParent();
560 continue;
561 }
Bob Wilson69743022011-01-13 20:59:44 +0000562
Chris Lattner4cc576b2010-04-16 00:24:57 +0000563 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
564 assert(SI->getOperand(0) != Ptr && "Consistency error!");
565 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
566 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
567 Builder);
568 Builder.CreateStore(New, NewAI);
569 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000570
Chris Lattner4cc576b2010-04-16 00:24:57 +0000571 // If the load we just inserted is now dead, then the inserted store
572 // overwrote the entire thing.
573 if (Old->use_empty())
574 Old->eraseFromParent();
575 continue;
576 }
Bob Wilson69743022011-01-13 20:59:44 +0000577
Chris Lattner4cc576b2010-04-16 00:24:57 +0000578 // If this is a constant sized memset of a constant value (e.g. 0) we can
579 // transform it into a store of the expanded constant value.
580 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
581 assert(MSI->getRawDest() == Ptr && "Consistency error!");
582 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
583 if (NumBytes != 0) {
584 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000585
Chris Lattner4cc576b2010-04-16 00:24:57 +0000586 // Compute the value replicated the right number of times.
587 APInt APVal(NumBytes*8, Val);
588
589 // Splat the value if non-zero.
590 if (Val)
591 for (unsigned i = 1; i != NumBytes; ++i)
592 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000593
Chris Lattner4cc576b2010-04-16 00:24:57 +0000594 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
595 Value *New = ConvertScalar_InsertValue(
596 ConstantInt::get(User->getContext(), APVal),
597 Old, Offset, Builder);
598 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000599
Chris Lattner4cc576b2010-04-16 00:24:57 +0000600 // If the load we just inserted is now dead, then the memset overwrote
601 // the entire thing.
602 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000603 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000604 }
605 MSI->eraseFromParent();
606 continue;
607 }
608
609 // If this is a memcpy or memmove into or out of the whole allocation, we
610 // can handle it like a load or store of the scalar type.
611 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
612 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000613
Chris Lattner4cc576b2010-04-16 00:24:57 +0000614 // If the source and destination are both to the same alloca, then this is
615 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
616 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000617 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000618
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000619 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000620 // Dest must be OrigAI, change this to be a load from the original
621 // pointer (bitcasted), then a store to our new alloca.
622 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
623 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000624 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
625 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
626 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
627 AIPTy = PointerType::get(AIPTy->getElementType(),
628 SPTy->getAddressSpace());
629 }
630 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
631
Chris Lattner4cc576b2010-04-16 00:24:57 +0000632 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
633 SrcVal->setAlignment(MTI->getAlignment());
634 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000635 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000636 // Src must be OrigAI, change this to be a load from NewAI then a store
637 // through the original dest pointer (bitcasted).
638 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
639 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
640
Mon P Wange90a6332010-12-23 01:41:32 +0000641 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
642 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
643 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
644 AIPTy = PointerType::get(AIPTy->getElementType(),
645 DPTy->getAddressSpace());
646 }
647 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
648
Chris Lattner4cc576b2010-04-16 00:24:57 +0000649 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
650 NewStore->setAlignment(MTI->getAlignment());
651 } else {
652 // Noop transfer. Src == Dst
653 }
654
655 MTI->eraseFromParent();
656 continue;
657 }
Bob Wilson69743022011-01-13 20:59:44 +0000658
Chris Lattner4cc576b2010-04-16 00:24:57 +0000659 llvm_unreachable("Unsupported operation!");
660 }
661}
662
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000663/// getScaledElementType - Gets a scaled element type for a partial vector
664/// access of an alloca. The input type must be an integer or float, and
665/// the resulting type must be an integer, float or double.
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000666static const Type *getScaledElementType(const Type *OldTy,
667 unsigned NewBitWidth) {
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000668 assert((OldTy->isIntegerTy() || OldTy->isFloatTy()) && "Partial vector "
669 "accesses must be scaled from integer or float elements.");
670
671 LLVMContext &Context = OldTy->getContext();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000672
673 if (OldTy->isIntegerTy())
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000674 return Type::getIntNTy(Context, NewBitWidth);
675 if (NewBitWidth == 32)
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000676 return Type::getFloatTy(Context);
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000677 if (NewBitWidth == 64)
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000678 return Type::getDoubleTy(Context);
679
680 llvm_unreachable("Invalid type for a partial vector access of an alloca!");
681}
682
Mon P Wangddf9abf2011-04-14 08:04:01 +0000683/// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
684/// to another vector of the same element type which has the same allocation
685/// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
686static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
687 IRBuilder<> &Builder) {
688 const Type *FromType = FromVal->getType();
Mon P Wang481823a2011-04-14 19:20:42 +0000689 const VectorType *FromVTy = cast<VectorType>(FromType);
690 const VectorType *ToVTy = cast<VectorType>(ToType);
691 assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
Mon P Wangddf9abf2011-04-14 08:04:01 +0000692 "Vectors must have the same element type");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000693 Value *UnV = UndefValue::get(FromType);
694 unsigned numEltsFrom = FromVTy->getNumElements();
695 unsigned numEltsTo = ToVTy->getNumElements();
696
697 SmallVector<Constant*, 3> Args;
Mon P Wang481823a2011-04-14 19:20:42 +0000698 const Type* Int32Ty = Builder.getInt32Ty();
Mon P Wangddf9abf2011-04-14 08:04:01 +0000699 unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
700 unsigned i;
701 for (i=0; i != minNumElts; ++i)
Mon P Wang481823a2011-04-14 19:20:42 +0000702 Args.push_back(ConstantInt::get(Int32Ty, i));
Mon P Wangddf9abf2011-04-14 08:04:01 +0000703
704 if (i < numEltsTo) {
Mon P Wang481823a2011-04-14 19:20:42 +0000705 Constant* UnC = UndefValue::get(Int32Ty);
Mon P Wangddf9abf2011-04-14 08:04:01 +0000706 for (; i != numEltsTo; ++i)
707 Args.push_back(UnC);
708 }
709 Constant *Mask = ConstantVector::get(Args);
710 return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
711}
712
Chris Lattner4cc576b2010-04-16 00:24:57 +0000713/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
714/// or vector value FromVal, extracting the bits from the offset specified by
715/// Offset. This returns the value, which is of type ToType.
716///
717/// This happens when we are converting an "integer union" to a single
718/// integer scalar, or when we are converting a "vector union" to a vector with
719/// insert/extractelement instructions.
720///
721/// Offset is an offset from the original alloca, in bits that need to be
722/// shifted to the right.
723Value *ConvertToScalarInfo::
724ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
725 uint64_t Offset, IRBuilder<> &Builder) {
726 // If the load is of the whole new alloca, no conversion is needed.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000727 const Type *FromType = FromVal->getType();
728 if (FromType == ToType && Offset == 0)
Chris Lattner4cc576b2010-04-16 00:24:57 +0000729 return FromVal;
730
731 // If the result alloca is a vector type, this is either an element
732 // access or a bitcast to another vector type of the same size.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000733 if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Cameron Zwarich9827b782011-03-29 05:19:52 +0000734 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000735 if (ToTypeSize == AllocaSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000736 // If the two types have the same primitive size, use a bit cast.
737 // Otherwise, it is two vectors with the same element type that has
738 // the same allocation size but different number of elements so use
739 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000740 if (FromType->getPrimitiveSizeInBits() ==
741 ToType->getPrimitiveSizeInBits())
742 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000743 else
744 return CreateShuffleVectorCast(FromVal, ToType, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000745 }
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000746
Cameron Zwarich9827b782011-03-29 05:19:52 +0000747 if (ToType->isVectorTy()) {
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000748 assert(isPowerOf2_64(AllocaSize / ToTypeSize) &&
749 "Partial vector access of an alloca must have a power-of-2 size "
750 "ratio.");
751 assert(Offset == 0 && "Can't extract a value of a smaller vector type "
752 "from a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000753
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000754 const Type *ToElementTy = cast<VectorType>(ToType)->getElementType();
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000755 const Type *CastElementTy = getScaledElementType(ToElementTy,
756 ToTypeSize * 8);
757 unsigned NumCastVectorElements = AllocaSize / ToTypeSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000758
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000759 LLVMContext &Context = FromVal->getContext();
760 const Type *CastTy = VectorType::get(CastElementTy,
761 NumCastVectorElements);
762 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
763 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
764 Type::getInt32Ty(Context), 0), "tmp");
765 return Builder.CreateBitCast(Extract, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000766 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000767
768 // Otherwise it must be an element access.
769 unsigned Elt = 0;
770 if (Offset) {
771 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
772 Elt = Offset/EltSize;
773 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
774 }
775 // Return the element extracted out of it.
776 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
777 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
778 if (V->getType() != ToType)
779 V = Builder.CreateBitCast(V, ToType, "tmp");
780 return V;
781 }
Bob Wilson69743022011-01-13 20:59:44 +0000782
Chris Lattner4cc576b2010-04-16 00:24:57 +0000783 // If ToType is a first class aggregate, extract out each of the pieces and
784 // use insertvalue's to form the FCA.
785 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
786 const StructLayout &Layout = *TD.getStructLayout(ST);
787 Value *Res = UndefValue::get(ST);
788 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
789 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
790 Offset+Layout.getElementOffsetInBits(i),
791 Builder);
792 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
793 }
794 return Res;
795 }
Bob Wilson69743022011-01-13 20:59:44 +0000796
Chris Lattner4cc576b2010-04-16 00:24:57 +0000797 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
798 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
799 Value *Res = UndefValue::get(AT);
800 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
801 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
802 Offset+i*EltSize, Builder);
803 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
804 }
805 return Res;
806 }
807
808 // Otherwise, this must be a union that was converted to an integer value.
809 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
810
811 // If this is a big-endian system and the load is narrower than the
812 // full alloca type, we need to do a shift to get the right bits.
813 int ShAmt = 0;
814 if (TD.isBigEndian()) {
815 // On big-endian machines, the lowest bit is stored at the bit offset
816 // from the pointer given by getTypeStoreSizeInBits. This matters for
817 // integers with a bitwidth that is not a multiple of 8.
818 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
819 TD.getTypeStoreSizeInBits(ToType) - Offset;
820 } else {
821 ShAmt = Offset;
822 }
823
824 // Note: we support negative bitwidths (with shl) which are not defined.
825 // We do this to support (f.e.) loads off the end of a structure where
826 // only some bits are used.
827 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
828 FromVal = Builder.CreateLShr(FromVal,
829 ConstantInt::get(FromVal->getType(),
830 ShAmt), "tmp");
831 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000832 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000833 ConstantInt::get(FromVal->getType(),
834 -ShAmt), "tmp");
835
836 // Finally, unconditionally truncate the integer to the right width.
837 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
838 if (LIBitWidth < NTy->getBitWidth())
839 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000840 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000841 LIBitWidth), "tmp");
842 else if (LIBitWidth > NTy->getBitWidth())
843 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000844 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000845 LIBitWidth), "tmp");
846
847 // If the result is an integer, this is a trunc or bitcast.
848 if (ToType->isIntegerTy()) {
849 // Should be done.
850 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
851 // Just do a bitcast, we know the sizes match up.
852 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
853 } else {
854 // Otherwise must be a pointer.
855 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
856 }
857 assert(FromVal->getType() == ToType && "Didn't convert right?");
858 return FromVal;
859}
860
861/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
862/// or vector value "Old" at the offset specified by Offset.
863///
864/// This happens when we are converting an "integer union" to a
865/// single integer scalar, or when we are converting a "vector union" to a
866/// vector with insert/extractelement instructions.
867///
868/// Offset is an offset from the original alloca, in bits that need to be
869/// shifted to the right.
870Value *ConvertToScalarInfo::
871ConvertScalar_InsertValue(Value *SV, Value *Old,
872 uint64_t Offset, IRBuilder<> &Builder) {
873 // Convert the stored type to the actual type, shift it left to insert
874 // then 'or' into place.
875 const Type *AllocaType = Old->getType();
876 LLVMContext &Context = Old->getContext();
877
878 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
879 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
880 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000881
Chris Lattner4cc576b2010-04-16 00:24:57 +0000882 // Changing the whole vector with memset or with an access of a different
883 // vector type?
Mon P Wangbe0761c2011-04-13 21:40:02 +0000884 if (ValSize == VecSize) {
Mon P Wangddf9abf2011-04-14 08:04:01 +0000885 // If the two types have the same primitive size, use a bit cast.
886 // Otherwise, it is two vectors with the same element type that has
887 // the same allocation size but different number of elements so use
888 // a shuffle vector.
Mon P Wangbe0761c2011-04-13 21:40:02 +0000889 if (VTy->getPrimitiveSizeInBits() ==
890 SV->getType()->getPrimitiveSizeInBits())
891 return Builder.CreateBitCast(SV, AllocaType, "tmp");
Mon P Wangddf9abf2011-04-14 08:04:01 +0000892 else
893 return CreateShuffleVectorCast(SV, VTy, Builder);
Mon P Wangbe0761c2011-04-13 21:40:02 +0000894 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000895
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000896 if (SV->getType()->isVectorTy() && isPowerOf2_64(VecSize / ValSize)) {
897 assert(Offset == 0 && "Can't insert a value of a smaller vector type at "
898 "a nonzero offset.");
899
900 const Type *ToElementTy =
901 cast<VectorType>(SV->getType())->getElementType();
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000902 const Type *CastElementTy = getScaledElementType(ToElementTy, ValSize);
903 unsigned NumCastVectorElements = VecSize / ValSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000904
905 LLVMContext &Context = SV->getContext();
906 const Type *OldCastTy = VectorType::get(CastElementTy,
907 NumCastVectorElements);
908 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
909
910 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
911 Value *Insert =
912 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
913 Type::getInt32Ty(Context), 0), "tmp");
914 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
915 }
916
Chris Lattner4cc576b2010-04-16 00:24:57 +0000917 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
918
919 // Must be an element insertion.
920 unsigned Elt = Offset/EltSize;
Bob Wilson69743022011-01-13 20:59:44 +0000921
Chris Lattner4cc576b2010-04-16 00:24:57 +0000922 if (SV->getType() != VTy->getElementType())
923 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000924
925 SV = Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000926 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
927 "tmp");
928 return SV;
929 }
Bob Wilson69743022011-01-13 20:59:44 +0000930
Chris Lattner4cc576b2010-04-16 00:24:57 +0000931 // If SV is a first-class aggregate value, insert each value recursively.
932 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
933 const StructLayout &Layout = *TD.getStructLayout(ST);
934 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
935 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000936 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000937 Offset+Layout.getElementOffsetInBits(i),
938 Builder);
939 }
940 return Old;
941 }
Bob Wilson69743022011-01-13 20:59:44 +0000942
Chris Lattner4cc576b2010-04-16 00:24:57 +0000943 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
944 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
945 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
946 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
947 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
948 }
949 return Old;
950 }
951
952 // If SV is a float, convert it to the appropriate integer type.
953 // If it is a pointer, do the same.
954 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
955 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
956 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
957 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
958 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
959 SV = Builder.CreateBitCast(SV,
960 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
961 else if (SV->getType()->isPointerTy())
962 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
963
964 // Zero extend or truncate the value if needed.
965 if (SV->getType() != AllocaType) {
966 if (SV->getType()->getPrimitiveSizeInBits() <
967 AllocaType->getPrimitiveSizeInBits())
968 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
969 else {
970 // Truncation may be needed if storing more than the alloca can hold
971 // (undefined behavior).
972 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
973 SrcWidth = DestWidth;
974 SrcStoreWidth = DestStoreWidth;
975 }
976 }
977
978 // If this is a big-endian system and the store is narrower than the
979 // full alloca type, we need to do a shift to get the right bits.
980 int ShAmt = 0;
981 if (TD.isBigEndian()) {
982 // On big-endian machines, the lowest bit is stored at the bit offset
983 // from the pointer given by getTypeStoreSizeInBits. This matters for
984 // integers with a bitwidth that is not a multiple of 8.
985 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
986 } else {
987 ShAmt = Offset;
988 }
989
990 // Note: we support negative bitwidths (with shr) which are not defined.
991 // We do this to support (f.e.) stores off the end of a structure where
992 // only some bits in the structure are set.
993 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
994 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
995 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
996 ShAmt), "tmp");
997 Mask <<= ShAmt;
998 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
999 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1000 -ShAmt), "tmp");
1001 Mask = Mask.lshr(-ShAmt);
1002 }
1003
1004 // Mask out the bits we are about to insert from the old value, and or
1005 // in the new bits.
1006 if (SrcWidth != DestWidth) {
1007 assert(DestWidth > SrcWidth);
1008 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1009 SV = Builder.CreateOr(Old, SV, "ins");
1010 }
1011 return SV;
1012}
1013
1014
1015//===----------------------------------------------------------------------===//
1016// SRoA Driver
1017//===----------------------------------------------------------------------===//
1018
1019
Chris Lattnered7b41e2003-05-27 15:45:27 +00001020bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001021 TD = getAnalysisIfAvailable<TargetData>();
1022
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001023 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +00001024
1025 // FIXME: ScalarRepl currently depends on TargetData more than it
1026 // theoretically needs to. It should be refactored in order to support
1027 // target-independent IR. Until this is done, just skip the actual
1028 // scalar-replacement portion of this pass.
1029 if (!TD) return Changed;
1030
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001031 while (1) {
1032 bool LocalChange = performScalarRepl(F);
1033 if (!LocalChange) break; // No need to repromote if no scalarrepl
1034 Changed = true;
1035 LocalChange = performPromotion(F);
1036 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1037 }
Chris Lattner38aec322003-09-11 16:45:55 +00001038
1039 return Changed;
1040}
1041
Chris Lattnerd0f56132011-01-14 19:50:47 +00001042namespace {
1043class AllocaPromoter : public LoadAndStorePromoter {
1044 AllocaInst *AI;
1045public:
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001046 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
1047 : LoadAndStorePromoter(Insts, S), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +00001048
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001049 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +00001050 // Remember which alloca we're promoting (for isInstInList).
1051 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001052 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +00001053 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001054 }
1055
Chris Lattnerd0f56132011-01-14 19:50:47 +00001056 virtual bool isInstInList(Instruction *I,
1057 const SmallVectorImpl<Instruction*> &Insts) const {
1058 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1059 return LI->getOperand(0) == AI;
1060 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001061 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001062};
1063} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001064
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001065/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1066/// subsequently loaded can be rewritten to load both input pointers and then
1067/// select between the result, allowing the load of the alloca to be promoted.
1068/// From this:
1069/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1070/// %V = load i32* %P2
1071/// to:
1072/// %V1 = load i32* %Alloca -> will be mem2reg'd
1073/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001074/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001075///
1076/// We can do this to a select if its only uses are loads and if the operand to
1077/// the select can be loaded unconditionally.
1078static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1079 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1080 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1081
1082 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1083 UI != UE; ++UI) {
1084 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1085 if (LI == 0 || LI->isVolatile()) return false;
1086
Chris Lattnere3357862011-01-24 01:07:11 +00001087 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001088 // (e.g. allocas) or at this point because we can see other accesses to it.
1089 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1090 LI->getAlignment(), TD))
1091 return false;
1092 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1093 LI->getAlignment(), TD))
1094 return false;
1095 }
1096
1097 return true;
1098}
1099
Chris Lattnere3357862011-01-24 01:07:11 +00001100/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1101/// subsequently loaded can be rewritten to load both input pointers in the pred
1102/// blocks and then PHI the results, allowing the load of the alloca to be
1103/// promoted.
1104/// From this:
1105/// %P2 = phi [i32* %Alloca, i32* %Other]
1106/// %V = load i32* %P2
1107/// to:
1108/// %V1 = load i32* %Alloca -> will be mem2reg'd
1109/// ...
1110/// %V2 = load i32* %Other
1111/// ...
1112/// %V = phi [i32 %V1, i32 %V2]
1113///
1114/// We can do this to a select if its only uses are loads and if the operand to
1115/// the select can be loaded unconditionally.
1116static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1117 // For now, we can only do this promotion if the load is in the same block as
1118 // the PHI, and if there are no stores between the phi and load.
1119 // TODO: Allow recursive phi users.
1120 // TODO: Allow stores.
1121 BasicBlock *BB = PN->getParent();
1122 unsigned MaxAlign = 0;
1123 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1124 UI != UE; ++UI) {
1125 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1126 if (LI == 0 || LI->isVolatile()) return false;
1127
1128 // For now we only allow loads in the same block as the PHI. This is a
1129 // common case that happens when instcombine merges two loads through a PHI.
1130 if (LI->getParent() != BB) return false;
1131
1132 // Ensure that there are no instructions between the PHI and the load that
1133 // could store.
1134 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1135 if (BBI->mayWriteToMemory())
1136 return false;
1137
1138 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1139 }
1140
1141 // Okay, we know that we have one or more loads in the same block as the PHI.
1142 // We can transform this if it is safe to push the loads into the predecessor
1143 // blocks. The only thing to watch out for is that we can't put a possibly
1144 // trapping load in the predecessor if it is a critical edge.
1145 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1146 BasicBlock *Pred = PN->getIncomingBlock(i);
1147
1148 // If the predecessor has a single successor, then the edge isn't critical.
1149 if (Pred->getTerminator()->getNumSuccessors() == 1)
1150 continue;
1151
1152 Value *InVal = PN->getIncomingValue(i);
1153
1154 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1155 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1156 if (II->getParent() == Pred)
1157 return false;
1158
1159 // If this pointer is always safe to load, or if we can prove that there is
1160 // already a load in the block, then we can move the load to the pred block.
1161 if (InVal->isDereferenceablePointer() ||
1162 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1163 continue;
1164
1165 return false;
1166 }
1167
1168 return true;
1169}
1170
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001171
1172/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1173/// direct (non-volatile) loads and stores to it. If the alloca is close but
1174/// not quite there, this will transform the code to allow promotion. As such,
1175/// it is a non-pure predicate.
1176static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1177 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1178 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1179
1180 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1181 UI != UE; ++UI) {
1182 User *U = *UI;
1183 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1184 if (LI->isVolatile())
1185 return false;
1186 continue;
1187 }
1188
1189 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1190 if (SI->getOperand(0) == AI || SI->isVolatile())
1191 return false; // Don't allow a store OF the AI, only INTO the AI.
1192 continue;
1193 }
1194
1195 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1196 // If the condition being selected on is a constant, fold the select, yes
1197 // this does (rarely) happen early on.
1198 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1199 Value *Result = SI->getOperand(1+CI->isZero());
1200 SI->replaceAllUsesWith(Result);
1201 SI->eraseFromParent();
1202
1203 // This is very rare and we just scrambled the use list of AI, start
1204 // over completely.
1205 return tryToMakeAllocaBePromotable(AI, TD);
1206 }
1207
1208 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1209 // loads, then we can transform this by rewriting the select.
1210 if (!isSafeSelectToSpeculate(SI, TD))
1211 return false;
1212
1213 InstsToRewrite.insert(SI);
1214 continue;
1215 }
1216
Chris Lattnere3357862011-01-24 01:07:11 +00001217 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1218 if (PN->use_empty()) { // Dead PHIs can be stripped.
1219 InstsToRewrite.insert(PN);
1220 continue;
1221 }
1222
1223 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1224 // in the pred blocks, then we can transform this by rewriting the PHI.
1225 if (!isSafePHIToSpeculate(PN, TD))
1226 return false;
1227
1228 InstsToRewrite.insert(PN);
1229 continue;
1230 }
1231
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001232 return false;
1233 }
1234
1235 // If there are no instructions to rewrite, then all uses are load/stores and
1236 // we're done!
1237 if (InstsToRewrite.empty())
1238 return true;
1239
1240 // If we have instructions that need to be rewritten for this to be promotable
1241 // take care of it now.
1242 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Chris Lattnere3357862011-01-24 01:07:11 +00001243 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1244 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1245 // loads with a new select.
1246 while (!SI->use_empty()) {
1247 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001248
Chris Lattnere3357862011-01-24 01:07:11 +00001249 IRBuilder<> Builder(LI);
1250 LoadInst *TrueLoad =
1251 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1252 LoadInst *FalseLoad =
1253 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1254
1255 // Transfer alignment and TBAA info if present.
1256 TrueLoad->setAlignment(LI->getAlignment());
1257 FalseLoad->setAlignment(LI->getAlignment());
1258 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1259 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1260 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1261 }
1262
1263 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1264 V->takeName(LI);
1265 LI->replaceAllUsesWith(V);
1266 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001267 }
Chris Lattnere3357862011-01-24 01:07:11 +00001268
1269 // Now that all the loads are gone, the select is gone too.
1270 SI->eraseFromParent();
1271 continue;
1272 }
1273
1274 // Otherwise, we have a PHI node which allows us to push the loads into the
1275 // predecessors.
1276 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1277 if (PN->use_empty()) {
1278 PN->eraseFromParent();
1279 continue;
1280 }
1281
1282 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
Jay Foad3ecfc862011-03-30 11:28:46 +00001283 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1284 PN->getName()+".ld", PN);
Chris Lattnere3357862011-01-24 01:07:11 +00001285
1286 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1287 // matter which one we get and if any differ, it doesn't matter.
1288 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1289 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1290 unsigned Align = SomeLoad->getAlignment();
1291
1292 // Rewrite all loads of the PN to use the new PHI.
1293 while (!PN->use_empty()) {
1294 LoadInst *LI = cast<LoadInst>(PN->use_back());
1295 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001296 LI->eraseFromParent();
1297 }
1298
Chris Lattnere3357862011-01-24 01:07:11 +00001299 // Inject loads into all of the pred blocks. Keep track of which blocks we
1300 // insert them into in case we have multiple edges from the same block.
1301 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1302
1303 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1304 BasicBlock *Pred = PN->getIncomingBlock(i);
1305 LoadInst *&Load = InsertedLoads[Pred];
1306 if (Load == 0) {
1307 Load = new LoadInst(PN->getIncomingValue(i),
1308 PN->getName() + "." + Pred->getName(),
1309 Pred->getTerminator());
1310 Load->setAlignment(Align);
1311 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1312 }
1313
1314 NewPN->addIncoming(Load, Pred);
1315 }
1316
1317 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001318 }
1319
1320 ++NumAdjusted;
1321 return true;
1322}
1323
1324
Chris Lattner38aec322003-09-11 16:45:55 +00001325bool SROA::performPromotion(Function &F) {
1326 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001327 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001328 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001329 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001330
Chris Lattner02a3be02003-09-20 14:39:18 +00001331 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +00001332
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001333 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001334 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001335 while (1) {
1336 Allocas.clear();
1337
1338 // Find allocas that are safe to promote, by looking at all instructions in
1339 // the entry node
1340 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1341 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001342 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001343 Allocas.push_back(AI);
1344
1345 if (Allocas.empty()) break;
1346
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001347 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001348 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001349 else {
1350 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001351 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1352 AllocaInst *AI = Allocas[i];
1353
1354 // Build list of instructions to promote.
1355 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1356 UI != E; ++UI)
1357 Insts.push_back(cast<Instruction>(*UI));
1358
1359 AllocaPromoter(Insts, SSA).run(AI, Insts);
1360 Insts.clear();
1361 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001362 }
Chris Lattner38aec322003-09-11 16:45:55 +00001363 NumPromoted += Allocas.size();
1364 Changed = true;
1365 }
1366
1367 return Changed;
1368}
1369
Chris Lattner4cc576b2010-04-16 00:24:57 +00001370
Bob Wilson3992feb2010-02-03 17:23:56 +00001371/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1372/// SROA. It must be a struct or array type with a small number of elements.
1373static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1374 const Type *T = AI->getAllocatedType();
1375 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +00001376 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001377 return ST->getNumElements() <= 32;
1378 // Arrays are much less likely to be safe for SROA; only consider
1379 // them if they are very small.
1380 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1381 return AT->getNumElements() <= 8;
1382 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001383}
1384
Chris Lattnerc4472072010-04-15 23:50:26 +00001385
Chris Lattner38aec322003-09-11 16:45:55 +00001386// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1387// which runs on all of the malloc/alloca instructions in the function, removing
1388// them if they are only used by getelementptr instructions.
1389//
1390bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001391 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001392
Chris Lattner31d80102010-04-15 21:59:20 +00001393 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001394 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001395 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001396 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001397 WorkList.push_back(A);
1398
1399 // Process the worklist
1400 bool Changed = false;
1401 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001402 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001403 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001404
Chris Lattneradd2bd72006-12-22 23:14:42 +00001405 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1406 // with unused elements.
1407 if (AI->use_empty()) {
1408 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001409 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001410 continue;
1411 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001412
1413 // If this alloca is impossible for us to promote, reject it early.
1414 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1415 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001416
Chris Lattner79b3bd32007-04-25 06:40:51 +00001417 // Check to see if this allocation is only modified by a memcpy/memmove from
1418 // a constant global. If this is the case, we can change all users to use
1419 // the constant global instead. This is commonly produced by the CFE by
1420 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1421 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +00001422 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +00001423 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1424 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +00001425 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001426 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +00001427 TheCopy->eraseFromParent(); // Don't mutate the global.
1428 AI->eraseFromParent();
1429 ++NumGlobals;
1430 Changed = true;
1431 continue;
1432 }
Bob Wilson69743022011-01-13 20:59:44 +00001433
Chris Lattner7809ecd2009-02-03 01:30:09 +00001434 // Check to see if we can perform the core SROA transformation. We cannot
1435 // transform the allocation instruction if it is an array allocation
1436 // (allocations OF arrays are ok though), and an allocation of a scalar
1437 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001438 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001439
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001440 // Do not promote [0 x %struct].
1441 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001442
Chris Lattner31d80102010-04-15 21:59:20 +00001443 // Do not promote any struct whose size is too big.
1444 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001445
Bob Wilson3992feb2010-02-03 17:23:56 +00001446 // If the alloca looks like a good candidate for scalar replacement, and if
1447 // all its users can be transformed, then split up the aggregate into its
1448 // separate elements.
1449 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1450 DoScalarReplacement(AI, WorkList);
1451 Changed = true;
1452 continue;
1453 }
1454
Chris Lattner6e733d32009-01-28 20:16:43 +00001455 // If we can turn this aggregate value (potentially with casts) into a
1456 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001457 // IsNotTrivial tracks whether this is something that mem2reg could have
1458 // promoted itself. If so, we don't want to transform it needlessly. Note
1459 // that we can't just check based on the type: the alloca may be of an i32
1460 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001461 if (AllocaInst *NewAI =
1462 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001463 NewAI->takeName(AI);
1464 AI->eraseFromParent();
1465 ++NumConverted;
1466 Changed = true;
1467 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001468 }
1469
Chris Lattner7809ecd2009-02-03 01:30:09 +00001470 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001471 }
1472
1473 return Changed;
1474}
Chris Lattner5e062a12003-05-30 04:15:41 +00001475
Chris Lattnera10b29b2007-04-25 05:02:56 +00001476/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1477/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001478void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001479 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001480 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001481 SmallVector<AllocaInst*, 32> ElementAllocas;
1482 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1483 ElementAllocas.reserve(ST->getNumContainedTypes());
1484 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001485 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001486 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001487 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001488 ElementAllocas.push_back(NA);
1489 WorkList.push_back(NA); // Add to worklist for recursive processing
1490 }
1491 } else {
1492 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1493 ElementAllocas.reserve(AT->getNumElements());
1494 const Type *ElTy = AT->getElementType();
1495 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001496 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001497 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001498 ElementAllocas.push_back(NA);
1499 WorkList.push_back(NA); // Add to worklist for recursive processing
1500 }
1501 }
1502
Bob Wilsonb742def2009-12-18 20:14:40 +00001503 // Now that we have created the new alloca instructions, rewrite all the
1504 // uses of the old alloca.
1505 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001506
Bob Wilsonb742def2009-12-18 20:14:40 +00001507 // Now erase any instructions that were made dead while rewriting the alloca.
1508 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001509 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001510
Dan Gohmanfe601042010-06-22 15:08:57 +00001511 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001512}
Chris Lattnera59adc42009-12-14 05:11:02 +00001513
Bob Wilsonb742def2009-12-18 20:14:40 +00001514/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1515/// recursively including all their operands that become trivially dead.
1516void SROA::DeleteDeadInstructions() {
1517 while (!DeadInsts.empty()) {
1518 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001519
Bob Wilsonb742def2009-12-18 20:14:40 +00001520 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1521 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1522 // Zero out the operand and see if it becomes trivially dead.
1523 // (But, don't add allocas to the dead instruction list -- they are
1524 // already on the worklist and will be deleted separately.)
1525 *OI = 0;
1526 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1527 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001528 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001529
1530 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001531 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001532}
Bob Wilson69743022011-01-13 20:59:44 +00001533
Bob Wilsonb742def2009-12-18 20:14:40 +00001534/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1535/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001536/// the Info parameter. Offset indicates the position within AI that is
1537/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001538void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001539 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001540 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1541 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001542
Bob Wilsonb742def2009-12-18 20:14:40 +00001543 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001544 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001545 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001546 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001547 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001548 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001549 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001550 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001551 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001552 if (Length == 0)
1553 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001554 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001555 UI.getOperandNo() == 0, Info, MI,
1556 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001557 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001558 if (LI->isVolatile())
1559 return MarkUnsafe(Info, User);
1560 const Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001561 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001562 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001563 Info.hasALoadOrStore = true;
1564
Bob Wilsonb742def2009-12-18 20:14:40 +00001565 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1566 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001567 if (SI->isVolatile() || SI->getOperand(0) == I)
1568 return MarkUnsafe(Info, User);
1569
1570 const Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001571 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001572 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001573 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001574 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1575 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1576 } else {
1577 return MarkUnsafe(Info, User);
1578 }
1579 if (Info.isUnsafe) return;
1580 }
1581}
1582
1583
1584/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1585/// derived from the alloca, we can often still split the alloca into elements.
1586/// This is useful if we have a large alloca where one element is phi'd
1587/// together somewhere: we can SRoA and promote all the other elements even if
1588/// we end up not being able to promote this one.
1589///
1590/// All we require is that the uses of the PHI do not index into other parts of
1591/// the alloca. The most important use case for this is single load and stores
1592/// that are PHI'd together, which can happen due to code sinking.
1593void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1594 AllocaInfo &Info) {
1595 // If we've already checked this PHI, don't do it again.
1596 if (PHINode *PN = dyn_cast<PHINode>(I))
1597 if (!Info.CheckedPHIs.insert(PN))
1598 return;
1599
1600 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1601 Instruction *User = cast<Instruction>(*UI);
1602
1603 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1604 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1605 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1606 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1607 // but would have to prove that we're staying inside of an element being
1608 // promoted.
1609 if (!GEPI->hasAllZeroIndices())
1610 return MarkUnsafe(Info, User);
1611 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1612 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1613 if (LI->isVolatile())
1614 return MarkUnsafe(Info, User);
1615 const Type *LIType = LI->getType();
1616 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1617 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1618 Info.hasALoadOrStore = true;
1619
1620 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1621 // Store is ok if storing INTO the pointer, not storing the pointer
1622 if (SI->isVolatile() || SI->getOperand(0) == I)
1623 return MarkUnsafe(Info, User);
1624
1625 const Type *SIType = SI->getOperand(0)->getType();
1626 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1627 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1628 Info.hasALoadOrStore = true;
1629 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1630 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001631 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001632 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001633 }
1634 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001635 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001636}
Bob Wilson39c88a62009-12-17 18:34:24 +00001637
Bob Wilsonb742def2009-12-18 20:14:40 +00001638/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1639/// replacement. It is safe when all the indices are constant, in-bounds
1640/// references, and when the resulting offset corresponds to an element within
1641/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001642/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001643void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001644 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001645 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1646 if (GEPIt == E)
1647 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001648
Chris Lattner88e6dc82008-08-23 05:21:06 +00001649 // Walk through the GEP type indices, checking the types that this indexes
1650 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001651 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001652 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001653 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001654 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001655
Bob Wilsonb742def2009-12-18 20:14:40 +00001656 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1657 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001658 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001659 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001660
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001661 // Compute the offset due to this GEP and check if the alloca has a
1662 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001663 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1664 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1665 &Indices[0], Indices.size());
Chris Lattner6c95d242011-01-23 07:29:29 +00001666 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001667 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001668}
1669
Bob Wilson704d1342011-01-13 17:45:11 +00001670/// isHomogeneousAggregate - Check if type T is a struct or array containing
1671/// elements of the same type (which is always true for arrays). If so,
1672/// return true with NumElts and EltTy set to the number of elements and the
1673/// element type, respectively.
1674static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1675 const Type *&EltTy) {
1676 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1677 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001678 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001679 return true;
1680 }
1681 if (const StructType *ST = dyn_cast<StructType>(T)) {
1682 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001683 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001684 for (unsigned n = 1; n < NumElts; ++n) {
1685 if (ST->getContainedType(n) != EltTy)
1686 return false;
1687 }
1688 return true;
1689 }
1690 return false;
1691}
1692
1693/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1694/// "homogeneous" aggregates with the same element type and number of elements.
1695static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1696 if (T1 == T2)
1697 return true;
1698
1699 unsigned NumElts1, NumElts2;
1700 const Type *EltTy1, *EltTy2;
1701 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1702 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1703 NumElts1 == NumElts2 &&
1704 EltTy1 == EltTy2)
1705 return true;
1706
1707 return false;
1708}
1709
Bob Wilsonb742def2009-12-18 20:14:40 +00001710/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1711/// alloca or has an offset and size that corresponds to a component element
1712/// within it. The offset checked here may have been formed from a GEP with a
1713/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001714///
1715/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1716/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001717void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001718 const Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001719 AllocaInfo &Info, Instruction *TheAccess,
1720 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001721 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001722 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001723 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001724 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1725 // loads/stores (which are essentially the same as the MemIntrinsics with
1726 // regard to copying padding between elements). But, if an alloca is
1727 // flagged as both a source and destination of such operations, we'll need
1728 // to check later for padding between elements.
1729 if (!MemOpType || MemOpType->isIntegerTy()) {
1730 if (isStore)
1731 Info.isMemCpyDst = true;
1732 else
1733 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001734 return;
1735 }
Bob Wilson704d1342011-01-13 17:45:11 +00001736 // This is also safe for references using a type that is compatible with
1737 // the type of the alloca, so that loads/stores can be rewritten using
1738 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001739 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001740 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001741 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001742 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001743 }
1744 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner6c95d242011-01-23 07:29:29 +00001745 const Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001746 if (TypeHasComponent(T, Offset, MemSize)) {
1747 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001748 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001749 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001750
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001751 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001752}
1753
1754/// TypeHasComponent - Return true if T has a component type with the
1755/// specified offset and size. If Size is zero, do not check the size.
1756bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1757 const Type *EltTy;
1758 uint64_t EltSize;
1759 if (const StructType *ST = dyn_cast<StructType>(T)) {
1760 const StructLayout *Layout = TD->getStructLayout(ST);
1761 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1762 EltTy = ST->getContainedType(EltIdx);
1763 EltSize = TD->getTypeAllocSize(EltTy);
1764 Offset -= Layout->getElementOffset(EltIdx);
1765 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1766 EltTy = AT->getElementType();
1767 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001768 if (Offset >= AT->getNumElements() * EltSize)
1769 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001770 Offset %= EltSize;
1771 } else {
1772 return false;
1773 }
1774 if (Offset == 0 && (Size == 0 || EltSize == Size))
1775 return true;
1776 // Check if the component spans multiple elements.
1777 if (Offset + Size > EltSize)
1778 return false;
1779 return TypeHasComponent(EltTy, Offset, Size);
1780}
1781
1782/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1783/// the instruction I, which references it, to use the separate elements.
1784/// Offset indicates the position within AI that is referenced by this
1785/// instruction.
1786void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1787 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001788 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1789 Use &TheUse = UI.getUse();
1790 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001791
1792 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1793 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001794 continue;
1795 }
1796
1797 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001798 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001799 continue;
1800 }
1801
1802 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001803 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1804 uint64_t MemSize = Length->getZExtValue();
1805 if (Offset == 0 &&
1806 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1807 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001808 // Otherwise the intrinsic can only touch a single element and the
1809 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001810 continue;
1811 }
1812
1813 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001814 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001815
Bob Wilson704d1342011-01-13 17:45:11 +00001816 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001817 // Replace:
1818 // %res = load { i32, i32 }* %alloc
1819 // with:
1820 // %load.0 = load i32* %alloc.0
1821 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1822 // %load.1 = load i32* %alloc.1
1823 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1824 // (Also works for arrays instead of structs)
1825 Value *Insert = UndefValue::get(LIType);
1826 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1827 Value *Load = new LoadInst(NewElts[i], "load", LI);
1828 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1829 }
1830 LI->replaceAllUsesWith(Insert);
1831 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001832 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001833 TD->getTypeAllocSize(LIType) ==
1834 TD->getTypeAllocSize(AI->getAllocatedType())) {
1835 // If this is a load of the entire alloca to an integer, rewrite it.
1836 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1837 }
Chris Lattner145c5322011-01-23 08:27:54 +00001838 continue;
1839 }
1840
1841 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001842 Value *Val = SI->getOperand(0);
1843 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001844 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001845 // Replace:
1846 // store { i32, i32 } %val, { i32, i32 }* %alloc
1847 // with:
1848 // %val.0 = extractvalue { i32, i32 } %val, 0
1849 // store i32 %val.0, i32* %alloc.0
1850 // %val.1 = extractvalue { i32, i32 } %val, 1
1851 // store i32 %val.1, i32* %alloc.1
1852 // (Also works for arrays instead of structs)
1853 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1854 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1855 new StoreInst(Extract, NewElts[i], SI);
1856 }
1857 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001858 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001859 TD->getTypeAllocSize(SIType) ==
1860 TD->getTypeAllocSize(AI->getAllocatedType())) {
1861 // If this is a store of the entire alloca from an integer, rewrite it.
1862 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1863 }
Chris Lattner145c5322011-01-23 08:27:54 +00001864 continue;
1865 }
1866
1867 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1868 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1869 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1870 // the new pointer.
1871 if (!isa<AllocaInst>(I)) continue;
1872
1873 assert(Offset == 0 && NewElts[0] &&
1874 "Direct alloca use should have a zero offset");
1875
1876 // If we have a use of the alloca, we know the derived uses will be
1877 // utilizing just the first element of the scalarized result. Insert a
1878 // bitcast of the first alloca before the user as required.
1879 AllocaInst *NewAI = NewElts[0];
1880 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1881 NewAI->moveBefore(BCI);
1882 TheUse = BCI;
1883 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001884 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001885 }
1886}
1887
Bob Wilsonb742def2009-12-18 20:14:40 +00001888/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1889/// and recursively continue updating all of its uses.
1890void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1891 SmallVector<AllocaInst*, 32> &NewElts) {
1892 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1893 if (BC->getOperand(0) != AI)
1894 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001895
Bob Wilsonb742def2009-12-18 20:14:40 +00001896 // The bitcast references the original alloca. Replace its uses with
1897 // references to the first new element alloca.
1898 Instruction *Val = NewElts[0];
1899 if (Val->getType() != BC->getDestTy()) {
1900 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1901 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001902 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001903 BC->replaceAllUsesWith(Val);
1904 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001905}
1906
Bob Wilsonb742def2009-12-18 20:14:40 +00001907/// FindElementAndOffset - Return the index of the element containing Offset
1908/// within the specified type, which must be either a struct or an array.
1909/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001910/// element. IdxTy is set to the type of the index result to be used in a
1911/// GEP instruction.
1912uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1913 const Type *&IdxTy) {
1914 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001915 if (const StructType *ST = dyn_cast<StructType>(T)) {
1916 const StructLayout *Layout = TD->getStructLayout(ST);
1917 Idx = Layout->getElementContainingOffset(Offset);
1918 T = ST->getContainedType(Idx);
1919 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001920 IdxTy = Type::getInt32Ty(T->getContext());
1921 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001922 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001923 const ArrayType *AT = cast<ArrayType>(T);
1924 T = AT->getElementType();
1925 uint64_t EltSize = TD->getTypeAllocSize(T);
1926 Idx = Offset / EltSize;
1927 Offset -= Idx * EltSize;
1928 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001929 return Idx;
1930}
1931
1932/// RewriteGEP - Check if this GEP instruction moves the pointer across
1933/// elements of the alloca that are being split apart, and if so, rewrite
1934/// the GEP to be relative to the new element.
1935void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1936 SmallVector<AllocaInst*, 32> &NewElts) {
1937 uint64_t OldOffset = Offset;
1938 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1939 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1940 &Indices[0], Indices.size());
1941
1942 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1943
1944 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001945 const Type *IdxTy;
1946 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001947 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001948 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001949
1950 T = AI->getAllocatedType();
1951 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001952 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001953
1954 // If this GEP does not move the pointer across elements of the alloca
1955 // being split, then it does not needs to be rewritten.
1956 if (Idx == OldIdx)
1957 return;
1958
1959 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1960 SmallVector<Value*, 8> NewArgs;
1961 NewArgs.push_back(Constant::getNullValue(i32Ty));
1962 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001963 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1964 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001965 }
1966 Instruction *Val = NewElts[Idx];
1967 if (NewArgs.size() > 1) {
1968 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1969 NewArgs.end(), "", GEPI);
1970 Val->takeName(GEPI);
1971 }
1972 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001973 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001974 GEPI->replaceAllUsesWith(Val);
1975 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001976}
1977
1978/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1979/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001980void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001981 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001982 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001983 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001984 // appropriate type. The "Other" pointer is the pointer that goes to memory
1985 // that doesn't have anything to do with the alloca that we are promoting. For
1986 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001987 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001988 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001989 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001990 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001991 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001992 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001993 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001994 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001995 }
1996 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001997
Chris Lattnerd93afec2009-01-07 07:18:45 +00001998 // If there is an other pointer, we want to convert it to the same pointer
1999 // type as AI has, so we can GEP through it safely.
2000 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00002001 unsigned AddrSpace =
2002 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00002003
2004 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2005 // optimization, but it's also required to detect the corner case where
2006 // both pointer operands are referencing the same memory, and where
2007 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2008 // function is only called for mem intrinsics that access the whole
2009 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00002010 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00002011
Bob Wilsona756b1d2010-01-19 04:32:48 +00002012 // Copying the alloca to itself is a no-op: just delete it.
2013 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2014 // This code will run twice for a no-op memcpy -- once for each operand.
2015 // Put only one reference to MI on the DeadInsts list.
2016 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2017 E = DeadInsts.end(); I != E; ++I)
2018 if (*I == MI) return;
2019 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00002020 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00002021 }
Bob Wilson69743022011-01-13 20:59:44 +00002022
Chris Lattnerd93afec2009-01-07 07:18:45 +00002023 // If the pointer is not the right type, insert a bitcast to the right
2024 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00002025 const Type *NewTy =
2026 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00002027
Chris Lattner0238f8c2010-07-08 00:27:05 +00002028 if (OtherPtr->getType() != NewTy)
2029 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002030 }
Bob Wilson69743022011-01-13 20:59:44 +00002031
Chris Lattnerd93afec2009-01-07 07:18:45 +00002032 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00002033 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00002034
Owen Anderson1d0be152009-08-13 21:58:54 +00002035 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00002036
2037 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2038 // If this is a memcpy/memmove, emit a GEP of the other element address.
2039 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002040 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00002041
Bob Wilsona756b1d2010-01-19 04:32:48 +00002042 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00002043 Value *Idx[2] = { Zero,
2044 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00002045 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00002046 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00002047 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00002048 uint64_t EltOffset;
2049 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002050 const Type *OtherTy = OtherPtrTy->getElementType();
2051 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002052 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2053 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002054 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002055 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00002056 }
Bob Wilson69743022011-01-13 20:59:44 +00002057
Chris Lattner1541e0f2009-03-04 19:20:50 +00002058 // The alignment of the other pointer is the guaranteed alignment of the
2059 // element, which is affected by both the known alignment of the whole
2060 // mem intrinsic and the alignment of the element. If the alignment of
2061 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2062 // known alignment is just 4 bytes.
2063 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002064 }
Bob Wilson69743022011-01-13 20:59:44 +00002065
Chris Lattnerd93afec2009-01-07 07:18:45 +00002066 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00002067 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002068
Chris Lattnerd93afec2009-01-07 07:18:45 +00002069 // If we got down to a scalar, insert a load or store as appropriate.
2070 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002071 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002072 if (SROADest) {
2073 // From Other to Alloca.
2074 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2075 new StoreInst(Elt, EltPtr, MI);
2076 } else {
2077 // From Alloca to Other.
2078 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2079 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2080 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002081 continue;
2082 }
2083 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002084
Chris Lattnerd93afec2009-01-07 07:18:45 +00002085 // If the stored element is zero (common case), just store a null
2086 // constant.
2087 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002088 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002089 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002090 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002091 } else {
2092 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00002093 const Type *ValTy = EltTy->getScalarType();
2094
Chris Lattnerd93afec2009-01-07 07:18:45 +00002095 // Construct an integer with the right value.
2096 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2097 APInt OneVal(EltSize, CI->getZExtValue());
2098 APInt TotalVal(OneVal);
2099 // Set each byte.
2100 for (unsigned i = 0; 8*i < EltSize; ++i) {
2101 TotalVal = TotalVal.shl(8);
2102 TotalVal |= OneVal;
2103 }
Bob Wilson69743022011-01-13 20:59:44 +00002104
Chris Lattnerd93afec2009-01-07 07:18:45 +00002105 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002106 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002107 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002108 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002109 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002110 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002111 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002112
Chris Lattnerd93afec2009-01-07 07:18:45 +00002113 // If the requested value was a vector constant, create it.
2114 if (EltTy != ValTy) {
2115 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2116 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002117 StoreVal = ConstantVector::get(Elts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002118 }
2119 }
2120 new StoreInst(StoreVal, EltPtr, MI);
2121 continue;
2122 }
2123 // Otherwise, if we're storing a byte variable, use a memset call for
2124 // this element.
2125 }
Bob Wilson69743022011-01-13 20:59:44 +00002126
Duncan Sands777d2302009-05-09 07:06:46 +00002127 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002128
Chris Lattner61db1f52010-12-26 22:57:41 +00002129 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002130
Chris Lattnerd93afec2009-01-07 07:18:45 +00002131 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002132 if (isa<MemSetInst>(MI)) {
2133 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2134 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002135 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002136 assert(isa<MemTransferInst>(MI));
2137 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2138 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002139
Chris Lattner61db1f52010-12-26 22:57:41 +00002140 if (isa<MemCpyInst>(MI))
2141 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2142 else
2143 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002144 }
Chris Lattner372dda82007-03-05 07:52:57 +00002145 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002146 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002147}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002148
Bob Wilson39fdd692009-12-04 21:57:37 +00002149/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002150/// overwrites the entire allocation. Extract out the pieces of the stored
2151/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002152void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002153 SmallVector<AllocaInst*, 32> &NewElts){
2154 // Extract each element out of the integer according to its structure offset
2155 // and store the element value to the individual alloca.
2156 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00002157 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002158 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002159
Chris Lattner70728532011-01-16 05:58:24 +00002160 IRBuilder<> Builder(SI);
2161
Eli Friedman41b33f42009-06-01 09:14:32 +00002162 // Handle tail padding by extending the operand
2163 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002164 SrcVal = Builder.CreateZExt(SrcVal,
2165 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002166
David Greene504c7d82010-01-05 01:27:09 +00002167 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002168 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002169
2170 // There are two forms here: AI could be an array or struct. Both cases
2171 // have different ways to compute the element offset.
2172 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2173 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002174
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002175 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2176 // Get the number of bits to shift SrcVal to get the value.
2177 const Type *FieldTy = EltSTy->getElementType(i);
2178 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002179
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002180 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002181 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002182
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002183 Value *EltVal = SrcVal;
2184 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002185 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002186 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002187 }
Bob Wilson69743022011-01-13 20:59:44 +00002188
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002189 // Truncate down to an integer of the right size.
2190 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002191
Chris Lattner583dd602009-01-09 18:18:43 +00002192 // Ignore zero sized fields like {}, they obviously contain no data.
2193 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002194
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002195 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002196 EltVal = Builder.CreateTrunc(EltVal,
2197 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002198 Value *DestField = NewElts[i];
2199 if (EltVal->getType() == FieldTy) {
2200 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002201 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002202 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002203 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002204 } else {
2205 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002206 DestField = Builder.CreateBitCast(DestField,
2207 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002208 }
2209 new StoreInst(EltVal, DestField, SI);
2210 }
Bob Wilson69743022011-01-13 20:59:44 +00002211
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002212 } else {
2213 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2214 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002215 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002216 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2217
2218 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002219
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002220 if (TD->isBigEndian())
2221 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002222 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002223 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002224
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002225 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002226 // Ignore zero sized fields like {}, they obviously contain no data.
2227 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002228
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002229 Value *EltVal = SrcVal;
2230 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002231 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002232 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002233 }
Bob Wilson69743022011-01-13 20:59:44 +00002234
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002235 // Truncate down to an integer of the right size.
2236 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002237 EltVal = Builder.CreateTrunc(EltVal,
2238 IntegerType::get(SI->getContext(),
2239 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002240 Value *DestField = NewElts[i];
2241 if (EltVal->getType() == ArrayEltTy) {
2242 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002243 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002244 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002245 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002246 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002247 } else {
2248 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002249 DestField = Builder.CreateBitCast(DestField,
2250 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002251 }
2252 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002253
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002254 if (TD->isBigEndian())
2255 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002256 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002257 Shift += ElementOffset;
2258 }
2259 }
Bob Wilson69743022011-01-13 20:59:44 +00002260
Bob Wilsonb742def2009-12-18 20:14:40 +00002261 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002262}
2263
Bob Wilson39fdd692009-12-04 21:57:37 +00002264/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002265/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002266void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002267 SmallVector<AllocaInst*, 32> &NewElts) {
2268 // Extract each element out of the NewElts according to its structure offset
2269 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00002270 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002271 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002272
David Greene504c7d82010-01-05 01:27:09 +00002273 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002274 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002275
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002276 // There are two forms here: AI could be an array or struct. Both cases
2277 // have different ways to compute the element offset.
2278 const StructLayout *Layout = 0;
2279 uint64_t ArrayEltBitOffset = 0;
2280 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2281 Layout = TD->getStructLayout(EltSTy);
2282 } else {
2283 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002284 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002285 }
2286
2287 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002288 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002289
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002290 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2291 // Load the value from the alloca. If the NewElt is an aggregate, cast
2292 // the pointer to an integer of the same size before doing the load.
2293 Value *SrcField = NewElts[i];
2294 const Type *FieldTy =
2295 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002296 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002297
Chris Lattner583dd602009-01-09 18:18:43 +00002298 // Ignore zero sized fields like {}, they obviously contain no data.
2299 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002300
2301 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002302 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002303 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2304 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002305 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002306 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002307 "", LI);
2308 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2309
2310 // If SrcField is a fp or vector of the right size but that isn't an
2311 // integer type, bitcast to an integer so we can shift it.
2312 if (SrcField->getType() != FieldIntTy)
2313 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2314
2315 // Zero extend the field to be the same size as the final alloca so that
2316 // we can shift and insert it.
2317 if (SrcField->getType() != ResultVal->getType())
2318 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002319
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002320 // Determine the number of bits to shift SrcField.
2321 uint64_t Shift;
2322 if (Layout) // Struct case.
2323 Shift = Layout->getElementOffsetInBits(i);
2324 else // Array case.
2325 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002326
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002327 if (TD->isBigEndian())
2328 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002329
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002330 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002331 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002332 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2333 }
2334
Chris Lattner14952472010-06-27 07:58:26 +00002335 // Don't create an 'or x, 0' on the first iteration.
2336 if (!isa<Constant>(ResultVal) ||
2337 !cast<Constant>(ResultVal)->isNullValue())
2338 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2339 else
2340 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002341 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002342
2343 // Handle tail padding by truncating the result
2344 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2345 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2346
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002347 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002348 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002349}
2350
Duncan Sands3cb36502007-11-04 14:43:57 +00002351/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002352/// alignment padding in between the elements that would be split apart
2353/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00002354static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002355 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2356 Ty = ATy->getElementType();
2357 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002358 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002359
2360 // SROA currently handles only Arrays and Structs.
2361 const StructType *STy = cast<StructType>(Ty);
2362 const StructLayout *SL = TD.getStructLayout(STy);
2363 unsigned PrevFieldBitOffset = 0;
2364 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2365 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2366
2367 // Check to see if there is any padding between this element and the
2368 // previous one.
2369 if (i) {
2370 unsigned PrevFieldEnd =
2371 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2372 if (PrevFieldEnd < FieldBitOffset)
2373 return true;
2374 }
2375 PrevFieldBitOffset = FieldBitOffset;
2376 }
2377 // Check for tail padding.
2378 if (unsigned EltCount = STy->getNumElements()) {
2379 unsigned PrevFieldEnd = PrevFieldBitOffset +
2380 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2381 if (PrevFieldEnd < SL->getSizeInBits())
2382 return true;
2383 }
2384 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002385}
Chris Lattner372dda82007-03-05 07:52:57 +00002386
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002387/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2388/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2389/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002390bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002391 // Loop over the use list of the alloca. We can only transform it if all of
2392 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002393 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002394
Chris Lattner6c95d242011-01-23 07:29:29 +00002395 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002396 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002397 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002398 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002399 }
Bob Wilson69743022011-01-13 20:59:44 +00002400
Chris Lattner39a1c042007-05-30 06:11:23 +00002401 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2402 // source and destination, we have to be careful. In particular, the memcpy
2403 // could be moving around elements that live in structure padding of the LLVM
2404 // types, but may actually be used. In these cases, we refuse to promote the
2405 // struct.
2406 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002407 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002408 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002409
Chris Lattner396a0562011-01-16 17:46:19 +00002410 // If the alloca never has an access to just *part* of it, but is accessed
2411 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002412 // the alloca instead of promoting each piece at a time and inserting fission
2413 // and fusion code.
2414 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2415 // If the struct/array just has one element, use basic SRoA.
2416 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2417 if (ST->getNumElements() > 1) return false;
2418 } else {
2419 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2420 return false;
2421 }
2422 }
Chris Lattner145c5322011-01-23 08:27:54 +00002423
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002424 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002425}
Chris Lattnera1888942005-12-12 07:19:13 +00002426
Chris Lattner800de312008-02-29 07:03:13 +00002427
Chris Lattner79b3bd32007-04-25 06:40:51 +00002428
2429/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2430/// some part of a constant global variable. This intentionally only accepts
2431/// constant expressions because we don't can't rewrite arbitrary instructions.
2432static bool PointsToConstantGlobal(Value *V) {
2433 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2434 return GV->isConstant();
2435 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002436 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002437 CE->getOpcode() == Instruction::GetElementPtr)
2438 return PointsToConstantGlobal(CE->getOperand(0));
2439 return false;
2440}
2441
2442/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2443/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2444/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2445/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2446/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002447/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002448/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00002449static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00002450 bool isOffset) {
2451 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002452 User *U = cast<Instruction>(*UI);
2453
Chris Lattner2e618492010-11-18 06:20:47 +00002454 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002455 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00002456 if (LI->isVolatile()) return false;
2457 continue;
2458 }
Bob Wilson69743022011-01-13 20:59:44 +00002459
Gabor Greif8a8a4352010-04-06 19:32:30 +00002460 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002461 // If uses of the bitcast are ok, we are ok.
2462 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2463 return false;
2464 continue;
2465 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002466 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002467 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2468 // doesn't, it does.
2469 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2470 isOffset || !GEP->hasAllZeroIndices()))
2471 return false;
2472 continue;
2473 }
Bob Wilson69743022011-01-13 20:59:44 +00002474
Chris Lattner62480652010-11-18 06:41:51 +00002475 if (CallSite CS = U) {
2476 // If this is a readonly/readnone call site, then we know it is just a
2477 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00002478 if (CS.onlyReadsMemory())
2479 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00002480
2481 // If this is the function being called then we treat it like a load and
2482 // ignore it.
2483 if (CS.isCallee(UI))
2484 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002485
Chris Lattner62480652010-11-18 06:41:51 +00002486 // If this is being passed as a byval argument, the caller is making a
2487 // copy, so it is only a read of the alloca.
2488 unsigned ArgNo = CS.getArgumentNo(UI);
2489 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2490 continue;
2491 }
Bob Wilson69743022011-01-13 20:59:44 +00002492
Chris Lattner79b3bd32007-04-25 06:40:51 +00002493 // If this is isn't our memcpy/memmove, reject it as something we can't
2494 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002495 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2496 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002497 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002498
Chris Lattner2e618492010-11-18 06:20:47 +00002499 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002500 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002501 if (UI.getOperandNo() == 1) {
2502 if (MI->isVolatile()) return false;
2503 continue;
2504 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002505
2506 // If we already have seen a copy, reject the second one.
2507 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002508
Chris Lattner79b3bd32007-04-25 06:40:51 +00002509 // If the pointer has been offset from the start of the alloca, we can't
2510 // safely handle this.
2511 if (isOffset) return false;
2512
2513 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002514 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002515
Chris Lattner79b3bd32007-04-25 06:40:51 +00002516 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002517 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002518 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002519
Chris Lattner79b3bd32007-04-25 06:40:51 +00002520 // Otherwise, the transform is safe. Remember the copy instruction.
2521 TheCopy = MI;
2522 }
2523 return true;
2524}
2525
2526/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2527/// modified by a copy from a constant global. If we can prove this, we can
2528/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00002529MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2530 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00002531 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2532 return TheCopy;
2533 return 0;
2534}