blob: c1c8e0387cf6e58d5d7e628956b4e8ea27c934d9 [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"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner32c19282009-02-03 19:41:50 +000036#include "llvm/Support/IRBuilder.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Support/MathExtras.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/StringExtras.h"
42using namespace llvm;
43
44STATISTIC(NumReplaced, "Number of allocas broken up");
45STATISTIC(NumPromoted, "Number of allocas promoted");
46STATISTIC(NumConverted, "Number of aggregates converted to scalar");
47STATISTIC(NumGlobals, "Number of allocas copied from constant global");
48
49namespace {
50 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
51 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000052 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053 if (T == -1)
Chris Lattner6d7faec2007-08-02 21:33:36 +000054 SRThreshold = 128;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 else
56 SRThreshold = T;
57 }
58
59 bool runOnFunction(Function &F);
60
61 bool performScalarRepl(Function &F);
62 bool performPromotion(Function &F);
63
64 // getAnalysisUsage - This pass does not require any passes, but we know it
65 // will not alter the CFG, so say so.
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<DominatorTree>();
68 AU.addRequired<DominanceFrontier>();
69 AU.addRequired<TargetData>();
70 AU.setPreservesCFG();
71 }
72
73 private:
Chris Lattner3fd59362009-01-07 06:34:28 +000074 TargetData *TD;
75
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
77 /// information about the uses. All these fields are initialized to false
78 /// and set to true when something is learned.
79 struct AllocaInfo {
80 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
81 bool isUnsafe : 1;
82
83 /// needsCanon - This is set to true if there is some use of the alloca
84 /// that requires canonicalization.
85 bool needsCanon : 1;
86
87 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
88 bool isMemCpySrc : 1;
89
90 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
91 bool isMemCpyDst : 1;
92
93 AllocaInfo()
94 : isUnsafe(false), needsCanon(false),
95 isMemCpySrc(false), isMemCpyDst(false) {}
96 };
97
98 unsigned SRThreshold;
99
100 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
101
102 int isSafeAllocaToScalarRepl(AllocationInst *AI);
103
104 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
105 AllocaInfo &Info);
106 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
107 AllocaInfo &Info);
108 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
109 unsigned OpNo, AllocaInfo &Info);
110 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
111 AllocaInfo &Info);
112
113 void DoScalarReplacement(AllocationInst *AI,
114 std::vector<AllocationInst*> &WorkList);
115 void CanonicalizeAllocaUsers(AllocationInst *AI);
116 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
117
118 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
119 SmallVector<AllocaInst*, 32> &NewElts);
120
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000121 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
122 AllocationInst *AI,
123 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000124 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
125 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner28401db2009-01-08 05:42:05 +0000126 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattner70ffe572009-01-28 20:16:43 +0000127 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000128
Chris Lattnerf235a322009-02-03 01:30:09 +0000129 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner38088d12009-02-03 18:15:05 +0000130 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000131 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattnerf73a10e2009-02-03 21:01:03 +0000132 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattnerececb0c2009-02-03 19:45:44 +0000133 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +0000134 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner32c19282009-02-03 19:41:50 +0000135 uint64_t Offset, IRBuilder<> &Builder);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
137 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138}
139
Dan Gohman089efff2008-05-13 00:00:25 +0000140char SROA::ID = 0;
141static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
142
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143// Public interface to the ScalarReplAggregates pass
144FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
145 return new SROA(Threshold);
146}
147
148
149bool SROA::runOnFunction(Function &F) {
Chris Lattner3fd59362009-01-07 06:34:28 +0000150 TD = &getAnalysis<TargetData>();
151
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152 bool Changed = performPromotion(F);
153 while (1) {
154 bool LocalChange = performScalarRepl(F);
155 if (!LocalChange) break; // No need to repromote if no scalarrepl
156 Changed = true;
157 LocalChange = performPromotion(F);
158 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
159 }
160
161 return Changed;
162}
163
164
165bool SROA::performPromotion(Function &F) {
166 std::vector<AllocaInst*> Allocas;
167 DominatorTree &DT = getAnalysis<DominatorTree>();
168 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
169
170 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
171
172 bool Changed = false;
173
174 while (1) {
175 Allocas.clear();
176
177 // Find allocas that are safe to promote, by looking at all instructions in
178 // the entry node
179 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
180 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
181 if (isAllocaPromotable(AI))
182 Allocas.push_back(AI);
183
184 if (Allocas.empty()) break;
185
186 PromoteMemToReg(Allocas, DT, DF);
187 NumPromoted += Allocas.size();
188 Changed = true;
189 }
190
191 return Changed;
192}
193
Chris Lattner0e99e692008-06-22 17:46:21 +0000194/// getNumSAElements - Return the number of elements in the specific struct or
195/// array.
196static uint64_t getNumSAElements(const Type *T) {
197 if (const StructType *ST = dyn_cast<StructType>(T))
198 return ST->getNumElements();
199 return cast<ArrayType>(T)->getNumElements();
200}
201
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202// performScalarRepl - This algorithm is a simple worklist driven algorithm,
203// which runs on all of the malloc/alloca instructions in the function, removing
204// them if they are only used by getelementptr instructions.
205//
206bool SROA::performScalarRepl(Function &F) {
207 std::vector<AllocationInst*> WorkList;
208
209 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
210 BasicBlock &BB = F.getEntryBlock();
211 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
212 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
213 WorkList.push_back(A);
214
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 // Process the worklist
216 bool Changed = false;
217 while (!WorkList.empty()) {
218 AllocationInst *AI = WorkList.back();
219 WorkList.pop_back();
220
221 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
222 // with unused elements.
223 if (AI->use_empty()) {
224 AI->eraseFromParent();
225 continue;
226 }
Chris Lattnerf235a322009-02-03 01:30:09 +0000227
228 // If this alloca is impossible for us to promote, reject it early.
229 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
230 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231
232 // Check to see if this allocation is only modified by a memcpy/memmove from
233 // a constant global. If this is the case, we can change all users to use
234 // the constant global instead. This is commonly produced by the CFE by
235 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
236 // is only subsequently read.
237 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
238 DOUT << "Found alloca equal to global: " << *AI;
239 DOUT << " memcpy = " << *TheCopy;
240 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
241 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
242 TheCopy->eraseFromParent(); // Don't mutate the global.
243 AI->eraseFromParent();
244 ++NumGlobals;
245 Changed = true;
246 continue;
247 }
Chris Lattner05ebfd72009-02-02 20:44:45 +0000248
Chris Lattnerf235a322009-02-03 01:30:09 +0000249 // Check to see if we can perform the core SROA transformation. We cannot
250 // transform the allocation instruction if it is an array allocation
251 // (allocations OF arrays are ok though), and an allocation of a scalar
252 // value cannot be decomposed at all.
253 uint64_t AllocaSize = TD->getTypePaddedSize(AI->getAllocatedType());
254
255 if ((isa<StructType>(AI->getAllocatedType()) ||
256 isa<ArrayType>(AI->getAllocatedType())) &&
257 // Do not promote any struct whose size is too big.
258 AllocaSize < SRThreshold &&
259 // Do not promote any struct into more than "32" separate vars.
260 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
261 // Check that all of the users of the allocation are capable of being
262 // transformed.
263 switch (isSafeAllocaToScalarRepl(AI)) {
264 default: assert(0 && "Unexpected value!");
265 case 0: // Not safe to scalar replace.
266 break;
267 case 1: // Safe, but requires cleanup/canonicalizations first
268 CanonicalizeAllocaUsers(AI);
269 // FALL THROUGH.
270 case 3: // Safe to scalar replace.
271 DoScalarReplacement(AI, WorkList);
272 Changed = true;
273 continue;
274 }
275 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000276
277 // If we can turn this aggregate value (potentially with casts) into a
278 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner4b9c8b72009-01-31 02:28:54 +0000279 // IsNotTrivial tracks whether this is something that mem2reg could have
280 // promoted itself. If so, we don't want to transform it needlessly. Note
281 // that we can't just check based on the type: the alloca may be of an i32
282 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner70ffe572009-01-28 20:16:43 +0000283 bool IsNotTrivial = false;
Chris Lattnerf235a322009-02-03 01:30:09 +0000284 const Type *VectorTy = 0;
Chris Lattner38088d12009-02-03 18:15:05 +0000285 bool HadAVector = false;
286 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattnerf235a322009-02-03 01:30:09 +0000287 0, unsigned(AllocaSize)) && IsNotTrivial) {
288 AllocaInst *NewAI;
Chris Lattner38088d12009-02-03 18:15:05 +0000289 // If we were able to find a vector type that can handle this with
290 // insert/extract elements, and if there was at least one use that had
291 // a vector type, promote this to a vector. We don't want to promote
292 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
293 // we just get a lot of insert/extracts. If at least one vector is
294 // involved, then we probably really do have a union of vector/array.
295 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Chris Lattnerf235a322009-02-03 01:30:09 +0000296 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
Chris Lattner05ebfd72009-02-02 20:44:45 +0000297
Chris Lattnerf235a322009-02-03 01:30:09 +0000298 // Create and insert the vector alloca.
299 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner05ebfd72009-02-02 20:44:45 +0000300 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattnerf235a322009-02-03 01:30:09 +0000301 } else {
302 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
303
304 // Create and insert the integer alloca.
305 const Type *NewTy = IntegerType::get(AllocaSize*8);
306 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
307 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner70ffe572009-01-28 20:16:43 +0000308 }
Chris Lattnerf235a322009-02-03 01:30:09 +0000309 NewAI->takeName(AI);
310 AI->eraseFromParent();
311 ++NumConverted;
312 Changed = true;
313 continue;
314 }
Chris Lattner70ffe572009-01-28 20:16:43 +0000315
Chris Lattnerf235a322009-02-03 01:30:09 +0000316 // Otherwise, couldn't process this alloca.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 }
318
319 return Changed;
320}
321
322/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
323/// predicate, do SROA now.
324void SROA::DoScalarReplacement(AllocationInst *AI,
325 std::vector<AllocationInst*> &WorkList) {
326 DOUT << "Found inst to SROA: " << *AI;
327 SmallVector<AllocaInst*, 32> ElementAllocas;
328 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
329 ElementAllocas.reserve(ST->getNumContainedTypes());
330 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
331 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
332 AI->getAlignment(),
333 AI->getName() + "." + utostr(i), AI);
334 ElementAllocas.push_back(NA);
335 WorkList.push_back(NA); // Add to worklist for recursive processing
336 }
337 } else {
338 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
339 ElementAllocas.reserve(AT->getNumElements());
340 const Type *ElTy = AT->getElementType();
341 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
342 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
343 AI->getName() + "." + utostr(i), AI);
344 ElementAllocas.push_back(NA);
345 WorkList.push_back(NA); // Add to worklist for recursive processing
346 }
347 }
348
349 // Now that we have created the alloca instructions that we want to use,
350 // expand the getelementptr instructions to use them.
351 //
352 while (!AI->use_empty()) {
353 Instruction *User = cast<Instruction>(AI->use_back());
354 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
355 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
356 BCInst->eraseFromParent();
357 continue;
358 }
359
Chris Lattner19e61a42008-06-23 17:11:23 +0000360 // Replace:
361 // %res = load { i32, i32 }* %alloc
362 // with:
363 // %load.0 = load i32* %alloc.0
364 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
365 // %load.1 = load i32* %alloc.1
366 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000367 // (Also works for arrays instead of structs)
368 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
369 Value *Insert = UndefValue::get(LI->getType());
370 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
371 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
372 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
373 }
374 LI->replaceAllUsesWith(Insert);
375 LI->eraseFromParent();
376 continue;
377 }
378
Chris Lattner19e61a42008-06-23 17:11:23 +0000379 // Replace:
380 // store { i32, i32 } %val, { i32, i32 }* %alloc
381 // with:
382 // %val.0 = extractvalue { i32, i32 } %val, 0
383 // store i32 %val.0, i32* %alloc.0
384 // %val.1 = extractvalue { i32, i32 } %val, 1
385 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000386 // (Also works for arrays instead of structs)
387 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
388 Value *Val = SI->getOperand(0);
389 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
390 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
391 new StoreInst(Extract, ElementAllocas[i], SI);
392 }
393 SI->eraseFromParent();
394 continue;
395 }
396
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
398 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
399 unsigned Idx =
400 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
401
402 assert(Idx < ElementAllocas.size() && "Index out of range?");
403 AllocaInst *AllocaToUse = ElementAllocas[Idx];
404
405 Value *RepValue;
406 if (GEPI->getNumOperands() == 3) {
407 // Do not insert a new getelementptr instruction with zero indices, only
408 // to have it optimized out later.
409 RepValue = AllocaToUse;
410 } else {
411 // We are indexing deeply into the structure, so we still need a
412 // getelement ptr instruction to finish the indexing. This may be
413 // expanded itself once the worklist is rerun.
414 //
415 SmallVector<Value*, 8> NewArgs;
416 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
417 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greifd6da1d02008-04-06 20:25:17 +0000418 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
419 NewArgs.end(), "", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 RepValue->takeName(GEPI);
421 }
422
423 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattner85591c62009-01-07 06:25:07 +0000424 if (Idx == 0 && GEPI->hasAllZeroIndices())
425 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426
427 // Move all of the users over to the new GEP.
428 GEPI->replaceAllUsesWith(RepValue);
429 // Delete the old GEP
430 GEPI->eraseFromParent();
431 }
432
433 // Finally, delete the Alloca instruction
434 AI->eraseFromParent();
435 NumReplaced++;
436}
437
438
439/// isSafeElementUse - Check to see if this use is an allowed use for a
440/// getelementptr instruction of an array aggregate allocation. isFirstElt
441/// indicates whether Ptr is known to the start of the aggregate.
442///
443void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
444 AllocaInfo &Info) {
445 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
446 I != E; ++I) {
447 Instruction *User = cast<Instruction>(*I);
448 switch (User->getOpcode()) {
449 case Instruction::Load: break;
450 case Instruction::Store:
451 // Store is ok if storing INTO the pointer, not storing the pointer
452 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
453 break;
454 case Instruction::GetElementPtr: {
455 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
456 bool AreAllZeroIndices = isFirstElt;
457 if (GEP->getNumOperands() > 1) {
458 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
459 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
460 // Using pointer arithmetic to navigate the array.
461 return MarkUnsafe(Info);
462
Chris Lattner85591c62009-01-07 06:25:07 +0000463 if (AreAllZeroIndices)
464 AreAllZeroIndices = GEP->hasAllZeroIndices();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465 }
466 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
467 if (Info.isUnsafe) return;
468 break;
469 }
470 case Instruction::BitCast:
471 if (isFirstElt) {
472 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
473 if (Info.isUnsafe) return;
474 break;
475 }
476 DOUT << " Transformation preventing inst: " << *User;
477 return MarkUnsafe(Info);
478 case Instruction::Call:
479 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
480 if (isFirstElt) {
481 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
482 if (Info.isUnsafe) return;
483 break;
484 }
485 }
486 DOUT << " Transformation preventing inst: " << *User;
487 return MarkUnsafe(Info);
488 default:
489 DOUT << " Transformation preventing inst: " << *User;
490 return MarkUnsafe(Info);
491 }
492 }
493 return; // All users look ok :)
494}
495
496/// AllUsersAreLoads - Return true if all users of this value are loads.
497static bool AllUsersAreLoads(Value *Ptr) {
498 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
499 I != E; ++I)
500 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
501 return false;
502 return true;
503}
504
505/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
506/// aggregate allocation.
507///
508void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
509 AllocaInfo &Info) {
510 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
511 return isSafeUseOfBitCastedAllocation(C, AI, Info);
512
Chris Lattner70ffe572009-01-28 20:16:43 +0000513 if (LoadInst *LI = dyn_cast<LoadInst>(User))
514 if (!LI->isVolatile())
515 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000516
Chris Lattner70ffe572009-01-28 20:16:43 +0000517 if (StoreInst *SI = dyn_cast<StoreInst>(User))
518 if (!SI->isVolatile() && SI->getOperand(0) != AI)
519 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman001006a2008-06-05 12:51:53 +0000520
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
522 if (GEPI == 0)
523 return MarkUnsafe(Info);
524
525 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
526
527 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
528 if (I == E ||
529 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
530 return MarkUnsafe(Info);
531 }
532
533 ++I;
534 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
535
536 bool IsAllZeroIndices = true;
537
Chris Lattnerd324da02008-08-23 05:21:06 +0000538 // If the first index is a non-constant index into an array, see if we can
539 // handle it as a special case.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattnerd324da02008-08-23 05:21:06 +0000541 if (!isa<ConstantInt>(I.getOperand())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000542 IsAllZeroIndices = 0;
Chris Lattnerd324da02008-08-23 05:21:06 +0000543 uint64_t NumElements = AT->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544
545 // If this is an array index and the index is not constant, we cannot
546 // promote... that is unless the array has exactly one or two elements in
547 // it, in which case we CAN promote it, but we have to canonicalize this
548 // out if this is the only problem.
549 if ((NumElements == 1 || NumElements == 2) &&
550 AllUsersAreLoads(GEPI)) {
551 Info.needsCanon = true;
552 return; // Canonicalization required!
553 }
554 return MarkUnsafe(Info);
555 }
556 }
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000557
Chris Lattnerd324da02008-08-23 05:21:06 +0000558 // Walk through the GEP type indices, checking the types that this indexes
559 // into.
560 for (; I != E; ++I) {
561 // Ignore struct elements, no extra checking needed for these.
562 if (isa<StructType>(*I))
563 continue;
564
Chris Lattnerd324da02008-08-23 05:21:06 +0000565 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
566 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000567
568 // Are all indices still zero?
Chris Lattnerd324da02008-08-23 05:21:06 +0000569 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000570
571 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
572 // This GEP indexes an array. Verify that this is an in-range constant
573 // integer. Specifically, consider A[0][i]. We cannot know that the user
574 // isn't doing invalid things like allowing i to index an out-of-range
575 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000576 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000577 if (IdxVal->getZExtValue() >= AT->getNumElements())
578 return MarkUnsafe(Info);
Dale Johannesen1f9b1862008-11-04 20:54:03 +0000579 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
580 if (IdxVal->getZExtValue() >= VT->getNumElements())
581 return MarkUnsafe(Info);
Matthijs Kooijman87ea5632008-10-06 16:23:31 +0000582 }
Chris Lattnerd324da02008-08-23 05:21:06 +0000583 }
584
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585 // If there are any non-simple uses of this getelementptr, make sure to reject
586 // them.
587 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
588}
589
590/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
591/// intrinsic can be promoted by SROA. At this point, we know that the operand
592/// of the memintrinsic is a pointer to the beginning of the allocation.
593void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
594 unsigned OpNo, AllocaInfo &Info) {
595 // If not constant length, give up.
596 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
597 if (!Length) return MarkUnsafe(Info);
598
599 // If not the whole aggregate, give up.
Duncan Sandsae5fd622007-11-04 14:43:57 +0000600 if (Length->getZExtValue() !=
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000601 TD->getTypePaddedSize(AI->getType()->getElementType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 return MarkUnsafe(Info);
603
604 // We only know about memcpy/memset/memmove.
605 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
606 return MarkUnsafe(Info);
607
608 // Otherwise, we can transform it. Determine whether this is a memcpy/set
609 // into or out of the aggregate.
610 if (OpNo == 1)
611 Info.isMemCpyDst = true;
612 else {
613 assert(OpNo == 2);
614 Info.isMemCpySrc = true;
615 }
616}
617
618/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
619/// are
620void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
621 AllocaInfo &Info) {
622 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
623 UI != E; ++UI) {
624 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
625 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
626 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
627 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattner71c75342009-01-07 08:11:13 +0000628 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000629 if (SI->isVolatile())
630 return MarkUnsafe(Info);
631
Chris Lattner71c75342009-01-07 08:11:13 +0000632 // If storing the entire alloca in one chunk through a bitcasted pointer
633 // to integer, we can transform it. This happens (for example) when you
634 // cast a {i32,i32}* to i64* and store through it. This is similar to the
635 // memcpy case and occurs in various "byval" cases and emulated memcpys.
636 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000637 TD->getTypePaddedSize(SI->getOperand(0)->getType()) ==
638 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner71c75342009-01-07 08:11:13 +0000639 Info.isMemCpyDst = true;
640 continue;
641 }
642 return MarkUnsafe(Info);
Chris Lattner28401db2009-01-08 05:42:05 +0000643 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner70ffe572009-01-28 20:16:43 +0000644 if (LI->isVolatile())
645 return MarkUnsafe(Info);
646
Chris Lattner28401db2009-01-08 05:42:05 +0000647 // If loading the entire alloca in one chunk through a bitcasted pointer
648 // to integer, we can transform it. This happens (for example) when you
649 // cast a {i32,i32}* to i64* and load through it. This is similar to the
650 // memcpy case and occurs in various "byval" cases and emulated memcpys.
651 if (isa<IntegerType>(LI->getType()) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000652 TD->getTypePaddedSize(LI->getType()) ==
653 TD->getTypePaddedSize(AI->getType()->getElementType())) {
Chris Lattner28401db2009-01-08 05:42:05 +0000654 Info.isMemCpySrc = true;
655 continue;
656 }
657 return MarkUnsafe(Info);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 } else {
659 return MarkUnsafe(Info);
660 }
661 if (Info.isUnsafe) return;
662 }
663}
664
665/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
666/// to its first element. Transform users of the cast to use the new values
667/// instead.
668void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
669 SmallVector<AllocaInst*, 32> &NewElts) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
671 while (UI != UE) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000672 Instruction *User = cast<Instruction>(*UI++);
673 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000674 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner71c75342009-01-07 08:11:13 +0000675 if (BCU->use_empty()) BCU->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676 continue;
677 }
678
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000679 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
680 // This must be memcpy/memmove/memset of the entire aggregate.
681 // Split into one per element.
682 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 continue;
684 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000685
Chris Lattner71c75342009-01-07 08:11:13 +0000686 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner28401db2009-01-08 05:42:05 +0000687 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattner71c75342009-01-07 08:11:13 +0000688 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
689 continue;
690 }
Chris Lattner28401db2009-01-08 05:42:05 +0000691
692 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
693 // If this is a load of the entire alloca to an integer, rewrite it.
694 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
695 continue;
696 }
Chris Lattner71c75342009-01-07 08:11:13 +0000697
698 // Otherwise it must be some other user of a gep of the first pointer. Just
699 // leave these alone.
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000700 continue;
Chris Lattner28401db2009-01-08 05:42:05 +0000701 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000702}
703
704/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
705/// Rewrite it to copy or set the elements of the scalarized memory.
706void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
707 AllocationInst *AI,
708 SmallVector<AllocaInst*, 32> &NewElts) {
709
710 // If this is a memcpy/memmove, construct the other pointer as the
711 // appropriate type.
712 Value *OtherPtr = 0;
713 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
714 if (BCInst == MCI->getRawDest())
715 OtherPtr = MCI->getRawSource();
716 else {
717 assert(BCInst == MCI->getRawSource());
718 OtherPtr = MCI->getRawDest();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000720 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
721 if (BCInst == MMI->getRawDest())
722 OtherPtr = MMI->getRawSource();
723 else {
724 assert(BCInst == MMI->getRawSource());
725 OtherPtr = MMI->getRawDest();
726 }
727 }
728
729 // If there is an other pointer, we want to convert it to the same pointer
730 // type as AI has, so we can GEP through it safely.
731 if (OtherPtr) {
732 // It is likely that OtherPtr is a bitcast, if so, remove it.
733 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
734 OtherPtr = BC->getOperand(0);
735 // All zero GEPs are effectively bitcasts.
736 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
737 if (GEP->hasAllZeroIndices())
738 OtherPtr = GEP->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000740 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
741 if (BCE->getOpcode() == Instruction::BitCast)
742 OtherPtr = BCE->getOperand(0);
743
744 // If the pointer is not the right type, insert a bitcast to the right
745 // type.
746 if (OtherPtr->getType() != AI->getType())
747 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
748 MI);
749 }
750
751 // Process each element of the aggregate.
752 Value *TheFn = MI->getOperand(0);
753 const Type *BytePtrTy = MI->getRawDest()->getType();
754 bool SROADest = MI->getRawDest() == BCInst;
755
756 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
757
758 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
759 // If this is a memcpy/memmove, emit a GEP of the other element address.
760 Value *OtherElt = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 if (OtherPtr) {
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000762 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
763 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner0e99e692008-06-22 17:46:21 +0000764 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000765 MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 }
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000767
768 Value *EltPtr = NewElts[i];
769 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
770
771 // If we got down to a scalar, insert a load or store as appropriate.
772 if (EltTy->isSingleValueType()) {
773 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
774 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
775 MI);
776 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
777 continue;
778 }
779 assert(isa<MemSetInst>(MI));
780
781 // If the stored element is zero (common case), just store a null
782 // constant.
783 Constant *StoreVal;
784 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
785 if (CI->isZero()) {
786 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
787 } else {
788 // If EltTy is a vector type, get the element type.
789 const Type *ValTy = EltTy;
790 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
791 ValTy = VTy->getElementType();
792
793 // Construct an integer with the right value.
794 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
795 APInt OneVal(EltSize, CI->getZExtValue());
796 APInt TotalVal(OneVal);
797 // Set each byte.
798 for (unsigned i = 0; 8*i < EltSize; ++i) {
799 TotalVal = TotalVal.shl(8);
800 TotalVal |= OneVal;
801 }
802
803 // Convert the integer value to the appropriate type.
804 StoreVal = ConstantInt::get(TotalVal);
805 if (isa<PointerType>(ValTy))
806 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
807 else if (ValTy->isFloatingPoint())
808 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
809 assert(StoreVal->getType() == ValTy && "Type mismatch!");
810
811 // If the requested value was a vector constant, create it.
812 if (EltTy != ValTy) {
813 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
814 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
815 StoreVal = ConstantVector::get(&Elts[0], NumElts);
816 }
817 }
818 new StoreInst(StoreVal, EltPtr, MI);
819 continue;
820 }
821 // Otherwise, if we're storing a byte variable, use a memset call for
822 // this element.
823 }
824
825 // Cast the element pointer to BytePtrTy.
826 if (EltPtr->getType() != BytePtrTy)
827 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
828
829 // Cast the other pointer (if we have one) to BytePtrTy.
830 if (OtherElt && OtherElt->getType() != BytePtrTy)
831 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
832 MI);
833
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000834 unsigned EltSize = TD->getTypePaddedSize(EltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000835
836 // Finally, insert the meminst for this element.
837 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
838 Value *Ops[] = {
839 SROADest ? EltPtr : OtherElt, // Dest ptr
840 SROADest ? OtherElt : EltPtr, // Src ptr
841 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
842 Zero // Align
843 };
844 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
845 } else {
846 assert(isa<MemSetInst>(MI));
847 Value *Ops[] = {
848 EltPtr, MI->getOperand(2), // Dest, Value,
849 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
850 Zero // Align
851 };
852 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
853 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 }
Chris Lattner71c75342009-01-07 08:11:13 +0000855 MI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856}
Chris Lattner71c75342009-01-07 08:11:13 +0000857
858/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
859/// overwrites the entire allocation. Extract out the pieces of the stored
860/// integer and store them individually.
861void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
862 AllocationInst *AI,
863 SmallVector<AllocaInst*, 32> &NewElts){
864 // Extract each element out of the integer according to its structure offset
865 // and store the element value to the individual alloca.
866 Value *SrcVal = SI->getOperand(0);
867 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000868 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner51f9e0b2009-01-07 07:18:45 +0000869
Chris Lattner71c75342009-01-07 08:11:13 +0000870 // If this isn't a store of an integer to the whole alloca, it may be a store
871 // to the first element. Just ignore the store in this case and normal SROA
872 // will handle it.
873 if (!isa<IntegerType>(SrcVal->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000874 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner71c75342009-01-07 08:11:13 +0000875 return;
876
877 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
878
879 // There are two forms here: AI could be an array or struct. Both cases
880 // have different ways to compute the element offset.
881 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
882 const StructLayout *Layout = TD->getStructLayout(EltSTy);
883
884 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
885 // Get the number of bits to shift SrcVal to get the value.
886 const Type *FieldTy = EltSTy->getElementType(i);
887 uint64_t Shift = Layout->getElementOffsetInBits(i);
888
889 if (TD->isBigEndian())
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000890 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000891
892 Value *EltVal = SrcVal;
893 if (Shift) {
894 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
895 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
896 "sroa.store.elt", SI);
897 }
898
899 // Truncate down to an integer of the right size.
900 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000901
902 // Ignore zero sized fields like {}, they obviously contain no data.
903 if (FieldSizeBits == 0) continue;
904
Chris Lattner71c75342009-01-07 08:11:13 +0000905 if (FieldSizeBits != AllocaSizeBits)
906 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI);
907 Value *DestField = NewElts[i];
908 if (EltVal->getType() == FieldTy) {
909 // Storing to an integer field of this size, just do it.
910 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
911 // Bitcast to the right element type (for fp/vector values).
912 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
913 } else {
914 // Otherwise, bitcast the dest pointer (for aggregates).
915 DestField = new BitCastInst(DestField,
916 PointerType::getUnqual(EltVal->getType()),
917 "", SI);
918 }
919 new StoreInst(EltVal, DestField, SI);
920 }
921
922 } else {
923 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
924 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000925 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner71c75342009-01-07 08:11:13 +0000926 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
927
928 uint64_t Shift;
929
930 if (TD->isBigEndian())
931 Shift = AllocaSizeBits-ElementOffset;
932 else
933 Shift = 0;
934
935 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerf7a2f092009-01-09 18:18:43 +0000936 // Ignore zero sized fields like {}, they obviously contain no data.
937 if (ElementSizeBits == 0) continue;
Chris Lattner71c75342009-01-07 08:11:13 +0000938
939 Value *EltVal = SrcVal;
940 if (Shift) {
941 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
942 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
943 "sroa.store.elt", SI);
944 }
945
946 // Truncate down to an integer of the right size.
947 if (ElementSizeBits != AllocaSizeBits)
948 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI);
949 Value *DestField = NewElts[i];
950 if (EltVal->getType() == ArrayEltTy) {
951 // Storing to an integer field of this size, just do it.
952 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
953 // Bitcast to the right element type (for fp/vector values).
954 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
955 } else {
956 // Otherwise, bitcast the dest pointer (for aggregates).
957 DestField = new BitCastInst(DestField,
958 PointerType::getUnqual(EltVal->getType()),
959 "", SI);
960 }
961 new StoreInst(EltVal, DestField, SI);
962
963 if (TD->isBigEndian())
964 Shift -= ElementOffset;
965 else
966 Shift += ElementOffset;
967 }
968 }
969
970 SI->eraseFromParent();
971}
972
Chris Lattner28401db2009-01-08 05:42:05 +0000973/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
974/// an integer. Load the individual pieces to form the aggregate value.
975void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
976 SmallVector<AllocaInst*, 32> &NewElts) {
977 // Extract each element out of the NewElts according to its structure offset
978 // and form the result value.
979 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000980 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +0000981
982 // If this isn't a load of the whole alloca to an integer, it may be a load
983 // of the first element. Just ignore the load in this case and normal SROA
984 // will handle it.
985 if (!isa<IntegerType>(LI->getType()) ||
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000986 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner28401db2009-01-08 05:42:05 +0000987 return;
988
989 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
990
991 // There are two forms here: AI could be an array or struct. Both cases
992 // have different ways to compute the element offset.
993 const StructLayout *Layout = 0;
994 uint64_t ArrayEltBitOffset = 0;
995 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
996 Layout = TD->getStructLayout(EltSTy);
997 } else {
998 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000999 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy);
Chris Lattner28401db2009-01-08 05:42:05 +00001000 }
1001
1002 Value *ResultVal = Constant::getNullValue(LI->getType());
1003
1004 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1005 // Load the value from the alloca. If the NewElt is an aggregate, cast
1006 // the pointer to an integer of the same size before doing the load.
1007 Value *SrcField = NewElts[i];
1008 const Type *FieldTy =
1009 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattnerf7a2f092009-01-09 18:18:43 +00001010 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1011
1012 // Ignore zero sized fields like {}, they obviously contain no data.
1013 if (FieldSizeBits == 0) continue;
1014
1015 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits);
Chris Lattner28401db2009-01-08 05:42:05 +00001016 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1017 !isa<VectorType>(FieldTy))
1018 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy),
1019 "", LI);
1020 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1021
1022 // If SrcField is a fp or vector of the right size but that isn't an
1023 // integer type, bitcast to an integer so we can shift it.
1024 if (SrcField->getType() != FieldIntTy)
1025 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1026
1027 // Zero extend the field to be the same size as the final alloca so that
1028 // we can shift and insert it.
1029 if (SrcField->getType() != ResultVal->getType())
1030 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1031
1032 // Determine the number of bits to shift SrcField.
1033 uint64_t Shift;
1034 if (Layout) // Struct case.
1035 Shift = Layout->getElementOffsetInBits(i);
1036 else // Array case.
1037 Shift = i*ArrayEltBitOffset;
1038
1039 if (TD->isBigEndian())
1040 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1041
1042 if (Shift) {
1043 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1044 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1045 }
1046
1047 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1048 }
1049
1050 LI->replaceAllUsesWith(ResultVal);
1051 LI->eraseFromParent();
1052}
1053
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054
Duncan Sandsae5fd622007-11-04 14:43:57 +00001055/// HasPadding - Return true if the specified type has any structure or
1056/// alignment padding, false otherwise.
Duncan Sands4afc5752008-06-04 08:21:45 +00001057static bool HasPadding(const Type *Ty, const TargetData &TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1059 const StructLayout *SL = TD.getStructLayout(STy);
1060 unsigned PrevFieldBitOffset = 0;
1061 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001062 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1063
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 // Padding in sub-elements?
Duncan Sands4afc5752008-06-04 08:21:45 +00001065 if (HasPadding(STy->getElementType(i), TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 return true;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001067
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068 // Check to see if there is any padding between this element and the
1069 // previous one.
1070 if (i) {
Duncan Sandsae5fd622007-11-04 14:43:57 +00001071 unsigned PrevFieldEnd =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1073 if (PrevFieldEnd < FieldBitOffset)
1074 return true;
1075 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001076
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077 PrevFieldBitOffset = FieldBitOffset;
1078 }
Duncan Sandsae5fd622007-11-04 14:43:57 +00001079
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 // Check for tail padding.
1081 if (unsigned EltCount = STy->getNumElements()) {
1082 unsigned PrevFieldEnd = PrevFieldBitOffset +
1083 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sandsae5fd622007-11-04 14:43:57 +00001084 if (PrevFieldEnd < SL->getSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 return true;
1086 }
1087
1088 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001089 return HasPadding(ATy->getElementType(), TD);
Duncan Sandsae5fd622007-11-04 14:43:57 +00001090 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sands4afc5752008-06-04 08:21:45 +00001091 return HasPadding(VTy->getElementType(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 }
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001093 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094}
1095
1096/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1097/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1098/// or 1 if safe after canonicalization has been performed.
1099///
1100int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
1101 // Loop over the use list of the alloca. We can only transform it if all of
1102 // the users are safe to transform.
1103 AllocaInfo Info;
1104
1105 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
1106 I != E; ++I) {
1107 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1108 if (Info.isUnsafe) {
1109 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
1110 return 0;
1111 }
1112 }
1113
1114 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1115 // source and destination, we have to be careful. In particular, the memcpy
1116 // could be moving around elements that live in structure padding of the LLVM
1117 // types, but may actually be used. In these cases, we refuse to promote the
1118 // struct.
1119 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner3fd59362009-01-07 06:34:28 +00001120 HasPadding(AI->getType()->getElementType(), *TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 return 0;
Duncan Sandsae5fd622007-11-04 14:43:57 +00001122
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123 // If we require cleanup, return 1, otherwise return 3.
1124 return Info.needsCanon ? 1 : 3;
1125}
1126
1127/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
1128/// allocation, but only if cleaned up, perform the cleanups required.
1129void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
1130 // At this point, we know that the end result will be SROA'd and promoted, so
1131 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1132 // up.
1133 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1134 UI != E; ) {
1135 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
1136 if (!GEPI) continue;
1137 gep_type_iterator I = gep_type_begin(GEPI);
1138 ++I;
1139
1140 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
1141 uint64_t NumElements = AT->getNumElements();
1142
1143 if (!isa<ConstantInt>(I.getOperand())) {
1144 if (NumElements == 1) {
1145 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
1146 } else {
1147 assert(NumElements == 2 && "Unhandled case!");
1148 // All users of the GEP must be loads. At each use of the GEP, insert
1149 // two loads of the appropriate indexed GEP and select between them.
1150 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
1151 Constant::getNullValue(I.getOperand()->getType()),
1152 "isone", GEPI);
1153 // Insert the new GEP instructions, which are properly indexed.
1154 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
1155 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001156 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1157 Indices.begin(),
1158 Indices.end(),
1159 GEPI->getName()+".0", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001161 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1162 Indices.begin(),
1163 Indices.end(),
1164 GEPI->getName()+".1", GEPI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 // Replace all loads of the variable index GEP with loads from both
1166 // indexes and a select.
1167 while (!GEPI->use_empty()) {
1168 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1169 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1170 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00001171 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 LI->replaceAllUsesWith(R);
1173 LI->eraseFromParent();
1174 }
1175 GEPI->eraseFromParent();
1176 }
1177 }
1178 }
1179 }
1180}
1181
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001182/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1183/// the offset specified by Offset (which is specified in bytes).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184///
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001185/// There are two cases we handle here:
1186/// 1) A union of vector types of the same size and potentially its elements.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187/// Here we turn element accesses into insert/extract element operations.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001188/// This promotes a <4 x float> with a store of float to the third element
1189/// into a <4 x float> that uses insert element.
1190/// 2) A fully general blob of memory, which we turn into some (potentially
1191/// large) integer type with extract and insert operations where the loads
1192/// and stores would mutate the memory.
Chris Lattnerf235a322009-02-03 01:30:09 +00001193static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1194 unsigned AllocaSize, const TargetData &TD) {
1195 // If this could be contributing to a vector, analyze it.
1196 if (VecTy != Type::VoidTy) { // either null or a vector type.
Chris Lattnerc2a5f2a2009-02-02 18:02:59 +00001197
Chris Lattnerf235a322009-02-03 01:30:09 +00001198 // If the In type is a vector that is the same size as the alloca, see if it
1199 // matches the existing VecTy.
1200 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1201 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1202 // If we're storing/loading a vector of the right size, allow it as a
1203 // vector. If this the first vector we see, remember the type so that
1204 // we know the element size.
1205 if (VecTy == 0)
1206 VecTy = VInTy;
1207 return;
1208 }
1209 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1210 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1211 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1212 // If we're accessing something that could be an element of a vector, see
1213 // if the implied vector agrees with what we already have and if Offset is
1214 // compatible with it.
1215 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1216 if (Offset % EltSize == 0 &&
1217 AllocaSize % EltSize == 0 &&
1218 (VecTy == 0 ||
1219 cast<VectorType>(VecTy)->getElementType()
1220 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1221 if (VecTy == 0)
1222 VecTy = VectorType::get(In, AllocaSize/EltSize);
1223 return;
1224 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001225 }
1226 }
1227
Chris Lattnerf235a322009-02-03 01:30:09 +00001228 // Otherwise, we have a case that we can't handle with an optimized vector
1229 // form. We can still turn this into a large integer.
1230 VecTy = Type::VoidTy;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231}
1232
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001233/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattnerf235a322009-02-03 01:30:09 +00001234/// its accesses to use a to single vector type, return true, and set VecTy to
1235/// the new type. If we could convert the alloca into a single promotable
1236/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1237/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1238/// is the current offset from the base of the alloca being analyzed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239///
Chris Lattner38088d12009-02-03 18:15:05 +00001240/// If we see at least one access to the value that is as a vector type, set the
1241/// SawVec flag.
1242///
1243bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1244 bool &SawVec, uint64_t Offset,
Chris Lattnerf235a322009-02-03 01:30:09 +00001245 unsigned AllocaSize) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1247 Instruction *User = cast<Instruction>(*UI);
1248
1249 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001250 // Don't break volatile loads.
Chris Lattner70ffe572009-01-28 20:16:43 +00001251 if (LI->isVolatile())
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001252 return false;
Chris Lattnerf235a322009-02-03 01:30:09 +00001253 MergeInType(LI->getType(), Offset, VecTy, AllocaSize, *TD);
Chris Lattner38088d12009-02-03 18:15:05 +00001254 SawVec |= isa<VectorType>(LI->getType());
Chris Lattner7cc97712009-01-07 06:39:58 +00001255 continue;
1256 }
1257
1258 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 // Storing the pointer, not into the value?
Chris Lattner70ffe572009-01-28 20:16:43 +00001260 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Chris Lattnerf235a322009-02-03 01:30:09 +00001261 MergeInType(SI->getOperand(0)->getType(), Offset, VecTy, AllocaSize, *TD);
Chris Lattner38088d12009-02-03 18:15:05 +00001262 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattner7cc97712009-01-07 06:39:58 +00001263 continue;
1264 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001265
1266 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner38088d12009-02-03 18:15:05 +00001267 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1268 AllocaSize))
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001269 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 IsNotTrivial = true;
Chris Lattner7cc97712009-01-07 06:39:58 +00001271 continue;
1272 }
1273
1274 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001275 // If this is a GEP with a variable indices, we can't handle it.
1276 if (!GEP->hasAllConstantIndices())
1277 return false;
Chris Lattner7cc97712009-01-07 06:39:58 +00001278
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001279 // Compute the offset that this GEP adds to the pointer.
1280 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1281 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1282 &Indices[0], Indices.size());
1283 // See if all uses can be converted.
Chris Lattner38088d12009-02-03 18:15:05 +00001284 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattnerf235a322009-02-03 01:30:09 +00001285 AllocaSize))
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001286 return false;
1287 IsNotTrivial = true;
1288 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 }
Chris Lattner7cc97712009-01-07 06:39:58 +00001290
Chris Lattnerfece0da2009-02-03 02:01:43 +00001291 // If this is a constant sized memset of a constant value (e.g. 0) we can
1292 // handle it.
1293 if (isa<MemSetInst>(User) &&
1294 // Store of constant value.
1295 isa<ConstantInt>(User->getOperand(2)) &&
1296 // Store with constant size.
1297 isa<ConstantInt>(User->getOperand(3))) {
1298 VecTy = Type::VoidTy;
1299 IsNotTrivial = true;
1300 continue;
1301 }
1302
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001303 // Otherwise, we cannot handle this!
1304 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001305 }
1306
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001307 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308}
1309
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310
1311/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1312/// directly. This happens when we are converting an "integer union" to a
1313/// single integer scalar, or when we are converting a "vector union" to a
1314/// vector with insert/extractelement instructions.
1315///
1316/// Offset is an offset from the original alloca, in bits that need to be
1317/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001318void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 while (!Ptr->use_empty()) {
1320 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands641f12c2009-02-02 10:06:20 +00001321
Chris Lattner7cc97712009-01-07 06:39:58 +00001322 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb1534532008-01-30 00:39:15 +00001323 ConvertUsesToScalar(CI, NewAI, Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 CI->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001325 continue;
1326 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001327
Chris Lattner7cc97712009-01-07 06:39:58 +00001328 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001329 // Compute the offset that this GEP adds to the pointer.
1330 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1331 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1332 &Indices[0], Indices.size());
1333 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 GEP->eraseFromParent();
Chris Lattner7cc97712009-01-07 06:39:58 +00001335 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 }
Chris Lattnerfece0da2009-02-03 02:01:43 +00001337
Chris Lattnerececb0c2009-02-03 19:45:44 +00001338 IRBuilder<> Builder(User->getParent(), User);
1339
1340 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001341 // The load is a bit extract from NewAI shifted right by Offset bits.
1342 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1343 Value *NewLoadVal
1344 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1345 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattnerececb0c2009-02-03 19:45:44 +00001346 LI->eraseFromParent();
1347 continue;
1348 }
1349
1350 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1351 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1352 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1353 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1354 Builder);
1355 Builder.CreateStore(New, NewAI);
1356 SI->eraseFromParent();
1357 continue;
1358 }
1359
Chris Lattnerfece0da2009-02-03 02:01:43 +00001360 // If this is a constant sized memset of a constant value (e.g. 0) we can
1361 // transform it into a store of the expanded constant value.
1362 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1363 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1364 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1365 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1366
1367 // Compute the value replicated the right number of times.
1368 APInt APVal(NumBytes*8, Val);
1369
1370 // Splat the value if non-zero.
1371 if (Val)
1372 for (unsigned i = 1; i != NumBytes; ++i)
1373 APVal |= APVal << 8;
1374
Chris Lattner32c19282009-02-03 19:41:50 +00001375 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
Chris Lattnercc0727c2009-02-03 19:30:11 +00001376 Value *New = ConvertScalar_InsertValue(ConstantInt::get(APVal), Old,
Chris Lattner32c19282009-02-03 19:41:50 +00001377 Offset, Builder);
1378 Builder.CreateStore(New, NewAI);
Chris Lattnerfece0da2009-02-03 02:01:43 +00001379 MSI->eraseFromParent();
1380 continue;
1381 }
1382
1383
Chris Lattner7cc97712009-01-07 06:39:58 +00001384 assert(0 && "Unsupported operation!");
1385 abort();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 }
1387}
1388
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001389/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1390/// or vector value FromVal, extracting the bits from the offset specified by
1391/// Offset. This returns the value, which is of type ToType.
1392///
1393/// This happens when we are converting an "integer union" to a single
Duncan Sands641f12c2009-02-02 10:06:20 +00001394/// integer scalar, or when we are converting a "vector union" to a vector with
1395/// insert/extractelement instructions.
Chris Lattner41d58652008-02-29 07:03:13 +00001396///
Duncan Sands641f12c2009-02-02 10:06:20 +00001397/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001398/// shifted to the right.
1399Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1400 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001401 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001402 if (FromVal->getType() == ToType && Offset == 0)
1403 return FromVal;
Chris Lattner5f062542008-02-29 07:12:06 +00001404
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001405 // If the result alloca is a vector type, this is either an element
1406 // access or a bitcast to another vector type of the same size.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001407 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1408 if (isa<VectorType>(ToType))
1409 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner5f062542008-02-29 07:12:06 +00001410
1411 // Otherwise it must be an element access.
Chris Lattner5f062542008-02-29 07:12:06 +00001412 unsigned Elt = 0;
1413 if (Offset) {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00001414 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType());
Chris Lattner5f062542008-02-29 07:12:06 +00001415 Elt = Offset/EltSize;
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001416 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner41d58652008-02-29 07:03:13 +00001417 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001418 // Return the element extracted out of it.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001419 Value *V = Builder.CreateExtractElement(FromVal,
Chris Lattnerececb0c2009-02-03 19:45:44 +00001420 ConstantInt::get(Type::Int32Ty,Elt),
1421 "tmp");
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001422 if (V->getType() != ToType)
1423 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001424 return V;
Chris Lattner5f062542008-02-29 07:12:06 +00001425 }
Chris Lattner7bac66b2009-02-03 21:08:45 +00001426
1427 // If ToType is a first class aggregate, extract out each of the pieces and
1428 // use insertvalue's to form the FCA.
1429 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1430 const StructLayout &Layout = *TD->getStructLayout(ST);
1431 Value *Res = UndefValue::get(ST);
1432 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1433 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
1434 Offset+Layout.getElementOffset(i),
1435 Builder);
1436 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1437 }
1438 return Res;
1439 }
1440
1441 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1442 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1443 Value *Res = UndefValue::get(AT);
1444 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1445 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1446 Offset+i*EltSize, Builder);
1447 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1448 }
1449 return Res;
1450 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001451
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001452 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001453 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands641f12c2009-02-02 10:06:20 +00001454
Chris Lattner5f062542008-02-29 07:12:06 +00001455 // If this is a big-endian system and the load is narrower than the
1456 // full alloca type, we need to do a shift to get the right bits.
1457 int ShAmt = 0;
Chris Lattner3fd59362009-01-07 06:34:28 +00001458 if (TD->isBigEndian()) {
Chris Lattner5f062542008-02-29 07:12:06 +00001459 // On big-endian machines, the lowest bit is stored at the bit offset
1460 // from the pointer given by getTypeStoreSizeInBits. This matters for
1461 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner3fd59362009-01-07 06:34:28 +00001462 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001463 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner5f062542008-02-29 07:12:06 +00001464 } else {
1465 ShAmt = Offset;
1466 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001467
Chris Lattner5f062542008-02-29 07:12:06 +00001468 // Note: we support negative bitwidths (with shl) which are not defined.
1469 // We do this to support (f.e.) loads off the end of a structure where
1470 // only some bits are used.
1471 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Chris Lattner7bac66b2009-02-03 21:08:45 +00001472 FromVal = Builder.CreateLShr(FromVal, ConstantInt::get(FromVal->getType(),
1473 ShAmt), "tmp");
Chris Lattner5f062542008-02-29 07:12:06 +00001474 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Chris Lattner7bac66b2009-02-03 21:08:45 +00001475 FromVal = Builder.CreateShl(FromVal, ConstantInt::get(FromVal->getType(),
1476 -ShAmt), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001477
Chris Lattner5f062542008-02-29 07:12:06 +00001478 // Finally, unconditionally truncate the integer to the right width.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001479 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner5f062542008-02-29 07:12:06 +00001480 if (LIBitWidth < NTy->getBitWidth())
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001481 FromVal = Builder.CreateTrunc(FromVal, IntegerType::get(LIBitWidth), "tmp");
Chris Lattnerb2290a12009-02-03 07:08:57 +00001482 else if (LIBitWidth > NTy->getBitWidth())
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001483 FromVal = Builder.CreateZExt(FromVal, IntegerType::get(LIBitWidth), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001484
Chris Lattner5f062542008-02-29 07:12:06 +00001485 // If the result is an integer, this is a trunc or bitcast.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001486 if (isa<IntegerType>(ToType)) {
Chris Lattner5f062542008-02-29 07:12:06 +00001487 // Should be done.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001488 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner5f062542008-02-29 07:12:06 +00001489 // Just do a bitcast, we know the sizes match up.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001490 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001491 } else {
Chris Lattner5f062542008-02-29 07:12:06 +00001492 // Otherwise must be a pointer.
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001493 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001494 }
Chris Lattnerf73a10e2009-02-03 21:01:03 +00001495 assert(FromVal->getType() == ToType && "Didn't convert right?");
1496 return FromVal;
Chris Lattner41d58652008-02-29 07:03:13 +00001497}
1498
1499
Chris Lattnercc0727c2009-02-03 19:30:11 +00001500/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1501/// or vector value "Old" at the offset specified by Offset.
1502///
1503/// This happens when we are converting an "integer union" to a
Chris Lattner41d58652008-02-29 07:03:13 +00001504/// single integer scalar, or when we are converting a "vector union" to a
1505/// vector with insert/extractelement instructions.
1506///
1507/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnercc0727c2009-02-03 19:30:11 +00001508/// shifted to the right.
1509Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner32c19282009-02-03 19:41:50 +00001510 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands641f12c2009-02-02 10:06:20 +00001511
Chris Lattner41d58652008-02-29 07:03:13 +00001512 // Convert the stored type to the actual type, shift it left to insert
1513 // then 'or' into place.
Chris Lattnercc0727c2009-02-03 19:30:11 +00001514 const Type *AllocaType = Old->getType();
Duncan Sands641f12c2009-02-02 10:06:20 +00001515
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001516 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner41d58652008-02-29 07:03:13 +00001517 // If the result alloca is a vector type, this is either an element
1518 // access or a bitcast to another vector type.
1519 if (isa<VectorType>(SV->getType())) {
Chris Lattner32c19282009-02-03 19:41:50 +00001520 SV = Builder.CreateBitCast(SV, AllocaType, "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001521 } else {
1522 // Must be an element insertion.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001523 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(VTy->getElementType());
Chris Lattnerf235a322009-02-03 01:30:09 +00001524
1525 if (SV->getType() != VTy->getElementType())
Chris Lattner32c19282009-02-03 19:41:50 +00001526 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001527
Chris Lattner32c19282009-02-03 19:41:50 +00001528 SV = Builder.CreateInsertElement(Old, SV,
1529 ConstantInt::get(Type::Int32Ty, Elt),
1530 "tmp");
Chris Lattner41d58652008-02-29 07:03:13 +00001531 }
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001532 return SV;
1533 }
Chris Lattnercc0727c2009-02-03 19:30:11 +00001534
1535 // If SV is a first-class aggregate value, insert each value recursively.
1536 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1537 const StructLayout &Layout = *TD->getStructLayout(ST);
1538 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner32c19282009-02-03 19:41:50 +00001539 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattnercc0727c2009-02-03 19:30:11 +00001540 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner32c19282009-02-03 19:41:50 +00001541 Offset+Layout.getElementOffset(i),
1542 Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +00001543 }
1544 return Old;
1545 }
1546
1547 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1548 uint64_t EltSize = TD->getTypePaddedSizeInBits(AT->getElementType());
1549 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner32c19282009-02-03 19:41:50 +00001550 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1551 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattnercc0727c2009-02-03 19:30:11 +00001552 }
1553 return Old;
1554 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001555
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001556 // If SV is a float, convert it to the appropriate integer type.
Chris Lattnercc0727c2009-02-03 19:30:11 +00001557 // If it is a pointer, do the same.
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001558 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1559 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1560 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1561 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1562 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Chris Lattner32c19282009-02-03 19:41:50 +00001563 SV = Builder.CreateBitCast(SV, IntegerType::get(SrcWidth), "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001564 else if (isa<PointerType>(SV->getType()))
Chris Lattner32c19282009-02-03 19:41:50 +00001565 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
Duncan Sands641f12c2009-02-02 10:06:20 +00001566
Chris Lattnerf235a322009-02-03 01:30:09 +00001567 // Zero extend or truncate the value if needed.
1568 if (SV->getType() != AllocaType) {
1569 if (SV->getType()->getPrimitiveSizeInBits() <
1570 AllocaType->getPrimitiveSizeInBits())
Chris Lattner32c19282009-02-03 19:41:50 +00001571 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001572 else {
1573 // Truncation may be needed if storing more than the alloca can hold
1574 // (undefined behavior).
Chris Lattner32c19282009-02-03 19:41:50 +00001575 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattnerf235a322009-02-03 01:30:09 +00001576 SrcWidth = DestWidth;
1577 SrcStoreWidth = DestStoreWidth;
1578 }
1579 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001580
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001581 // If this is a big-endian system and the store is narrower than the
1582 // full alloca type, we need to do a shift to get the right bits.
1583 int ShAmt = 0;
1584 if (TD->isBigEndian()) {
1585 // On big-endian machines, the lowest bit is stored at the bit offset
1586 // from the pointer given by getTypeStoreSizeInBits. This matters for
1587 // integers with a bitwidth that is not a multiple of 8.
1588 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner41d58652008-02-29 07:03:13 +00001589 } else {
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001590 ShAmt = Offset;
1591 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001592
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001593 // Note: we support negative bitwidths (with shr) which are not defined.
1594 // We do this to support (f.e.) stores off the end of a structure where
1595 // only some bits in the structure are set.
1596 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1597 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Chris Lattner32c19282009-02-03 19:41:50 +00001598 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt), "tmp");
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001599 Mask <<= ShAmt;
1600 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Chris Lattner32c19282009-02-03 19:41:50 +00001601 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt), "tmp");
Duncan Sandsced29632009-02-02 09:53:14 +00001602 Mask = Mask.lshr(-ShAmt);
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001603 }
Duncan Sands641f12c2009-02-02 10:06:20 +00001604
Chris Lattner4b9c8b72009-01-31 02:28:54 +00001605 // Mask out the bits we are about to insert from the old value, and or
1606 // in the new bits.
1607 if (SrcWidth != DestWidth) {
1608 assert(DestWidth > SrcWidth);
Chris Lattner32c19282009-02-03 19:41:50 +00001609 Old = Builder.CreateAnd(Old, ConstantInt::get(~Mask), "mask");
1610 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner41d58652008-02-29 07:03:13 +00001611 }
1612 return SV;
1613}
1614
1615
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001616
1617/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1618/// some part of a constant global variable. This intentionally only accepts
1619/// constant expressions because we don't can't rewrite arbitrary instructions.
1620static bool PointsToConstantGlobal(Value *V) {
1621 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1622 return GV->isConstant();
1623 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1624 if (CE->getOpcode() == Instruction::BitCast ||
1625 CE->getOpcode() == Instruction::GetElementPtr)
1626 return PointsToConstantGlobal(CE->getOperand(0));
1627 return false;
1628}
1629
1630/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1631/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1632/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1633/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1634/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1635/// the alloca, and if the source pointer is a pointer to a constant global, we
1636/// can optimize this.
1637static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1638 bool isOffset) {
1639 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner70ffe572009-01-28 20:16:43 +00001640 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1641 // Ignore non-volatile loads, they are always ok.
1642 if (!LI->isVolatile())
1643 continue;
1644
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1646 // If uses of the bitcast are ok, we are ok.
1647 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1648 return false;
1649 continue;
1650 }
1651 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1652 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1653 // doesn't, it does.
1654 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1655 isOffset || !GEP->hasAllZeroIndices()))
1656 return false;
1657 continue;
1658 }
1659
1660 // If this is isn't our memcpy/memmove, reject it as something we can't
1661 // handle.
1662 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1663 return false;
1664
1665 // If we already have seen a copy, reject the second one.
1666 if (TheCopy) return false;
1667
1668 // If the pointer has been offset from the start of the alloca, we can't
1669 // safely handle this.
1670 if (isOffset) return false;
1671
1672 // If the memintrinsic isn't using the alloca as the dest, reject it.
1673 if (UI.getOperandNo() != 1) return false;
1674
1675 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1676
1677 // If the source of the memcpy/move is not a constant global, reject it.
1678 if (!PointsToConstantGlobal(MI->getOperand(2)))
1679 return false;
1680
1681 // Otherwise, the transform is safe. Remember the copy instruction.
1682 TheCopy = MI;
1683 }
1684 return true;
1685}
1686
1687/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1688/// modified by a copy from a constant global. If we can prove this, we can
1689/// replace any uses of the alloca with uses of the global directly.
1690Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1691 Instruction *TheCopy = 0;
1692 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1693 return TheCopy;
1694 return 0;
1695}