blob: 3a4201bf81e894ca87f04702e576df7c881e446a [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());
Bill Wendling0a1fb242009-03-01 03:55:12 +0000256
Chris Lattnerf235a322009-02-03 01:30:09 +0000257 if ((isa<StructType>(AI->getAllocatedType()) ||
258 isa<ArrayType>(AI->getAllocatedType())) &&
Bill Wendling0a1fb242009-03-01 03:55:12 +0000259 // Do not promote any struct whose size is too big.
260 AllocaSize < SRThreshold &&
Chris Lattnerf235a322009-02-03 01:30:09 +0000261 // Do not promote any struct into more than "32" separate vars.
262 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
263 // Check that all of the users of the allocation are capable of being
264 // transformed.
265 switch (isSafeAllocaToScalarRepl(AI)) {
266 default: assert(0 && "Unexpected value!");
267 case 0: // Not safe to scalar replace.
268 break;
269 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel83637b12009-02-10 07:00:59 +0000270 CleanupAllocaUsers(AI);
Chris Lattnerf235a322009-02-03 01:30:09 +0000271 // FALL THROUGH.
272 case 3: // Safe to scalar replace.
273 DoScalarReplacement(AI, WorkList);
274 Changed = true;
275 continue;
276 }
277 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000278
279 // If we can turn this aggregate value (potentially with casts) into a
280 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000281 // IsNotTrivial tracks whether this is something that mem2reg could have
282 // promoted itself. If so, we don't want to transform it needlessly. Note
283 // that we can't just check based on the type: the alloca may be of an i32
284 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner70ffe572009-01-28 20:16:43 +0000285 bool IsNotTrivial = false;
Chris Lattnerf235a322009-02-03 01:30:09 +0000286 const Type *VectorTy = 0;
Chris Lattner38088d12009-02-03 18:15:05 +0000287 bool HadAVector = false;
288 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattnerf235a322009-02-03 01:30:09 +0000289 0, unsigned(AllocaSize)) && IsNotTrivial) {
290 AllocaInst *NewAI;
Chris Lattner38088d12009-02-03 18:15:05 +0000291 // If we were able to find a vector type that can handle this with
292 // insert/extract elements, and if there was at least one use that had
293 // a vector type, promote this to a vector. We don't want to promote
294 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
295 // we just get a lot of insert/extracts. If at least one vector is
296 // involved, then we probably really do have a union of vector/array.
297 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Chris Lattnerf235a322009-02-03 01:30:09 +0000298 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
Chris Lattner05ebfd72009-02-02 20:44:45 +0000299
Chris Lattnerf235a322009-02-03 01:30:09 +0000300 // Create and insert the vector alloca.
301 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner05ebfd72009-02-02 20:44:45 +0000302 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattnerf235a322009-02-03 01:30:09 +0000303 } else {
304 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
305
306 // Create and insert the integer alloca.
307 const Type *NewTy = IntegerType::get(AllocaSize*8);
308 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
309 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner70ffe572009-01-28 20:16:43 +0000310 }
Chris Lattnerf235a322009-02-03 01:30:09 +0000311 NewAI->takeName(AI);
312 AI->eraseFromParent();
313 ++NumConverted;
314 Changed = true;
315 continue;
316 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000317
Chris Lattnerf235a322009-02-03 01:30:09 +0000318 // Otherwise, couldn't process this alloca.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 }
320
321 return Changed;
322}
323
324/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
325/// predicate, do SROA now.
326void SROA::DoScalarReplacement(AllocationInst *AI,
327 std::vector<AllocationInst*> &WorkList) {
328 DOUT << "Found inst to SROA: " << *AI;
329 SmallVector<AllocaInst*, 32> ElementAllocas;
330 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
331 ElementAllocas.reserve(ST->getNumContainedTypes());
332 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
333 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
334 AI->getAlignment(),
335 AI->getName() + "." + utostr(i), AI);
336 ElementAllocas.push_back(NA);
337 WorkList.push_back(NA); // Add to worklist for recursive processing
338 }
339 } else {
340 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
341 ElementAllocas.reserve(AT->getNumElements());
342 const Type *ElTy = AT->getElementType();
343 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
344 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
345 AI->getName() + "." + utostr(i), AI);
346 ElementAllocas.push_back(NA);
347 WorkList.push_back(NA); // Add to worklist for recursive processing
348 }
349 }
350
351 // Now that we have created the alloca instructions that we want to use,
352 // expand the getelementptr instructions to use them.
353 //
354 while (!AI->use_empty()) {
355 Instruction *User = cast<Instruction>(AI->use_back());
356 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
357 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
358 BCInst->eraseFromParent();
359 continue;
360 }
361
Chris Lattner19e61a42008-06-23 17:11:23 +0000362 // Replace:
363 // %res = load { i32, i32 }* %alloc
364 // with:
365 // %load.0 = load i32* %alloc.0
366 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
367 // %load.1 = load i32* %alloc.1
368 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000369 // (Also works for arrays instead of structs)
370 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
371 Value *Insert = UndefValue::get(LI->getType());
372 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
373 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
374 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
375 }
376 LI->replaceAllUsesWith(Insert);
377 LI->eraseFromParent();
378 continue;
379 }
380
Chris Lattner19e61a42008-06-23 17:11:23 +0000381 // Replace:
382 // store { i32, i32 } %val, { i32, i32 }* %alloc
383 // with:
384 // %val.0 = extractvalue { i32, i32 } %val, 0
385 // store i32 %val.0, i32* %alloc.0
386 // %val.1 = extractvalue { i32, i32 } %val, 1
387 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000388 // (Also works for arrays instead of structs)
389 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
390 Value *Val = SI->getOperand(0);
391 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
392 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
393 new StoreInst(Extract, ElementAllocas[i], SI);
394 }
395 SI->eraseFromParent();
396 continue;
397 }
398
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
400 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
401 unsigned Idx =
402 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
403
404 assert(Idx < ElementAllocas.size() && "Index out of range?");
405 AllocaInst *AllocaToUse = ElementAllocas[Idx];
406
407 Value *RepValue;
408 if (GEPI->getNumOperands() == 3) {
409 // Do not insert a new getelementptr instruction with zero indices, only
410 // to have it optimized out later.
411 RepValue = AllocaToUse;
412 } else {
413 // We are indexing deeply into the structure, so we still need a
414 // getelement ptr instruction to finish the indexing. This may be
415 // expanded itself once the worklist is rerun.
416 //
417 SmallVector<Value*, 8> NewArgs;
418 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
419 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greifd6da1d02008-04-06 20:25:17 +0000420 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
421 NewArgs.end(), "", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422 RepValue->takeName(GEPI);
423 }
424
425 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattner85591c62009-01-07 06:25:07 +0000426 if (Idx == 0 && GEPI->hasAllZeroIndices())
427 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428
429 // Move all of the users over to the new GEP.
430 GEPI->replaceAllUsesWith(RepValue);
431 // Delete the old GEP
432 GEPI->eraseFromParent();
433 }
434
435 // Finally, delete the Alloca instruction
436 AI->eraseFromParent();
437 NumReplaced++;
438}
439
440
441/// isSafeElementUse - Check to see if this use is an allowed use for a
442/// getelementptr instruction of an array aggregate allocation. isFirstElt
443/// indicates whether Ptr is known to the start of the aggregate.
444///
445void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
446 AllocaInfo &Info) {
447 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
448 I != E; ++I) {
449 Instruction *User = cast<Instruction>(*I);
450 switch (User->getOpcode()) {
451 case Instruction::Load: break;
452 case Instruction::Store:
453 // Store is ok if storing INTO the pointer, not storing the pointer
454 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
455 break;
456 case Instruction::GetElementPtr: {
457 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
458 bool AreAllZeroIndices = isFirstElt;
459 if (GEP->getNumOperands() > 1) {
460 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
461 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
462 // Using pointer arithmetic to navigate the array.
463 return MarkUnsafe(Info);
464
Chris Lattner85591c62009-01-07 06:25:07 +0000465 if (AreAllZeroIndices)
466 AreAllZeroIndices = GEP->hasAllZeroIndices();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 }
468 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
469 if (Info.isUnsafe) return;
470 break;
471 }
472 case Instruction::BitCast:
473 if (isFirstElt) {
474 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
475 if (Info.isUnsafe) return;
476 break;
477 }
478 DOUT << " Transformation preventing inst: " << *User;
479 return MarkUnsafe(Info);
480 case Instruction::Call:
481 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
482 if (isFirstElt) {
483 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
484 if (Info.isUnsafe) return;
485 break;
486 }
487 }
488 DOUT << " Transformation preventing inst: " << *User;
489 return MarkUnsafe(Info);
490 default:
491 DOUT << " Transformation preventing inst: " << *User;
492 return MarkUnsafe(Info);
493 }
494 }
495 return; // All users look ok :)
496}
497
498/// AllUsersAreLoads - Return true if all users of this value are loads.
499static bool AllUsersAreLoads(Value *Ptr) {
500 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
501 I != E; ++I)
502 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
503 return false;
504 return true;
505}
506
507/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
508/// aggregate allocation.
509///
510void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
511 AllocaInfo &Info) {
512 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
513 return isSafeUseOfBitCastedAllocation(C, AI, Info);
514
Chris Lattner70ffe572009-01-28 20:16:43 +0000515 if (LoadInst *LI = dyn_cast<LoadInst>(User))
516 if (!LI->isVolatile())
517 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000518
Chris Lattner70ffe572009-01-28 20:16:43 +0000519 if (StoreInst *SI = dyn_cast<StoreInst>(User))
520 if (!SI->isVolatile() && SI->getOperand(0) != AI)
521 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000522
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
524 if (GEPI == 0)
525 return MarkUnsafe(Info);
526
527 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
528
529 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
530 if (I == E ||
531 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
532 return MarkUnsafe(Info);
533 }
534
535 ++I;
536 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
537
538 bool IsAllZeroIndices = true;
539
Chris Lattnerd324da02008-08-23 05:21:06 +0000540 // If the first index is a non-constant index into an array, see if we can
541 // handle it as a special case.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000542 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattnerd324da02008-08-23 05:21:06 +0000543 if (!isa<ConstantInt>(I.getOperand())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 IsAllZeroIndices = 0;
Chris Lattnerd324da02008-08-23 05:21:06 +0000545 uint64_t NumElements = AT->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546
547 // If this is an array index and the index is not constant, we cannot
548 // promote... that is unless the array has exactly one or two elements in
549 // it, in which case we CAN promote it, but we have to canonicalize this
550 // out if this is the only problem.
551 if ((NumElements == 1 || NumElements == 2) &&
552 AllUsersAreLoads(GEPI)) {
Devang Patel83637b12009-02-10 07:00:59 +0000553 Info.needsCleanup = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 return; // Canonicalization required!
555 }
556 return MarkUnsafe(Info);
557 }
558 }
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000559
Chris Lattnerd324da02008-08-23 05:21:06 +0000560 // Walk through the GEP type indices, checking the types that this indexes
561 // into.
562 for (; I != E; ++I) {
563 // Ignore struct elements, no extra checking needed for these.
564 if (isa<StructType>(*I))
565 continue;
566
Chris Lattnerd324da02008-08-23 05:21:06 +0000567 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
568 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000569
570 // Are all indices still zero?
Chris Lattnerd324da02008-08-23 05:21:06 +0000571 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000572
573 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
574 // This GEP indexes an array. Verify that this is an in-range constant
575 // integer. Specifically, consider A[0][i]. We cannot know that the user
576 // isn't doing invalid things like allowing i to index an out-of-range
577 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000578 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000579 if (IdxVal->getZExtValue() >= AT->getNumElements())
580 return MarkUnsafe(Info);
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000581 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
582 if (IdxVal->getZExtValue() >= VT->getNumElements())
583 return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000584 }
Chris Lattnerd324da02008-08-23 05:21:06 +0000585 }
586
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587 // If there are any non-simple uses of this getelementptr, make sure to reject
588 // them.
589 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
590}
591
592/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
593/// intrinsic can be promoted by SROA. At this point, we know that the operand
594/// of the memintrinsic is a pointer to the beginning of the allocation.
595void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
596 unsigned OpNo, AllocaInfo &Info) {
597 // If not constant length, give up.
598 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
599 if (!Length) return MarkUnsafe(Info);
600
601 // If not the whole aggregate, give up.
Duncan Sandsae5fd622007-11-04 14:43:57 +0000602 if (Length->getZExtValue() !=
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000603 TD->getTypePaddedSize(AI->getType()->getElementType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 return MarkUnsafe(Info);
605
606 // We only know about memcpy/memset/memmove.
607 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
608 return MarkUnsafe(Info);
609
610 // Otherwise, we can transform it. Determine whether this is a memcpy/set
611 // into or out of the aggregate.
612 if (OpNo == 1)
613 Info.isMemCpyDst = true;
614 else {
615 assert(OpNo == 2);
616 Info.isMemCpySrc = true;
617 }
618}
619
620/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
621/// are
622void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
623 AllocaInfo &Info) {
624 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
625 UI != E; ++UI) {
626 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
627 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
628 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
629 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattner71c75342009-01-07 08:11:13 +0000630 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000631 if (SI->isVolatile())
632 return MarkUnsafe(Info);
633
Chris Lattner71c75342009-01-07 08:11:13 +0000634 // If storing the entire alloca in one chunk through a bitcasted pointer
635 // to integer, we can transform it. This happens (for example) when you
636 // cast a {i32,i32}* to i64* and store through it. This is similar to the
637 // memcpy case and occurs in various "byval" cases and emulated memcpys.
638 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000639 TD->getTypePaddedSize(SI->getOperand(0)->getType()) ==
640 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner71c75342009-01-07 08:11:13 +0000641 Info.isMemCpyDst = true;
642 continue;
643 }
644 return MarkUnsafe(Info);
Chris Lattner28401db2009-01-08 05:42:05 +0000645 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000646 if (LI->isVolatile())
647 return MarkUnsafe(Info);
648
Chris Lattner28401db2009-01-08 05:42:05 +0000649 // If loading the entire alloca in one chunk through a bitcasted pointer
650 // to integer, we can transform it. This happens (for example) when you
651 // cast a {i32,i32}* to i64* and load through it. This is similar to the
652 // memcpy case and occurs in various "byval" cases and emulated memcpys.
653 if (isa<IntegerType>(LI->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000654 TD->getTypePaddedSize(LI->getType()) ==
655 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner28401db2009-01-08 05:42:05 +0000656 Info.isMemCpySrc = true;
657 continue;
658 }
659 return MarkUnsafe(Info);
Devang Patel83637b12009-02-10 07:00:59 +0000660 } else if (isa<DbgInfoIntrinsic>(UI)) {
661 // If one user is DbgInfoIntrinsic then check if all users are
662 // DbgInfoIntrinsics.
663 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
664 Info.needsCleanup = true;
665 return;
666 }
667 else
668 MarkUnsafe(Info);
669 }
670 else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 return MarkUnsafe(Info);
672 }
673 if (Info.isUnsafe) return;
674 }
675}
676
677/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
678/// to its first element. Transform users of the cast to use the new values
679/// instead.
680void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
681 SmallVector<AllocaInst*, 32> &NewElts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
683 while (UI != UE) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000684 Instruction *User = cast<Instruction>(*UI++);
685 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000686 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000687 if (BCU->use_empty()) BCU->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 continue;
689 }
690
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000691 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
692 // This must be memcpy/memmove/memset of the entire aggregate.
693 // Split into one per element.
694 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 continue;
696 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000697
Chris Lattner71c75342009-01-07 08:11:13 +0000698 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner28401db2009-01-08 05:42:05 +0000699 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattner71c75342009-01-07 08:11:13 +0000700 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
701 continue;
702 }
Chris Lattner28401db2009-01-08 05:42:05 +0000703
704 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
705 // If this is a load of the entire alloca to an integer, rewrite it.
706 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
707 continue;
708 }
Chris Lattner71c75342009-01-07 08:11:13 +0000709
710 // Otherwise it must be some other user of a gep of the first pointer. Just
711 // leave these alone.
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000712 continue;
Chris Lattner28401db2009-01-08 05:42:05 +0000713 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000714}
715
716/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
717/// Rewrite it to copy or set the elements of the scalarized memory.
718void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
719 AllocationInst *AI,
720 SmallVector<AllocaInst*, 32> &NewElts) {
721
722 // If this is a memcpy/memmove, construct the other pointer as the
723 // appropriate type.
724 Value *OtherPtr = 0;
725 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
726 if (BCInst == MCI->getRawDest())
727 OtherPtr = MCI->getRawSource();
728 else {
729 assert(BCInst == MCI->getRawSource());
730 OtherPtr = MCI->getRawDest();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000732 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
733 if (BCInst == MMI->getRawDest())
734 OtherPtr = MMI->getRawSource();
735 else {
736 assert(BCInst == MMI->getRawSource());
737 OtherPtr = MMI->getRawDest();
738 }
739 }
740
741 // If there is an other pointer, we want to convert it to the same pointer
742 // type as AI has, so we can GEP through it safely.
743 if (OtherPtr) {
744 // It is likely that OtherPtr is a bitcast, if so, remove it.
745 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
746 OtherPtr = BC->getOperand(0);
747 // All zero GEPs are effectively bitcasts.
748 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
749 if (GEP->hasAllZeroIndices())
750 OtherPtr = GEP->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000752 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
753 if (BCE->getOpcode() == Instruction::BitCast)
754 OtherPtr = BCE->getOperand(0);
755
756 // If the pointer is not the right type, insert a bitcast to the right
757 // type.
758 if (OtherPtr->getType() != AI->getType())
759 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
760 MI);
761 }
762
763 // Process each element of the aggregate.
764 Value *TheFn = MI->getOperand(0);
765 const Type *BytePtrTy = MI->getRawDest()->getType();
766 bool SROADest = MI->getRawDest() == BCInst;
767
768 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
769
770 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
771 // If this is a memcpy/memmove, emit a GEP of the other element address.
772 Value *OtherElt = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 if (OtherPtr) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000774 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
775 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner0e99e692008-06-22 17:46:21 +0000776 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000777 MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000779
780 Value *EltPtr = NewElts[i];
781 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
782
783 // If we got down to a scalar, insert a load or store as appropriate.
784 if (EltTy->isSingleValueType()) {
785 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
786 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
787 MI);
788 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
789 continue;
790 }
791 assert(isa<MemSetInst>(MI));
792
793 // If the stored element is zero (common case), just store a null
794 // constant.
795 Constant *StoreVal;
796 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
797 if (CI->isZero()) {
798 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
799 } else {
800 // If EltTy is a vector type, get the element type.
801 const Type *ValTy = EltTy;
802 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
803 ValTy = VTy->getElementType();
804
805 // Construct an integer with the right value.
806 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
807 APInt OneVal(EltSize, CI->getZExtValue());
808 APInt TotalVal(OneVal);
809 // Set each byte.
810 for (unsigned i = 0; 8*i < EltSize; ++i) {
811 TotalVal = TotalVal.shl(8);
812 TotalVal |= OneVal;
813 }
814
815 // Convert the integer value to the appropriate type.
816 StoreVal = ConstantInt::get(TotalVal);
817 if (isa<PointerType>(ValTy))
818 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
819 else if (ValTy->isFloatingPoint())
820 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
821 assert(StoreVal->getType() == ValTy && "Type mismatch!");
822
823 // If the requested value was a vector constant, create it.
824 if (EltTy != ValTy) {
825 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
826 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
827 StoreVal = ConstantVector::get(&Elts[0], NumElts);
828 }
829 }
830 new StoreInst(StoreVal, EltPtr, MI);
831 continue;
832 }
833 // Otherwise, if we're storing a byte variable, use a memset call for
834 // this element.
835 }
836
837 // Cast the element pointer to BytePtrTy.
838 if (EltPtr->getType() != BytePtrTy)
839 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
840
841 // Cast the other pointer (if we have one) to BytePtrTy.
842 if (OtherElt && OtherElt->getType() != BytePtrTy)
843 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
844 MI);
845
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000846 unsigned EltSize = TD->getTypePaddedSize(EltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000847
848 // Finally, insert the meminst for this element.
849 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
850 Value *Ops[] = {
851 SROADest ? EltPtr : OtherElt, // Dest ptr
852 SROADest ? OtherElt : EltPtr, // Src ptr
853 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
854 Zero // Align
855 };
856 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
857 } else {
858 assert(isa<MemSetInst>(MI));
859 Value *Ops[] = {
860 EltPtr, MI->getOperand(2), // Dest, Value,
861 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
862 Zero // Align
863 };
864 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
865 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 }
Chris Lattner71c75342009-01-07 08:11:13 +0000867 MI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000868}
Chris Lattner71c75342009-01-07 08:11:13 +0000869
870/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
871/// overwrites the entire allocation. Extract out the pieces of the stored
872/// integer and store them individually.
873void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
874 AllocationInst *AI,
875 SmallVector<AllocaInst*, 32> &NewElts){
876 // Extract each element out of the integer according to its structure offset
877 // and store the element value to the individual alloca.
878 Value *SrcVal = SI->getOperand(0);
879 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000880 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000881
Chris Lattner71c75342009-01-07 08:11:13 +0000882 // If this isn't a store of an integer to the whole alloca, it may be a store
883 // to the first element. Just ignore the store in this case and normal SROA
884 // will handle it.
885 if (!isa<IntegerType>(SrcVal->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000886 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner71c75342009-01-07 08:11:13 +0000887 return;
888
889 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
890
891 // There are two forms here: AI could be an array or struct. Both cases
892 // have different ways to compute the element offset.
893 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
894 const StructLayout *Layout = TD->getStructLayout(EltSTy);
895
896 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
897 // Get the number of bits to shift SrcVal to get the value.
898 const Type *FieldTy = EltSTy->getElementType(i);
899 uint64_t Shift = Layout->getElementOffsetInBits(i);
900
901 if (TD->isBigEndian())
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000902 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000903
904 Value *EltVal = SrcVal;
905 if (Shift) {
906 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
907 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
908 "sroa.store.elt", SI);
909 }
910
911 // Truncate down to an integer of the right size.
912 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000913
914 // Ignore zero sized fields like {}, they obviously contain no data.
915 if (FieldSizeBits == 0) continue;
916
Chris Lattner71c75342009-01-07 08:11:13 +0000917 if (FieldSizeBits != AllocaSizeBits)
918 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
919 Value *DestField = NewElts[i];
920 if (EltVal->getType() == FieldTy) {
921 // Storing to an integer field of this size, just do it.
922 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
923 // Bitcast to the right element type (for fp/vector values).
924 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
925 } else {
926 // Otherwise, bitcast the dest pointer (for aggregates).
927 DestField = new BitCastInst(DestField,
928 PointerType::getUnqual(EltVal->getType()),
929 "", SI);
930 }
931 new StoreInst(EltVal, DestField, SI);
932 }
933
934 } else {
935 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
936 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000937 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000938 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
939
940 uint64_t Shift;
941
942 if (TD->isBigEndian())
943 Shift = AllocaSizeBits-ElementOffset;
944 else
945 Shift = 0;
946
947 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000948 // Ignore zero sized fields like {}, they obviously contain no data.
949 if (ElementSizeBits == 0) continue;
Chris Lattner71c75342009-01-07 08:11:13 +0000950
951 Value *EltVal = SrcVal;
952 if (Shift) {
953 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
954 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
955 "sroa.store.elt", SI);
956 }
957
958 // Truncate down to an integer of the right size.
959 if (ElementSizeBits != AllocaSizeBits)
960 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
961 Value *DestField = NewElts[i];
962 if (EltVal->getType() == ArrayEltTy) {
963 // Storing to an integer field of this size, just do it.
964 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
965 // Bitcast to the right element type (for fp/vector values).
966 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
967 } else {
968 // Otherwise, bitcast the dest pointer (for aggregates).
969 DestField = new BitCastInst(DestField,
970 PointerType::getUnqual(EltVal->getType()),
971 "", SI);
972 }
973 new StoreInst(EltVal, DestField, SI);
974
975 if (TD->isBigEndian())
976 Shift -= ElementOffset;
977 else
978 Shift += ElementOffset;
979 }
980 }
981
982 SI->eraseFromParent();
983}
984
Chris Lattner28401db2009-01-08 05:42:05 +0000985/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
986/// an integer. Load the individual pieces to form the aggregate value.
987void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
988 SmallVector<AllocaInst*, 32> &NewElts) {
989 // Extract each element out of the NewElts according to its structure offset
990 // and form the result value.
991 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000992 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +0000993
994 // If this isn't a load of the whole alloca to an integer, it may be a load
995 // of the first element. Just ignore the load in this case and normal SROA
996 // will handle it.
997 if (!isa<IntegerType>(LI->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000998 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner28401db2009-01-08 05:42:05 +0000999 return;
1000
1001 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
1002
1003 // There are two forms here: AI could be an array or struct. Both cases
1004 // have different ways to compute the element offset.
1005 const StructLayout *Layout = 0;
1006 uint64_t ArrayEltBitOffset = 0;
1007 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1008 Layout = TD->getStructLayout(EltSTy);
1009 } else {
1010 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001011 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +00001012 }
1013
1014 Value *ResultVal = Constant::getNullValue(LI->getType());
1015
1016 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1017 // Load the value from the alloca. If the NewElt is an aggregate, cast
1018 // the pointer to an integer of the same size before doing the load.
1019 Value *SrcField = NewElts[i];
1020 const Type *FieldTy =
1021 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattnerf7a2f092009-01-09 18:18:43 +00001022 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1023
1024 // Ignore zero sized fields like {}, they obviously contain no data.
1025 if (FieldSizeBits == 0) continue;
1026
1027 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
Chris Lattner28401db2009-01-08 05:42:05 +00001028 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1029 !isa<VectorType>(FieldTy))
1030 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
1031 "", LI);
1032 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1033
1034 // If SrcField is a fp or vector of the right size but that isn't an
1035 // integer type, bitcast to an integer so we can shift it.
1036 if (SrcField->getType() != FieldIntTy)
1037 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1038
1039 // Zero extend the field to be the same size as the final alloca so that
1040 // we can shift and insert it.
1041 if (SrcField->getType() != ResultVal->getType())
1042 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1043
1044 // Determine the number of bits to shift SrcField.
1045 uint64_t Shift;
1046 if (Layout) // Struct case.
1047 Shift = Layout->getElementOffsetInBits(i);
1048 else // Array case.
1049 Shift = i*ArrayEltBitOffset;
1050
1051 if (TD->isBigEndian())
1052 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1053
1054 if (Shift) {
1055 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1056 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1057 }
1058
1059 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1060 }
1061
1062 LI->replaceAllUsesWith(ResultVal);
1063 LI->eraseFromParent();
1064}
1065
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066
Duncan Sandsae5fd622007-11-04 14:43:57 +00001067/// HasPadding - Return true if the specified type has any structure or
1068/// alignment padding, false otherwise.
Duncan Sands4afc5752008-06-04 08:21:45 +00001069static bool HasPadding(const Type *Ty, const TargetData &TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1071 const StructLayout *SL = TD.getStructLayout(STy);
1072 unsigned PrevFieldBitOffset = 0;
1073 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001074 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 // Padding in sub-elements?
Duncan Sands4afc5752008-06-04 08:21:45 +00001077 if (HasPadding(STy->getElementType(i), TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 return true;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001079
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 // Check to see if there is any padding between this element and the
1081 // previous one.
1082 if (i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001083 unsigned PrevFieldEnd =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1085 if (PrevFieldEnd < FieldBitOffset)
1086 return true;
1087 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001088
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 PrevFieldBitOffset = FieldBitOffset;
1090 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001091
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 // Check for tail padding.
1093 if (unsigned EltCount = STy->getNumElements()) {
1094 unsigned PrevFieldEnd = PrevFieldBitOffset +
1095 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sandsae5fd622007-11-04 14:43:57 +00001096 if (PrevFieldEnd < SL->getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 return true;
1098 }
1099
1100 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001101 return HasPadding(ATy->getElementType(), TD);
Duncan Sandsae5fd622007-11-04 14:43:57 +00001102 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001103 return HasPadding(VTy->getElementType(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104 }
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001105 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106}
1107
1108/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1109/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1110/// or 1 if safe after canonicalization has been performed.
1111///
1112int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1113 // Loop over the use list of the alloca. We can only transform it if all of
1114 // the users are safe to transform.
1115 AllocaInfo Info;
1116
1117 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1118 I != E; ++I) {
1119 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1120 if (Info.isUnsafe) {
1121 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1122 return 0;
1123 }
1124 }
1125
1126 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1127 // source and destination, we have to be careful. In particular, the memcpy
1128 // could be moving around elements that live in structure padding of the LLVM
1129 // types, but may actually be used. In these cases, we refuse to promote the
1130 // struct.
1131 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner3fd59362009-01-07 06:34:28 +00001132 HasPadding(AI->getType()->getElementType(), *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 return 0;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001134
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135 // If we require cleanup, return 1, otherwise return 3.
Devang Patel83637b12009-02-10 07:00:59 +00001136 return Info.needsCleanup ? 1 : 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137}
1138
Devang Patel83637b12009-02-10 07:00:59 +00001139/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1140/// is canonicalized here.
1141void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1142 gep_type_iterator I = gep_type_begin(GEPI);
1143 ++I;
1144
Devang Pateleb5423c2009-02-10 19:28:07 +00001145 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1146 if (!AT)
1147 return;
1148
1149 uint64_t NumElements = AT->getNumElements();
1150
1151 if (isa<ConstantInt>(I.getOperand()))
1152 return;
1153
1154 if (NumElements == 1) {
1155 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1156 return;
1157 }
Devang Patel83637b12009-02-10 07:00:59 +00001158
Devang Pateleb5423c2009-02-10 19:28:07 +00001159 assert(NumElements == 2 && "Unhandled case!");
1160 // All users of the GEP must be loads. At each use of the GEP, insert
1161 // two loads of the appropriate indexed GEP and select between them.
1162 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1163 Constant::getNullValue(I.getOperand()->getType()),
1164 "isone", GEPI);
1165 // Insert the new GEP instructions, which are properly indexed.
1166 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1167 Indices[1] = Constant::getNullValue(Type::Int32Ty);
1168 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1169 Indices.begin(),
1170 Indices.end(),
1171 GEPI->getName()+".0", GEPI);
1172 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
1173 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1174 Indices.begin(),
1175 Indices.end(),
1176 GEPI->getName()+".1", GEPI);
1177 // Replace all loads of the variable index GEP with loads from both
1178 // indexes and a select.
1179 while (!GEPI->use_empty()) {
1180 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1181 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1182 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1183 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1184 LI->replaceAllUsesWith(R);
1185 LI->eraseFromParent();
Devang Patel83637b12009-02-10 07:00:59 +00001186 }
Devang Pateleb5423c2009-02-10 19:28:07 +00001187 GEPI->eraseFromParent();
Devang Patel83637b12009-02-10 07:00:59 +00001188}
1189
Devang Pateleb5423c2009-02-10 19:28:07 +00001190
Devang Patel83637b12009-02-10 07:00:59 +00001191/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192/// allocation, but only if cleaned up, perform the cleanups required.
Devang Patel83637b12009-02-10 07:00:59 +00001193void SROA::CleanupAllocaUsers(AllocationInst *AI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 // At this point, we know that the end result will be SROA'd and promoted, so
1195 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1196 // up.
1197 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1198 UI != E; ) {
Devang Patel83637b12009-02-10 07:00:59 +00001199 User *U = *UI++;
1200 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1201 CleanupGEP(GEPI);
1202 else if (Instruction *I = dyn_cast<Instruction>(U)) {
1203 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1204 if (OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1205 // Safe to remove debug info uses.
1206 while (!DbgInUses.empty()) {
1207 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1208 DI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 }
Devang Patel83637b12009-02-10 07:00:59 +00001210 I->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 }
1212 }
1213 }
1214}
1215
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001216/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1217/// the offset specified by Offset (which is specified in bytes).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218///
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001219/// There are two cases we handle here:
1220/// 1) A union of vector types of the same size and potentially its elements.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001221/// Here we turn element accesses into insert/extract element operations.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001222/// This promotes a <4 x float> with a store of float to the third element
1223/// into a <4 x float> that uses insert element.
1224/// 2) A fully general blob of memory, which we turn into some (potentially
1225/// large) integer type with extract and insert operations where the loads
1226/// and stores would mutate the memory.
Chris Lattnerf235a322009-02-03 01:30:09 +00001227static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1228 unsigned AllocaSize, const TargetData &TD) {
1229 // If this could be contributing to a vector, analyze it.
1230 if (VecTy != Type::VoidTy) { // either null or a vector type.
Chris Lattnerc2a5f2a2009-02-02 18:02:59 +00001231
Chris Lattnerf235a322009-02-03 01:30:09 +00001232 // If the In type is a vector that is the same size as the alloca, see if it
1233 // matches the existing VecTy.
1234 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1235 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1236 // If we're storing/loading a vector of the right size, allow it as a
1237 // vector. If this the first vector we see, remember the type so that
1238 // we know the element size.
1239 if (VecTy == 0)
1240 VecTy = VInTy;
1241 return;
1242 }
1243 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1244 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1245 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1246 // If we're accessing something that could be an element of a vector, see
1247 // if the implied vector agrees with what we already have and if Offset is
1248 // compatible with it.
1249 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1250 if (Offset % EltSize == 0 &&
1251 AllocaSize % EltSize == 0 &&
1252 (VecTy == 0 ||
1253 cast<VectorType>(VecTy)->getElementType()
1254 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1255 if (VecTy == 0)
1256 VecTy = VectorType::get(In, AllocaSize/EltSize);
1257 return;
1258 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001259 }
1260 }
1261
Chris Lattnerf235a322009-02-03 01:30:09 +00001262 // Otherwise, we have a case that we can't handle with an optimized vector
1263 // form. We can still turn this into a large integer.
1264 VecTy = Type::VoidTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265}
1266
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001267/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattnerf235a322009-02-03 01:30:09 +00001268/// its accesses to use a to single vector type, return true, and set VecTy to
1269/// the new type. If we could convert the alloca into a single promotable
1270/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1271/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1272/// is the current offset from the base of the alloca being analyzed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273///
Chris Lattner38088d12009-02-03 18:15:05 +00001274/// If we see at least one access to the value that is as a vector type, set the
1275/// SawVec flag.
1276///
1277bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1278 bool &SawVec, uint64_t Offset,
Chris Lattnerf235a322009-02-03 01:30:09 +00001279 unsigned AllocaSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1281 Instruction *User = cast<Instruction>(*UI);
1282
1283 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001284 // Don't break volatile loads.
Chris Lattner70ffe572009-01-28 20:16:43 +00001285 if (LI->isVolatile())
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001286 return false;
Chris Lattnerf235a322009-02-03 01:30:09 +00001287 MergeInType(LI->getType(), Offset, VecTy, AllocaSize, *TD);
Chris Lattner38088d12009-02-03 18:15:05 +00001288 SawVec |= isa<VectorType>(LI->getType());
Chris Lattner7cc97712009-01-07 06:39:58 +00001289 continue;
1290 }
1291
1292 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 // Storing the pointer, not into the value?
Chris Lattner70ffe572009-01-28 20:16:43 +00001294 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Chris Lattnerf235a322009-02-03 01:30:09 +00001295 MergeInType(SI->getOperand(0)->getType(), Offset, VecTy, AllocaSize, *TD);
Chris Lattner38088d12009-02-03 18:15:05 +00001296 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattner7cc97712009-01-07 06:39:58 +00001297 continue;
1298 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001299
1300 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner38088d12009-02-03 18:15:05 +00001301 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1302 AllocaSize))
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001303 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 IsNotTrivial = true;
Chris Lattner7cc97712009-01-07 06:39:58 +00001305 continue;
1306 }
1307
1308 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001309 // If this is a GEP with a variable indices, we can't handle it.
1310 if (!GEP->hasAllConstantIndices())
1311 return false;
Chris Lattner7cc97712009-01-07 06:39:58 +00001312
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001313 // Compute the offset that this GEP adds to the pointer.
1314 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1315 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1316 &Indices[0], Indices.size());
1317 // See if all uses can be converted.
Chris Lattner38088d12009-02-03 18:15:05 +00001318 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattnerf235a322009-02-03 01:30:09 +00001319 AllocaSize))
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001320 return false;
1321 IsNotTrivial = true;
1322 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001324
Chris Lattnerfece0da2009-02-03 02:01:43 +00001325 // If this is a constant sized memset of a constant value (e.g. 0) we can
1326 // handle it.
1327 if (isa<MemSetInst>(User) &&
1328 // Store of constant value.
1329 isa<ConstantInt>(User->getOperand(2)) &&
1330 // Store with constant size.
1331 isa<ConstantInt>(User->getOperand(3))) {
1332 VecTy = Type::VoidTy;
1333 IsNotTrivial = true;
1334 continue;
1335 }
1336
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001337 // Otherwise, we cannot handle this!
1338 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339 }
1340
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001341 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342}
1343
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344
1345/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1346/// directly. This happens when we are converting an "integer union" to a
1347/// single integer scalar, or when we are converting a "vector union" to a
1348/// vector with insert/extractelement instructions.
1349///
1350/// Offset is an offset from the original alloca, in bits that need to be
1351/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001352void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 while (!Ptr->use_empty()) {
1354 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands641f12c2009-02-02 10:06:20 +00001355
Chris Lattner7cc97712009-01-07 06:39:58 +00001356 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb1534532008-01-30 00:39:15 +00001357 ConvertUsesToScalar(CI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358 CI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001359 continue;
1360 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001361
Chris Lattner7cc97712009-01-07 06:39:58 +00001362 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001363 // Compute the offset that this GEP adds to the pointer.
1364 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1365 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1366 &Indices[0], Indices.size());
1367 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 GEP->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001369 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 }
Chris Lattnerfece0da2009-02-03 02:01:43 +00001371
Chris Lattnerececb0c2009-02-03 19:45:44 +00001372 IRBuilder<> Builder(User->getParent(), User);
1373
1374 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001375 // The load is a bit extract from NewAI shifted right by Offset bits.
1376 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1377 Value *NewLoadVal
1378 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1379 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattnerececb0c2009-02-03 19:45:44 +00001380 LI->eraseFromParent();
1381 continue;
1382 }
1383
1384 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1385 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1386 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1387 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1388 Builder);
1389 Builder.CreateStore(New, NewAI);
1390 SI->eraseFromParent();
1391 continue;
1392 }
1393
Chris Lattnerfece0da2009-02-03 02:01:43 +00001394 // If this is a constant sized memset of a constant value (e.g. 0) we can
1395 // transform it into a store of the expanded constant value.
1396 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1397 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1398 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1399 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1400
1401 // Compute the value replicated the right number of times.
1402 APInt APVal(NumBytes*8, Val);
1403
1404 // Splat the value if non-zero.
1405 if (Val)
1406 for (unsigned i = 1; i != NumBytes; ++i)
1407 APVal |= APVal << 8;
1408
Chris Lattner32c19282009-02-03 19:41:50 +00001409 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
Chris Lattnercc0727c2009-02-03 19:30:11 +00001410 Value *New = ConvertScalar_InsertValue(ConstantInt::get(APVal), Old,
Chris Lattner32c19282009-02-03 19:41:50 +00001411 Offset, Builder);
1412 Builder.CreateStore(New, NewAI);
Chris Lattnerfece0da2009-02-03 02:01:43 +00001413 MSI->eraseFromParent();
1414 continue;
1415 }
1416
1417
Chris Lattner7cc97712009-01-07 06:39:58 +00001418 assert(0 && "Unsupported operation!");
1419 abort();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420 }
1421}
1422
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001423/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1424/// or vector value FromVal, extracting the bits from the offset specified by
1425/// Offset. This returns the value, which is of type ToType.
1426///
1427/// This happens when we are converting an "integer union" to a single
Duncan Sands641f12c2009-02-02 10:06:20 +00001428/// integer scalar, or when we are converting a "vector union" to a vector with
1429/// insert/extractelement instructions.
Chris Lattner41d58652008-02-29 07:03:13 +00001430///
Duncan Sands641f12c2009-02-02 10:06:20 +00001431/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001432/// shifted to the right.
1433Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1434 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001435 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001436 if (FromVal->getType() == ToType && Offset == 0)
1437 return FromVal;
Chris Lattner5f062542008-02-29 07:12:06 +00001438
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001439 // If the result alloca is a vector type, this is either an element
1440 // access or a bitcast to another vector type of the same size.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001441 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1442 if (isa<VectorType>(ToType))
1443 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner5f062542008-02-29 07:12:06 +00001444
1445 // Otherwise it must be an element access.
Chris Lattner5f062542008-02-29 07:12:06 +00001446 unsigned Elt = 0;
1447 if (Offset) {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001448 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType());
Chris Lattner5f062542008-02-29 07:12:06 +00001449 Elt = Offset/EltSize;
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001450 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner41d58652008-02-29 07:03:13 +00001451 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001452 // Return the element extracted out of it.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001453 Value *V = Builder.CreateExtractElement(FromVal,
Chris Lattnerececb0c2009-02-03 19:45:44 +00001454 ConstantInt::get(Type::Int32Ty,Elt),
1455 "tmp");
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001456 if (V->getType() != ToType)
1457 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001458 return V;
Chris Lattner5f062542008-02-29 07:12:06 +00001459 }
Chris Lattner7bac66b2009-02-03 21:08:45 +00001460
1461 // If ToType is a first class aggregate, extract out each of the pieces and
1462 // use insertvalue's to form the FCA.
1463 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1464 const StructLayout &Layout = *TD->getStructLayout(ST);
1465 Value *Res = UndefValue::get(ST);
1466 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1467 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattner97e1f382009-02-06 04:34:07 +00001468 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner7bac66b2009-02-03 21:08:45 +00001469 Builder);
1470 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1471 }
1472 return Res;
1473 }
1474
1475 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1476 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1477 Value *Res = UndefValue::get(AT);
1478 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1479 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1480 Offset+i*EltSize, Builder);
1481 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1482 }
1483 return Res;
1484 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001485
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001486 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001487 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands641f12c2009-02-02 10:06:20 +00001488
Chris Lattner5f062542008-02-29 07:12:06 +00001489 // If this is a big-endian system and the load is narrower than the
1490 // full alloca type, we need to do a shift to get the right bits.
1491 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001492 if (TD->isBigEndian()) {
Chris Lattner5f062542008-02-29 07:12:06 +00001493 // On big-endian machines, the lowest bit is stored at the bit offset
1494 // from the pointer given by getTypeStoreSizeInBits. This matters for
1495 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner3fd59362009-01-07 06:34:28 +00001496 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001497 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner5f062542008-02-29 07:12:06 +00001498 } else {
1499 ShAmt = Offset;
1500 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001501
Chris Lattner5f062542008-02-29 07:12:06 +00001502 // Note: we support negative bitwidths (with shl) which are not defined.
1503 // We do this to support (f.e.) loads off the end of a structure where
1504 // only some bits are used.
1505 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Chris Lattner7bac66b2009-02-03 21:08:45 +00001506 FromVal = Builder.CreateLShr(FromVal, ConstantInt::get(FromVal->getType(),
1507 ShAmt), "tmp");
Chris Lattner5f062542008-02-29 07:12:06 +00001508 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Chris Lattner7bac66b2009-02-03 21:08:45 +00001509 FromVal = Builder.CreateShl(FromVal, ConstantInt::get(FromVal->getType(),
1510 -ShAmt), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001511
Chris Lattner5f062542008-02-29 07:12:06 +00001512 // Finally, unconditionally truncate the integer to the right width.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001513 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner5f062542008-02-29 07:12:06 +00001514 if (LIBitWidth < NTy->getBitWidth())
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001515 FromVal = Builder.CreateTrunc(FromVal, IntegerType::get(LIBitWidth), "tmp");
Chris Lattnerb2290a12009-02-03 07:08:57 +00001516 else if (LIBitWidth > NTy->getBitWidth())
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001517 FromVal = Builder.CreateZExt(FromVal, IntegerType::get(LIBitWidth), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001518
Chris Lattner5f062542008-02-29 07:12:06 +00001519 // If the result is an integer, this is a trunc or bitcast.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001520 if (isa<IntegerType>(ToType)) {
Chris Lattner5f062542008-02-29 07:12:06 +00001521 // Should be done.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001522 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner5f062542008-02-29 07:12:06 +00001523 // Just do a bitcast, we know the sizes match up.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001524 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001525 } else {
Chris Lattner5f062542008-02-29 07:12:06 +00001526 // Otherwise must be a pointer.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001527 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001528 }
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001529 assert(FromVal->getType() == ToType && "Didn't convert right?");
1530 return FromVal;
Chris Lattner41d58652008-02-29 07:03:13 +00001531}
1532
1533
Chris Lattnercc0727c2009-02-03 19:30:11 +00001534/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1535/// or vector value "Old" at the offset specified by Offset.
1536///
1537/// This happens when we are converting an "integer union" to a
Chris Lattner41d58652008-02-29 07:03:13 +00001538/// single integer scalar, or when we are converting a "vector union" to a
1539/// vector with insert/extractelement instructions.
1540///
1541/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnercc0727c2009-02-03 19:30:11 +00001542/// shifted to the right.
1543Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner32c19282009-02-03 19:41:50 +00001544 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands641f12c2009-02-02 10:06:20 +00001545
Chris Lattner41d58652008-02-29 07:03:13 +00001546 // Convert the stored type to the actual type, shift it left to insert
1547 // then 'or' into place.
Chris Lattnercc0727c2009-02-03 19:30:11 +00001548 const Type *AllocaType = Old->getType();
Duncan Sands641f12c2009-02-02 10:06:20 +00001549
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001550 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner41d58652008-02-29 07:03:13 +00001551 // If the result alloca is a vector type, this is either an element
1552 // access or a bitcast to another vector type.
1553 if (isa<VectorType>(SV->getType())) {
Chris Lattner32c19282009-02-03 19:41:50 +00001554 SV = Builder.CreateBitCast(SV, AllocaType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001555 } else {
1556 // Must be an element insertion.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001557 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(VTy->getElementType());
Chris Lattnerf235a322009-02-03 01:30:09 +00001558
1559 if (SV->getType() != VTy->getElementType())
Chris Lattner32c19282009-02-03 19:41:50 +00001560 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001561
Chris Lattner32c19282009-02-03 19:41:50 +00001562 SV = Builder.CreateInsertElement(Old, SV,
1563 ConstantInt::get(Type::Int32Ty, Elt),
1564 "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001565 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001566 return SV;
1567 }
Chris Lattnercc0727c2009-02-03 19:30:11 +00001568
1569 // If SV is a first-class aggregate value, insert each value recursively.
1570 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1571 const StructLayout &Layout = *TD->getStructLayout(ST);
1572 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner32c19282009-02-03 19:41:50 +00001573 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattnercc0727c2009-02-03 19:30:11 +00001574 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner97e1f382009-02-06 04:34:07 +00001575 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner32c19282009-02-03 19:41:50 +00001576 Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +00001577 }
1578 return Old;
1579 }
1580
1581 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1582 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1583 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner32c19282009-02-03 19:41:50 +00001584 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1585 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +00001586 }
1587 return Old;
1588 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001589
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001590 // If SV is a float, convert it to the appropriate integer type.
Chris Lattnercc0727c2009-02-03 19:30:11 +00001591 // If it is a pointer, do the same.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001592 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1593 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1594 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1595 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1596 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Chris Lattner32c19282009-02-03 19:41:50 +00001597 SV = Builder.CreateBitCast(SV, IntegerType::get(SrcWidth), "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001598 else if (isa<PointerType>(SV->getType()))
Chris Lattner32c19282009-02-03 19:41:50 +00001599 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001600
Chris Lattnerf235a322009-02-03 01:30:09 +00001601 // Zero extend or truncate the value if needed.
1602 if (SV->getType() != AllocaType) {
1603 if (SV->getType()->getPrimitiveSizeInBits() <
1604 AllocaType->getPrimitiveSizeInBits())
Chris Lattner32c19282009-02-03 19:41:50 +00001605 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001606 else {
1607 // Truncation may be needed if storing more than the alloca can hold
1608 // (undefined behavior).
Chris Lattner32c19282009-02-03 19:41:50 +00001609 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001610 SrcWidth = DestWidth;
1611 SrcStoreWidth = DestStoreWidth;
1612 }
1613 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001614
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001615 // If this is a big-endian system and the store is narrower than the
1616 // full alloca type, we need to do a shift to get the right bits.
1617 int ShAmt = 0;
1618 if (TD->isBigEndian()) {
1619 // On big-endian machines, the lowest bit is stored at the bit offset
1620 // from the pointer given by getTypeStoreSizeInBits. This matters for
1621 // integers with a bitwidth that is not a multiple of 8.
1622 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner41d58652008-02-29 07:03:13 +00001623 } else {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001624 ShAmt = Offset;
1625 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001626
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001627 // Note: we support negative bitwidths (with shr) which are not defined.
1628 // We do this to support (f.e.) stores off the end of a structure where
1629 // only some bits in the structure are set.
1630 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1631 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Chris Lattner32c19282009-02-03 19:41:50 +00001632 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt), "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001633 Mask <<= ShAmt;
1634 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Chris Lattner32c19282009-02-03 19:41:50 +00001635 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt), "tmp");
Duncan Sandsced29632009-02-02 09:53:14 +00001636 Mask = Mask.lshr(-ShAmt);
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001637 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001638
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001639 // Mask out the bits we are about to insert from the old value, and or
1640 // in the new bits.
1641 if (SrcWidth != DestWidth) {
1642 assert(DestWidth > SrcWidth);
Chris Lattner32c19282009-02-03 19:41:50 +00001643 Old = Builder.CreateAnd(Old, ConstantInt::get(~Mask), "mask");
1644 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner41d58652008-02-29 07:03:13 +00001645 }
1646 return SV;
1647}
1648
1649
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001650
1651/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1652/// some part of a constant global variable. This intentionally only accepts
1653/// constant expressions because we don't can't rewrite arbitrary instructions.
1654static bool PointsToConstantGlobal(Value *V) {
1655 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1656 return GV->isConstant();
1657 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1658 if (CE->getOpcode() == Instruction::BitCast ||
1659 CE->getOpcode() == Instruction::GetElementPtr)
1660 return PointsToConstantGlobal(CE->getOperand(0));
1661 return false;
1662}
1663
1664/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1665/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1666/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1667/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1668/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1669/// the alloca, and if the source pointer is a pointer to a constant global, we
1670/// can optimize this.
1671static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1672 bool isOffset) {
1673 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner70ffe572009-01-28 20:16:43 +00001674 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1675 // Ignore non-volatile loads, they are always ok.
1676 if (!LI->isVolatile())
1677 continue;
1678
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1680 // If uses of the bitcast are ok, we are ok.
1681 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1682 return false;
1683 continue;
1684 }
1685 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1686 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1687 // doesn't, it does.
1688 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1689 isOffset || !GEP->hasAllZeroIndices()))
1690 return false;
1691 continue;
1692 }
1693
1694 // If this is isn't our memcpy/memmove, reject it as something we can't
1695 // handle.
1696 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1697 return false;
1698
1699 // If we already have seen a copy, reject the second one.
1700 if (TheCopy) return false;
1701
1702 // If the pointer has been offset from the start of the alloca, we can't
1703 // safely handle this.
1704 if (isOffset) return false;
1705
1706 // If the memintrinsic isn't using the alloca as the dest, reject it.
1707 if (UI.getOperandNo() != 1) return false;
1708
1709 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1710
1711 // If the source of the memcpy/move is not a constant global, reject it.
1712 if (!PointsToConstantGlobal(MI->getOperand(2)))
1713 return false;
1714
1715 // Otherwise, the transform is safe. Remember the copy instruction.
1716 TheCopy = MI;
1717 }
1718 return true;
1719}
1720
1721/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1722/// modified by a copy from a constant global. If we can prove this, we can
1723/// replace any uses of the alloca with uses of the global directly.
1724Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1725 Instruction *TheCopy = 0;
1726 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1727 return TheCopy;
1728 return 0;
1729}