blob: de7bb41e7de5c00636c48f3a0c0aeffeefcb9e11 [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);
255 void MergeInType(const Type *In, uint64_t Offset);
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.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000318void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnera001b662010-04-16 00:38:19 +0000319 // If we already decided to turn this into a blob of integer memory, there is
320 // nothing to be done.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000321 if (VectorTy && VectorTy->isVoidTy())
322 return;
Bob Wilson69743022011-01-13 20:59:44 +0000323
Chris Lattner4cc576b2010-04-16 00:24:57 +0000324 // If this could be contributing to a vector, analyze it.
325
326 // If the In type is a vector that is the same size as the alloca, see if it
327 // matches the existing VecTy.
328 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000329 if (MergeInVectorType(VInTy, Offset))
Chris Lattner4cc576b2010-04-16 00:24:57 +0000330 return;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000331 } else if (In->isFloatTy() || In->isDoubleTy() ||
332 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
333 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
334 // If we're accessing something that could be an element of a vector, see
335 // if the implied vector agrees with what we already have and if Offset is
336 // compatible with it.
337 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
338 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Bob Wilson69743022011-01-13 20:59:44 +0000339 (VectorTy == 0 ||
Chris Lattner4cc576b2010-04-16 00:24:57 +0000340 cast<VectorType>(VectorTy)->getElementType()
341 ->getPrimitiveSizeInBits()/8 == EltSize)) {
342 if (VectorTy == 0)
343 VectorTy = VectorType::get(In, AllocaSize/EltSize);
344 return;
345 }
346 }
Bob Wilson69743022011-01-13 20:59:44 +0000347
Chris Lattner4cc576b2010-04-16 00:24:57 +0000348 // Otherwise, we have a case that we can't handle with an optimized vector
349 // form. We can still turn this into a large integer.
350 VectorTy = Type::getVoidTy(In->getContext());
351}
352
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000353/// MergeInVectorType - Handles the vector case of MergeInType, returning true
354/// if the type was successfully merged and false otherwise.
355bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
356 uint64_t Offset) {
357 // Remember if we saw a vector type.
358 HadAVector = true;
359
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000360 // TODO: Support nonzero offsets?
361 if (Offset != 0)
362 return false;
363
364 // Only allow vectors that are a power-of-2 away from the size of the alloca.
365 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
366 return false;
367
368 // If this the first vector we see, remember the type so that we know the
369 // element size.
370 if (!VectorTy) {
371 VectorTy = VInTy;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000372 return true;
373 }
374
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000375 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
376 unsigned InBitWidth = VInTy->getBitWidth();
377
378 // Vectors of the same size can be converted using a simple bitcast.
379 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8))
380 return true;
381
382 const Type *ElementTy = cast<VectorType>(VectorTy)->getElementType();
Cameron Zwarichc77a10f2011-03-26 04:58:50 +0000383 const Type *InElementTy = cast<VectorType>(VInTy)->getElementType();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000384
385 // Do not allow mixed integer and floating-point accesses from vectors of
386 // different sizes.
387 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
388 return false;
389
390 if (ElementTy->isFloatingPointTy()) {
391 // Only allow floating-point vectors of different sizes if they have the
392 // same element type.
393 // TODO: This could be loosened a bit, but would anything benefit?
394 if (ElementTy != InElementTy)
395 return false;
396
397 // There are no arbitrary-precision floating-point types, which limits the
398 // number of legal vector types with larger element types that we can form
399 // to bitcast and extract a subvector.
400 // TODO: We could support some more cases with mixed fp128 and double here.
401 if (!(BitWidth == 64 || BitWidth == 128) ||
402 !(InBitWidth == 64 || InBitWidth == 128))
403 return false;
404 } else {
405 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
406 "or floating-point.");
407 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
408 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
409
410 // Do not allow integer types smaller than a byte or types whose widths are
411 // not a multiple of a byte.
412 if (BitWidth < 8 || InBitWidth < 8 ||
413 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
414 return false;
415 }
416
417 // Pick the largest of the two vector types.
418 if (InBitWidth > BitWidth)
419 VectorTy = VInTy;
420
421 return true;
Cameron Zwarichc9ecd142011-03-09 05:43:01 +0000422}
423
Chris Lattner4cc576b2010-04-16 00:24:57 +0000424/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
425/// its accesses to a single vector type, return true and set VecTy to
426/// the new type. If we could convert the alloca into a single promotable
427/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
428/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
429/// is the current offset from the base of the alloca being analyzed.
430///
431/// If we see at least one access to the value that is as a vector type, set the
432/// SawVec flag.
433bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
434 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
435 Instruction *User = cast<Instruction>(*UI);
Bob Wilson69743022011-01-13 20:59:44 +0000436
Chris Lattner4cc576b2010-04-16 00:24:57 +0000437 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
438 // Don't break volatile loads.
439 if (LI->isVolatile())
440 return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000441 // Don't touch MMX operations.
442 if (LI->getType()->isX86_MMXTy())
443 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000444 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000445 MergeInType(LI->getType(), Offset);
446 continue;
447 }
Bob Wilson69743022011-01-13 20:59:44 +0000448
Chris Lattner4cc576b2010-04-16 00:24:57 +0000449 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
450 // Storing the pointer, not into the value?
451 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Dale Johannesen0488fb62010-09-30 23:57:10 +0000452 // Don't touch MMX operations.
453 if (SI->getOperand(0)->getType()->isX86_MMXTy())
454 return false;
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000455 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000456 MergeInType(SI->getOperand(0)->getType(), Offset);
457 continue;
458 }
Bob Wilson69743022011-01-13 20:59:44 +0000459
Chris Lattner4cc576b2010-04-16 00:24:57 +0000460 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000461 IsNotTrivial = true; // Can't be mem2reg'd.
Chris Lattner4cc576b2010-04-16 00:24:57 +0000462 if (!CanConvertToScalar(BCI, Offset))
463 return false;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000464 continue;
465 }
466
467 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
468 // If this is a GEP with a variable indices, we can't handle it.
469 if (!GEP->hasAllConstantIndices())
470 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000471
Chris Lattner4cc576b2010-04-16 00:24:57 +0000472 // Compute the offset that this GEP adds to the pointer.
473 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
474 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
475 &Indices[0], Indices.size());
476 // See if all uses can be converted.
477 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
478 return false;
Chris Lattnera001b662010-04-16 00:38:19 +0000479 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000480 HadNonMemTransferAccess = true;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000481 continue;
482 }
483
484 // If this is a constant sized memset of a constant value (e.g. 0) we can
485 // handle it.
486 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
487 // Store of constant value and constant size.
Chris Lattnera001b662010-04-16 00:38:19 +0000488 if (!isa<ConstantInt>(MSI->getValue()) ||
489 !isa<ConstantInt>(MSI->getLength()))
490 return false;
491 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich85b0f462011-03-16 00:13:44 +0000492 HadNonMemTransferAccess = true;
Chris Lattnera001b662010-04-16 00:38:19 +0000493 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000494 }
495
496 // If this is a memcpy or memmove into or out of the whole allocation, we
497 // can handle it like a load or store of the scalar type.
498 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
Chris Lattnera001b662010-04-16 00:38:19 +0000499 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
500 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
501 return false;
Bob Wilson69743022011-01-13 20:59:44 +0000502
Chris Lattnera001b662010-04-16 00:38:19 +0000503 IsNotTrivial = true; // Can't be mem2reg'd.
504 continue;
Chris Lattner4cc576b2010-04-16 00:24:57 +0000505 }
Bob Wilson69743022011-01-13 20:59:44 +0000506
Chris Lattner4cc576b2010-04-16 00:24:57 +0000507 // Otherwise, we cannot handle this!
508 return false;
509 }
Bob Wilson69743022011-01-13 20:59:44 +0000510
Chris Lattner4cc576b2010-04-16 00:24:57 +0000511 return true;
512}
513
514/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
515/// directly. This happens when we are converting an "integer union" to a
516/// single integer scalar, or when we are converting a "vector union" to a
517/// vector with insert/extractelement instructions.
518///
519/// Offset is an offset from the original alloca, in bits that need to be
520/// shifted to the right. By the end of this, there should be no uses of Ptr.
521void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
522 uint64_t Offset) {
523 while (!Ptr->use_empty()) {
524 Instruction *User = cast<Instruction>(Ptr->use_back());
525
526 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
527 ConvertUsesToScalar(CI, NewAI, Offset);
528 CI->eraseFromParent();
529 continue;
530 }
531
532 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
533 // Compute the offset that this GEP adds to the pointer.
534 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
535 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
536 &Indices[0], Indices.size());
537 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
538 GEP->eraseFromParent();
539 continue;
540 }
Bob Wilson69743022011-01-13 20:59:44 +0000541
Chris Lattner61db1f52010-12-26 22:57:41 +0000542 IRBuilder<> Builder(User);
Bob Wilson69743022011-01-13 20:59:44 +0000543
Chris Lattner4cc576b2010-04-16 00:24:57 +0000544 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
545 // The load is a bit extract from NewAI shifted right by Offset bits.
546 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
547 Value *NewLoadVal
548 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
549 LI->replaceAllUsesWith(NewLoadVal);
550 LI->eraseFromParent();
551 continue;
552 }
Bob Wilson69743022011-01-13 20:59:44 +0000553
Chris Lattner4cc576b2010-04-16 00:24:57 +0000554 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
555 assert(SI->getOperand(0) != Ptr && "Consistency error!");
556 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
557 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
558 Builder);
559 Builder.CreateStore(New, NewAI);
560 SI->eraseFromParent();
Bob Wilson69743022011-01-13 20:59:44 +0000561
Chris Lattner4cc576b2010-04-16 00:24:57 +0000562 // If the load we just inserted is now dead, then the inserted store
563 // overwrote the entire thing.
564 if (Old->use_empty())
565 Old->eraseFromParent();
566 continue;
567 }
Bob Wilson69743022011-01-13 20:59:44 +0000568
Chris Lattner4cc576b2010-04-16 00:24:57 +0000569 // If this is a constant sized memset of a constant value (e.g. 0) we can
570 // transform it into a store of the expanded constant value.
571 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
572 assert(MSI->getRawDest() == Ptr && "Consistency error!");
573 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
574 if (NumBytes != 0) {
575 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson69743022011-01-13 20:59:44 +0000576
Chris Lattner4cc576b2010-04-16 00:24:57 +0000577 // Compute the value replicated the right number of times.
578 APInt APVal(NumBytes*8, Val);
579
580 // Splat the value if non-zero.
581 if (Val)
582 for (unsigned i = 1; i != NumBytes; ++i)
583 APVal |= APVal << 8;
Bob Wilson69743022011-01-13 20:59:44 +0000584
Chris Lattner4cc576b2010-04-16 00:24:57 +0000585 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
586 Value *New = ConvertScalar_InsertValue(
587 ConstantInt::get(User->getContext(), APVal),
588 Old, Offset, Builder);
589 Builder.CreateStore(New, NewAI);
Bob Wilson69743022011-01-13 20:59:44 +0000590
Chris Lattner4cc576b2010-04-16 00:24:57 +0000591 // If the load we just inserted is now dead, then the memset overwrote
592 // the entire thing.
593 if (Old->use_empty())
Bob Wilson69743022011-01-13 20:59:44 +0000594 Old->eraseFromParent();
Chris Lattner4cc576b2010-04-16 00:24:57 +0000595 }
596 MSI->eraseFromParent();
597 continue;
598 }
599
600 // If this is a memcpy or memmove into or out of the whole allocation, we
601 // can handle it like a load or store of the scalar type.
602 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
603 assert(Offset == 0 && "must be store to start of alloca");
Bob Wilson69743022011-01-13 20:59:44 +0000604
Chris Lattner4cc576b2010-04-16 00:24:57 +0000605 // If the source and destination are both to the same alloca, then this is
606 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
607 // as appropriate.
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000608 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
Bob Wilson69743022011-01-13 20:59:44 +0000609
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000610 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000611 // Dest must be OrigAI, change this to be a load from the original
612 // pointer (bitcasted), then a store to our new alloca.
613 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
614 Value *SrcPtr = MTI->getSource();
Mon P Wange90a6332010-12-23 01:41:32 +0000615 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
616 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
617 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
618 AIPTy = PointerType::get(AIPTy->getElementType(),
619 SPTy->getAddressSpace());
620 }
621 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
622
Chris Lattner4cc576b2010-04-16 00:24:57 +0000623 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
624 SrcVal->setAlignment(MTI->getAlignment());
625 Builder.CreateStore(SrcVal, NewAI);
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000626 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
Chris Lattner4cc576b2010-04-16 00:24:57 +0000627 // Src must be OrigAI, change this to be a load from NewAI then a store
628 // through the original dest pointer (bitcasted).
629 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
630 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
631
Mon P Wange90a6332010-12-23 01:41:32 +0000632 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
633 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
634 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
635 AIPTy = PointerType::get(AIPTy->getElementType(),
636 DPTy->getAddressSpace());
637 }
638 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
639
Chris Lattner4cc576b2010-04-16 00:24:57 +0000640 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
641 NewStore->setAlignment(MTI->getAlignment());
642 } else {
643 // Noop transfer. Src == Dst
644 }
645
646 MTI->eraseFromParent();
647 continue;
648 }
Bob Wilson69743022011-01-13 20:59:44 +0000649
Chris Lattner4cc576b2010-04-16 00:24:57 +0000650 llvm_unreachable("Unsupported operation!");
651 }
652}
653
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000654/// getScaledElementType - Gets a scaled element type for a partial vector
655/// access of an alloca. The input type must be an integer or float, and
656/// the resulting type must be an integer, float or double.
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000657static const Type *getScaledElementType(const Type *OldTy,
658 unsigned NewBitWidth) {
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000659 assert((OldTy->isIntegerTy() || OldTy->isFloatTy()) && "Partial vector "
660 "accesses must be scaled from integer or float elements.");
661
662 LLVMContext &Context = OldTy->getContext();
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000663
664 if (OldTy->isIntegerTy())
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000665 return Type::getIntNTy(Context, NewBitWidth);
666 if (NewBitWidth == 32)
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000667 return Type::getFloatTy(Context);
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000668 if (NewBitWidth == 64)
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000669 return Type::getDoubleTy(Context);
670
671 llvm_unreachable("Invalid type for a partial vector access of an alloca!");
672}
673
Chris Lattner4cc576b2010-04-16 00:24:57 +0000674/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
675/// or vector value FromVal, extracting the bits from the offset specified by
676/// Offset. This returns the value, which is of type ToType.
677///
678/// This happens when we are converting an "integer union" to a single
679/// integer scalar, or when we are converting a "vector union" to a vector with
680/// insert/extractelement instructions.
681///
682/// Offset is an offset from the original alloca, in bits that need to be
683/// shifted to the right.
684Value *ConvertToScalarInfo::
685ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
686 uint64_t Offset, IRBuilder<> &Builder) {
687 // If the load is of the whole new alloca, no conversion is needed.
688 if (FromVal->getType() == ToType && Offset == 0)
689 return FromVal;
690
691 // If the result alloca is a vector type, this is either an element
692 // access or a bitcast to another vector type of the same size.
693 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000694 if (ToType->isVectorTy()) {
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000695 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
696 if (ToTypeSize == AllocaSize)
697 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000698
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000699 assert(isPowerOf2_64(AllocaSize / ToTypeSize) &&
700 "Partial vector access of an alloca must have a power-of-2 size "
701 "ratio.");
702 assert(Offset == 0 && "Can't extract a value of a smaller vector type "
703 "from a nonzero offset.");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000704
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000705 const Type *ToElementTy = cast<VectorType>(ToType)->getElementType();
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000706 const Type *CastElementTy = getScaledElementType(ToElementTy,
707 ToTypeSize * 8);
708 unsigned NumCastVectorElements = AllocaSize / ToTypeSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000709
Cameron Zwarich032c10f2011-03-09 07:34:11 +0000710 LLVMContext &Context = FromVal->getContext();
711 const Type *CastTy = VectorType::get(CastElementTy,
712 NumCastVectorElements);
713 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
714 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
715 Type::getInt32Ty(Context), 0), "tmp");
716 return Builder.CreateBitCast(Extract, ToType, "tmp");
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000717 }
Chris Lattner4cc576b2010-04-16 00:24:57 +0000718
719 // Otherwise it must be an element access.
720 unsigned Elt = 0;
721 if (Offset) {
722 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
723 Elt = Offset/EltSize;
724 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
725 }
726 // Return the element extracted out of it.
727 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
728 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
729 if (V->getType() != ToType)
730 V = Builder.CreateBitCast(V, ToType, "tmp");
731 return V;
732 }
Bob Wilson69743022011-01-13 20:59:44 +0000733
Chris Lattner4cc576b2010-04-16 00:24:57 +0000734 // If ToType is a first class aggregate, extract out each of the pieces and
735 // use insertvalue's to form the FCA.
736 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
737 const StructLayout &Layout = *TD.getStructLayout(ST);
738 Value *Res = UndefValue::get(ST);
739 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
740 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
741 Offset+Layout.getElementOffsetInBits(i),
742 Builder);
743 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
744 }
745 return Res;
746 }
Bob Wilson69743022011-01-13 20:59:44 +0000747
Chris Lattner4cc576b2010-04-16 00:24:57 +0000748 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
749 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
750 Value *Res = UndefValue::get(AT);
751 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
752 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
753 Offset+i*EltSize, Builder);
754 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
755 }
756 return Res;
757 }
758
759 // Otherwise, this must be a union that was converted to an integer value.
760 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
761
762 // If this is a big-endian system and the load is narrower than the
763 // full alloca type, we need to do a shift to get the right bits.
764 int ShAmt = 0;
765 if (TD.isBigEndian()) {
766 // On big-endian machines, the lowest bit is stored at the bit offset
767 // from the pointer given by getTypeStoreSizeInBits. This matters for
768 // integers with a bitwidth that is not a multiple of 8.
769 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
770 TD.getTypeStoreSizeInBits(ToType) - Offset;
771 } else {
772 ShAmt = Offset;
773 }
774
775 // Note: we support negative bitwidths (with shl) which are not defined.
776 // We do this to support (f.e.) loads off the end of a structure where
777 // only some bits are used.
778 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
779 FromVal = Builder.CreateLShr(FromVal,
780 ConstantInt::get(FromVal->getType(),
781 ShAmt), "tmp");
782 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson69743022011-01-13 20:59:44 +0000783 FromVal = Builder.CreateShl(FromVal,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000784 ConstantInt::get(FromVal->getType(),
785 -ShAmt), "tmp");
786
787 // Finally, unconditionally truncate the integer to the right width.
788 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
789 if (LIBitWidth < NTy->getBitWidth())
790 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000791 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000792 LIBitWidth), "tmp");
793 else if (LIBitWidth > NTy->getBitWidth())
794 FromVal =
Bob Wilson69743022011-01-13 20:59:44 +0000795 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Chris Lattner4cc576b2010-04-16 00:24:57 +0000796 LIBitWidth), "tmp");
797
798 // If the result is an integer, this is a trunc or bitcast.
799 if (ToType->isIntegerTy()) {
800 // Should be done.
801 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
802 // Just do a bitcast, we know the sizes match up.
803 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
804 } else {
805 // Otherwise must be a pointer.
806 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
807 }
808 assert(FromVal->getType() == ToType && "Didn't convert right?");
809 return FromVal;
810}
811
812/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
813/// or vector value "Old" at the offset specified by Offset.
814///
815/// This happens when we are converting an "integer union" to a
816/// single integer scalar, or when we are converting a "vector union" to a
817/// vector with insert/extractelement instructions.
818///
819/// Offset is an offset from the original alloca, in bits that need to be
820/// shifted to the right.
821Value *ConvertToScalarInfo::
822ConvertScalar_InsertValue(Value *SV, Value *Old,
823 uint64_t Offset, IRBuilder<> &Builder) {
824 // Convert the stored type to the actual type, shift it left to insert
825 // then 'or' into place.
826 const Type *AllocaType = Old->getType();
827 LLVMContext &Context = Old->getContext();
828
829 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
830 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
831 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Bob Wilson69743022011-01-13 20:59:44 +0000832
Chris Lattner4cc576b2010-04-16 00:24:57 +0000833 // Changing the whole vector with memset or with an access of a different
834 // vector type?
835 if (ValSize == VecSize)
836 return Builder.CreateBitCast(SV, AllocaType, "tmp");
837
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000838 if (SV->getType()->isVectorTy() && isPowerOf2_64(VecSize / ValSize)) {
839 assert(Offset == 0 && "Can't insert a value of a smaller vector type at "
840 "a nonzero offset.");
841
842 const Type *ToElementTy =
843 cast<VectorType>(SV->getType())->getElementType();
Cameron Zwarich1537ce72011-03-23 05:25:55 +0000844 const Type *CastElementTy = getScaledElementType(ToElementTy, ValSize);
845 unsigned NumCastVectorElements = VecSize / ValSize;
Cameron Zwarichb2fd7702011-03-09 05:43:05 +0000846
847 LLVMContext &Context = SV->getContext();
848 const Type *OldCastTy = VectorType::get(CastElementTy,
849 NumCastVectorElements);
850 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
851
852 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
853 Value *Insert =
854 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
855 Type::getInt32Ty(Context), 0), "tmp");
856 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
857 }
858
Chris Lattner4cc576b2010-04-16 00:24:57 +0000859 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
860
861 // Must be an element insertion.
862 unsigned Elt = Offset/EltSize;
Bob Wilson69743022011-01-13 20:59:44 +0000863
Chris Lattner4cc576b2010-04-16 00:24:57 +0000864 if (SV->getType() != VTy->getElementType())
865 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000866
867 SV = Builder.CreateInsertElement(Old, SV,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000868 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
869 "tmp");
870 return SV;
871 }
Bob Wilson69743022011-01-13 20:59:44 +0000872
Chris Lattner4cc576b2010-04-16 00:24:57 +0000873 // If SV is a first-class aggregate value, insert each value recursively.
874 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
875 const StructLayout &Layout = *TD.getStructLayout(ST);
876 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
877 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Bob Wilson69743022011-01-13 20:59:44 +0000878 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner4cc576b2010-04-16 00:24:57 +0000879 Offset+Layout.getElementOffsetInBits(i),
880 Builder);
881 }
882 return Old;
883 }
Bob Wilson69743022011-01-13 20:59:44 +0000884
Chris Lattner4cc576b2010-04-16 00:24:57 +0000885 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
886 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
887 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
888 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
889 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
890 }
891 return Old;
892 }
893
894 // If SV is a float, convert it to the appropriate integer type.
895 // If it is a pointer, do the same.
896 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
897 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
898 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
899 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
900 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
901 SV = Builder.CreateBitCast(SV,
902 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
903 else if (SV->getType()->isPointerTy())
904 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
905
906 // Zero extend or truncate the value if needed.
907 if (SV->getType() != AllocaType) {
908 if (SV->getType()->getPrimitiveSizeInBits() <
909 AllocaType->getPrimitiveSizeInBits())
910 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
911 else {
912 // Truncation may be needed if storing more than the alloca can hold
913 // (undefined behavior).
914 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
915 SrcWidth = DestWidth;
916 SrcStoreWidth = DestStoreWidth;
917 }
918 }
919
920 // If this is a big-endian system and the store is narrower than the
921 // full alloca type, we need to do a shift to get the right bits.
922 int ShAmt = 0;
923 if (TD.isBigEndian()) {
924 // On big-endian machines, the lowest bit is stored at the bit offset
925 // from the pointer given by getTypeStoreSizeInBits. This matters for
926 // integers with a bitwidth that is not a multiple of 8.
927 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
928 } else {
929 ShAmt = Offset;
930 }
931
932 // Note: we support negative bitwidths (with shr) which are not defined.
933 // We do this to support (f.e.) stores off the end of a structure where
934 // only some bits in the structure are set.
935 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
936 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
937 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
938 ShAmt), "tmp");
939 Mask <<= ShAmt;
940 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
941 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
942 -ShAmt), "tmp");
943 Mask = Mask.lshr(-ShAmt);
944 }
945
946 // Mask out the bits we are about to insert from the old value, and or
947 // in the new bits.
948 if (SrcWidth != DestWidth) {
949 assert(DestWidth > SrcWidth);
950 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
951 SV = Builder.CreateOr(Old, SV, "ins");
952 }
953 return SV;
954}
955
956
957//===----------------------------------------------------------------------===//
958// SRoA Driver
959//===----------------------------------------------------------------------===//
960
961
Chris Lattnered7b41e2003-05-27 15:45:27 +0000962bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000963 TD = getAnalysisIfAvailable<TargetData>();
964
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000965 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000966
967 // FIXME: ScalarRepl currently depends on TargetData more than it
968 // theoretically needs to. It should be refactored in order to support
969 // target-independent IR. Until this is done, just skip the actual
970 // scalar-replacement portion of this pass.
971 if (!TD) return Changed;
972
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000973 while (1) {
974 bool LocalChange = performScalarRepl(F);
975 if (!LocalChange) break; // No need to repromote if no scalarrepl
976 Changed = true;
977 LocalChange = performPromotion(F);
978 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
979 }
Chris Lattner38aec322003-09-11 16:45:55 +0000980
981 return Changed;
982}
983
Chris Lattnerd0f56132011-01-14 19:50:47 +0000984namespace {
985class AllocaPromoter : public LoadAndStorePromoter {
986 AllocaInst *AI;
987public:
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000988 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
989 : LoadAndStorePromoter(Insts, S), AI(0) {}
Chris Lattnerd0f56132011-01-14 19:50:47 +0000990
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000991 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerd0f56132011-01-14 19:50:47 +0000992 // Remember which alloca we're promoting (for isInstInList).
993 this->AI = AI;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +0000994 LoadAndStorePromoter::run(Insts);
Chris Lattnerd0f56132011-01-14 19:50:47 +0000995 AI->eraseFromParent();
Chris Lattnere0a1a5b2011-01-14 07:50:47 +0000996 }
997
Chris Lattnerd0f56132011-01-14 19:50:47 +0000998 virtual bool isInstInList(Instruction *I,
999 const SmallVectorImpl<Instruction*> &Insts) const {
1000 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1001 return LI->getOperand(0) == AI;
1002 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001003 }
Chris Lattnerd0f56132011-01-14 19:50:47 +00001004};
1005} // end anon namespace
Chris Lattner38aec322003-09-11 16:45:55 +00001006
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001007/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1008/// subsequently loaded can be rewritten to load both input pointers and then
1009/// select between the result, allowing the load of the alloca to be promoted.
1010/// From this:
1011/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1012/// %V = load i32* %P2
1013/// to:
1014/// %V1 = load i32* %Alloca -> will be mem2reg'd
1015/// %V2 = load i32* %Other
Chris Lattnere3357862011-01-24 01:07:11 +00001016/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001017///
1018/// We can do this to a select if its only uses are loads and if the operand to
1019/// the select can be loaded unconditionally.
1020static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1021 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1022 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1023
1024 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1025 UI != UE; ++UI) {
1026 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1027 if (LI == 0 || LI->isVolatile()) return false;
1028
Chris Lattnere3357862011-01-24 01:07:11 +00001029 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001030 // (e.g. allocas) or at this point because we can see other accesses to it.
1031 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1032 LI->getAlignment(), TD))
1033 return false;
1034 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1035 LI->getAlignment(), TD))
1036 return false;
1037 }
1038
1039 return true;
1040}
1041
Chris Lattnere3357862011-01-24 01:07:11 +00001042/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1043/// subsequently loaded can be rewritten to load both input pointers in the pred
1044/// blocks and then PHI the results, allowing the load of the alloca to be
1045/// promoted.
1046/// From this:
1047/// %P2 = phi [i32* %Alloca, i32* %Other]
1048/// %V = load i32* %P2
1049/// to:
1050/// %V1 = load i32* %Alloca -> will be mem2reg'd
1051/// ...
1052/// %V2 = load i32* %Other
1053/// ...
1054/// %V = phi [i32 %V1, i32 %V2]
1055///
1056/// We can do this to a select if its only uses are loads and if the operand to
1057/// the select can be loaded unconditionally.
1058static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1059 // For now, we can only do this promotion if the load is in the same block as
1060 // the PHI, and if there are no stores between the phi and load.
1061 // TODO: Allow recursive phi users.
1062 // TODO: Allow stores.
1063 BasicBlock *BB = PN->getParent();
1064 unsigned MaxAlign = 0;
1065 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1066 UI != UE; ++UI) {
1067 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1068 if (LI == 0 || LI->isVolatile()) return false;
1069
1070 // For now we only allow loads in the same block as the PHI. This is a
1071 // common case that happens when instcombine merges two loads through a PHI.
1072 if (LI->getParent() != BB) return false;
1073
1074 // Ensure that there are no instructions between the PHI and the load that
1075 // could store.
1076 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1077 if (BBI->mayWriteToMemory())
1078 return false;
1079
1080 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1081 }
1082
1083 // Okay, we know that we have one or more loads in the same block as the PHI.
1084 // We can transform this if it is safe to push the loads into the predecessor
1085 // blocks. The only thing to watch out for is that we can't put a possibly
1086 // trapping load in the predecessor if it is a critical edge.
1087 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1088 BasicBlock *Pred = PN->getIncomingBlock(i);
1089
1090 // If the predecessor has a single successor, then the edge isn't critical.
1091 if (Pred->getTerminator()->getNumSuccessors() == 1)
1092 continue;
1093
1094 Value *InVal = PN->getIncomingValue(i);
1095
1096 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1097 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1098 if (II->getParent() == Pred)
1099 return false;
1100
1101 // If this pointer is always safe to load, or if we can prove that there is
1102 // already a load in the block, then we can move the load to the pred block.
1103 if (InVal->isDereferenceablePointer() ||
1104 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1105 continue;
1106
1107 return false;
1108 }
1109
1110 return true;
1111}
1112
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001113
1114/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1115/// direct (non-volatile) loads and stores to it. If the alloca is close but
1116/// not quite there, this will transform the code to allow promotion. As such,
1117/// it is a non-pure predicate.
1118static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1119 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1120 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1121
1122 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1123 UI != UE; ++UI) {
1124 User *U = *UI;
1125 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1126 if (LI->isVolatile())
1127 return false;
1128 continue;
1129 }
1130
1131 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1132 if (SI->getOperand(0) == AI || SI->isVolatile())
1133 return false; // Don't allow a store OF the AI, only INTO the AI.
1134 continue;
1135 }
1136
1137 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1138 // If the condition being selected on is a constant, fold the select, yes
1139 // this does (rarely) happen early on.
1140 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1141 Value *Result = SI->getOperand(1+CI->isZero());
1142 SI->replaceAllUsesWith(Result);
1143 SI->eraseFromParent();
1144
1145 // This is very rare and we just scrambled the use list of AI, start
1146 // over completely.
1147 return tryToMakeAllocaBePromotable(AI, TD);
1148 }
1149
1150 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1151 // loads, then we can transform this by rewriting the select.
1152 if (!isSafeSelectToSpeculate(SI, TD))
1153 return false;
1154
1155 InstsToRewrite.insert(SI);
1156 continue;
1157 }
1158
Chris Lattnere3357862011-01-24 01:07:11 +00001159 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1160 if (PN->use_empty()) { // Dead PHIs can be stripped.
1161 InstsToRewrite.insert(PN);
1162 continue;
1163 }
1164
1165 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1166 // in the pred blocks, then we can transform this by rewriting the PHI.
1167 if (!isSafePHIToSpeculate(PN, TD))
1168 return false;
1169
1170 InstsToRewrite.insert(PN);
1171 continue;
1172 }
1173
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001174 return false;
1175 }
1176
1177 // If there are no instructions to rewrite, then all uses are load/stores and
1178 // we're done!
1179 if (InstsToRewrite.empty())
1180 return true;
1181
1182 // If we have instructions that need to be rewritten for this to be promotable
1183 // take care of it now.
1184 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Chris Lattnere3357862011-01-24 01:07:11 +00001185 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1186 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1187 // loads with a new select.
1188 while (!SI->use_empty()) {
1189 LoadInst *LI = cast<LoadInst>(SI->use_back());
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001190
Chris Lattnere3357862011-01-24 01:07:11 +00001191 IRBuilder<> Builder(LI);
1192 LoadInst *TrueLoad =
1193 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1194 LoadInst *FalseLoad =
1195 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1196
1197 // Transfer alignment and TBAA info if present.
1198 TrueLoad->setAlignment(LI->getAlignment());
1199 FalseLoad->setAlignment(LI->getAlignment());
1200 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1201 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1202 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1203 }
1204
1205 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1206 V->takeName(LI);
1207 LI->replaceAllUsesWith(V);
1208 LI->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001209 }
Chris Lattnere3357862011-01-24 01:07:11 +00001210
1211 // Now that all the loads are gone, the select is gone too.
1212 SI->eraseFromParent();
1213 continue;
1214 }
1215
1216 // Otherwise, we have a PHI node which allows us to push the loads into the
1217 // predecessors.
1218 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1219 if (PN->use_empty()) {
1220 PN->eraseFromParent();
1221 continue;
1222 }
1223
1224 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1225 PHINode *NewPN = PHINode::Create(LoadTy, PN->getName()+".ld", PN);
1226
1227 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1228 // matter which one we get and if any differ, it doesn't matter.
1229 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1230 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1231 unsigned Align = SomeLoad->getAlignment();
1232
1233 // Rewrite all loads of the PN to use the new PHI.
1234 while (!PN->use_empty()) {
1235 LoadInst *LI = cast<LoadInst>(PN->use_back());
1236 LI->replaceAllUsesWith(NewPN);
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001237 LI->eraseFromParent();
1238 }
1239
Chris Lattnere3357862011-01-24 01:07:11 +00001240 // Inject loads into all of the pred blocks. Keep track of which blocks we
1241 // insert them into in case we have multiple edges from the same block.
1242 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1243
1244 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1245 BasicBlock *Pred = PN->getIncomingBlock(i);
1246 LoadInst *&Load = InsertedLoads[Pred];
1247 if (Load == 0) {
1248 Load = new LoadInst(PN->getIncomingValue(i),
1249 PN->getName() + "." + Pred->getName(),
1250 Pred->getTerminator());
1251 Load->setAlignment(Align);
1252 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1253 }
1254
1255 NewPN->addIncoming(Load, Pred);
1256 }
1257
1258 PN->eraseFromParent();
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001259 }
1260
1261 ++NumAdjusted;
1262 return true;
1263}
1264
1265
Chris Lattner38aec322003-09-11 16:45:55 +00001266bool SROA::performPromotion(Function &F) {
1267 std::vector<AllocaInst*> Allocas;
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001268 DominatorTree *DT = 0;
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001269 if (HasDomTree)
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001270 DT = &getAnalysis<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +00001271
Chris Lattner02a3be02003-09-20 14:39:18 +00001272 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +00001273
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +00001274 bool Changed = false;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001275 SmallVector<Instruction*, 64> Insts;
Chris Lattner38aec322003-09-11 16:45:55 +00001276 while (1) {
1277 Allocas.clear();
1278
1279 // Find allocas that are safe to promote, by looking at all instructions in
1280 // the entry node
1281 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1282 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Chris Lattnerc87c50a2011-01-23 22:04:55 +00001283 if (tryToMakeAllocaBePromotable(AI, TD))
Chris Lattner38aec322003-09-11 16:45:55 +00001284 Allocas.push_back(AI);
1285
1286 if (Allocas.empty()) break;
1287
Cameron Zwarichb1686c32011-01-18 03:53:26 +00001288 if (HasDomTree)
Cameron Zwarich419e8a62011-01-17 17:38:41 +00001289 PromoteMemToReg(Allocas, *DT);
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001290 else {
1291 SSAUpdater SSA;
Chris Lattnerdeaf55f2011-01-15 00:12:35 +00001292 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1293 AllocaInst *AI = Allocas[i];
1294
1295 // Build list of instructions to promote.
1296 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1297 UI != E; ++UI)
1298 Insts.push_back(cast<Instruction>(*UI));
1299
1300 AllocaPromoter(Insts, SSA).run(AI, Insts);
1301 Insts.clear();
1302 }
Chris Lattnere0a1a5b2011-01-14 07:50:47 +00001303 }
Chris Lattner38aec322003-09-11 16:45:55 +00001304 NumPromoted += Allocas.size();
1305 Changed = true;
1306 }
1307
1308 return Changed;
1309}
1310
Chris Lattner4cc576b2010-04-16 00:24:57 +00001311
Bob Wilson3992feb2010-02-03 17:23:56 +00001312/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1313/// SROA. It must be a struct or array type with a small number of elements.
1314static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1315 const Type *T = AI->getAllocatedType();
1316 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +00001317 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +00001318 return ST->getNumElements() <= 32;
1319 // Arrays are much less likely to be safe for SROA; only consider
1320 // them if they are very small.
1321 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1322 return AT->getNumElements() <= 8;
1323 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +00001324}
1325
Chris Lattnerc4472072010-04-15 23:50:26 +00001326
Chris Lattner38aec322003-09-11 16:45:55 +00001327// performScalarRepl - This algorithm is a simple worklist driven algorithm,
1328// which runs on all of the malloc/alloca instructions in the function, removing
1329// them if they are only used by getelementptr instructions.
1330//
1331bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001332 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +00001333
Chris Lattner31d80102010-04-15 21:59:20 +00001334 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +00001335 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001336 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +00001337 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +00001338 WorkList.push_back(A);
1339
1340 // Process the worklist
1341 bool Changed = false;
1342 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +00001343 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +00001344 WorkList.pop_back();
Bob Wilson69743022011-01-13 20:59:44 +00001345
Chris Lattneradd2bd72006-12-22 23:14:42 +00001346 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1347 // with unused elements.
1348 if (AI->use_empty()) {
1349 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +00001350 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +00001351 continue;
1352 }
Chris Lattner7809ecd2009-02-03 01:30:09 +00001353
1354 // If this alloca is impossible for us to promote, reject it early.
1355 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1356 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001357
Chris Lattner79b3bd32007-04-25 06:40:51 +00001358 // Check to see if this allocation is only modified by a memcpy/memmove from
1359 // a constant global. If this is the case, we can change all users to use
1360 // the constant global instead. This is commonly produced by the CFE by
1361 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1362 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +00001363 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +00001364 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1365 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +00001366 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +00001367 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +00001368 TheCopy->eraseFromParent(); // Don't mutate the global.
1369 AI->eraseFromParent();
1370 ++NumGlobals;
1371 Changed = true;
1372 continue;
1373 }
Bob Wilson69743022011-01-13 20:59:44 +00001374
Chris Lattner7809ecd2009-02-03 01:30:09 +00001375 // Check to see if we can perform the core SROA transformation. We cannot
1376 // transform the allocation instruction if it is an array allocation
1377 // (allocations OF arrays are ok though), and an allocation of a scalar
1378 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +00001379 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +00001380
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +00001381 // Do not promote [0 x %struct].
1382 if (AllocaSize == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001383
Chris Lattner31d80102010-04-15 21:59:20 +00001384 // Do not promote any struct whose size is too big.
1385 if (AllocaSize > SRThreshold) continue;
Bob Wilson69743022011-01-13 20:59:44 +00001386
Bob Wilson3992feb2010-02-03 17:23:56 +00001387 // If the alloca looks like a good candidate for scalar replacement, and if
1388 // all its users can be transformed, then split up the aggregate into its
1389 // separate elements.
1390 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1391 DoScalarReplacement(AI, WorkList);
1392 Changed = true;
1393 continue;
1394 }
1395
Chris Lattner6e733d32009-01-28 20:16:43 +00001396 // If we can turn this aggregate value (potentially with casts) into a
1397 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001398 // IsNotTrivial tracks whether this is something that mem2reg could have
1399 // promoted itself. If so, we don't want to transform it needlessly. Note
1400 // that we can't just check based on the type: the alloca may be of an i32
1401 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +00001402 if (AllocaInst *NewAI =
1403 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001404 NewAI->takeName(AI);
1405 AI->eraseFromParent();
1406 ++NumConverted;
1407 Changed = true;
1408 continue;
Bob Wilson69743022011-01-13 20:59:44 +00001409 }
1410
Chris Lattner7809ecd2009-02-03 01:30:09 +00001411 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +00001412 }
1413
1414 return Changed;
1415}
Chris Lattner5e062a12003-05-30 04:15:41 +00001416
Chris Lattnera10b29b2007-04-25 05:02:56 +00001417/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1418/// predicate, do SROA now.
Bob Wilson69743022011-01-13 20:59:44 +00001419void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001420 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +00001421 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +00001422 SmallVector<AllocaInst*, 32> ElementAllocas;
1423 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1424 ElementAllocas.reserve(ST->getNumContainedTypes());
1425 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Bob Wilson69743022011-01-13 20:59:44 +00001426 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +00001427 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001428 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001429 ElementAllocas.push_back(NA);
1430 WorkList.push_back(NA); // Add to worklist for recursive processing
1431 }
1432 } else {
1433 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1434 ElementAllocas.reserve(AT->getNumElements());
1435 const Type *ElTy = AT->getElementType();
1436 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +00001437 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +00001438 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +00001439 ElementAllocas.push_back(NA);
1440 WorkList.push_back(NA); // Add to worklist for recursive processing
1441 }
1442 }
1443
Bob Wilsonb742def2009-12-18 20:14:40 +00001444 // Now that we have created the new alloca instructions, rewrite all the
1445 // uses of the old alloca.
1446 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +00001447
Bob Wilsonb742def2009-12-18 20:14:40 +00001448 // Now erase any instructions that were made dead while rewriting the alloca.
1449 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +00001450 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +00001451
Dan Gohmanfe601042010-06-22 15:08:57 +00001452 ++NumReplaced;
Chris Lattnera10b29b2007-04-25 05:02:56 +00001453}
Chris Lattnera59adc42009-12-14 05:11:02 +00001454
Bob Wilsonb742def2009-12-18 20:14:40 +00001455/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1456/// recursively including all their operands that become trivially dead.
1457void SROA::DeleteDeadInstructions() {
1458 while (!DeadInsts.empty()) {
1459 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +00001460
Bob Wilsonb742def2009-12-18 20:14:40 +00001461 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1462 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1463 // Zero out the operand and see if it becomes trivially dead.
1464 // (But, don't add allocas to the dead instruction list -- they are
1465 // already on the worklist and will be deleted separately.)
1466 *OI = 0;
1467 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1468 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +00001469 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001470
1471 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +00001472 }
Chris Lattnera59adc42009-12-14 05:11:02 +00001473}
Bob Wilson69743022011-01-13 20:59:44 +00001474
Bob Wilsonb742def2009-12-18 20:14:40 +00001475/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1476/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001477/// the Info parameter. Offset indicates the position within AI that is
1478/// referenced by this instruction.
Chris Lattner6c95d242011-01-23 07:29:29 +00001479void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001480 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001481 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1482 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +00001483
Bob Wilsonb742def2009-12-18 20:14:40 +00001484 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner6c95d242011-01-23 07:29:29 +00001485 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001486 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001487 uint64_t GEPOffset = Offset;
Chris Lattner6c95d242011-01-23 07:29:29 +00001488 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001489 if (!Info.isUnsafe)
Chris Lattner6c95d242011-01-23 07:29:29 +00001490 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif19101c72010-06-28 11:20:42 +00001491 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001492 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001493 if (Length == 0)
1494 return MarkUnsafe(Info, User);
Chris Lattner6c95d242011-01-23 07:29:29 +00001495 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
Chris Lattner145c5322011-01-23 08:27:54 +00001496 UI.getOperandNo() == 0, Info, MI,
1497 true /*AllowWholeAccess*/);
Bob Wilsonb742def2009-12-18 20:14:40 +00001498 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001499 if (LI->isVolatile())
1500 return MarkUnsafe(Info, User);
1501 const Type *LIType = LI->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001502 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001503 LIType, false, Info, LI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001504 Info.hasALoadOrStore = true;
1505
Bob Wilsonb742def2009-12-18 20:14:40 +00001506 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1507 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001508 if (SI->isVolatile() || SI->getOperand(0) == I)
1509 return MarkUnsafe(Info, User);
1510
1511 const Type *SIType = SI->getOperand(0)->getType();
Chris Lattner6c95d242011-01-23 07:29:29 +00001512 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
Chris Lattner145c5322011-01-23 08:27:54 +00001513 SIType, true, Info, SI, true /*AllowWholeAccess*/);
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001514 Info.hasALoadOrStore = true;
Chris Lattner145c5322011-01-23 08:27:54 +00001515 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1516 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1517 } else {
1518 return MarkUnsafe(Info, User);
1519 }
1520 if (Info.isUnsafe) return;
1521 }
1522}
1523
1524
1525/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1526/// derived from the alloca, we can often still split the alloca into elements.
1527/// This is useful if we have a large alloca where one element is phi'd
1528/// together somewhere: we can SRoA and promote all the other elements even if
1529/// we end up not being able to promote this one.
1530///
1531/// All we require is that the uses of the PHI do not index into other parts of
1532/// the alloca. The most important use case for this is single load and stores
1533/// that are PHI'd together, which can happen due to code sinking.
1534void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1535 AllocaInfo &Info) {
1536 // If we've already checked this PHI, don't do it again.
1537 if (PHINode *PN = dyn_cast<PHINode>(I))
1538 if (!Info.CheckedPHIs.insert(PN))
1539 return;
1540
1541 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1542 Instruction *User = cast<Instruction>(*UI);
1543
1544 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1545 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1546 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1547 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1548 // but would have to prove that we're staying inside of an element being
1549 // promoted.
1550 if (!GEPI->hasAllZeroIndices())
1551 return MarkUnsafe(Info, User);
1552 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1553 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1554 if (LI->isVolatile())
1555 return MarkUnsafe(Info, User);
1556 const Type *LIType = LI->getType();
1557 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1558 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1559 Info.hasALoadOrStore = true;
1560
1561 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1562 // Store is ok if storing INTO the pointer, not storing the pointer
1563 if (SI->isVolatile() || SI->getOperand(0) == I)
1564 return MarkUnsafe(Info, User);
1565
1566 const Type *SIType = SI->getOperand(0)->getType();
1567 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1568 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1569 Info.hasALoadOrStore = true;
1570 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1571 isSafePHISelectUseForScalarRepl(User, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001572 } else {
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001573 return MarkUnsafe(Info, User);
Bob Wilsonb742def2009-12-18 20:14:40 +00001574 }
1575 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001576 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001577}
Bob Wilson39c88a62009-12-17 18:34:24 +00001578
Bob Wilsonb742def2009-12-18 20:14:40 +00001579/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1580/// replacement. It is safe when all the indices are constant, in-bounds
1581/// references, and when the resulting offset corresponds to an element within
1582/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001583/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner6c95d242011-01-23 07:29:29 +00001584void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001585 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001586 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1587 if (GEPIt == E)
1588 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001589
Chris Lattner88e6dc82008-08-23 05:21:06 +00001590 // Walk through the GEP type indices, checking the types that this indexes
1591 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +00001592 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +00001593 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +00001594 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +00001595 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +00001596
Bob Wilsonb742def2009-12-18 20:14:40 +00001597 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1598 if (!IdxVal)
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001599 return MarkUnsafe(Info, GEPI);
Chris Lattner88e6dc82008-08-23 05:21:06 +00001600 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001601
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001602 // Compute the offset due to this GEP and check if the alloca has a
1603 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001604 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1605 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1606 &Indices[0], Indices.size());
Chris Lattner6c95d242011-01-23 07:29:29 +00001607 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001608 MarkUnsafe(Info, GEPI);
Chris Lattner5e062a12003-05-30 04:15:41 +00001609}
1610
Bob Wilson704d1342011-01-13 17:45:11 +00001611/// isHomogeneousAggregate - Check if type T is a struct or array containing
1612/// elements of the same type (which is always true for arrays). If so,
1613/// return true with NumElts and EltTy set to the number of elements and the
1614/// element type, respectively.
1615static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1616 const Type *&EltTy) {
1617 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1618 NumElts = AT->getNumElements();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001619 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
Bob Wilson704d1342011-01-13 17:45:11 +00001620 return true;
1621 }
1622 if (const StructType *ST = dyn_cast<StructType>(T)) {
1623 NumElts = ST->getNumContainedTypes();
Bob Wilsonf0908ae2011-01-13 18:26:59 +00001624 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
Bob Wilson704d1342011-01-13 17:45:11 +00001625 for (unsigned n = 1; n < NumElts; ++n) {
1626 if (ST->getContainedType(n) != EltTy)
1627 return false;
1628 }
1629 return true;
1630 }
1631 return false;
1632}
1633
1634/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1635/// "homogeneous" aggregates with the same element type and number of elements.
1636static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1637 if (T1 == T2)
1638 return true;
1639
1640 unsigned NumElts1, NumElts2;
1641 const Type *EltTy1, *EltTy2;
1642 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1643 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1644 NumElts1 == NumElts2 &&
1645 EltTy1 == EltTy2)
1646 return true;
1647
1648 return false;
1649}
1650
Bob Wilsonb742def2009-12-18 20:14:40 +00001651/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1652/// alloca or has an offset and size that corresponds to a component element
1653/// within it. The offset checked here may have been formed from a GEP with a
1654/// pointer bitcasted to a different type.
Chris Lattner145c5322011-01-23 08:27:54 +00001655///
1656/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1657/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner6c95d242011-01-23 07:29:29 +00001658void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +00001659 const Type *MemOpType, bool isStore,
Chris Lattner145c5322011-01-23 08:27:54 +00001660 AllocaInfo &Info, Instruction *TheAccess,
1661 bool AllowWholeAccess) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001662 // Check if this is a load/store of the entire alloca.
Chris Lattner145c5322011-01-23 08:27:54 +00001663 if (Offset == 0 && AllowWholeAccess &&
Chris Lattner6c95d242011-01-23 07:29:29 +00001664 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson704d1342011-01-13 17:45:11 +00001665 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1666 // loads/stores (which are essentially the same as the MemIntrinsics with
1667 // regard to copying padding between elements). But, if an alloca is
1668 // flagged as both a source and destination of such operations, we'll need
1669 // to check later for padding between elements.
1670 if (!MemOpType || MemOpType->isIntegerTy()) {
1671 if (isStore)
1672 Info.isMemCpyDst = true;
1673 else
1674 Info.isMemCpySrc = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001675 return;
1676 }
Bob Wilson704d1342011-01-13 17:45:11 +00001677 // This is also safe for references using a type that is compatible with
1678 // the type of the alloca, so that loads/stores can be rewritten using
1679 // insertvalue/extractvalue.
Chris Lattner6c95d242011-01-23 07:29:29 +00001680 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner7e9b4272011-01-16 06:18:28 +00001681 Info.hasSubelementAccess = true;
Bob Wilson704d1342011-01-13 17:45:11 +00001682 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001683 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001684 }
1685 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner6c95d242011-01-23 07:29:29 +00001686 const Type *T = Info.AI->getAllocatedType();
Chris Lattner7e9b4272011-01-16 06:18:28 +00001687 if (TypeHasComponent(T, Offset, MemSize)) {
1688 Info.hasSubelementAccess = true;
Bob Wilsonb742def2009-12-18 20:14:40 +00001689 return;
Chris Lattner7e9b4272011-01-16 06:18:28 +00001690 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001691
Chris Lattnerd01a0da2011-01-23 07:05:44 +00001692 return MarkUnsafe(Info, TheAccess);
Bob Wilsonb742def2009-12-18 20:14:40 +00001693}
1694
1695/// TypeHasComponent - Return true if T has a component type with the
1696/// specified offset and size. If Size is zero, do not check the size.
1697bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1698 const Type *EltTy;
1699 uint64_t EltSize;
1700 if (const StructType *ST = dyn_cast<StructType>(T)) {
1701 const StructLayout *Layout = TD->getStructLayout(ST);
1702 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1703 EltTy = ST->getContainedType(EltIdx);
1704 EltSize = TD->getTypeAllocSize(EltTy);
1705 Offset -= Layout->getElementOffset(EltIdx);
1706 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1707 EltTy = AT->getElementType();
1708 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +00001709 if (Offset >= AT->getNumElements() * EltSize)
1710 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +00001711 Offset %= EltSize;
1712 } else {
1713 return false;
1714 }
1715 if (Offset == 0 && (Size == 0 || EltSize == Size))
1716 return true;
1717 // Check if the component spans multiple elements.
1718 if (Offset + Size > EltSize)
1719 return false;
1720 return TypeHasComponent(EltTy, Offset, Size);
1721}
1722
1723/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1724/// the instruction I, which references it, to use the separate elements.
1725/// Offset indicates the position within AI that is referenced by this
1726/// instruction.
1727void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1728 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner145c5322011-01-23 08:27:54 +00001729 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1730 Use &TheUse = UI.getUse();
1731 Instruction *User = cast<Instruction>(*UI++);
Bob Wilsonb742def2009-12-18 20:14:40 +00001732
1733 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1734 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001735 continue;
1736 }
1737
1738 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001739 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner145c5322011-01-23 08:27:54 +00001740 continue;
1741 }
1742
1743 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001744 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1745 uint64_t MemSize = Length->getZExtValue();
1746 if (Offset == 0 &&
1747 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1748 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +00001749 // Otherwise the intrinsic can only touch a single element and the
1750 // address operand will be updated, so nothing else needs to be done.
Chris Lattner145c5322011-01-23 08:27:54 +00001751 continue;
1752 }
1753
1754 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001755 const Type *LIType = LI->getType();
Chris Lattner192228e2011-01-16 05:28:59 +00001756
Bob Wilson704d1342011-01-13 17:45:11 +00001757 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001758 // Replace:
1759 // %res = load { i32, i32 }* %alloc
1760 // with:
1761 // %load.0 = load i32* %alloc.0
1762 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1763 // %load.1 = load i32* %alloc.1
1764 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1765 // (Also works for arrays instead of structs)
1766 Value *Insert = UndefValue::get(LIType);
1767 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1768 Value *Load = new LoadInst(NewElts[i], "load", LI);
1769 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1770 }
1771 LI->replaceAllUsesWith(Insert);
1772 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001773 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001774 TD->getTypeAllocSize(LIType) ==
1775 TD->getTypeAllocSize(AI->getAllocatedType())) {
1776 // If this is a load of the entire alloca to an integer, rewrite it.
1777 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1778 }
Chris Lattner145c5322011-01-23 08:27:54 +00001779 continue;
1780 }
1781
1782 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001783 Value *Val = SI->getOperand(0);
1784 const Type *SIType = Val->getType();
Bob Wilson704d1342011-01-13 17:45:11 +00001785 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +00001786 // Replace:
1787 // store { i32, i32 } %val, { i32, i32 }* %alloc
1788 // with:
1789 // %val.0 = extractvalue { i32, i32 } %val, 0
1790 // store i32 %val.0, i32* %alloc.0
1791 // %val.1 = extractvalue { i32, i32 } %val, 1
1792 // store i32 %val.1, i32* %alloc.1
1793 // (Also works for arrays instead of structs)
1794 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1795 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1796 new StoreInst(Extract, NewElts[i], SI);
1797 }
1798 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +00001799 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001800 TD->getTypeAllocSize(SIType) ==
1801 TD->getTypeAllocSize(AI->getAllocatedType())) {
1802 // If this is a store of the entire alloca from an integer, rewrite it.
1803 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1804 }
Chris Lattner145c5322011-01-23 08:27:54 +00001805 continue;
1806 }
1807
1808 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1809 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1810 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1811 // the new pointer.
1812 if (!isa<AllocaInst>(I)) continue;
1813
1814 assert(Offset == 0 && NewElts[0] &&
1815 "Direct alloca use should have a zero offset");
1816
1817 // If we have a use of the alloca, we know the derived uses will be
1818 // utilizing just the first element of the scalarized result. Insert a
1819 // bitcast of the first alloca before the user as required.
1820 AllocaInst *NewAI = NewElts[0];
1821 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1822 NewAI->moveBefore(BCI);
1823 TheUse = BCI;
1824 continue;
Bob Wilsonb742def2009-12-18 20:14:40 +00001825 }
Bob Wilson39c88a62009-12-17 18:34:24 +00001826 }
1827}
1828
Bob Wilsonb742def2009-12-18 20:14:40 +00001829/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1830/// and recursively continue updating all of its uses.
1831void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1832 SmallVector<AllocaInst*, 32> &NewElts) {
1833 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1834 if (BC->getOperand(0) != AI)
1835 return;
Bob Wilson39c88a62009-12-17 18:34:24 +00001836
Bob Wilsonb742def2009-12-18 20:14:40 +00001837 // The bitcast references the original alloca. Replace its uses with
1838 // references to the first new element alloca.
1839 Instruction *Val = NewElts[0];
1840 if (Val->getType() != BC->getDestTy()) {
1841 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1842 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001843 }
Bob Wilsonb742def2009-12-18 20:14:40 +00001844 BC->replaceAllUsesWith(Val);
1845 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +00001846}
1847
Bob Wilsonb742def2009-12-18 20:14:40 +00001848/// FindElementAndOffset - Return the index of the element containing Offset
1849/// within the specified type, which must be either a struct or an array.
1850/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +00001851/// element. IdxTy is set to the type of the index result to be used in a
1852/// GEP instruction.
1853uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1854 const Type *&IdxTy) {
1855 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +00001856 if (const StructType *ST = dyn_cast<StructType>(T)) {
1857 const StructLayout *Layout = TD->getStructLayout(ST);
1858 Idx = Layout->getElementContainingOffset(Offset);
1859 T = ST->getContainedType(Idx);
1860 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +00001861 IdxTy = Type::getInt32Ty(T->getContext());
1862 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +00001863 }
Bob Wilsone88728d2009-12-19 06:53:17 +00001864 const ArrayType *AT = cast<ArrayType>(T);
1865 T = AT->getElementType();
1866 uint64_t EltSize = TD->getTypeAllocSize(T);
1867 Idx = Offset / EltSize;
1868 Offset -= Idx * EltSize;
1869 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +00001870 return Idx;
1871}
1872
1873/// RewriteGEP - Check if this GEP instruction moves the pointer across
1874/// elements of the alloca that are being split apart, and if so, rewrite
1875/// the GEP to be relative to the new element.
1876void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1877 SmallVector<AllocaInst*, 32> &NewElts) {
1878 uint64_t OldOffset = Offset;
1879 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1880 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1881 &Indices[0], Indices.size());
1882
1883 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1884
1885 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +00001886 const Type *IdxTy;
1887 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001888 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +00001889 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +00001890
1891 T = AI->getAllocatedType();
1892 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +00001893 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +00001894
1895 // If this GEP does not move the pointer across elements of the alloca
1896 // being split, then it does not needs to be rewritten.
1897 if (Idx == OldIdx)
1898 return;
1899
1900 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1901 SmallVector<Value*, 8> NewArgs;
1902 NewArgs.push_back(Constant::getNullValue(i32Ty));
1903 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +00001904 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1905 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +00001906 }
1907 Instruction *Val = NewElts[Idx];
1908 if (NewArgs.size() > 1) {
1909 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1910 NewArgs.end(), "", GEPI);
1911 Val->takeName(GEPI);
1912 }
1913 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001914 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001915 GEPI->replaceAllUsesWith(Val);
1916 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001917}
1918
1919/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1920/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +00001921void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +00001922 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +00001923 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00001924 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +00001925 // appropriate type. The "Other" pointer is the pointer that goes to memory
1926 // that doesn't have anything to do with the alloca that we are promoting. For
1927 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +00001928 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001929 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +00001930 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +00001931 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +00001932 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001933 else {
Bob Wilsonb742def2009-12-18 20:14:40 +00001934 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +00001935 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +00001936 }
1937 }
Bob Wilson78c50b82009-12-08 18:22:03 +00001938
Chris Lattnerd93afec2009-01-07 07:18:45 +00001939 // If there is an other pointer, we want to convert it to the same pointer
1940 // type as AI has, so we can GEP through it safely.
1941 if (OtherPtr) {
Chris Lattner0238f8c2010-07-08 00:27:05 +00001942 unsigned AddrSpace =
1943 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilsonb742def2009-12-18 20:14:40 +00001944
1945 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1946 // optimization, but it's also required to detect the corner case where
1947 // both pointer operands are referencing the same memory, and where
1948 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1949 // function is only called for mem intrinsics that access the whole
1950 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattner0238f8c2010-07-08 00:27:05 +00001951 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson69743022011-01-13 20:59:44 +00001952
Bob Wilsona756b1d2010-01-19 04:32:48 +00001953 // Copying the alloca to itself is a no-op: just delete it.
1954 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1955 // This code will run twice for a no-op memcpy -- once for each operand.
1956 // Put only one reference to MI on the DeadInsts list.
1957 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1958 E = DeadInsts.end(); I != E; ++I)
1959 if (*I == MI) return;
1960 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +00001961 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +00001962 }
Bob Wilson69743022011-01-13 20:59:44 +00001963
Chris Lattnerd93afec2009-01-07 07:18:45 +00001964 // If the pointer is not the right type, insert a bitcast to the right
1965 // type.
Chris Lattner0238f8c2010-07-08 00:27:05 +00001966 const Type *NewTy =
1967 PointerType::get(AI->getType()->getElementType(), AddrSpace);
Bob Wilson69743022011-01-13 20:59:44 +00001968
Chris Lattner0238f8c2010-07-08 00:27:05 +00001969 if (OtherPtr->getType() != NewTy)
1970 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +00001971 }
Bob Wilson69743022011-01-13 20:59:44 +00001972
Chris Lattnerd93afec2009-01-07 07:18:45 +00001973 // Process each element of the aggregate.
Bob Wilsonb742def2009-12-18 20:14:40 +00001974 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson69743022011-01-13 20:59:44 +00001975
Owen Anderson1d0be152009-08-13 21:58:54 +00001976 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +00001977
1978 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1979 // If this is a memcpy/memmove, emit a GEP of the other element address.
1980 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001981 unsigned OtherEltAlign = MemAlignment;
Bob Wilson69743022011-01-13 20:59:44 +00001982
Bob Wilsona756b1d2010-01-19 04:32:48 +00001983 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001984 Value *Idx[2] = { Zero,
1985 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +00001986 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +00001987 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +00001988 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +00001989 uint64_t EltOffset;
1990 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001991 const Type *OtherTy = OtherPtrTy->getElementType();
1992 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00001993 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1994 } else {
Chris Lattnerd55c1c12010-04-16 01:05:38 +00001995 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001996 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +00001997 }
Bob Wilson69743022011-01-13 20:59:44 +00001998
Chris Lattner1541e0f2009-03-04 19:20:50 +00001999 // The alignment of the other pointer is the guaranteed alignment of the
2000 // element, which is affected by both the known alignment of the whole
2001 // mem intrinsic and the alignment of the element. If the alignment of
2002 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2003 // known alignment is just 4 bytes.
2004 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +00002005 }
Bob Wilson69743022011-01-13 20:59:44 +00002006
Chris Lattnerd93afec2009-01-07 07:18:45 +00002007 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +00002008 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Bob Wilson69743022011-01-13 20:59:44 +00002009
Chris Lattnerd93afec2009-01-07 07:18:45 +00002010 // If we got down to a scalar, insert a load or store as appropriate.
2011 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00002012 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +00002013 if (SROADest) {
2014 // From Other to Alloca.
2015 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2016 new StoreInst(Elt, EltPtr, MI);
2017 } else {
2018 // From Alloca to Other.
2019 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2020 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2021 }
Chris Lattnerd93afec2009-01-07 07:18:45 +00002022 continue;
2023 }
2024 assert(isa<MemSetInst>(MI));
Bob Wilson69743022011-01-13 20:59:44 +00002025
Chris Lattnerd93afec2009-01-07 07:18:45 +00002026 // If the stored element is zero (common case), just store a null
2027 // constant.
2028 Constant *StoreVal;
Gabor Greif6f14c8c2010-06-30 09:16:16 +00002029 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +00002030 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00002031 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +00002032 } else {
2033 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +00002034 const Type *ValTy = EltTy->getScalarType();
2035
Chris Lattnerd93afec2009-01-07 07:18:45 +00002036 // Construct an integer with the right value.
2037 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2038 APInt OneVal(EltSize, CI->getZExtValue());
2039 APInt TotalVal(OneVal);
2040 // Set each byte.
2041 for (unsigned i = 0; 8*i < EltSize; ++i) {
2042 TotalVal = TotalVal.shl(8);
2043 TotalVal |= OneVal;
2044 }
Bob Wilson69743022011-01-13 20:59:44 +00002045
Chris Lattnerd93afec2009-01-07 07:18:45 +00002046 // Convert the integer value to the appropriate type.
Chris Lattnerd55c1c12010-04-16 01:05:38 +00002047 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +00002048 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002049 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002050 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00002051 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002052 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson69743022011-01-13 20:59:44 +00002053
Chris Lattnerd93afec2009-01-07 07:18:45 +00002054 // If the requested value was a vector constant, create it.
2055 if (EltTy != ValTy) {
2056 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2057 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Chris Lattner2ca5c862011-02-15 00:14:00 +00002058 StoreVal = ConstantVector::get(Elts);
Chris Lattnerd93afec2009-01-07 07:18:45 +00002059 }
2060 }
2061 new StoreInst(StoreVal, EltPtr, MI);
2062 continue;
2063 }
2064 // Otherwise, if we're storing a byte variable, use a memset call for
2065 // this element.
2066 }
Bob Wilson69743022011-01-13 20:59:44 +00002067
Duncan Sands777d2302009-05-09 07:06:46 +00002068 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002069
Chris Lattner61db1f52010-12-26 22:57:41 +00002070 IRBuilder<> Builder(MI);
Bob Wilson69743022011-01-13 20:59:44 +00002071
Chris Lattnerd93afec2009-01-07 07:18:45 +00002072 // Finally, insert the meminst for this element.
Chris Lattner61db1f52010-12-26 22:57:41 +00002073 if (isa<MemSetInst>(MI)) {
2074 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2075 MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002076 } else {
Chris Lattner61db1f52010-12-26 22:57:41 +00002077 assert(isa<MemTransferInst>(MI));
2078 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2079 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson69743022011-01-13 20:59:44 +00002080
Chris Lattner61db1f52010-12-26 22:57:41 +00002081 if (isa<MemCpyInst>(MI))
2082 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2083 else
2084 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattnerd93afec2009-01-07 07:18:45 +00002085 }
Chris Lattner372dda82007-03-05 07:52:57 +00002086 }
Bob Wilsonb742def2009-12-18 20:14:40 +00002087 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +00002088}
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002089
Bob Wilson39fdd692009-12-04 21:57:37 +00002090/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002091/// overwrites the entire allocation. Extract out the pieces of the stored
2092/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002093void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002094 SmallVector<AllocaInst*, 32> &NewElts){
2095 // Extract each element out of the integer according to its structure offset
2096 // and store the element value to the individual alloca.
2097 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +00002098 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002099 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002100
Chris Lattner70728532011-01-16 05:58:24 +00002101 IRBuilder<> Builder(SI);
2102
Eli Friedman41b33f42009-06-01 09:14:32 +00002103 // Handle tail padding by extending the operand
2104 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002105 SrcVal = Builder.CreateZExt(SrcVal,
2106 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002107
David Greene504c7d82010-01-05 01:27:09 +00002108 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +00002109 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002110
2111 // There are two forms here: AI could be an array or struct. Both cases
2112 // have different ways to compute the element offset.
2113 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2114 const StructLayout *Layout = TD->getStructLayout(EltSTy);
Bob Wilson69743022011-01-13 20:59:44 +00002115
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002116 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2117 // Get the number of bits to shift SrcVal to get the value.
2118 const Type *FieldTy = EltSTy->getElementType(i);
2119 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson69743022011-01-13 20:59:44 +00002120
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002121 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +00002122 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002123
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002124 Value *EltVal = SrcVal;
2125 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002126 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002127 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002128 }
Bob Wilson69743022011-01-13 20:59:44 +00002129
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002130 // Truncate down to an integer of the right size.
2131 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002132
Chris Lattner583dd602009-01-09 18:18:43 +00002133 // Ignore zero sized fields like {}, they obviously contain no data.
2134 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002135
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002136 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002137 EltVal = Builder.CreateTrunc(EltVal,
2138 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002139 Value *DestField = NewElts[i];
2140 if (EltVal->getType() == FieldTy) {
2141 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +00002142 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002143 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002144 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002145 } else {
2146 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002147 DestField = Builder.CreateBitCast(DestField,
2148 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002149 }
2150 new StoreInst(EltVal, DestField, SI);
2151 }
Bob Wilson69743022011-01-13 20:59:44 +00002152
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002153 } else {
2154 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2155 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002156 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002157 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2158
2159 uint64_t Shift;
Bob Wilson69743022011-01-13 20:59:44 +00002160
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002161 if (TD->isBigEndian())
2162 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002163 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002164 Shift = 0;
Bob Wilson69743022011-01-13 20:59:44 +00002165
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002166 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00002167 // Ignore zero sized fields like {}, they obviously contain no data.
2168 if (ElementSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002169
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002170 Value *EltVal = SrcVal;
2171 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002172 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner70728532011-01-16 05:58:24 +00002173 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002174 }
Bob Wilson69743022011-01-13 20:59:44 +00002175
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002176 // Truncate down to an integer of the right size.
2177 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner70728532011-01-16 05:58:24 +00002178 EltVal = Builder.CreateTrunc(EltVal,
2179 IntegerType::get(SI->getContext(),
2180 ElementSizeBits));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002181 Value *DestField = NewElts[i];
2182 if (EltVal->getType() == ArrayEltTy) {
2183 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00002184 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00002185 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002186 // Bitcast to the right element type (for fp/vector values).
Chris Lattner70728532011-01-16 05:58:24 +00002187 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002188 } else {
2189 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner70728532011-01-16 05:58:24 +00002190 DestField = Builder.CreateBitCast(DestField,
2191 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002192 }
2193 new StoreInst(EltVal, DestField, SI);
Bob Wilson69743022011-01-13 20:59:44 +00002194
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002195 if (TD->isBigEndian())
2196 Shift -= ElementOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002197 else
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002198 Shift += ElementOffset;
2199 }
2200 }
Bob Wilson69743022011-01-13 20:59:44 +00002201
Bob Wilsonb742def2009-12-18 20:14:40 +00002202 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00002203}
2204
Bob Wilson39fdd692009-12-04 21:57:37 +00002205/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002206/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00002207void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002208 SmallVector<AllocaInst*, 32> &NewElts) {
2209 // Extract each element out of the NewElts according to its structure offset
2210 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00002211 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002212 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002213
David Greene504c7d82010-01-05 01:27:09 +00002214 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00002215 << '\n');
Bob Wilson69743022011-01-13 20:59:44 +00002216
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002217 // There are two forms here: AI could be an array or struct. Both cases
2218 // have different ways to compute the element offset.
2219 const StructLayout *Layout = 0;
2220 uint64_t ArrayEltBitOffset = 0;
2221 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2222 Layout = TD->getStructLayout(EltSTy);
2223 } else {
2224 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00002225 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson69743022011-01-13 20:59:44 +00002226 }
2227
2228 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00002229 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson69743022011-01-13 20:59:44 +00002230
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002231 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2232 // Load the value from the alloca. If the NewElt is an aggregate, cast
2233 // the pointer to an integer of the same size before doing the load.
2234 Value *SrcField = NewElts[i];
2235 const Type *FieldTy =
2236 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00002237 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Bob Wilson69743022011-01-13 20:59:44 +00002238
Chris Lattner583dd602009-01-09 18:18:43 +00002239 // Ignore zero sized fields like {}, they obviously contain no data.
2240 if (FieldSizeBits == 0) continue;
Bob Wilson69743022011-01-13 20:59:44 +00002241
2242 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson1d0be152009-08-13 21:58:54 +00002243 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00002244 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2245 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00002246 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00002247 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002248 "", LI);
2249 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2250
2251 // If SrcField is a fp or vector of the right size but that isn't an
2252 // integer type, bitcast to an integer so we can shift it.
2253 if (SrcField->getType() != FieldIntTy)
2254 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2255
2256 // Zero extend the field to be the same size as the final alloca so that
2257 // we can shift and insert it.
2258 if (SrcField->getType() != ResultVal->getType())
2259 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson69743022011-01-13 20:59:44 +00002260
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002261 // Determine the number of bits to shift SrcField.
2262 uint64_t Shift;
2263 if (Layout) // Struct case.
2264 Shift = Layout->getElementOffsetInBits(i);
2265 else // Array case.
2266 Shift = i*ArrayEltBitOffset;
Bob Wilson69743022011-01-13 20:59:44 +00002267
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002268 if (TD->isBigEndian())
2269 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson69743022011-01-13 20:59:44 +00002270
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002271 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002272 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002273 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2274 }
2275
Chris Lattner14952472010-06-27 07:58:26 +00002276 // Don't create an 'or x, 0' on the first iteration.
2277 if (!isa<Constant>(ResultVal) ||
2278 !cast<Constant>(ResultVal)->isNullValue())
2279 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2280 else
2281 ResultVal = SrcField;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002282 }
Eli Friedman41b33f42009-06-01 09:14:32 +00002283
2284 // Handle tail padding by truncating the result
2285 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2286 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2287
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002288 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00002289 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00002290}
2291
Duncan Sands3cb36502007-11-04 14:43:57 +00002292/// HasPadding - Return true if the specified type has any structure or
Bob Wilson694a10e2011-01-13 17:45:08 +00002293/// alignment padding in between the elements that would be split apart
2294/// by SROA; return false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00002295static bool HasPadding(const Type *Ty, const TargetData &TD) {
Bob Wilson694a10e2011-01-13 17:45:08 +00002296 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2297 Ty = ATy->getElementType();
2298 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00002299 }
Bob Wilson694a10e2011-01-13 17:45:08 +00002300
2301 // SROA currently handles only Arrays and Structs.
2302 const StructType *STy = cast<StructType>(Ty);
2303 const StructLayout *SL = TD.getStructLayout(STy);
2304 unsigned PrevFieldBitOffset = 0;
2305 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2306 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2307
2308 // Check to see if there is any padding between this element and the
2309 // previous one.
2310 if (i) {
2311 unsigned PrevFieldEnd =
2312 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2313 if (PrevFieldEnd < FieldBitOffset)
2314 return true;
2315 }
2316 PrevFieldBitOffset = FieldBitOffset;
2317 }
2318 // Check for tail padding.
2319 if (unsigned EltCount = STy->getNumElements()) {
2320 unsigned PrevFieldEnd = PrevFieldBitOffset +
2321 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2322 if (PrevFieldEnd < SL->getSizeInBits())
2323 return true;
2324 }
2325 return false;
Chris Lattner39a1c042007-05-30 06:11:23 +00002326}
Chris Lattner372dda82007-03-05 07:52:57 +00002327
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002328/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2329/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2330/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002331bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00002332 // Loop over the use list of the alloca. We can only transform it if all of
2333 // the users are safe to transform.
Chris Lattner6c95d242011-01-23 07:29:29 +00002334 AllocaInfo Info(AI);
Bob Wilson69743022011-01-13 20:59:44 +00002335
Chris Lattner6c95d242011-01-23 07:29:29 +00002336 isSafeForScalarRepl(AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00002337 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00002338 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002339 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00002340 }
Bob Wilson69743022011-01-13 20:59:44 +00002341
Chris Lattner39a1c042007-05-30 06:11:23 +00002342 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2343 // source and destination, we have to be careful. In particular, the memcpy
2344 // could be moving around elements that live in structure padding of the LLVM
2345 // types, but may actually be used. In these cases, we refuse to promote the
2346 // struct.
2347 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00002348 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002349 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00002350
Chris Lattner396a0562011-01-16 17:46:19 +00002351 // If the alloca never has an access to just *part* of it, but is accessed
2352 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner7e9b4272011-01-16 06:18:28 +00002353 // the alloca instead of promoting each piece at a time and inserting fission
2354 // and fusion code.
2355 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2356 // If the struct/array just has one element, use basic SRoA.
2357 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2358 if (ST->getNumElements() > 1) return false;
2359 } else {
2360 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2361 return false;
2362 }
2363 }
Chris Lattner145c5322011-01-23 08:27:54 +00002364
Victor Hernandez6c146ee2010-01-21 23:05:53 +00002365 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00002366}
Chris Lattnera1888942005-12-12 07:19:13 +00002367
Chris Lattner800de312008-02-29 07:03:13 +00002368
Chris Lattner79b3bd32007-04-25 06:40:51 +00002369
2370/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2371/// some part of a constant global variable. This intentionally only accepts
2372/// constant expressions because we don't can't rewrite arbitrary instructions.
2373static bool PointsToConstantGlobal(Value *V) {
2374 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2375 return GV->isConstant();
2376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Bob Wilson69743022011-01-13 20:59:44 +00002377 if (CE->getOpcode() == Instruction::BitCast ||
Chris Lattner79b3bd32007-04-25 06:40:51 +00002378 CE->getOpcode() == Instruction::GetElementPtr)
2379 return PointsToConstantGlobal(CE->getOperand(0));
2380 return false;
2381}
2382
2383/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2384/// pointer to an alloca. Ignore any reads of the pointer, return false if we
2385/// see any stores or other unknown uses. If we see pointer arithmetic, keep
2386/// track of whether it moves the pointer (with isOffset) but otherwise traverse
2387/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
Nick Lewycky081f8002010-11-24 22:04:20 +00002388/// the alloca, and if the source pointer is a pointer to a constant global, we
Chris Lattner79b3bd32007-04-25 06:40:51 +00002389/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00002390static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00002391 bool isOffset) {
2392 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00002393 User *U = cast<Instruction>(*UI);
2394
Chris Lattner2e618492010-11-18 06:20:47 +00002395 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner6e733d32009-01-28 20:16:43 +00002396 // Ignore non-volatile loads, they are always ok.
Chris Lattner2e618492010-11-18 06:20:47 +00002397 if (LI->isVolatile()) return false;
2398 continue;
2399 }
Bob Wilson69743022011-01-13 20:59:44 +00002400
Gabor Greif8a8a4352010-04-06 19:32:30 +00002401 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002402 // If uses of the bitcast are ok, we are ok.
2403 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2404 return false;
2405 continue;
2406 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00002407 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00002408 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2409 // doesn't, it does.
2410 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2411 isOffset || !GEP->hasAllZeroIndices()))
2412 return false;
2413 continue;
2414 }
Bob Wilson69743022011-01-13 20:59:44 +00002415
Chris Lattner62480652010-11-18 06:41:51 +00002416 if (CallSite CS = U) {
2417 // If this is a readonly/readnone call site, then we know it is just a
2418 // load and we can ignore it.
Chris Lattnera9be1df2010-11-18 06:26:49 +00002419 if (CS.onlyReadsMemory())
2420 continue;
Nick Lewycky081f8002010-11-24 22:04:20 +00002421
2422 // If this is the function being called then we treat it like a load and
2423 // ignore it.
2424 if (CS.isCallee(UI))
2425 continue;
Bob Wilson69743022011-01-13 20:59:44 +00002426
Chris Lattner62480652010-11-18 06:41:51 +00002427 // If this is being passed as a byval argument, the caller is making a
2428 // copy, so it is only a read of the alloca.
2429 unsigned ArgNo = CS.getArgumentNo(UI);
2430 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2431 continue;
2432 }
Bob Wilson69743022011-01-13 20:59:44 +00002433
Chris Lattner79b3bd32007-04-25 06:40:51 +00002434 // If this is isn't our memcpy/memmove, reject it as something we can't
2435 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00002436 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2437 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00002438 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002439
Chris Lattner2e618492010-11-18 06:20:47 +00002440 // If the transfer is using the alloca as a source of the transfer, then
Chris Lattner2e29ebd2010-11-18 07:32:33 +00002441 // ignore it since it is a load (unless the transfer is volatile).
Chris Lattner2e618492010-11-18 06:20:47 +00002442 if (UI.getOperandNo() == 1) {
2443 if (MI->isVolatile()) return false;
2444 continue;
2445 }
Chris Lattner79b3bd32007-04-25 06:40:51 +00002446
2447 // If we already have seen a copy, reject the second one.
2448 if (TheCopy) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002449
Chris Lattner79b3bd32007-04-25 06:40:51 +00002450 // If the pointer has been offset from the start of the alloca, we can't
2451 // safely handle this.
2452 if (isOffset) return false;
2453
2454 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greifa6aac4c2010-07-16 09:38:02 +00002455 if (UI.getOperandNo() != 0) return false;
Bob Wilson69743022011-01-13 20:59:44 +00002456
Chris Lattner79b3bd32007-04-25 06:40:51 +00002457 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00002458 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00002459 return false;
Bob Wilson69743022011-01-13 20:59:44 +00002460
Chris Lattner79b3bd32007-04-25 06:40:51 +00002461 // Otherwise, the transform is safe. Remember the copy instruction.
2462 TheCopy = MI;
2463 }
2464 return true;
2465}
2466
2467/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2468/// modified by a copy from a constant global. If we can prove this, we can
2469/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00002470MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2471 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00002472 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
2473 return TheCopy;
2474 return 0;
2475}