blob: 4b686ccd2979fc7195061c33a078b59c2e331789 [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 Lattner372dda82007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000049STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000052 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000054 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000055 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000056 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000057 else
58 SRThreshold = T;
59 }
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnered7b41e2003-05-27 15:45:27 +000061 bool runOnFunction(Function &F);
62
Chris Lattner38aec322003-09-11 16:45:55 +000063 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
65
Chris Lattnera15854c2003-08-31 00:45:13 +000066 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000069 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000070 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000071 AU.setPreservesCFG();
72 }
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
76
Chris Lattner39a1c042007-05-30 06:11:23 +000077 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
78 /// information about the uses. All these fields are initialized to false
79 /// and set to true when something is learned.
80 struct AllocaInfo {
81 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
82 bool isUnsafe : 1;
83
Devang Patel4afc90d2009-02-10 07:00:59 +000084 /// needsCleanup - This is set to true if there is some use of the alloca
85 /// that requires cleanup.
86 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000087
88 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 bool isMemCpySrc : 1;
90
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000091 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000092 bool isMemCpyDst : 1;
93
94 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000095 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +000096 isMemCpySrc(false), isMemCpyDst(false) {}
97 };
98
Devang Patelff366852007-07-09 21:19:23 +000099 unsigned SRThreshold;
100
Chris Lattner39a1c042007-05-30 06:11:23 +0000101 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
102
Victor Hernandez7b929da2009-10-23 21:09:37 +0000103 int isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000104
Bob Wilson73a1b672009-12-11 23:47:40 +0000105 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
106 uint64_t ArrayOffset, AllocaInfo &Info);
107 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
108 uint64_t &ArrayOffset, AllocaInfo &Info);
109 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t ArrayOffset,
110 uint64_t MemSize, const Type *MemOpType, bool isStore,
111 AllocaInfo &Info);
112 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
113 unsigned FindElementAndOffset(const Type *&T, uint64_t &Offset);
Chris Lattner39a1c042007-05-30 06:11:23 +0000114
Victor Hernandez7b929da2009-10-23 21:09:37 +0000115 void DoScalarReplacement(AllocaInst *AI,
116 std::vector<AllocaInst*> &WorkList);
Devang Patel4afc90d2009-02-10 07:00:59 +0000117 void CleanupGEP(GetElementPtrInst *GEP);
Bob Wilson73a1b672009-12-11 23:47:40 +0000118 void CleanupAllocaUsers(Value *V);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000119 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000120
Bob Wilson73a1b672009-12-11 23:47:40 +0000121 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000126 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000127 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000132
Chris Lattner7809ecd2009-02-03 01:30:09 +0000133 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000134 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000135 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000136 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000137 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000138 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000139 uint64_t Offset, IRBuilder<> &Builder);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000140 static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000141 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000142}
143
Dan Gohman844731a2008-05-13 00:00:25 +0000144char SROA::ID = 0;
145static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
146
Brian Gaeked0fde302003-11-11 22:41:34 +0000147// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000148FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
149 return new SROA(Threshold);
150}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000151
152
Chris Lattnered7b41e2003-05-27 15:45:27 +0000153bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000154 TD = getAnalysisIfAvailable<TargetData>();
155
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000156 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000157
158 // FIXME: ScalarRepl currently depends on TargetData more than it
159 // theoretically needs to. It should be refactored in order to support
160 // target-independent IR. Until this is done, just skip the actual
161 // scalar-replacement portion of this pass.
162 if (!TD) return Changed;
163
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000164 while (1) {
165 bool LocalChange = performScalarRepl(F);
166 if (!LocalChange) break; // No need to repromote if no scalarrepl
167 Changed = true;
168 LocalChange = performPromotion(F);
169 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
170 }
Chris Lattner38aec322003-09-11 16:45:55 +0000171
172 return Changed;
173}
174
175
176bool SROA::performPromotion(Function &F) {
177 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000178 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000179 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000180
Chris Lattner02a3be02003-09-20 14:39:18 +0000181 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000182
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000183 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000184
Chris Lattner38aec322003-09-11 16:45:55 +0000185 while (1) {
186 Allocas.clear();
187
188 // Find allocas that are safe to promote, by looking at all instructions in
189 // the entry node
190 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
191 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000192 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000193 Allocas.push_back(AI);
194
195 if (Allocas.empty()) break;
196
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000197 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000198 NumPromoted += Allocas.size();
199 Changed = true;
200 }
201
202 return Changed;
203}
204
Chris Lattner963a97f2008-06-22 17:46:21 +0000205/// getNumSAElements - Return the number of elements in the specific struct or
206/// array.
207static uint64_t getNumSAElements(const Type *T) {
208 if (const StructType *ST = dyn_cast<StructType>(T))
209 return ST->getNumElements();
210 return cast<ArrayType>(T)->getNumElements();
211}
212
Chris Lattner38aec322003-09-11 16:45:55 +0000213// performScalarRepl - This algorithm is a simple worklist driven algorithm,
214// which runs on all of the malloc/alloca instructions in the function, removing
215// them if they are only used by getelementptr instructions.
216//
217bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000218 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000219
220 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000221 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000222 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000223 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000224 WorkList.push_back(A);
225
226 // Process the worklist
227 bool Changed = false;
228 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000229 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000230 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000231
Chris Lattneradd2bd72006-12-22 23:14:42 +0000232 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
233 // with unused elements.
234 if (AI->use_empty()) {
235 AI->eraseFromParent();
236 continue;
237 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000238
239 // If this alloca is impossible for us to promote, reject it early.
240 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
241 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000242
243 // Check to see if this allocation is only modified by a memcpy/memmove from
244 // a constant global. If this is the case, we can change all users to use
245 // the constant global instead. This is commonly produced by the CFE by
246 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
247 // is only subsequently read.
248 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
Nick Lewycky59136252009-09-15 07:08:25 +0000249 DEBUG(errs() << "Found alloca equal to global: " << *AI << '\n');
250 DEBUG(errs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner79b3bd32007-04-25 06:40:51 +0000251 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000252 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000253 TheCopy->eraseFromParent(); // Don't mutate the global.
254 AI->eraseFromParent();
255 ++NumGlobals;
256 Changed = true;
257 continue;
258 }
Chris Lattner15c82772009-02-02 20:44:45 +0000259
Chris Lattner7809ecd2009-02-03 01:30:09 +0000260 // Check to see if we can perform the core SROA transformation. We cannot
261 // transform the allocation instruction if it is an array allocation
262 // (allocations OF arrays are ok though), and an allocation of a scalar
263 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000264 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000265
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000266 // Do not promote [0 x %struct].
267 if (AllocaSize == 0) continue;
268
Bill Wendling5a377cb2009-03-03 12:12:58 +0000269 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000270 if (AllocaSize > SRThreshold) continue;
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000271
Chris Lattner7809ecd2009-02-03 01:30:09 +0000272 if ((isa<StructType>(AI->getAllocatedType()) ||
273 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000274 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000275 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000276 // Check that all of the users of the allocation are capable of being
277 // transformed.
278 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000279 default: llvm_unreachable("Unexpected value!");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000280 case 0: // Not safe to scalar replace.
281 break;
282 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000283 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000284 // FALL THROUGH.
285 case 3: // Safe to scalar replace.
286 DoScalarReplacement(AI, WorkList);
287 Changed = true;
288 continue;
289 }
290 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000291
292 // If we can turn this aggregate value (potentially with casts) into a
293 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000294 // IsNotTrivial tracks whether this is something that mem2reg could have
295 // promoted itself. If so, we don't want to transform it needlessly. Note
296 // that we can't just check based on the type: the alloca may be of an i32
297 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000298 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000299 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000300 bool HadAVector = false;
301 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000302 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000303 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000304 // If we were able to find a vector type that can handle this with
305 // insert/extract elements, and if there was at least one use that had
306 // a vector type, promote this to a vector. We don't want to promote
307 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
308 // we just get a lot of insert/extracts. If at least one vector is
309 // involved, then we probably really do have a union of vector/array.
310 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Nick Lewycky59136252009-09-15 07:08:25 +0000311 DEBUG(errs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattnerbdff5482009-08-23 04:37:46 +0000312 << *VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000313
Chris Lattner7809ecd2009-02-03 01:30:09 +0000314 // Create and insert the vector alloca.
Owen Anderson50dead02009-07-15 23:53:25 +0000315 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000316 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000317 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000318 DEBUG(errs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000319
320 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000321 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000322 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000323 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000324 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000325 NewAI->takeName(AI);
326 AI->eraseFromParent();
327 ++NumConverted;
328 Changed = true;
329 continue;
330 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000331
Chris Lattner7809ecd2009-02-03 01:30:09 +0000332 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000333 }
334
335 return Changed;
336}
Chris Lattner5e062a12003-05-30 04:15:41 +0000337
Chris Lattnera10b29b2007-04-25 05:02:56 +0000338/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
339/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000340void SROA::DoScalarReplacement(AllocaInst *AI,
341 std::vector<AllocaInst*> &WorkList) {
Chris Lattnerff114702009-09-15 05:14:57 +0000342 DEBUG(errs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000343 SmallVector<AllocaInst*, 32> ElementAllocas;
344 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
345 ElementAllocas.reserve(ST->getNumContainedTypes());
346 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000347 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000348 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000349 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000350 ElementAllocas.push_back(NA);
351 WorkList.push_back(NA); // Add to worklist for recursive processing
352 }
353 } else {
354 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
355 ElementAllocas.reserve(AT->getNumElements());
356 const Type *ElTy = AT->getElementType();
357 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000358 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000359 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000360 ElementAllocas.push_back(NA);
361 WorkList.push_back(NA); // Add to worklist for recursive processing
362 }
363 }
364
Bob Wilson73a1b672009-12-11 23:47:40 +0000365 // Now that we have created the new alloca instructions, rewrite all the
366 // uses of the old alloca.
367 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000368 NumReplaced++;
369}
Bob Wilson73a1b672009-12-11 23:47:40 +0000370
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000371/// AllUsersAreLoads - Return true if all users of this value are loads.
372static bool AllUsersAreLoads(Value *Ptr) {
373 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
374 I != E; ++I)
375 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
376 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000377 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000378}
379
Bob Wilson73a1b672009-12-11 23:47:40 +0000380/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
381/// performing scalar replacement of alloca AI. The results are flagged in
382/// the Info parameter. Offset and ArrayOffset indicate the position within
383/// AI that is referenced by this instruction.
384void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
385 uint64_t ArrayOffset, AllocaInfo &Info) {
386 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
387 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000388
Bob Wilson73a1b672009-12-11 23:47:40 +0000389 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
390 isSafeForScalarRepl(BC, AI, Offset, ArrayOffset, Info);
391 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
392 uint64_t GEPArrayOffset = ArrayOffset;
393 uint64_t GEPOffset = Offset;
394 isSafeGEP(GEPI, AI, GEPOffset, GEPArrayOffset, Info);
395 if (!Info.isUnsafe)
396 isSafeForScalarRepl(GEPI, AI, GEPOffset, GEPArrayOffset, Info);
397 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
398 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
399 if (Length)
400 isSafeMemAccess(AI, Offset, ArrayOffset, Length->getZExtValue(), 0,
401 UI.getOperandNo() == 1, Info);
402 else
403 MarkUnsafe(Info);
404 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
405 if (!LI->isVolatile()) {
406 const Type *LIType = LI->getType();
407 isSafeMemAccess(AI, Offset, ArrayOffset, TD->getTypeAllocSize(LIType),
408 LIType, false, Info);
409 } else
410 MarkUnsafe(Info);
411 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
412 // Store is ok if storing INTO the pointer, not storing the pointer
413 if (!SI->isVolatile() && SI->getOperand(0) != I) {
414 const Type *SIType = SI->getOperand(0)->getType();
415 isSafeMemAccess(AI, Offset, ArrayOffset, TD->getTypeAllocSize(SIType),
416 SIType, true, Info);
417 } else
418 MarkUnsafe(Info);
419 } else if (isa<DbgInfoIntrinsic>(UI)) {
420 // If one user is DbgInfoIntrinsic then check if all users are
421 // DbgInfoIntrinsics.
422 if (OnlyUsedByDbgInfoIntrinsics(I)) {
423 Info.needsCleanup = true;
424 return;
425 }
426 MarkUnsafe(Info);
427 } else {
428 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
429 MarkUnsafe(Info);
430 }
431 if (Info.isUnsafe) return;
Chris Lattner39a1c042007-05-30 06:11:23 +0000432 }
Bob Wilson73a1b672009-12-11 23:47:40 +0000433}
Chris Lattnerbe883a22003-11-25 21:09:18 +0000434
Bob Wilson73a1b672009-12-11 23:47:40 +0000435/// isSafeGEP - Check if a GEP instruction can be handled for scalar
436/// replacement. It is safe when all the indices are constant, in-bounds
437/// references, and when the resulting offset corresponds to an element within
438/// the alloca type. The results are flagged in the Info parameter. Upon
439/// return, Offset is adjusted as specified by the GEP indices. For the
440/// special case of a variable index to a 2-element array, ArrayOffset is set
441/// to the array element size.
442void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
443 uint64_t &Offset, uint64_t &ArrayOffset,
444 AllocaInfo &Info) {
445 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
446 if (GEPIt == E)
447 return;
Chris Lattnerbe883a22003-11-25 21:09:18 +0000448
Bob Wilson73a1b672009-12-11 23:47:40 +0000449 // The first GEP index must be zero.
450 if (!isa<ConstantInt>(GEPIt.getOperand()) ||
451 !cast<ConstantInt>(GEPIt.getOperand())->isZero())
452 return MarkUnsafe(Info);
453 if (++GEPIt == E)
454 return;
455
Chris Lattner88e6dc82008-08-23 05:21:06 +0000456 // If the first index is a non-constant index into an array, see if we can
457 // handle it as a special case.
Bob Wilson73a1b672009-12-11 23:47:40 +0000458 const Type *ArrayEltTy = 0;
459 if (ArrayOffset == 0 && Offset == 0) {
460 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPIt)) {
461 if (!isa<ConstantInt>(GEPIt.getOperand())) {
462 uint64_t NumElements = AT->getNumElements();
463
464 // If this is an array index and the index is not constant, we cannot
465 // promote... that is unless the array has exactly one or two elements
466 // in it, in which case we CAN promote it, but we have to canonicalize
467 // this out if this is the only problem.
468 if ((NumElements != 1 && NumElements != 2) || !AllUsersAreLoads(GEPI))
469 return MarkUnsafe(Info);
Devang Patel4afc90d2009-02-10 07:00:59 +0000470 Info.needsCleanup = true;
Bob Wilson73a1b672009-12-11 23:47:40 +0000471 ArrayOffset = TD->getTypeAllocSizeInBits(AT->getElementType());
472 ArrayEltTy = AT->getElementType();
473 ++GEPIt;
Chris Lattner39a1c042007-05-30 06:11:23 +0000474 }
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000475 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000476 }
Bob Wilson73a1b672009-12-11 23:47:40 +0000477
Chris Lattner88e6dc82008-08-23 05:21:06 +0000478 // Walk through the GEP type indices, checking the types that this indexes
479 // into.
Bob Wilson73a1b672009-12-11 23:47:40 +0000480 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000481 // Ignore struct elements, no extra checking needed for these.
Bob Wilson73a1b672009-12-11 23:47:40 +0000482 if (isa<StructType>(*GEPIt))
Chris Lattner88e6dc82008-08-23 05:21:06 +0000483 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000484
Bob Wilson73a1b672009-12-11 23:47:40 +0000485 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
486 if (!IdxVal)
487 return MarkUnsafe(Info);
488
489 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPIt)) {
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000490 // This GEP indexes an array. Verify that this is an in-range constant
491 // integer. Specifically, consider A[0][i]. We cannot know that the user
492 // isn't doing invalid things like allowing i to index an out-of-range
493 // subscript that accesses A[1]. Because of this, we have to reject SROA
Bob Wilsond614a1f2009-12-04 21:51:35 +0000494 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000495 if (IdxVal->getZExtValue() >= AT->getNumElements())
496 return MarkUnsafe(Info);
Bob Wilson73a1b672009-12-11 23:47:40 +0000497 } else {
498 const VectorType *VT = dyn_cast<VectorType>(*GEPIt);
499 assert(VT && "unexpected type in GEP type iterator");
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000500 if (IdxVal->getZExtValue() >= VT->getNumElements())
501 return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000502 }
Chris Lattner88e6dc82008-08-23 05:21:06 +0000503 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000504
Bob Wilson73a1b672009-12-11 23:47:40 +0000505 // All the indices are safe. Now compute the offset due to this GEP and
506 // check if the alloca has a component element at that offset.
507 if (ArrayOffset == 0) {
508 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
509 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
510 &Indices[0], Indices.size());
511 } else {
512 // Both array elements have the same type, so it suffices to check one of
513 // them. Copy the GEP indices starting from the array index, but replace
514 // that variable index with a constant zero.
515 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 2, GEPI->op_end());
516 Indices[0] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
517 const Type *ArrayEltPtr = PointerType::getUnqual(ArrayEltTy);
518 Offset += TD->getIndexedOffset(ArrayEltPtr, &Indices[0], Indices.size());
Chris Lattner39a1c042007-05-30 06:11:23 +0000519 }
Bob Wilson73a1b672009-12-11 23:47:40 +0000520 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
521 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +0000522}
523
Bob Wilson73a1b672009-12-11 23:47:40 +0000524/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
525/// alloca or has an offset and size that corresponds to a component element
526/// within it. The offset checked here may have been formed from a GEP with a
527/// pointer bitcasted to a different type.
528void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset,
529 uint64_t ArrayOffset, uint64_t MemSize,
530 const Type *MemOpType, bool isStore,
531 AllocaInfo &Info) {
532 // Check if this is a load/store of the entire alloca.
533 if (Offset == 0 && ArrayOffset == 0 &&
534 MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
535 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
536 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
537 // (which are essentially the same as the MemIntrinsics, especially with
538 // regard to copying padding between elements), or references using the
539 // aggregate type of the alloca.
540 if (!MemOpType || isa<IntegerType>(MemOpType) || UsesAggregateType) {
541 if (!UsesAggregateType) {
542 if (isStore)
543 Info.isMemCpyDst = true;
544 else
545 Info.isMemCpySrc = true;
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000546 }
Bob Wilson73a1b672009-12-11 23:47:40 +0000547 return;
Devang Patel4afc90d2009-02-10 07:00:59 +0000548 }
Chris Lattner372dda82007-03-05 07:52:57 +0000549 }
Bob Wilson73a1b672009-12-11 23:47:40 +0000550 // Check if the offset/size correspond to a component within the alloca type.
551 const Type *T = AI->getAllocatedType();
552 if (TypeHasComponent(T, Offset, MemSize) &&
553 (ArrayOffset == 0 || TypeHasComponent(T, Offset + ArrayOffset, MemSize)))
554 return;
555
556 return MarkUnsafe(Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000557}
558
Bob Wilson73a1b672009-12-11 23:47:40 +0000559/// TypeHasComponent - Return true if T has a component type with the
560/// specified offset and size. If Size is zero, do not check the size.
561bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
562 const Type *EltTy;
563 uint64_t EltSize;
564 if (const StructType *ST = dyn_cast<StructType>(T)) {
565 const StructLayout *Layout = TD->getStructLayout(ST);
566 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
567 EltTy = ST->getContainedType(EltIdx);
568 EltSize = TD->getTypeAllocSize(EltTy);
569 Offset -= Layout->getElementOffset(EltIdx);
570 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
571 EltTy = AT->getElementType();
572 EltSize = TD->getTypeAllocSize(EltTy);
573 Offset %= EltSize;
574 } else {
575 return false;
576 }
577 if (Offset == 0 && (Size == 0 || EltSize == Size))
578 return true;
579 // Check if the component spans multiple elements.
580 if (Offset + Size > EltSize)
581 return false;
582 return TypeHasComponent(EltTy, Offset, Size);
583}
584
585/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
586/// the instruction I, which references it, to use the separate elements.
587/// Offset indicates the position within AI that is referenced by this
588/// instruction.
589void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
590 SmallVector<AllocaInst*, 32> &NewElts) {
591 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000592 Instruction *User = cast<Instruction>(*UI++);
Chris Lattner372dda82007-03-05 07:52:57 +0000593
Bob Wilson73a1b672009-12-11 23:47:40 +0000594 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
595 if (BC->getOperand(0) == AI)
596 BC->setOperand(0, NewElts[0]);
597 // If the bitcast type now matches the operand type, it will be removed
598 // after processing its uses.
599 RewriteForScalarRepl(BC, AI, Offset, NewElts);
600 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
601 RewriteGEP(GEPI, AI, Offset, NewElts);
602 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
603 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
604 uint64_t MemSize = Length->getZExtValue();
605 if (Offset == 0 &&
606 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
607 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
608 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
609 const Type *LIType = LI->getType();
610 if (LIType == AI->getAllocatedType()) {
611 // Replace:
612 // %res = load { i32, i32 }* %alloc
613 // with:
614 // %load.0 = load i32* %alloc.0
615 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
616 // %load.1 = load i32* %alloc.1
617 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
618 // (Also works for arrays instead of structs)
619 Value *Insert = UndefValue::get(LIType);
620 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
621 Value *Load = new LoadInst(NewElts[i], "load", LI);
622 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
623 }
624 LI->replaceAllUsesWith(Insert);
625 LI->eraseFromParent();
626 } else if (isa<IntegerType>(LIType) &&
627 TD->getTypeAllocSize(LIType) ==
628 TD->getTypeAllocSize(AI->getAllocatedType())) {
629 // If this is a load of the entire alloca to an integer, rewrite it.
630 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
631 }
632 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
633 Value *Val = SI->getOperand(0);
634 const Type *SIType = Val->getType();
635 if (SIType == AI->getAllocatedType()) {
636 // Replace:
637 // store { i32, i32 } %val, { i32, i32 }* %alloc
638 // with:
639 // %val.0 = extractvalue { i32, i32 } %val, 0
640 // store i32 %val.0, i32* %alloc.0
641 // %val.1 = extractvalue { i32, i32 } %val, 1
642 // store i32 %val.1, i32* %alloc.1
643 // (Also works for arrays instead of structs)
644 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
645 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
646 new StoreInst(Extract, NewElts[i], SI);
647 }
648 SI->eraseFromParent();
649 } else if (isa<IntegerType>(SIType) &&
650 TD->getTypeAllocSize(SIType) ==
651 TD->getTypeAllocSize(AI->getAllocatedType())) {
652 // If this is a store of the entire alloca from an integer, rewrite it.
653 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
654 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000655 }
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000656 }
Bob Wilson73a1b672009-12-11 23:47:40 +0000657 // Delete unused instructions and identity bitcasts.
658 if (I->use_empty())
659 I->eraseFromParent();
660 else if (BitCastInst *BC = dyn_cast<BitCastInst>(I)) {
661 if (BC->getDestTy() == BC->getSrcTy()) {
662 BC->replaceAllUsesWith(BC->getOperand(0));
663 BC->eraseFromParent();
664 }
665 }
666}
667
668/// FindElementAndOffset - Return the index of the element containing Offset
669/// within the specified type, which must be either a struct or an array.
670/// Sets T to the type of the element and Offset to the offset within that
671/// element.
672unsigned SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset) {
673 unsigned Idx = 0;
674 if (const StructType *ST = dyn_cast<StructType>(T)) {
675 const StructLayout *Layout = TD->getStructLayout(ST);
676 Idx = Layout->getElementContainingOffset(Offset);
677 T = ST->getContainedType(Idx);
678 Offset -= Layout->getElementOffset(Idx);
679 } else {
680 const ArrayType *AT = dyn_cast<ArrayType>(T);
681 assert(AT && "unexpected type for scalar replacement");
682 T = AT->getElementType();
683 uint64_t EltSize = TD->getTypeAllocSize(T);
684 Idx = (unsigned)(Offset / EltSize);
685 Offset -= Idx * EltSize;
686 }
687 return Idx;
688}
689
690/// RewriteGEP - Check if this GEP instruction moves the pointer across
691/// elements of the alloca that are being split apart, and if so, rewrite
692/// the GEP to be relative to the new element.
693void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
694 SmallVector<AllocaInst*, 32> &NewElts) {
695 Instruction *Val = GEPI;
696
697 uint64_t OldOffset = Offset;
698 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
699 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
700 &Indices[0], Indices.size());
701
702 const Type *T = AI->getAllocatedType();
703 unsigned OldIdx = FindElementAndOffset(T, OldOffset);
704 if (GEPI->getOperand(0) == AI)
705 OldIdx = ~0U; // Force the GEP to be rewritten.
706
707 T = AI->getAllocatedType();
708 uint64_t EltOffset = Offset;
709 unsigned Idx = FindElementAndOffset(T, EltOffset);
710
711 // If this GEP moves the pointer across elements of the alloca that are
712 // being split, then it needs to be rewritten.
713 if (Idx != OldIdx) {
714 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
715 SmallVector<Value*, 8> NewArgs;
716 NewArgs.push_back(Constant::getNullValue(i32Ty));
717 while (EltOffset != 0) {
718 unsigned EltIdx = FindElementAndOffset(T, EltOffset);
719 NewArgs.push_back(ConstantInt::get(i32Ty, EltIdx));
720 }
721 if (NewArgs.size() > 1) {
722 Val = GetElementPtrInst::CreateInBounds(NewElts[Idx], NewArgs.begin(),
723 NewArgs.end(), "", GEPI);
724 Val->takeName(GEPI);
725 if (Val->getType() != GEPI->getType())
726 Val = new BitCastInst(Val, GEPI->getType(), Val->getNameStr(), GEPI);
727 } else {
728 Val = NewElts[Idx];
729 // Insert a new bitcast. If the types match, it will be removed after
730 // handling all of its uses.
731 Val = new BitCastInst(Val, GEPI->getType(), Val->getNameStr(), GEPI);
732 Val->takeName(GEPI);
733 }
734
735 GEPI->replaceAllUsesWith(Val);
736 GEPI->eraseFromParent();
737 }
738
739 RewriteForScalarRepl(Val, AI, Offset, NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000740}
741
742/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
743/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilson73a1b672009-12-11 23:47:40 +0000744void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000745 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000746 SmallVector<AllocaInst*, 32> &NewElts) {
747
748 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000749 // appropriate type. The "Other" pointer is the pointer that goes to memory
750 // that doesn't have anything to do with the alloca that we are promoting. For
751 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000752 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000753 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000754 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000755 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilson73a1b672009-12-11 23:47:40 +0000756 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +0000757 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000758 else {
Bob Wilson73a1b672009-12-11 23:47:40 +0000759 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +0000760 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000761 }
762 }
Bob Wilson78c50b82009-12-08 18:22:03 +0000763
764 // Keep track of the other intrinsic argument, so it can be removed if it
765 // is dead when the intrinsic is replaced.
766 Value *PossiblyDead = OtherPtr;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000767
768 // If there is an other pointer, we want to convert it to the same pointer
769 // type as AI has, so we can GEP through it safely.
770 if (OtherPtr) {
771 // It is likely that OtherPtr is a bitcast, if so, remove it.
772 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
773 OtherPtr = BC->getOperand(0);
774 // All zero GEPs are effectively bitcasts.
775 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
776 if (GEP->hasAllZeroIndices())
777 OtherPtr = GEP->getOperand(0);
Chris Lattner372dda82007-03-05 07:52:57 +0000778
Chris Lattnerd93afec2009-01-07 07:18:45 +0000779 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
780 if (BCE->getOpcode() == Instruction::BitCast)
781 OtherPtr = BCE->getOperand(0);
782
783 // If the pointer is not the right type, insert a bitcast to the right
784 // type.
785 if (OtherPtr->getType() != AI->getType())
786 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
787 MI);
788 }
789
790 // Process each element of the aggregate.
791 Value *TheFn = MI->getOperand(0);
792 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilson73a1b672009-12-11 23:47:40 +0000793 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000794
Owen Anderson1d0be152009-08-13 21:58:54 +0000795 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000796
797 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
798 // If this is a memcpy/memmove, emit a GEP of the other element address.
799 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000800 unsigned OtherEltAlign = MemAlignment;
801
Chris Lattner372dda82007-03-05 07:52:57 +0000802 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000803 Value *Idx[2] = { Zero,
804 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilson73a1b672009-12-11 23:47:40 +0000805 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000806 OtherPtr->getNameStr()+"."+Twine(i),
Bob Wilson73a1b672009-12-11 23:47:40 +0000807 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000808 uint64_t EltOffset;
809 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
810 if (const StructType *ST =
811 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
812 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
813 } else {
814 const Type *EltTy =
815 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000816 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000817 }
818
819 // The alignment of the other pointer is the guaranteed alignment of the
820 // element, which is affected by both the known alignment of the whole
821 // mem intrinsic and the alignment of the element. If the alignment of
822 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
823 // known alignment is just 4 bytes.
824 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000825 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000826
827 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000828 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000829
830 // If we got down to a scalar, insert a load or store as appropriate.
831 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000832 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000833 if (SROADest) {
834 // From Other to Alloca.
835 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
836 new StoreInst(Elt, EltPtr, MI);
837 } else {
838 // From Alloca to Other.
839 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
840 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
841 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000842 continue;
843 }
844 assert(isa<MemSetInst>(MI));
845
846 // If the stored element is zero (common case), just store a null
847 // constant.
848 Constant *StoreVal;
849 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
850 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000851 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000852 } else {
853 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000854 const Type *ValTy = EltTy->getScalarType();
855
Chris Lattnerd93afec2009-01-07 07:18:45 +0000856 // Construct an integer with the right value.
857 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
858 APInt OneVal(EltSize, CI->getZExtValue());
859 APInt TotalVal(OneVal);
860 // Set each byte.
861 for (unsigned i = 0; 8*i < EltSize; ++i) {
862 TotalVal = TotalVal.shl(8);
863 TotalVal |= OneVal;
864 }
865
866 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000867 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000868 if (isa<PointerType>(ValTy))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000869 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000870 else if (ValTy->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000871 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000872 assert(StoreVal->getType() == ValTy && "Type mismatch!");
873
874 // If the requested value was a vector constant, create it.
875 if (EltTy != ValTy) {
876 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
877 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000878 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000879 }
880 }
881 new StoreInst(StoreVal, EltPtr, MI);
882 continue;
883 }
884 // Otherwise, if we're storing a byte variable, use a memset call for
885 // this element.
886 }
887
888 // Cast the element pointer to BytePtrTy.
889 if (EltPtr->getType() != BytePtrTy)
890 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
891
892 // Cast the other pointer (if we have one) to BytePtrTy.
893 if (OtherElt && OtherElt->getType() != BytePtrTy)
894 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
895 MI);
896
Duncan Sands777d2302009-05-09 07:06:46 +0000897 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000898
899 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000900 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000901 Value *Ops[] = {
902 SROADest ? EltPtr : OtherElt, // Dest ptr
903 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneed707b2009-07-24 23:12:02 +0000904 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000905 // Align
906 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattnerd93afec2009-01-07 07:18:45 +0000907 };
908 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
909 } else {
910 assert(isa<MemSetInst>(MI));
911 Value *Ops[] = {
912 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneed707b2009-07-24 23:12:02 +0000913 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000914 Zero // Align
915 };
916 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
917 }
Chris Lattner372dda82007-03-05 07:52:57 +0000918 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000919 MI->eraseFromParent();
Bob Wilson78c50b82009-12-08 18:22:03 +0000920 if (PossiblyDead)
921 RecursivelyDeleteTriviallyDeadInstructions(PossiblyDead);
Chris Lattner372dda82007-03-05 07:52:57 +0000922}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000923
Bob Wilson39fdd692009-12-04 21:57:37 +0000924/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000925/// overwrites the entire allocation. Extract out the pieces of the stored
926/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000927void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000928 SmallVector<AllocaInst*, 32> &NewElts){
929 // Extract each element out of the integer according to its structure offset
930 // and store the element value to the individual alloca.
931 Value *SrcVal = SI->getOperand(0);
Bob Wilson73a1b672009-12-11 23:47:40 +0000932 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000933 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000934
Eli Friedman41b33f42009-06-01 09:14:32 +0000935 // Handle tail padding by extending the operand
936 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000937 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000938 IntegerType::get(SI->getContext(), AllocaSizeBits),
939 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000940
Nick Lewycky59136252009-09-15 07:08:25 +0000941 DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
942 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000943
944 // There are two forms here: AI could be an array or struct. Both cases
945 // have different ways to compute the element offset.
946 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
947 const StructLayout *Layout = TD->getStructLayout(EltSTy);
948
949 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
950 // Get the number of bits to shift SrcVal to get the value.
951 const Type *FieldTy = EltSTy->getElementType(i);
952 uint64_t Shift = Layout->getElementOffsetInBits(i);
953
954 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000955 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000956
957 Value *EltVal = SrcVal;
958 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000959 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000960 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
961 "sroa.store.elt", SI);
962 }
963
964 // Truncate down to an integer of the right size.
965 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000966
967 // Ignore zero sized fields like {}, they obviously contain no data.
968 if (FieldSizeBits == 0) continue;
969
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000970 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000971 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000972 IntegerType::get(SI->getContext(), FieldSizeBits),
973 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000974 Value *DestField = NewElts[i];
975 if (EltVal->getType() == FieldTy) {
976 // Storing to an integer field of this size, just do it.
977 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
978 // Bitcast to the right element type (for fp/vector values).
979 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
980 } else {
981 // Otherwise, bitcast the dest pointer (for aggregates).
982 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000983 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000984 "", SI);
985 }
986 new StoreInst(EltVal, DestField, SI);
987 }
988
989 } else {
990 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
991 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000992 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000993 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
994
995 uint64_t Shift;
996
997 if (TD->isBigEndian())
998 Shift = AllocaSizeBits-ElementOffset;
999 else
1000 Shift = 0;
1001
1002 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001003 // Ignore zero sized fields like {}, they obviously contain no data.
1004 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001005
1006 Value *EltVal = SrcVal;
1007 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001008 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001009 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1010 "sroa.store.elt", SI);
1011 }
1012
1013 // Truncate down to an integer of the right size.
1014 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001015 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001016 IntegerType::get(SI->getContext(),
1017 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001018 Value *DestField = NewElts[i];
1019 if (EltVal->getType() == ArrayEltTy) {
1020 // Storing to an integer field of this size, just do it.
1021 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1022 // Bitcast to the right element type (for fp/vector values).
1023 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1024 } else {
1025 // Otherwise, bitcast the dest pointer (for aggregates).
1026 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001027 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001028 "", SI);
1029 }
1030 new StoreInst(EltVal, DestField, SI);
1031
1032 if (TD->isBigEndian())
1033 Shift -= ElementOffset;
1034 else
1035 Shift += ElementOffset;
1036 }
1037 }
1038
1039 SI->eraseFromParent();
1040}
1041
Bob Wilson39fdd692009-12-04 21:57:37 +00001042/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001043/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001044void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001045 SmallVector<AllocaInst*, 32> &NewElts) {
1046 // Extract each element out of the NewElts according to its structure offset
1047 // and form the result value.
Bob Wilson73a1b672009-12-11 23:47:40 +00001048 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001049 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001050
Nick Lewycky59136252009-09-15 07:08:25 +00001051 DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1052 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001053
1054 // There are two forms here: AI could be an array or struct. Both cases
1055 // have different ways to compute the element offset.
1056 const StructLayout *Layout = 0;
1057 uint64_t ArrayEltBitOffset = 0;
1058 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1059 Layout = TD->getStructLayout(EltSTy);
1060 } else {
1061 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001062 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001063 }
Owen Andersone922c022009-07-22 00:24:57 +00001064
Owen Andersone922c022009-07-22 00:24:57 +00001065 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001066 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001067
1068 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1069 // Load the value from the alloca. If the NewElt is an aggregate, cast
1070 // the pointer to an integer of the same size before doing the load.
1071 Value *SrcField = NewElts[i];
1072 const Type *FieldTy =
1073 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001074 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1075
1076 // Ignore zero sized fields like {}, they obviously contain no data.
1077 if (FieldSizeBits == 0) continue;
1078
Owen Anderson1d0be152009-08-13 21:58:54 +00001079 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1080 FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001081 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1082 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001083 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001084 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001085 "", LI);
1086 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1087
1088 // If SrcField is a fp or vector of the right size but that isn't an
1089 // integer type, bitcast to an integer so we can shift it.
1090 if (SrcField->getType() != FieldIntTy)
1091 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1092
1093 // Zero extend the field to be the same size as the final alloca so that
1094 // we can shift and insert it.
1095 if (SrcField->getType() != ResultVal->getType())
1096 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1097
1098 // Determine the number of bits to shift SrcField.
1099 uint64_t Shift;
1100 if (Layout) // Struct case.
1101 Shift = Layout->getElementOffsetInBits(i);
1102 else // Array case.
1103 Shift = i*ArrayEltBitOffset;
1104
1105 if (TD->isBigEndian())
1106 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1107
1108 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001109 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001110 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1111 }
1112
1113 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1114 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001115
1116 // Handle tail padding by truncating the result
1117 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1118 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1119
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001120 LI->replaceAllUsesWith(ResultVal);
1121 LI->eraseFromParent();
1122}
1123
Duncan Sands3cb36502007-11-04 14:43:57 +00001124/// HasPadding - Return true if the specified type has any structure or
1125/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001126static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001127 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1128 const StructLayout *SL = TD.getStructLayout(STy);
1129 unsigned PrevFieldBitOffset = 0;
1130 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001131 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1132
Chris Lattner39a1c042007-05-30 06:11:23 +00001133 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001134 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001135 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001136
Chris Lattner39a1c042007-05-30 06:11:23 +00001137 // Check to see if there is any padding between this element and the
1138 // previous one.
1139 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001140 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001141 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1142 if (PrevFieldEnd < FieldBitOffset)
1143 return true;
1144 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001145
Chris Lattner39a1c042007-05-30 06:11:23 +00001146 PrevFieldBitOffset = FieldBitOffset;
1147 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001148
Chris Lattner39a1c042007-05-30 06:11:23 +00001149 // Check for tail padding.
1150 if (unsigned EltCount = STy->getNumElements()) {
1151 unsigned PrevFieldEnd = PrevFieldBitOffset +
1152 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001153 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001154 return true;
1155 }
1156
1157 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001158 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001159 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001160 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001161 }
Duncan Sands777d2302009-05-09 07:06:46 +00001162 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001163}
Chris Lattner372dda82007-03-05 07:52:57 +00001164
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001165/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1166/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1167/// or 1 if safe after canonicalization has been performed.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001168int SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001169 // Loop over the use list of the alloca. We can only transform it if all of
1170 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001171 AllocaInfo Info;
1172
Bob Wilson73a1b672009-12-11 23:47:40 +00001173 isSafeForScalarRepl(AI, AI, 0, 0, Info);
1174 if (Info.isUnsafe) {
1175 DEBUG(errs() << "Cannot transform: " << *AI << '\n');
1176 return 0;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001177 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001178
1179 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1180 // source and destination, we have to be careful. In particular, the memcpy
1181 // could be moving around elements that live in structure padding of the LLVM
1182 // types, but may actually be used. In these cases, we refuse to promote the
1183 // struct.
1184 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilson73a1b672009-12-11 23:47:40 +00001185 HasPadding(AI->getAllocatedType(), *TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001186 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +00001187
Chris Lattner39a1c042007-05-30 06:11:23 +00001188 // If we require cleanup, return 1, otherwise return 3.
Devang Patel4afc90d2009-02-10 07:00:59 +00001189 return Info.needsCleanup ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001190}
1191
Bob Wilson65ab34f2009-12-08 18:27:03 +00001192/// CleanupGEP - GEP is used by an Alloca, which can be promoted after the GEP
Devang Patel4afc90d2009-02-10 07:00:59 +00001193/// is canonicalized here.
1194void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1195 gep_type_iterator I = gep_type_begin(GEPI);
1196 ++I;
1197
Devang Patel7afe8fa2009-02-10 19:28:07 +00001198 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1199 if (!AT)
1200 return;
1201
1202 uint64_t NumElements = AT->getNumElements();
1203
1204 if (isa<ConstantInt>(I.getOperand()))
1205 return;
1206
1207 if (NumElements == 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001208 GEPI->setOperand(2,
1209 Constant::getNullValue(Type::getInt32Ty(GEPI->getContext())));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001210 return;
1211 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001212
Devang Patel7afe8fa2009-02-10 19:28:07 +00001213 assert(NumElements == 2 && "Unhandled case!");
1214 // All users of the GEP must be loads. At each use of the GEP, insert
1215 // two loads of the appropriate indexed GEP and select between them.
Owen Anderson333c4002009-07-09 23:48:35 +00001216 Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(),
Owen Andersona7235ea2009-07-31 20:28:14 +00001217 Constant::getNullValue(I.getOperand()->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001218 "isone");
Devang Patel7afe8fa2009-02-10 19:28:07 +00001219 // Insert the new GEP instructions, which are properly indexed.
1220 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Anderson1d0be152009-08-13 21:58:54 +00001221 Indices[1] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
Bob Wilson73a1b672009-12-11 23:47:40 +00001222 Value *ZeroIdx = GetElementPtrInst::CreateInBounds(GEPI->getOperand(0),
1223 Indices.begin(),
1224 Indices.end(),
1225 GEPI->getName()+".0",GEPI);
Owen Anderson1d0be152009-08-13 21:58:54 +00001226 Indices[1] = ConstantInt::get(Type::getInt32Ty(GEPI->getContext()), 1);
Bob Wilson73a1b672009-12-11 23:47:40 +00001227 Value *OneIdx = GetElementPtrInst::CreateInBounds(GEPI->getOperand(0),
1228 Indices.begin(),
1229 Indices.end(),
1230 GEPI->getName()+".1", GEPI);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001231 // Replace all loads of the variable index GEP with loads from both
1232 // indexes and a select.
1233 while (!GEPI->use_empty()) {
1234 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1235 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1236 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1237 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1238 LI->replaceAllUsesWith(R);
1239 LI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001240 }
1241}
1242
1243/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001244/// allocation, but only if cleaned up, perform the cleanups required.
Bob Wilson73a1b672009-12-11 23:47:40 +00001245void SROA::CleanupAllocaUsers(Value *V) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001246 // At this point, we know that the end result will be SROA'd and promoted, so
1247 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1248 // up.
Bob Wilson73a1b672009-12-11 23:47:40 +00001249 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001250 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001251 User *U = *UI++;
Bob Wilson73a1b672009-12-11 23:47:40 +00001252 if (isa<BitCastInst>(U)) {
1253 CleanupAllocaUsers(U);
1254 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001255 CleanupGEP(GEPI);
Bob Wilson73a1b672009-12-11 23:47:40 +00001256 CleanupAllocaUsers(GEPI);
1257 if (GEPI->use_empty()) GEPI->eraseFromParent();
1258 } else {
Jay Foad0906b1b2009-06-06 17:49:35 +00001259 Instruction *I = cast<Instruction>(U);
Devang Patel4afc90d2009-02-10 07:00:59 +00001260 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Shengb0c41992009-03-18 12:48:48 +00001261 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001262 // Safe to remove debug info uses.
1263 while (!DbgInUses.empty()) {
1264 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1265 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001266 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001267 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001268 }
1269 }
1270 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001271}
Chris Lattnera1888942005-12-12 07:19:13 +00001272
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001273/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1274/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001275///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001276/// There are two cases we handle here:
1277/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001278/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001279/// This promotes a <4 x float> with a store of float to the third element
1280/// into a <4 x float> that uses insert element.
1281/// 2) A fully general blob of memory, which we turn into some (potentially
1282/// large) integer type with extract and insert operations where the loads
1283/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001284static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001285 unsigned AllocaSize, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001286 LLVMContext &Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001287 // If this could be contributing to a vector, analyze it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001288 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001289
Chris Lattner7809ecd2009-02-03 01:30:09 +00001290 // If the In type is a vector that is the same size as the alloca, see if it
1291 // matches the existing VecTy.
1292 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1293 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1294 // If we're storing/loading a vector of the right size, allow it as a
1295 // vector. If this the first vector we see, remember the type so that
1296 // we know the element size.
1297 if (VecTy == 0)
1298 VecTy = VInTy;
1299 return;
1300 }
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001301 } else if (In->isFloatTy() || In->isDoubleTy() ||
Chris Lattner7809ecd2009-02-03 01:30:09 +00001302 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1303 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1304 // If we're accessing something that could be an element of a vector, see
1305 // if the implied vector agrees with what we already have and if Offset is
1306 // compatible with it.
1307 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1308 if (Offset % EltSize == 0 &&
1309 AllocaSize % EltSize == 0 &&
1310 (VecTy == 0 ||
1311 cast<VectorType>(VecTy)->getElementType()
1312 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1313 if (VecTy == 0)
Owen Andersondebcb012009-07-29 22:17:13 +00001314 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001315 return;
1316 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001317 }
1318 }
1319
Chris Lattner7809ecd2009-02-03 01:30:09 +00001320 // Otherwise, we have a case that we can't handle with an optimized vector
1321 // form. We can still turn this into a large integer.
Owen Anderson1d0be152009-08-13 21:58:54 +00001322 VecTy = Type::getVoidTy(Context);
Chris Lattnera1888942005-12-12 07:19:13 +00001323}
1324
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001325/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Bob Wilsonefc58e72009-12-09 18:05:27 +00001326/// its accesses to a single vector type, return true and set VecTy to
Chris Lattner7809ecd2009-02-03 01:30:09 +00001327/// the new type. If we could convert the alloca into a single promotable
1328/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1329/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1330/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001331///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001332/// If we see at least one access to the value that is as a vector type, set the
1333/// SawVec flag.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001334bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1335 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001336 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001337 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1338 Instruction *User = cast<Instruction>(*UI);
1339
1340 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001341 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001342 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001343 return false;
Owen Andersone922c022009-07-22 00:24:57 +00001344 MergeInType(LI->getType(), Offset, VecTy,
1345 AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001346 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001347 continue;
1348 }
1349
1350 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001351 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001352 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001353 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Andersone922c022009-07-22 00:24:57 +00001354 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001355 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001356 continue;
1357 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001358
1359 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001360 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1361 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001362 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001363 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001364 continue;
1365 }
1366
1367 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001368 // If this is a GEP with a variable indices, we can't handle it.
1369 if (!GEP->hasAllConstantIndices())
1370 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001371
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001372 // Compute the offset that this GEP adds to the pointer.
1373 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilson73a1b672009-12-11 23:47:40 +00001374 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001375 &Indices[0], Indices.size());
1376 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001377 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001378 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001379 return false;
1380 IsNotTrivial = true;
1381 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001382 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001383
Chris Lattner3d730f72009-02-03 02:01:43 +00001384 // If this is a constant sized memset of a constant value (e.g. 0) we can
1385 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001386 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1387 // Store of constant value and constant size.
1388 if (isa<ConstantInt>(MSI->getValue()) &&
1389 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001390 IsNotTrivial = true;
1391 continue;
1392 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001393 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001394
1395 // If this is a memcpy or memmove into or out of the whole allocation, we
1396 // can handle it like a load or store of the scalar type.
1397 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1398 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1399 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1400 IsNotTrivial = true;
1401 continue;
1402 }
1403 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001404
Devang Patel00e389c2009-03-06 07:03:54 +00001405 // Ignore dbg intrinsic.
1406 if (isa<DbgInfoIntrinsic>(User))
1407 continue;
1408
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001409 // Otherwise, we cannot handle this!
1410 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001411 }
1412
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001413 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001414}
1415
Chris Lattnera1888942005-12-12 07:19:13 +00001416/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001417/// directly. This happens when we are converting an "integer union" to a
1418/// single integer scalar, or when we are converting a "vector union" to a
1419/// vector with insert/extractelement instructions.
1420///
1421/// Offset is an offset from the original alloca, in bits that need to be
1422/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001423void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001424 while (!Ptr->use_empty()) {
1425 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001426
Chris Lattnercf321862009-01-07 06:39:58 +00001427 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001428 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001429 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001430 continue;
1431 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001432
Chris Lattnercf321862009-01-07 06:39:58 +00001433 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001434 // Compute the offset that this GEP adds to the pointer.
1435 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Bob Wilson73a1b672009-12-11 23:47:40 +00001436 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001437 &Indices[0], Indices.size());
1438 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001439 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001440 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001441 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001442
Chris Lattner9bc67da2009-02-03 19:45:44 +00001443 IRBuilder<> Builder(User->getParent(), User);
1444
1445 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001446 // The load is a bit extract from NewAI shifted right by Offset bits.
1447 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1448 Value *NewLoadVal
1449 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1450 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001451 LI->eraseFromParent();
1452 continue;
1453 }
1454
1455 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1456 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Benjamin Kramere6f32942009-11-29 21:17:48 +00001457 // FIXME: Remove once builder has Twine API.
Bob Wilsond614a1f2009-12-04 21:51:35 +00001458 Value *Old = Builder.CreateLoad(NewAI,
1459 (NewAI->getName()+".in").str().c_str());
Chris Lattner9bc67da2009-02-03 19:45:44 +00001460 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1461 Builder);
1462 Builder.CreateStore(New, NewAI);
1463 SI->eraseFromParent();
1464 continue;
1465 }
1466
Chris Lattner3d730f72009-02-03 02:01:43 +00001467 // If this is a constant sized memset of a constant value (e.g. 0) we can
1468 // transform it into a store of the expanded constant value.
1469 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1470 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1471 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001472 if (NumBytes != 0) {
1473 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1474
1475 // Compute the value replicated the right number of times.
1476 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001477
Chris Lattner33e24ad2009-04-21 16:52:12 +00001478 // Splat the value if non-zero.
1479 if (Val)
1480 for (unsigned i = 1; i != NumBytes; ++i)
1481 APVal |= APVal << 8;
Benjamin Kramere6f32942009-11-29 21:17:48 +00001482
1483 // FIXME: Remove once builder has Twine API.
Bob Wilsond614a1f2009-12-04 21:51:35 +00001484 Value *Old = Builder.CreateLoad(NewAI,
1485 (NewAI->getName()+".in").str().c_str());
Owen Andersone922c022009-07-22 00:24:57 +00001486 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001487 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001488 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001489 Builder.CreateStore(New, NewAI);
1490 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001491 MSI->eraseFromParent();
1492 continue;
1493 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001494
1495 // If this is a memcpy or memmove into or out of the whole allocation, we
1496 // can handle it like a load or store of the scalar type.
1497 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1498 assert(Offset == 0 && "must be store to start of alloca");
1499
1500 // If the source and destination are both to the same alloca, then this is
1501 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1502 // as appropriate.
1503 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1504
1505 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1506 // Dest must be OrigAI, change this to be a load from the original
1507 // pointer (bitcasted), then a store to our new alloca.
1508 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1509 Value *SrcPtr = MTI->getSource();
1510 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1511
1512 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1513 SrcVal->setAlignment(MTI->getAlignment());
1514 Builder.CreateStore(SrcVal, NewAI);
1515 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1516 // Src must be OrigAI, change this to be a load from NewAI then a store
1517 // through the original dest pointer (bitcasted).
1518 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1519 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1520
1521 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1522 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1523 NewStore->setAlignment(MTI->getAlignment());
1524 } else {
1525 // Noop transfer. Src == Dst
1526 }
1527
1528
1529 MTI->eraseFromParent();
1530 continue;
1531 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001532
Devang Patel00e389c2009-03-06 07:03:54 +00001533 // If user is a dbg info intrinsic then it is safe to remove it.
1534 if (isa<DbgInfoIntrinsic>(User)) {
1535 User->eraseFromParent();
1536 continue;
1537 }
1538
Torok Edwinc23197a2009-07-14 16:55:14 +00001539 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001540 }
1541}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001542
Chris Lattner6e011152009-02-03 21:01:03 +00001543/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1544/// or vector value FromVal, extracting the bits from the offset specified by
1545/// Offset. This returns the value, which is of type ToType.
1546///
1547/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001548/// integer scalar, or when we are converting a "vector union" to a vector with
1549/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001550///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001551/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001552/// shifted to the right.
1553Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1554 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001555 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001556 if (FromVal->getType() == ToType && Offset == 0)
1557 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001558
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001559 // If the result alloca is a vector type, this is either an element
1560 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001561 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1562 if (isa<VectorType>(ToType))
1563 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001564
1565 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001566 unsigned Elt = 0;
1567 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001568 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001569 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001570 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001571 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001572 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001573 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1574 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001575 if (V->getType() != ToType)
1576 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001577 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001578 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001579
1580 // If ToType is a first class aggregate, extract out each of the pieces and
1581 // use insertvalue's to form the FCA.
1582 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1583 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001584 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001585 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1586 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001587 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001588 Builder);
1589 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1590 }
1591 return Res;
1592 }
1593
1594 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001595 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001596 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001597 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1598 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1599 Offset+i*EltSize, Builder);
1600 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1601 }
1602 return Res;
1603 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001604
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001605 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001606 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001607
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001608 // If this is a big-endian system and the load is narrower than the
1609 // full alloca type, we need to do a shift to get the right bits.
1610 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001611 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001612 // On big-endian machines, the lowest bit is stored at the bit offset
1613 // from the pointer given by getTypeStoreSizeInBits. This matters for
1614 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001615 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001616 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001617 } else {
1618 ShAmt = Offset;
1619 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001620
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001621 // Note: we support negative bitwidths (with shl) which are not defined.
1622 // We do this to support (f.e.) loads off the end of a structure where
1623 // only some bits are used.
1624 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001625 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001626 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001627 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001628 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001629 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001630 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001631 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001632
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001633 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001634 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001635 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001636 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001637 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1638 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001639 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001640 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001641 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1642 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001643
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001644 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001645 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001646 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001647 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001648 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001649 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001650 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001651 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001652 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001653 }
Chris Lattner6e011152009-02-03 21:01:03 +00001654 assert(FromVal->getType() == ToType && "Didn't convert right?");
1655 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001656}
1657
Chris Lattner9b872db2009-02-03 19:30:11 +00001658/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1659/// or vector value "Old" at the offset specified by Offset.
1660///
1661/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001662/// single integer scalar, or when we are converting a "vector union" to a
1663/// vector with insert/extractelement instructions.
1664///
1665/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001666/// shifted to the right.
1667Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001668 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001669
Chris Lattner800de312008-02-29 07:03:13 +00001670 // Convert the stored type to the actual type, shift it left to insert
1671 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001672 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001673 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001674
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001675 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001676 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1677 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001678
1679 // Changing the whole vector with memset or with an access of a different
1680 // vector type?
1681 if (ValSize == VecSize)
1682 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1683
Duncan Sands777d2302009-05-09 07:06:46 +00001684 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001685
1686 // Must be an element insertion.
1687 unsigned Elt = Offset/EltSize;
1688
1689 if (SV->getType() != VTy->getElementType())
1690 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1691
1692 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001693 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001694 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001695 return SV;
1696 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001697
1698 // If SV is a first-class aggregate value, insert each value recursively.
1699 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1700 const StructLayout &Layout = *TD->getStructLayout(ST);
1701 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001702 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001703 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001704 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001705 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001706 }
1707 return Old;
1708 }
1709
1710 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001711 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001712 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001713 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1714 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001715 }
1716 return Old;
1717 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001718
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001719 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001720 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001721 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1722 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1723 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1724 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1725 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001726 SV = Builder.CreateBitCast(SV,
1727 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001728 else if (isa<PointerType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001729 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001730
Chris Lattner7809ecd2009-02-03 01:30:09 +00001731 // Zero extend or truncate the value if needed.
1732 if (SV->getType() != AllocaType) {
1733 if (SV->getType()->getPrimitiveSizeInBits() <
1734 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001735 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001736 else {
1737 // Truncation may be needed if storing more than the alloca can hold
1738 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001739 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001740 SrcWidth = DestWidth;
1741 SrcStoreWidth = DestStoreWidth;
1742 }
1743 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001744
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001745 // If this is a big-endian system and the store is narrower than the
1746 // full alloca type, we need to do a shift to get the right bits.
1747 int ShAmt = 0;
1748 if (TD->isBigEndian()) {
1749 // On big-endian machines, the lowest bit is stored at the bit offset
1750 // from the pointer given by getTypeStoreSizeInBits. This matters for
1751 // integers with a bitwidth that is not a multiple of 8.
1752 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001753 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001754 ShAmt = Offset;
1755 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001756
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001757 // Note: we support negative bitwidths (with shr) which are not defined.
1758 // We do this to support (f.e.) stores off the end of a structure where
1759 // only some bits in the structure are set.
1760 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1761 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001762 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001763 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001764 Mask <<= ShAmt;
1765 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001766 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001767 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001768 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001769 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001770
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001771 // Mask out the bits we are about to insert from the old value, and or
1772 // in the new bits.
1773 if (SrcWidth != DestWidth) {
1774 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001775 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001776 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001777 }
1778 return SV;
1779}
1780
1781
Chris Lattner79b3bd32007-04-25 06:40:51 +00001782
1783/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1784/// some part of a constant global variable. This intentionally only accepts
1785/// constant expressions because we don't can't rewrite arbitrary instructions.
1786static bool PointsToConstantGlobal(Value *V) {
1787 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1788 return GV->isConstant();
1789 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1790 if (CE->getOpcode() == Instruction::BitCast ||
1791 CE->getOpcode() == Instruction::GetElementPtr)
1792 return PointsToConstantGlobal(CE->getOperand(0));
1793 return false;
1794}
1795
1796/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1797/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1798/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1799/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1800/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1801/// the alloca, and if the source pointer is a pointer to a constant global, we
1802/// can optimize this.
1803static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1804 bool isOffset) {
1805 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001806 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1807 // Ignore non-volatile loads, they are always ok.
1808 if (!LI->isVolatile())
1809 continue;
1810
Chris Lattner79b3bd32007-04-25 06:40:51 +00001811 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1812 // If uses of the bitcast are ok, we are ok.
1813 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1814 return false;
1815 continue;
1816 }
1817 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1818 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1819 // doesn't, it does.
1820 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1821 isOffset || !GEP->hasAllZeroIndices()))
1822 return false;
1823 continue;
1824 }
1825
1826 // If this is isn't our memcpy/memmove, reject it as something we can't
1827 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001828 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001829 return false;
1830
1831 // If we already have seen a copy, reject the second one.
1832 if (TheCopy) return false;
1833
1834 // If the pointer has been offset from the start of the alloca, we can't
1835 // safely handle this.
1836 if (isOffset) return false;
1837
1838 // If the memintrinsic isn't using the alloca as the dest, reject it.
1839 if (UI.getOperandNo() != 1) return false;
1840
1841 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1842
1843 // If the source of the memcpy/move is not a constant global, reject it.
1844 if (!PointsToConstantGlobal(MI->getOperand(2)))
1845 return false;
1846
1847 // Otherwise, the transform is safe. Remember the copy instruction.
1848 TheCopy = MI;
1849 }
1850 return true;
1851}
1852
1853/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1854/// modified by a copy from a constant global. If we can prove this, we can
1855/// replace any uses of the alloca with uses of the global directly.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001856Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001857 Instruction *TheCopy = 0;
1858 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1859 return TheCopy;
1860 return 0;
1861}