blob: 92ac76be74f34dfcf7724ed8ae1c27e4fcf3e823 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
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
13// 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.
19//
20//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "scalarrepl"
23#include "llvm/Transforms/Scalar.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Function.h"
27#include "llvm/GlobalVariable.h"
28#include "llvm/Instructions.h"
29#include "llvm/IntrinsicInst.h"
30#include "llvm/Pass.h"
31#include "llvm/Analysis/Dominators.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel83637b12009-02-10 07:00:59 +000034#include "llvm/Transforms/Utils/Local.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/Support/Debug.h"
36#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner32c19282009-02-03 19:41:50 +000037#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038#include "llvm/Support/MathExtras.h"
39#include "llvm/Support/Compiler.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/StringExtras.h"
43using namespace llvm;
44
45STATISTIC(NumReplaced, "Number of allocas broken up");
46STATISTIC(NumPromoted, "Number of allocas promoted");
47STATISTIC(NumConverted, "Number of aggregates converted to scalar");
48STATISTIC(NumGlobals, "Number of allocas copied from constant global");
49
50namespace {
51 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
52 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000053 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054 if (T == -1)
Chris Lattner6d7faec2007-08-02 21:33:36 +000055 SRThreshold = 128;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 else
57 SRThreshold = T;
58 }
59
60 bool runOnFunction(Function &F);
61
62 bool performScalarRepl(Function &F);
63 bool performPromotion(Function &F);
64
65 // getAnalysisUsage - This pass does not require any passes, but we know it
66 // will not alter the CFG, so say so.
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68 AU.addRequired<DominatorTree>();
69 AU.addRequired<DominanceFrontier>();
70 AU.addRequired<TargetData>();
71 AU.setPreservesCFG();
72 }
73
74 private:
Chris Lattner3fd59362009-01-07 06:34:28 +000075 TargetData *TD;
76
Dan Gohmanf17a25c2007-07-18 16:29:46 +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 Patel83637b12009-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087
88 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 bool isMemCpySrc : 1;
90
91 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
92 bool isMemCpyDst : 1;
93
94 AllocaInfo()
Devang Patel83637b12009-02-10 07:00:59 +000095 : isUnsafe(false), needsCleanup(false),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096 isMemCpySrc(false), isMemCpyDst(false) {}
97 };
98
99 unsigned SRThreshold;
100
101 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
102
103 int isSafeAllocaToScalarRepl(AllocationInst *AI);
104
105 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
106 AllocaInfo &Info);
107 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
108 AllocaInfo &Info);
109 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
110 unsigned OpNo, AllocaInfo &Info);
111 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
112 AllocaInfo &Info);
113
114 void DoScalarReplacement(AllocationInst *AI,
115 std::vector<AllocationInst*> &WorkList);
Devang Patel83637b12009-02-10 07:00:59 +0000116 void CleanupGEP(GetElementPtrInst *GEP);
117 void CleanupAllocaUsers(AllocationInst *AI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
119
120 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
121 SmallVector<AllocaInst*, 32> &NewElts);
122
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000123 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
124 AllocationInst *AI,
125 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000126 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
127 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner28401db2009-01-08 05:42:05 +0000128 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattner70ffe572009-01-28 20:16:43 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000130
Chris Lattnerf235a322009-02-03 01:30:09 +0000131 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner38088d12009-02-03 18:15:05 +0000132 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000133 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattnerf73a10e2009-02-03 21:01:03 +0000134 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattnerececb0c2009-02-03 19:45:44 +0000135 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +0000136 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner32c19282009-02-03 19:41:50 +0000137 uint64_t Offset, IRBuilder<> &Builder);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
139 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140}
141
Dan Gohman089efff2008-05-13 00:00:25 +0000142char SROA::ID = 0;
143static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
144
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145// Public interface to the ScalarReplAggregates pass
146FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
147 return new SROA(Threshold);
148}
149
150
151bool SROA::runOnFunction(Function &F) {
Chris Lattner3fd59362009-01-07 06:34:28 +0000152 TD = &getAnalysis<TargetData>();
153
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 bool Changed = performPromotion(F);
155 while (1) {
156 bool LocalChange = performScalarRepl(F);
157 if (!LocalChange) break; // No need to repromote if no scalarrepl
158 Changed = true;
159 LocalChange = performPromotion(F);
160 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
161 }
162
163 return Changed;
164}
165
166
167bool SROA::performPromotion(Function &F) {
168 std::vector<AllocaInst*> Allocas;
169 DominatorTree &DT = getAnalysis<DominatorTree>();
170 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
171
172 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
173
174 bool Changed = false;
175
176 while (1) {
177 Allocas.clear();
178
179 // Find allocas that are safe to promote, by looking at all instructions in
180 // the entry node
181 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
182 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
183 if (isAllocaPromotable(AI))
184 Allocas.push_back(AI);
185
186 if (Allocas.empty()) break;
187
188 PromoteMemToReg(Allocas, DT, DF);
189 NumPromoted += Allocas.size();
190 Changed = true;
191 }
192
193 return Changed;
194}
195
Chris Lattner0e99e692008-06-22 17:46:21 +0000196/// getNumSAElements - Return the number of elements in the specific struct or
197/// array.
198static uint64_t getNumSAElements(const Type *T) {
199 if (const StructType *ST = dyn_cast<StructType>(T))
200 return ST->getNumElements();
201 return cast<ArrayType>(T)->getNumElements();
202}
203
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204// performScalarRepl - This algorithm is a simple worklist driven algorithm,
205// which runs on all of the malloc/alloca instructions in the function, removing
206// them if they are only used by getelementptr instructions.
207//
208bool SROA::performScalarRepl(Function &F) {
209 std::vector<AllocationInst*> WorkList;
210
211 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
212 BasicBlock &BB = F.getEntryBlock();
213 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
214 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
215 WorkList.push_back(A);
216
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 // Process the worklist
218 bool Changed = false;
219 while (!WorkList.empty()) {
220 AllocationInst *AI = WorkList.back();
221 WorkList.pop_back();
222
223 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
224 // with unused elements.
225 if (AI->use_empty()) {
226 AI->eraseFromParent();
227 continue;
228 }
Chris Lattnerf235a322009-02-03 01:30:09 +0000229
230 // If this alloca is impossible for us to promote, reject it early.
231 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
232 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233
234 // Check to see if this allocation is only modified by a memcpy/memmove from
235 // a constant global. If this is the case, we can change all users to use
236 // the constant global instead. This is commonly produced by the CFE by
237 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
238 // is only subsequently read.
239 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
240 DOUT << "Found alloca equal to global: " << *AI;
241 DOUT << " memcpy = " << *TheCopy;
242 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
243 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
244 TheCopy->eraseFromParent(); // Don't mutate the global.
245 AI->eraseFromParent();
246 ++NumGlobals;
247 Changed = true;
248 continue;
249 }
Chris Lattner05ebfd72009-02-02 20:44:45 +0000250
Chris Lattnerf235a322009-02-03 01:30:09 +0000251 // Check to see if we can perform the core SROA transformation. We cannot
252 // transform the allocation instruction if it is an array allocation
253 // (allocations OF arrays are ok though), and an allocation of a scalar
254 // value cannot be decomposed at all.
255 uint64_t AllocaSize = TD->getTypePaddedSize(AI->getAllocatedType());
Chris Lattnerd67e9de2009-03-01 02:26:47 +0000256
257 // Do not promote any struct whose size is too big.
258 if (AllocaSize < SRThreshold)
259 continue;
260
Chris Lattnerf235a322009-02-03 01:30:09 +0000261 if ((isa<StructType>(AI->getAllocatedType()) ||
262 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattnerf235a322009-02-03 01:30:09 +0000263 // Do not promote any struct into more than "32" separate vars.
264 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
265 // Check that all of the users of the allocation are capable of being
266 // transformed.
267 switch (isSafeAllocaToScalarRepl(AI)) {
268 default: assert(0 && "Unexpected value!");
269 case 0: // Not safe to scalar replace.
270 break;
271 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel83637b12009-02-10 07:00:59 +0000272 CleanupAllocaUsers(AI);
Chris Lattnerf235a322009-02-03 01:30:09 +0000273 // FALL THROUGH.
274 case 3: // Safe to scalar replace.
275 DoScalarReplacement(AI, WorkList);
276 Changed = true;
277 continue;
278 }
279 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000280
281 // If we can turn this aggregate value (potentially with casts) into a
282 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000283 // IsNotTrivial tracks whether this is something that mem2reg could have
284 // promoted itself. If so, we don't want to transform it needlessly. Note
285 // that we can't just check based on the type: the alloca may be of an i32
286 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner70ffe572009-01-28 20:16:43 +0000287 bool IsNotTrivial = false;
Chris Lattnerf235a322009-02-03 01:30:09 +0000288 const Type *VectorTy = 0;
Chris Lattner38088d12009-02-03 18:15:05 +0000289 bool HadAVector = false;
290 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattnerf235a322009-02-03 01:30:09 +0000291 0, unsigned(AllocaSize)) && IsNotTrivial) {
292 AllocaInst *NewAI;
Chris Lattner38088d12009-02-03 18:15:05 +0000293 // If we were able to find a vector type that can handle this with
294 // insert/extract elements, and if there was at least one use that had
295 // a vector type, promote this to a vector. We don't want to promote
296 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
297 // we just get a lot of insert/extracts. If at least one vector is
298 // involved, then we probably really do have a union of vector/array.
299 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Chris Lattnerf235a322009-02-03 01:30:09 +0000300 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
Chris Lattner05ebfd72009-02-02 20:44:45 +0000301
Chris Lattnerf235a322009-02-03 01:30:09 +0000302 // Create and insert the vector alloca.
303 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner05ebfd72009-02-02 20:44:45 +0000304 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattnerf235a322009-02-03 01:30:09 +0000305 } else {
306 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
307
308 // Create and insert the integer alloca.
309 const Type *NewTy = IntegerType::get(AllocaSize*8);
310 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
311 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner70ffe572009-01-28 20:16:43 +0000312 }
Chris Lattnerf235a322009-02-03 01:30:09 +0000313 NewAI->takeName(AI);
314 AI->eraseFromParent();
315 ++NumConverted;
316 Changed = true;
317 continue;
318 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000319
Chris Lattnerf235a322009-02-03 01:30:09 +0000320 // Otherwise, couldn't process this alloca.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 }
322
323 return Changed;
324}
325
326/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
327/// predicate, do SROA now.
328void SROA::DoScalarReplacement(AllocationInst *AI,
329 std::vector<AllocationInst*> &WorkList) {
330 DOUT << "Found inst to SROA: " << *AI;
331 SmallVector<AllocaInst*, 32> ElementAllocas;
332 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
333 ElementAllocas.reserve(ST->getNumContainedTypes());
334 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
335 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
336 AI->getAlignment(),
337 AI->getName() + "." + utostr(i), AI);
338 ElementAllocas.push_back(NA);
339 WorkList.push_back(NA); // Add to worklist for recursive processing
340 }
341 } else {
342 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
343 ElementAllocas.reserve(AT->getNumElements());
344 const Type *ElTy = AT->getElementType();
345 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
346 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
347 AI->getName() + "." + utostr(i), AI);
348 ElementAllocas.push_back(NA);
349 WorkList.push_back(NA); // Add to worklist for recursive processing
350 }
351 }
352
353 // Now that we have created the alloca instructions that we want to use,
354 // expand the getelementptr instructions to use them.
355 //
356 while (!AI->use_empty()) {
357 Instruction *User = cast<Instruction>(AI->use_back());
358 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
359 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
360 BCInst->eraseFromParent();
361 continue;
362 }
363
Chris Lattner19e61a42008-06-23 17:11:23 +0000364 // Replace:
365 // %res = load { i32, i32 }* %alloc
366 // with:
367 // %load.0 = load i32* %alloc.0
368 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
369 // %load.1 = load i32* %alloc.1
370 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000371 // (Also works for arrays instead of structs)
372 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
373 Value *Insert = UndefValue::get(LI->getType());
374 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
375 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
376 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
377 }
378 LI->replaceAllUsesWith(Insert);
379 LI->eraseFromParent();
380 continue;
381 }
382
Chris Lattner19e61a42008-06-23 17:11:23 +0000383 // Replace:
384 // store { i32, i32 } %val, { i32, i32 }* %alloc
385 // with:
386 // %val.0 = extractvalue { i32, i32 } %val, 0
387 // store i32 %val.0, i32* %alloc.0
388 // %val.1 = extractvalue { i32, i32 } %val, 1
389 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000390 // (Also works for arrays instead of structs)
391 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
392 Value *Val = SI->getOperand(0);
393 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
394 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
395 new StoreInst(Extract, ElementAllocas[i], SI);
396 }
397 SI->eraseFromParent();
398 continue;
399 }
400
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
402 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
403 unsigned Idx =
404 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
405
406 assert(Idx < ElementAllocas.size() && "Index out of range?");
407 AllocaInst *AllocaToUse = ElementAllocas[Idx];
408
409 Value *RepValue;
410 if (GEPI->getNumOperands() == 3) {
411 // Do not insert a new getelementptr instruction with zero indices, only
412 // to have it optimized out later.
413 RepValue = AllocaToUse;
414 } else {
415 // We are indexing deeply into the structure, so we still need a
416 // getelement ptr instruction to finish the indexing. This may be
417 // expanded itself once the worklist is rerun.
418 //
419 SmallVector<Value*, 8> NewArgs;
420 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
421 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greifd6da1d02008-04-06 20:25:17 +0000422 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
423 NewArgs.end(), "", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 RepValue->takeName(GEPI);
425 }
426
427 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattner85591c62009-01-07 06:25:07 +0000428 if (Idx == 0 && GEPI->hasAllZeroIndices())
429 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430
431 // Move all of the users over to the new GEP.
432 GEPI->replaceAllUsesWith(RepValue);
433 // Delete the old GEP
434 GEPI->eraseFromParent();
435 }
436
437 // Finally, delete the Alloca instruction
438 AI->eraseFromParent();
439 NumReplaced++;
440}
441
442
443/// isSafeElementUse - Check to see if this use is an allowed use for a
444/// getelementptr instruction of an array aggregate allocation. isFirstElt
445/// indicates whether Ptr is known to the start of the aggregate.
446///
447void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
448 AllocaInfo &Info) {
449 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
450 I != E; ++I) {
451 Instruction *User = cast<Instruction>(*I);
452 switch (User->getOpcode()) {
453 case Instruction::Load: break;
454 case Instruction::Store:
455 // Store is ok if storing INTO the pointer, not storing the pointer
456 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
457 break;
458 case Instruction::GetElementPtr: {
459 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
460 bool AreAllZeroIndices = isFirstElt;
461 if (GEP->getNumOperands() > 1) {
462 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
463 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
464 // Using pointer arithmetic to navigate the array.
465 return MarkUnsafe(Info);
466
Chris Lattner85591c62009-01-07 06:25:07 +0000467 if (AreAllZeroIndices)
468 AreAllZeroIndices = GEP->hasAllZeroIndices();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 }
470 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
471 if (Info.isUnsafe) return;
472 break;
473 }
474 case Instruction::BitCast:
475 if (isFirstElt) {
476 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
477 if (Info.isUnsafe) return;
478 break;
479 }
480 DOUT << " Transformation preventing inst: " << *User;
481 return MarkUnsafe(Info);
482 case Instruction::Call:
483 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
484 if (isFirstElt) {
485 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
486 if (Info.isUnsafe) return;
487 break;
488 }
489 }
490 DOUT << " Transformation preventing inst: " << *User;
491 return MarkUnsafe(Info);
492 default:
493 DOUT << " Transformation preventing inst: " << *User;
494 return MarkUnsafe(Info);
495 }
496 }
497 return; // All users look ok :)
498}
499
500/// AllUsersAreLoads - Return true if all users of this value are loads.
501static bool AllUsersAreLoads(Value *Ptr) {
502 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
503 I != E; ++I)
504 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
505 return false;
506 return true;
507}
508
509/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
510/// aggregate allocation.
511///
512void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
513 AllocaInfo &Info) {
514 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
515 return isSafeUseOfBitCastedAllocation(C, AI, Info);
516
Chris Lattner70ffe572009-01-28 20:16:43 +0000517 if (LoadInst *LI = dyn_cast<LoadInst>(User))
518 if (!LI->isVolatile())
519 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000520
Chris Lattner70ffe572009-01-28 20:16:43 +0000521 if (StoreInst *SI = dyn_cast<StoreInst>(User))
522 if (!SI->isVolatile() && SI->getOperand(0) != AI)
523 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000524
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
526 if (GEPI == 0)
527 return MarkUnsafe(Info);
528
529 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
530
531 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
532 if (I == E ||
533 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
534 return MarkUnsafe(Info);
535 }
536
537 ++I;
538 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
539
540 bool IsAllZeroIndices = true;
541
Chris Lattnerd324da02008-08-23 05:21:06 +0000542 // If the first index is a non-constant index into an array, see if we can
543 // handle it as a special case.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattnerd324da02008-08-23 05:21:06 +0000545 if (!isa<ConstantInt>(I.getOperand())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546 IsAllZeroIndices = 0;
Chris Lattnerd324da02008-08-23 05:21:06 +0000547 uint64_t NumElements = AT->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548
549 // If this is an array index and the index is not constant, we cannot
550 // promote... that is unless the array has exactly one or two elements in
551 // it, in which case we CAN promote it, but we have to canonicalize this
552 // out if this is the only problem.
553 if ((NumElements == 1 || NumElements == 2) &&
554 AllUsersAreLoads(GEPI)) {
Devang Patel83637b12009-02-10 07:00:59 +0000555 Info.needsCleanup = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000556 return; // Canonicalization required!
557 }
558 return MarkUnsafe(Info);
559 }
560 }
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000561
Chris Lattnerd324da02008-08-23 05:21:06 +0000562 // Walk through the GEP type indices, checking the types that this indexes
563 // into.
564 for (; I != E; ++I) {
565 // Ignore struct elements, no extra checking needed for these.
566 if (isa<StructType>(*I))
567 continue;
568
Chris Lattnerd324da02008-08-23 05:21:06 +0000569 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
570 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000571
572 // Are all indices still zero?
Chris Lattnerd324da02008-08-23 05:21:06 +0000573 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000574
575 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
576 // This GEP indexes an array. Verify that this is an in-range constant
577 // integer. Specifically, consider A[0][i]. We cannot know that the user
578 // isn't doing invalid things like allowing i to index an out-of-range
579 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000580 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000581 if (IdxVal->getZExtValue() >= AT->getNumElements())
582 return MarkUnsafe(Info);
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000583 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
584 if (IdxVal->getZExtValue() >= VT->getNumElements())
585 return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000586 }
Chris Lattnerd324da02008-08-23 05:21:06 +0000587 }
588
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 // If there are any non-simple uses of this getelementptr, make sure to reject
590 // them.
591 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
592}
593
594/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
595/// intrinsic can be promoted by SROA. At this point, we know that the operand
596/// of the memintrinsic is a pointer to the beginning of the allocation.
597void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
598 unsigned OpNo, AllocaInfo &Info) {
599 // If not constant length, give up.
600 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
601 if (!Length) return MarkUnsafe(Info);
602
603 // If not the whole aggregate, give up.
Duncan Sandsae5fd622007-11-04 14:43:57 +0000604 if (Length->getZExtValue() !=
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000605 TD->getTypePaddedSize(AI->getType()->getElementType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 return MarkUnsafe(Info);
607
608 // We only know about memcpy/memset/memmove.
609 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
610 return MarkUnsafe(Info);
611
612 // Otherwise, we can transform it. Determine whether this is a memcpy/set
613 // into or out of the aggregate.
614 if (OpNo == 1)
615 Info.isMemCpyDst = true;
616 else {
617 assert(OpNo == 2);
618 Info.isMemCpySrc = true;
619 }
620}
621
622/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
623/// are
624void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
625 AllocaInfo &Info) {
626 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
627 UI != E; ++UI) {
628 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
629 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
630 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
631 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattner71c75342009-01-07 08:11:13 +0000632 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000633 if (SI->isVolatile())
634 return MarkUnsafe(Info);
635
Chris Lattner71c75342009-01-07 08:11:13 +0000636 // If storing the entire alloca in one chunk through a bitcasted pointer
637 // to integer, we can transform it. This happens (for example) when you
638 // cast a {i32,i32}* to i64* and store through it. This is similar to the
639 // memcpy case and occurs in various "byval" cases and emulated memcpys.
640 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000641 TD->getTypePaddedSize(SI->getOperand(0)->getType()) ==
642 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner71c75342009-01-07 08:11:13 +0000643 Info.isMemCpyDst = true;
644 continue;
645 }
646 return MarkUnsafe(Info);
Chris Lattner28401db2009-01-08 05:42:05 +0000647 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000648 if (LI->isVolatile())
649 return MarkUnsafe(Info);
650
Chris Lattner28401db2009-01-08 05:42:05 +0000651 // If loading the entire alloca in one chunk through a bitcasted pointer
652 // to integer, we can transform it. This happens (for example) when you
653 // cast a {i32,i32}* to i64* and load through it. This is similar to the
654 // memcpy case and occurs in various "byval" cases and emulated memcpys.
655 if (isa<IntegerType>(LI->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000656 TD->getTypePaddedSize(LI->getType()) ==
657 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner28401db2009-01-08 05:42:05 +0000658 Info.isMemCpySrc = true;
659 continue;
660 }
661 return MarkUnsafe(Info);
Devang Patel83637b12009-02-10 07:00:59 +0000662 } else if (isa<DbgInfoIntrinsic>(UI)) {
663 // If one user is DbgInfoIntrinsic then check if all users are
664 // DbgInfoIntrinsics.
665 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
666 Info.needsCleanup = true;
667 return;
668 }
669 else
670 MarkUnsafe(Info);
671 }
672 else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 return MarkUnsafe(Info);
674 }
675 if (Info.isUnsafe) return;
676 }
677}
678
679/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
680/// to its first element. Transform users of the cast to use the new values
681/// instead.
682void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
683 SmallVector<AllocaInst*, 32> &NewElts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
685 while (UI != UE) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000686 Instruction *User = cast<Instruction>(*UI++);
687 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000689 if (BCU->use_empty()) BCU->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 continue;
691 }
692
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000693 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
694 // This must be memcpy/memmove/memset of the entire aggregate.
695 // Split into one per element.
696 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000697 continue;
698 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000699
Chris Lattner71c75342009-01-07 08:11:13 +0000700 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner28401db2009-01-08 05:42:05 +0000701 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattner71c75342009-01-07 08:11:13 +0000702 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
703 continue;
704 }
Chris Lattner28401db2009-01-08 05:42:05 +0000705
706 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
707 // If this is a load of the entire alloca to an integer, rewrite it.
708 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
709 continue;
710 }
Chris Lattner71c75342009-01-07 08:11:13 +0000711
712 // Otherwise it must be some other user of a gep of the first pointer. Just
713 // leave these alone.
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000714 continue;
Chris Lattner28401db2009-01-08 05:42:05 +0000715 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000716}
717
718/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
719/// Rewrite it to copy or set the elements of the scalarized memory.
720void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
721 AllocationInst *AI,
722 SmallVector<AllocaInst*, 32> &NewElts) {
723
724 // If this is a memcpy/memmove, construct the other pointer as the
725 // appropriate type.
726 Value *OtherPtr = 0;
727 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
728 if (BCInst == MCI->getRawDest())
729 OtherPtr = MCI->getRawSource();
730 else {
731 assert(BCInst == MCI->getRawSource());
732 OtherPtr = MCI->getRawDest();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000734 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
735 if (BCInst == MMI->getRawDest())
736 OtherPtr = MMI->getRawSource();
737 else {
738 assert(BCInst == MMI->getRawSource());
739 OtherPtr = MMI->getRawDest();
740 }
741 }
742
743 // If there is an other pointer, we want to convert it to the same pointer
744 // type as AI has, so we can GEP through it safely.
745 if (OtherPtr) {
746 // It is likely that OtherPtr is a bitcast, if so, remove it.
747 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
748 OtherPtr = BC->getOperand(0);
749 // All zero GEPs are effectively bitcasts.
750 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
751 if (GEP->hasAllZeroIndices())
752 OtherPtr = GEP->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000754 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
755 if (BCE->getOpcode() == Instruction::BitCast)
756 OtherPtr = BCE->getOperand(0);
757
758 // If the pointer is not the right type, insert a bitcast to the right
759 // type.
760 if (OtherPtr->getType() != AI->getType())
761 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
762 MI);
763 }
764
765 // Process each element of the aggregate.
766 Value *TheFn = MI->getOperand(0);
767 const Type *BytePtrTy = MI->getRawDest()->getType();
768 bool SROADest = MI->getRawDest() == BCInst;
769
770 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
771
772 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
773 // If this is a memcpy/memmove, emit a GEP of the other element address.
774 Value *OtherElt = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000775 if (OtherPtr) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000776 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
777 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner0e99e692008-06-22 17:46:21 +0000778 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000779 MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000781
782 Value *EltPtr = NewElts[i];
783 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
784
785 // If we got down to a scalar, insert a load or store as appropriate.
786 if (EltTy->isSingleValueType()) {
787 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
788 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
789 MI);
790 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
791 continue;
792 }
793 assert(isa<MemSetInst>(MI));
794
795 // If the stored element is zero (common case), just store a null
796 // constant.
797 Constant *StoreVal;
798 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
799 if (CI->isZero()) {
800 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
801 } else {
802 // If EltTy is a vector type, get the element type.
803 const Type *ValTy = EltTy;
804 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
805 ValTy = VTy->getElementType();
806
807 // Construct an integer with the right value.
808 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
809 APInt OneVal(EltSize, CI->getZExtValue());
810 APInt TotalVal(OneVal);
811 // Set each byte.
812 for (unsigned i = 0; 8*i < EltSize; ++i) {
813 TotalVal = TotalVal.shl(8);
814 TotalVal |= OneVal;
815 }
816
817 // Convert the integer value to the appropriate type.
818 StoreVal = ConstantInt::get(TotalVal);
819 if (isa<PointerType>(ValTy))
820 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
821 else if (ValTy->isFloatingPoint())
822 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
823 assert(StoreVal->getType() == ValTy && "Type mismatch!");
824
825 // If the requested value was a vector constant, create it.
826 if (EltTy != ValTy) {
827 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
828 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
829 StoreVal = ConstantVector::get(&Elts[0], NumElts);
830 }
831 }
832 new StoreInst(StoreVal, EltPtr, MI);
833 continue;
834 }
835 // Otherwise, if we're storing a byte variable, use a memset call for
836 // this element.
837 }
838
839 // Cast the element pointer to BytePtrTy.
840 if (EltPtr->getType() != BytePtrTy)
841 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
842
843 // Cast the other pointer (if we have one) to BytePtrTy.
844 if (OtherElt && OtherElt->getType() != BytePtrTy)
845 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
846 MI);
847
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000848 unsigned EltSize = TD->getTypePaddedSize(EltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000849
850 // Finally, insert the meminst for this element.
851 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
852 Value *Ops[] = {
853 SROADest ? EltPtr : OtherElt, // Dest ptr
854 SROADest ? OtherElt : EltPtr, // Src ptr
855 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
856 Zero // Align
857 };
858 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
859 } else {
860 assert(isa<MemSetInst>(MI));
861 Value *Ops[] = {
862 EltPtr, MI->getOperand(2), // Dest, Value,
863 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
864 Zero // Align
865 };
866 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
867 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868 }
Chris Lattner71c75342009-01-07 08:11:13 +0000869 MI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870}
Chris Lattner71c75342009-01-07 08:11:13 +0000871
872/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
873/// overwrites the entire allocation. Extract out the pieces of the stored
874/// integer and store them individually.
875void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
876 AllocationInst *AI,
877 SmallVector<AllocaInst*, 32> &NewElts){
878 // Extract each element out of the integer according to its structure offset
879 // and store the element value to the individual alloca.
880 Value *SrcVal = SI->getOperand(0);
881 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000882 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000883
Chris Lattner71c75342009-01-07 08:11:13 +0000884 // If this isn't a store of an integer to the whole alloca, it may be a store
885 // to the first element. Just ignore the store in this case and normal SROA
886 // will handle it.
887 if (!isa<IntegerType>(SrcVal->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000888 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner71c75342009-01-07 08:11:13 +0000889 return;
890
891 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
892
893 // There are two forms here: AI could be an array or struct. Both cases
894 // have different ways to compute the element offset.
895 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
896 const StructLayout *Layout = TD->getStructLayout(EltSTy);
897
898 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
899 // Get the number of bits to shift SrcVal to get the value.
900 const Type *FieldTy = EltSTy->getElementType(i);
901 uint64_t Shift = Layout->getElementOffsetInBits(i);
902
903 if (TD->isBigEndian())
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000904 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000905
906 Value *EltVal = SrcVal;
907 if (Shift) {
908 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
909 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
910 "sroa.store.elt", SI);
911 }
912
913 // Truncate down to an integer of the right size.
914 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000915
916 // Ignore zero sized fields like {}, they obviously contain no data.
917 if (FieldSizeBits == 0) continue;
918
Chris Lattner71c75342009-01-07 08:11:13 +0000919 if (FieldSizeBits != AllocaSizeBits)
920 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
921 Value *DestField = NewElts[i];
922 if (EltVal->getType() == FieldTy) {
923 // Storing to an integer field of this size, just do it.
924 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
925 // Bitcast to the right element type (for fp/vector values).
926 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
927 } else {
928 // Otherwise, bitcast the dest pointer (for aggregates).
929 DestField = new BitCastInst(DestField,
930 PointerType::getUnqual(EltVal->getType()),
931 "", SI);
932 }
933 new StoreInst(EltVal, DestField, SI);
934 }
935
936 } else {
937 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
938 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000939 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000940 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
941
942 uint64_t Shift;
943
944 if (TD->isBigEndian())
945 Shift = AllocaSizeBits-ElementOffset;
946 else
947 Shift = 0;
948
949 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000950 // Ignore zero sized fields like {}, they obviously contain no data.
951 if (ElementSizeBits == 0) continue;
Chris Lattner71c75342009-01-07 08:11:13 +0000952
953 Value *EltVal = SrcVal;
954 if (Shift) {
955 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
956 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
957 "sroa.store.elt", SI);
958 }
959
960 // Truncate down to an integer of the right size.
961 if (ElementSizeBits != AllocaSizeBits)
962 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
963 Value *DestField = NewElts[i];
964 if (EltVal->getType() == ArrayEltTy) {
965 // Storing to an integer field of this size, just do it.
966 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
967 // Bitcast to the right element type (for fp/vector values).
968 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
969 } else {
970 // Otherwise, bitcast the dest pointer (for aggregates).
971 DestField = new BitCastInst(DestField,
972 PointerType::getUnqual(EltVal->getType()),
973 "", SI);
974 }
975 new StoreInst(EltVal, DestField, SI);
976
977 if (TD->isBigEndian())
978 Shift -= ElementOffset;
979 else
980 Shift += ElementOffset;
981 }
982 }
983
984 SI->eraseFromParent();
985}
986
Chris Lattner28401db2009-01-08 05:42:05 +0000987/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
988/// an integer. Load the individual pieces to form the aggregate value.
989void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
990 SmallVector<AllocaInst*, 32> &NewElts) {
991 // Extract each element out of the NewElts according to its structure offset
992 // and form the result value.
993 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000994 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +0000995
996 // If this isn't a load of the whole alloca to an integer, it may be a load
997 // of the first element. Just ignore the load in this case and normal SROA
998 // will handle it.
999 if (!isa<IntegerType>(LI->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001000 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner28401db2009-01-08 05:42:05 +00001001 return;
1002
1003 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
1004
1005 // There are two forms here: AI could be an array or struct. Both cases
1006 // have different ways to compute the element offset.
1007 const StructLayout *Layout = 0;
1008 uint64_t ArrayEltBitOffset = 0;
1009 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1010 Layout = TD->getStructLayout(EltSTy);
1011 } else {
1012 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001013 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +00001014 }
1015
1016 Value *ResultVal = Constant::getNullValue(LI->getType());
1017
1018 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1019 // Load the value from the alloca. If the NewElt is an aggregate, cast
1020 // the pointer to an integer of the same size before doing the load.
1021 Value *SrcField = NewElts[i];
1022 const Type *FieldTy =
1023 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattnerf7a2f092009-01-09 18:18:43 +00001024 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1025
1026 // Ignore zero sized fields like {}, they obviously contain no data.
1027 if (FieldSizeBits == 0) continue;
1028
1029 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
Chris Lattner28401db2009-01-08 05:42:05 +00001030 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1031 !isa<VectorType>(FieldTy))
1032 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
1033 "", LI);
1034 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1035
1036 // If SrcField is a fp or vector of the right size but that isn't an
1037 // integer type, bitcast to an integer so we can shift it.
1038 if (SrcField->getType() != FieldIntTy)
1039 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1040
1041 // Zero extend the field to be the same size as the final alloca so that
1042 // we can shift and insert it.
1043 if (SrcField->getType() != ResultVal->getType())
1044 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1045
1046 // Determine the number of bits to shift SrcField.
1047 uint64_t Shift;
1048 if (Layout) // Struct case.
1049 Shift = Layout->getElementOffsetInBits(i);
1050 else // Array case.
1051 Shift = i*ArrayEltBitOffset;
1052
1053 if (TD->isBigEndian())
1054 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1055
1056 if (Shift) {
1057 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1058 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1059 }
1060
1061 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1062 }
1063
1064 LI->replaceAllUsesWith(ResultVal);
1065 LI->eraseFromParent();
1066}
1067
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068
Duncan Sandsae5fd622007-11-04 14:43:57 +00001069/// HasPadding - Return true if the specified type has any structure or
1070/// alignment padding, false otherwise.
Duncan Sands4afc5752008-06-04 08:21:45 +00001071static bool HasPadding(const Type *Ty, const TargetData &TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1073 const StructLayout *SL = TD.getStructLayout(STy);
1074 unsigned PrevFieldBitOffset = 0;
1075 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001076 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1077
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 // Padding in sub-elements?
Duncan Sands4afc5752008-06-04 08:21:45 +00001079 if (HasPadding(STy->getElementType(i), TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 return true;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001081
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 // Check to see if there is any padding between this element and the
1083 // previous one.
1084 if (i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001085 unsigned PrevFieldEnd =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1087 if (PrevFieldEnd < FieldBitOffset)
1088 return true;
1089 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001090
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001091 PrevFieldBitOffset = FieldBitOffset;
1092 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001093
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 // Check for tail padding.
1095 if (unsigned EltCount = STy->getNumElements()) {
1096 unsigned PrevFieldEnd = PrevFieldBitOffset +
1097 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sandsae5fd622007-11-04 14:43:57 +00001098 if (PrevFieldEnd < SL->getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 return true;
1100 }
1101
1102 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001103 return HasPadding(ATy->getElementType(), TD);
Duncan Sandsae5fd622007-11-04 14:43:57 +00001104 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001105 return HasPadding(VTy->getElementType(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106 }
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001107 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108}
1109
1110/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1111/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1112/// or 1 if safe after canonicalization has been performed.
1113///
1114int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1115 // Loop over the use list of the alloca. We can only transform it if all of
1116 // the users are safe to transform.
1117 AllocaInfo Info;
1118
1119 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1120 I != E; ++I) {
1121 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1122 if (Info.isUnsafe) {
1123 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1124 return 0;
1125 }
1126 }
1127
1128 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1129 // source and destination, we have to be careful. In particular, the memcpy
1130 // could be moving around elements that live in structure padding of the LLVM
1131 // types, but may actually be used. In these cases, we refuse to promote the
1132 // struct.
1133 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner3fd59362009-01-07 06:34:28 +00001134 HasPadding(AI->getType()->getElementType(), *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 return 0;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001136
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 // If we require cleanup, return 1, otherwise return 3.
Devang Patel83637b12009-02-10 07:00:59 +00001138 return Info.needsCleanup ? 1 : 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139}
1140
Devang Patel83637b12009-02-10 07:00:59 +00001141/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1142/// is canonicalized here.
1143void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1144 gep_type_iterator I = gep_type_begin(GEPI);
1145 ++I;
1146
Devang Pateleb5423c2009-02-10 19:28:07 +00001147 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1148 if (!AT)
1149 return;
1150
1151 uint64_t NumElements = AT->getNumElements();
1152
1153 if (isa<ConstantInt>(I.getOperand()))
1154 return;
1155
1156 if (NumElements == 1) {
1157 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1158 return;
1159 }
Devang Patel83637b12009-02-10 07:00:59 +00001160
Devang Pateleb5423c2009-02-10 19:28:07 +00001161 assert(NumElements == 2 && "Unhandled case!");
1162 // All users of the GEP must be loads. At each use of the GEP, insert
1163 // two loads of the appropriate indexed GEP and select between them.
1164 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1165 Constant::getNullValue(I.getOperand()->getType()),
1166 "isone", GEPI);
1167 // Insert the new GEP instructions, which are properly indexed.
1168 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1169 Indices[1] = Constant::getNullValue(Type::Int32Ty);
1170 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1171 Indices.begin(),
1172 Indices.end(),
1173 GEPI->getName()+".0", GEPI);
1174 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
1175 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1176 Indices.begin(),
1177 Indices.end(),
1178 GEPI->getName()+".1", GEPI);
1179 // Replace all loads of the variable index GEP with loads from both
1180 // indexes and a select.
1181 while (!GEPI->use_empty()) {
1182 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1183 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1184 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1185 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1186 LI->replaceAllUsesWith(R);
1187 LI->eraseFromParent();
Devang Patel83637b12009-02-10 07:00:59 +00001188 }
Devang Pateleb5423c2009-02-10 19:28:07 +00001189 GEPI->eraseFromParent();
Devang Patel83637b12009-02-10 07:00:59 +00001190}
1191
Devang Pateleb5423c2009-02-10 19:28:07 +00001192
Devang Patel83637b12009-02-10 07:00:59 +00001193/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194/// allocation, but only if cleaned up, perform the cleanups required.
Devang Patel83637b12009-02-10 07:00:59 +00001195void SROA::CleanupAllocaUsers(AllocationInst *AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 // At this point, we know that the end result will be SROA'd and promoted, so
1197 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1198 // up.
1199 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1200 UI != E; ) {
Devang Patel83637b12009-02-10 07:00:59 +00001201 User *U = *UI++;
1202 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1203 CleanupGEP(GEPI);
1204 else if (Instruction *I = dyn_cast<Instruction>(U)) {
1205 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1206 if (OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1207 // Safe to remove debug info uses.
1208 while (!DbgInUses.empty()) {
1209 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1210 DI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 }
Devang Patel83637b12009-02-10 07:00:59 +00001212 I->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001213 }
1214 }
1215 }
1216}
1217
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001218/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1219/// the offset specified by Offset (which is specified in bytes).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220///
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001221/// There are two cases we handle here:
1222/// 1) A union of vector types of the same size and potentially its elements.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223/// Here we turn element accesses into insert/extract element operations.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001224/// This promotes a <4 x float> with a store of float to the third element
1225/// into a <4 x float> that uses insert element.
1226/// 2) A fully general blob of memory, which we turn into some (potentially
1227/// large) integer type with extract and insert operations where the loads
1228/// and stores would mutate the memory.
Chris Lattnerf235a322009-02-03 01:30:09 +00001229static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1230 unsigned AllocaSize, const TargetData &TD) {
1231 // If this could be contributing to a vector, analyze it.
1232 if (VecTy != Type::VoidTy) { // either null or a vector type.
Chris Lattnerc2a5f2a2009-02-02 18:02:59 +00001233
Chris Lattnerf235a322009-02-03 01:30:09 +00001234 // If the In type is a vector that is the same size as the alloca, see if it
1235 // matches the existing VecTy.
1236 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1237 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1238 // If we're storing/loading a vector of the right size, allow it as a
1239 // vector. If this the first vector we see, remember the type so that
1240 // we know the element size.
1241 if (VecTy == 0)
1242 VecTy = VInTy;
1243 return;
1244 }
1245 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1246 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1247 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1248 // If we're accessing something that could be an element of a vector, see
1249 // if the implied vector agrees with what we already have and if Offset is
1250 // compatible with it.
1251 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1252 if (Offset % EltSize == 0 &&
1253 AllocaSize % EltSize == 0 &&
1254 (VecTy == 0 ||
1255 cast<VectorType>(VecTy)->getElementType()
1256 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1257 if (VecTy == 0)
1258 VecTy = VectorType::get(In, AllocaSize/EltSize);
1259 return;
1260 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001261 }
1262 }
1263
Chris Lattnerf235a322009-02-03 01:30:09 +00001264 // Otherwise, we have a case that we can't handle with an optimized vector
1265 // form. We can still turn this into a large integer.
1266 VecTy = Type::VoidTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267}
1268
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001269/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattnerf235a322009-02-03 01:30:09 +00001270/// its accesses to use a to single vector type, return true, and set VecTy to
1271/// the new type. If we could convert the alloca into a single promotable
1272/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1273/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1274/// is the current offset from the base of the alloca being analyzed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275///
Chris Lattner38088d12009-02-03 18:15:05 +00001276/// If we see at least one access to the value that is as a vector type, set the
1277/// SawVec flag.
1278///
1279bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1280 bool &SawVec, uint64_t Offset,
Chris Lattnerf235a322009-02-03 01:30:09 +00001281 unsigned AllocaSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1283 Instruction *User = cast<Instruction>(*UI);
1284
1285 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001286 // Don't break volatile loads.
Chris Lattner70ffe572009-01-28 20:16:43 +00001287 if (LI->isVolatile())
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001288 return false;
Chris Lattnerf235a322009-02-03 01:30:09 +00001289 MergeInType(LI->getType(), Offset, VecTy, AllocaSize, *TD);
Chris Lattner38088d12009-02-03 18:15:05 +00001290 SawVec |= isa<VectorType>(LI->getType());
Chris Lattner7cc97712009-01-07 06:39:58 +00001291 continue;
1292 }
1293
1294 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 // Storing the pointer, not into the value?
Chris Lattner70ffe572009-01-28 20:16:43 +00001296 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Chris Lattnerf235a322009-02-03 01:30:09 +00001297 MergeInType(SI->getOperand(0)->getType(), Offset, VecTy, AllocaSize, *TD);
Chris Lattner38088d12009-02-03 18:15:05 +00001298 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattner7cc97712009-01-07 06:39:58 +00001299 continue;
1300 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001301
1302 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner38088d12009-02-03 18:15:05 +00001303 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1304 AllocaSize))
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001305 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 IsNotTrivial = true;
Chris Lattner7cc97712009-01-07 06:39:58 +00001307 continue;
1308 }
1309
1310 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001311 // If this is a GEP with a variable indices, we can't handle it.
1312 if (!GEP->hasAllConstantIndices())
1313 return false;
Chris Lattner7cc97712009-01-07 06:39:58 +00001314
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001315 // Compute the offset that this GEP adds to the pointer.
1316 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1317 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1318 &Indices[0], Indices.size());
1319 // See if all uses can be converted.
Chris Lattner38088d12009-02-03 18:15:05 +00001320 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattnerf235a322009-02-03 01:30:09 +00001321 AllocaSize))
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001322 return false;
1323 IsNotTrivial = true;
1324 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001326
Chris Lattnerfece0da2009-02-03 02:01:43 +00001327 // If this is a constant sized memset of a constant value (e.g. 0) we can
1328 // handle it.
1329 if (isa<MemSetInst>(User) &&
1330 // Store of constant value.
1331 isa<ConstantInt>(User->getOperand(2)) &&
1332 // Store with constant size.
1333 isa<ConstantInt>(User->getOperand(3))) {
1334 VecTy = Type::VoidTy;
1335 IsNotTrivial = true;
1336 continue;
1337 }
1338
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001339 // Otherwise, we cannot handle this!
1340 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 }
1342
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001343 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344}
1345
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346
1347/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1348/// directly. This happens when we are converting an "integer union" to a
1349/// single integer scalar, or when we are converting a "vector union" to a
1350/// vector with insert/extractelement instructions.
1351///
1352/// Offset is an offset from the original alloca, in bits that need to be
1353/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001354void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001355 while (!Ptr->use_empty()) {
1356 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands641f12c2009-02-02 10:06:20 +00001357
Chris Lattner7cc97712009-01-07 06:39:58 +00001358 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb1534532008-01-30 00:39:15 +00001359 ConvertUsesToScalar(CI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 CI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001361 continue;
1362 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001363
Chris Lattner7cc97712009-01-07 06:39:58 +00001364 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001365 // Compute the offset that this GEP adds to the pointer.
1366 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1367 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1368 &Indices[0], Indices.size());
1369 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 GEP->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001371 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001372 }
Chris Lattnerfece0da2009-02-03 02:01:43 +00001373
Chris Lattnerececb0c2009-02-03 19:45:44 +00001374 IRBuilder<> Builder(User->getParent(), User);
1375
1376 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001377 // The load is a bit extract from NewAI shifted right by Offset bits.
1378 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1379 Value *NewLoadVal
1380 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1381 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattnerececb0c2009-02-03 19:45:44 +00001382 LI->eraseFromParent();
1383 continue;
1384 }
1385
1386 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1387 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1388 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1389 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1390 Builder);
1391 Builder.CreateStore(New, NewAI);
1392 SI->eraseFromParent();
1393 continue;
1394 }
1395
Chris Lattnerfece0da2009-02-03 02:01:43 +00001396 // If this is a constant sized memset of a constant value (e.g. 0) we can
1397 // transform it into a store of the expanded constant value.
1398 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1399 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1400 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1401 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1402
1403 // Compute the value replicated the right number of times.
1404 APInt APVal(NumBytes*8, Val);
1405
1406 // Splat the value if non-zero.
1407 if (Val)
1408 for (unsigned i = 1; i != NumBytes; ++i)
1409 APVal |= APVal << 8;
1410
Chris Lattner32c19282009-02-03 19:41:50 +00001411 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
Chris Lattnercc0727c2009-02-03 19:30:11 +00001412 Value *New = ConvertScalar_InsertValue(ConstantInt::get(APVal), Old,
Chris Lattner32c19282009-02-03 19:41:50 +00001413 Offset, Builder);
1414 Builder.CreateStore(New, NewAI);
Chris Lattnerfece0da2009-02-03 02:01:43 +00001415 MSI->eraseFromParent();
1416 continue;
1417 }
1418
1419
Chris Lattner7cc97712009-01-07 06:39:58 +00001420 assert(0 && "Unsupported operation!");
1421 abort();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 }
1423}
1424
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001425/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1426/// or vector value FromVal, extracting the bits from the offset specified by
1427/// Offset. This returns the value, which is of type ToType.
1428///
1429/// This happens when we are converting an "integer union" to a single
Duncan Sands641f12c2009-02-02 10:06:20 +00001430/// integer scalar, or when we are converting a "vector union" to a vector with
1431/// insert/extractelement instructions.
Chris Lattner41d58652008-02-29 07:03:13 +00001432///
Duncan Sands641f12c2009-02-02 10:06:20 +00001433/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001434/// shifted to the right.
1435Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1436 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001437 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001438 if (FromVal->getType() == ToType && Offset == 0)
1439 return FromVal;
Chris Lattner5f062542008-02-29 07:12:06 +00001440
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001441 // If the result alloca is a vector type, this is either an element
1442 // access or a bitcast to another vector type of the same size.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001443 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1444 if (isa<VectorType>(ToType))
1445 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner5f062542008-02-29 07:12:06 +00001446
1447 // Otherwise it must be an element access.
Chris Lattner5f062542008-02-29 07:12:06 +00001448 unsigned Elt = 0;
1449 if (Offset) {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001450 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType());
Chris Lattner5f062542008-02-29 07:12:06 +00001451 Elt = Offset/EltSize;
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001452 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner41d58652008-02-29 07:03:13 +00001453 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001454 // Return the element extracted out of it.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001455 Value *V = Builder.CreateExtractElement(FromVal,
Chris Lattnerececb0c2009-02-03 19:45:44 +00001456 ConstantInt::get(Type::Int32Ty,Elt),
1457 "tmp");
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001458 if (V->getType() != ToType)
1459 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001460 return V;
Chris Lattner5f062542008-02-29 07:12:06 +00001461 }
Chris Lattner7bac66b2009-02-03 21:08:45 +00001462
1463 // If ToType is a first class aggregate, extract out each of the pieces and
1464 // use insertvalue's to form the FCA.
1465 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1466 const StructLayout &Layout = *TD->getStructLayout(ST);
1467 Value *Res = UndefValue::get(ST);
1468 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1469 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattner97e1f382009-02-06 04:34:07 +00001470 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner7bac66b2009-02-03 21:08:45 +00001471 Builder);
1472 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1473 }
1474 return Res;
1475 }
1476
1477 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1478 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1479 Value *Res = UndefValue::get(AT);
1480 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1481 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1482 Offset+i*EltSize, Builder);
1483 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1484 }
1485 return Res;
1486 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001487
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001488 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001489 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands641f12c2009-02-02 10:06:20 +00001490
Chris Lattner5f062542008-02-29 07:12:06 +00001491 // If this is a big-endian system and the load is narrower than the
1492 // full alloca type, we need to do a shift to get the right bits.
1493 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001494 if (TD->isBigEndian()) {
Chris Lattner5f062542008-02-29 07:12:06 +00001495 // On big-endian machines, the lowest bit is stored at the bit offset
1496 // from the pointer given by getTypeStoreSizeInBits. This matters for
1497 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner3fd59362009-01-07 06:34:28 +00001498 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001499 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner5f062542008-02-29 07:12:06 +00001500 } else {
1501 ShAmt = Offset;
1502 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001503
Chris Lattner5f062542008-02-29 07:12:06 +00001504 // Note: we support negative bitwidths (with shl) which are not defined.
1505 // We do this to support (f.e.) loads off the end of a structure where
1506 // only some bits are used.
1507 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Chris Lattner7bac66b2009-02-03 21:08:45 +00001508 FromVal = Builder.CreateLShr(FromVal, ConstantInt::get(FromVal->getType(),
1509 ShAmt), "tmp");
Chris Lattner5f062542008-02-29 07:12:06 +00001510 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Chris Lattner7bac66b2009-02-03 21:08:45 +00001511 FromVal = Builder.CreateShl(FromVal, ConstantInt::get(FromVal->getType(),
1512 -ShAmt), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001513
Chris Lattner5f062542008-02-29 07:12:06 +00001514 // Finally, unconditionally truncate the integer to the right width.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001515 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner5f062542008-02-29 07:12:06 +00001516 if (LIBitWidth < NTy->getBitWidth())
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001517 FromVal = Builder.CreateTrunc(FromVal, IntegerType::get(LIBitWidth), "tmp");
Chris Lattnerb2290a12009-02-03 07:08:57 +00001518 else if (LIBitWidth > NTy->getBitWidth())
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001519 FromVal = Builder.CreateZExt(FromVal, IntegerType::get(LIBitWidth), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001520
Chris Lattner5f062542008-02-29 07:12:06 +00001521 // If the result is an integer, this is a trunc or bitcast.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001522 if (isa<IntegerType>(ToType)) {
Chris Lattner5f062542008-02-29 07:12:06 +00001523 // Should be done.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001524 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner5f062542008-02-29 07:12:06 +00001525 // Just do a bitcast, we know the sizes match up.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001526 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001527 } else {
Chris Lattner5f062542008-02-29 07:12:06 +00001528 // Otherwise must be a pointer.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001529 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001530 }
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001531 assert(FromVal->getType() == ToType && "Didn't convert right?");
1532 return FromVal;
Chris Lattner41d58652008-02-29 07:03:13 +00001533}
1534
1535
Chris Lattnercc0727c2009-02-03 19:30:11 +00001536/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1537/// or vector value "Old" at the offset specified by Offset.
1538///
1539/// This happens when we are converting an "integer union" to a
Chris Lattner41d58652008-02-29 07:03:13 +00001540/// single integer scalar, or when we are converting a "vector union" to a
1541/// vector with insert/extractelement instructions.
1542///
1543/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnercc0727c2009-02-03 19:30:11 +00001544/// shifted to the right.
1545Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner32c19282009-02-03 19:41:50 +00001546 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands641f12c2009-02-02 10:06:20 +00001547
Chris Lattner41d58652008-02-29 07:03:13 +00001548 // Convert the stored type to the actual type, shift it left to insert
1549 // then 'or' into place.
Chris Lattnercc0727c2009-02-03 19:30:11 +00001550 const Type *AllocaType = Old->getType();
Duncan Sands641f12c2009-02-02 10:06:20 +00001551
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001552 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner41d58652008-02-29 07:03:13 +00001553 // If the result alloca is a vector type, this is either an element
1554 // access or a bitcast to another vector type.
1555 if (isa<VectorType>(SV->getType())) {
Chris Lattner32c19282009-02-03 19:41:50 +00001556 SV = Builder.CreateBitCast(SV, AllocaType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001557 } else {
1558 // Must be an element insertion.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001559 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(VTy->getElementType());
Chris Lattnerf235a322009-02-03 01:30:09 +00001560
1561 if (SV->getType() != VTy->getElementType())
Chris Lattner32c19282009-02-03 19:41:50 +00001562 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001563
Chris Lattner32c19282009-02-03 19:41:50 +00001564 SV = Builder.CreateInsertElement(Old, SV,
1565 ConstantInt::get(Type::Int32Ty, Elt),
1566 "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001567 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001568 return SV;
1569 }
Chris Lattnercc0727c2009-02-03 19:30:11 +00001570
1571 // If SV is a first-class aggregate value, insert each value recursively.
1572 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1573 const StructLayout &Layout = *TD->getStructLayout(ST);
1574 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner32c19282009-02-03 19:41:50 +00001575 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattnercc0727c2009-02-03 19:30:11 +00001576 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner97e1f382009-02-06 04:34:07 +00001577 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner32c19282009-02-03 19:41:50 +00001578 Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +00001579 }
1580 return Old;
1581 }
1582
1583 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1584 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1585 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner32c19282009-02-03 19:41:50 +00001586 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1587 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +00001588 }
1589 return Old;
1590 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001591
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001592 // If SV is a float, convert it to the appropriate integer type.
Chris Lattnercc0727c2009-02-03 19:30:11 +00001593 // If it is a pointer, do the same.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001594 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1595 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1596 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1597 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1598 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Chris Lattner32c19282009-02-03 19:41:50 +00001599 SV = Builder.CreateBitCast(SV, IntegerType::get(SrcWidth), "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001600 else if (isa<PointerType>(SV->getType()))
Chris Lattner32c19282009-02-03 19:41:50 +00001601 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001602
Chris Lattnerf235a322009-02-03 01:30:09 +00001603 // Zero extend or truncate the value if needed.
1604 if (SV->getType() != AllocaType) {
1605 if (SV->getType()->getPrimitiveSizeInBits() <
1606 AllocaType->getPrimitiveSizeInBits())
Chris Lattner32c19282009-02-03 19:41:50 +00001607 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001608 else {
1609 // Truncation may be needed if storing more than the alloca can hold
1610 // (undefined behavior).
Chris Lattner32c19282009-02-03 19:41:50 +00001611 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001612 SrcWidth = DestWidth;
1613 SrcStoreWidth = DestStoreWidth;
1614 }
1615 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001616
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001617 // If this is a big-endian system and the store is narrower than the
1618 // full alloca type, we need to do a shift to get the right bits.
1619 int ShAmt = 0;
1620 if (TD->isBigEndian()) {
1621 // On big-endian machines, the lowest bit is stored at the bit offset
1622 // from the pointer given by getTypeStoreSizeInBits. This matters for
1623 // integers with a bitwidth that is not a multiple of 8.
1624 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner41d58652008-02-29 07:03:13 +00001625 } else {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001626 ShAmt = Offset;
1627 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001628
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001629 // Note: we support negative bitwidths (with shr) which are not defined.
1630 // We do this to support (f.e.) stores off the end of a structure where
1631 // only some bits in the structure are set.
1632 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1633 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Chris Lattner32c19282009-02-03 19:41:50 +00001634 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt), "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001635 Mask <<= ShAmt;
1636 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Chris Lattner32c19282009-02-03 19:41:50 +00001637 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt), "tmp");
Duncan Sandsced29632009-02-02 09:53:14 +00001638 Mask = Mask.lshr(-ShAmt);
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001639 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001640
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001641 // Mask out the bits we are about to insert from the old value, and or
1642 // in the new bits.
1643 if (SrcWidth != DestWidth) {
1644 assert(DestWidth > SrcWidth);
Chris Lattner32c19282009-02-03 19:41:50 +00001645 Old = Builder.CreateAnd(Old, ConstantInt::get(~Mask), "mask");
1646 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner41d58652008-02-29 07:03:13 +00001647 }
1648 return SV;
1649}
1650
1651
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652
1653/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1654/// some part of a constant global variable. This intentionally only accepts
1655/// constant expressions because we don't can't rewrite arbitrary instructions.
1656static bool PointsToConstantGlobal(Value *V) {
1657 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1658 return GV->isConstant();
1659 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1660 if (CE->getOpcode() == Instruction::BitCast ||
1661 CE->getOpcode() == Instruction::GetElementPtr)
1662 return PointsToConstantGlobal(CE->getOperand(0));
1663 return false;
1664}
1665
1666/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1667/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1668/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1669/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1670/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1671/// the alloca, and if the source pointer is a pointer to a constant global, we
1672/// can optimize this.
1673static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1674 bool isOffset) {
1675 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner70ffe572009-01-28 20:16:43 +00001676 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1677 // Ignore non-volatile loads, they are always ok.
1678 if (!LI->isVolatile())
1679 continue;
1680
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1682 // If uses of the bitcast are ok, we are ok.
1683 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1684 return false;
1685 continue;
1686 }
1687 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1688 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1689 // doesn't, it does.
1690 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1691 isOffset || !GEP->hasAllZeroIndices()))
1692 return false;
1693 continue;
1694 }
1695
1696 // If this is isn't our memcpy/memmove, reject it as something we can't
1697 // handle.
1698 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1699 return false;
1700
1701 // If we already have seen a copy, reject the second one.
1702 if (TheCopy) return false;
1703
1704 // If the pointer has been offset from the start of the alloca, we can't
1705 // safely handle this.
1706 if (isOffset) return false;
1707
1708 // If the memintrinsic isn't using the alloca as the dest, reject it.
1709 if (UI.getOperandNo() != 1) return false;
1710
1711 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1712
1713 // If the source of the memcpy/move is not a constant global, reject it.
1714 if (!PointsToConstantGlobal(MI->getOperand(2)))
1715 return false;
1716
1717 // Otherwise, the transform is safe. Remember the copy instruction.
1718 TheCopy = MI;
1719 }
1720 return true;
1721}
1722
1723/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1724/// modified by a copy from a constant global. If we can prove this, we can
1725/// replace any uses of the alloca with uses of the global directly.
1726Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1727 Instruction *TheCopy = 0;
1728 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1729 return TheCopy;
1730 return 0;
1731}