1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
20 //===----------------------------------------------------------------------===//
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/LLVMContext.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
35 #include "llvm/Transforms/Utils/Local.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/GetElementPtrTypeIterator.h"
39 #include "llvm/Support/IRBuilder.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
46 STATISTIC(NumReplaced, "Number of allocas broken up");
47 STATISTIC(NumPromoted, "Number of allocas promoted");
48 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
49 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
52 struct SROA : public FunctionPass {
53 static char ID; // Pass identification, replacement for typeid
54 explicit SROA(signed T = -1) : FunctionPass(&ID) {
61 bool runOnFunction(Function &F);
63 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
66 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<DominatorTree>();
70 AU.addRequired<DominanceFrontier>();
77 /// DeadInsts - Keep track of instructions we have made dead, so that
78 /// we can remove them after we are done working.
79 SmallVector<Value*, 32> DeadInsts;
81 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
82 /// information about the uses. All these fields are initialized to false
83 /// and set to true when something is learned.
85 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
88 /// needsCleanup - This is set to true if there is some use of the alloca
89 /// that requires cleanup.
90 bool needsCleanup : 1;
92 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
95 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
99 : isUnsafe(false), needsCleanup(false),
100 isMemCpySrc(false), isMemCpyDst(false) {}
103 unsigned SRThreshold;
105 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
107 int isSafeAllocaToScalarRepl(AllocaInst *AI);
109 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
111 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
113 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
114 const Type *MemOpType, bool isStore, AllocaInfo &Info);
115 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
116 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
119 void DoScalarReplacement(AllocaInst *AI,
120 std::vector<AllocaInst*> &WorkList);
121 void DeleteDeadInstructions();
122 void CleanupAllocaUsers(Value *V);
123 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
125 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
126 SmallVector<AllocaInst*, 32> &NewElts);
127 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
128 SmallVector<AllocaInst*, 32> &NewElts);
129 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
130 SmallVector<AllocaInst*, 32> &NewElts);
131 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
133 SmallVector<AllocaInst*, 32> &NewElts);
134 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
135 SmallVector<AllocaInst*, 32> &NewElts);
136 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
137 SmallVector<AllocaInst*, 32> &NewElts);
139 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
140 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
141 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
142 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
143 uint64_t Offset, IRBuilder<> &Builder);
144 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
145 uint64_t Offset, IRBuilder<> &Builder);
146 static Instruction *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
151 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
153 // Public interface to the ScalarReplAggregates pass
154 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
155 return new SROA(Threshold);
159 bool SROA::runOnFunction(Function &F) {
160 TD = getAnalysisIfAvailable<TargetData>();
162 bool Changed = performPromotion(F);
164 // FIXME: ScalarRepl currently depends on TargetData more than it
165 // theoretically needs to. It should be refactored in order to support
166 // target-independent IR. Until this is done, just skip the actual
167 // scalar-replacement portion of this pass.
168 if (!TD) return Changed;
171 bool LocalChange = performScalarRepl(F);
172 if (!LocalChange) break; // No need to repromote if no scalarrepl
174 LocalChange = performPromotion(F);
175 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
182 bool SROA::performPromotion(Function &F) {
183 std::vector<AllocaInst*> Allocas;
184 DominatorTree &DT = getAnalysis<DominatorTree>();
185 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
187 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
189 bool Changed = false;
194 // Find allocas that are safe to promote, by looking at all instructions in
196 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
197 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
198 if (isAllocaPromotable(AI))
199 Allocas.push_back(AI);
201 if (Allocas.empty()) break;
203 PromoteMemToReg(Allocas, DT, DF);
204 NumPromoted += Allocas.size();
211 /// getNumSAElements - Return the number of elements in the specific struct or
213 static uint64_t getNumSAElements(const Type *T) {
214 if (const StructType *ST = dyn_cast<StructType>(T))
215 return ST->getNumElements();
216 return cast<ArrayType>(T)->getNumElements();
219 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
220 // which runs on all of the malloc/alloca instructions in the function, removing
221 // them if they are only used by getelementptr instructions.
223 bool SROA::performScalarRepl(Function &F) {
224 std::vector<AllocaInst*> WorkList;
226 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
227 BasicBlock &BB = F.getEntryBlock();
228 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
229 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
230 WorkList.push_back(A);
232 // Process the worklist
233 bool Changed = false;
234 while (!WorkList.empty()) {
235 AllocaInst *AI = WorkList.back();
238 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
239 // with unused elements.
240 if (AI->use_empty()) {
241 AI->eraseFromParent();
245 // If this alloca is impossible for us to promote, reject it early.
246 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
249 // Check to see if this allocation is only modified by a memcpy/memmove from
250 // a constant global. If this is the case, we can change all users to use
251 // the constant global instead. This is commonly produced by the CFE by
252 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
253 // is only subsequently read.
254 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
255 DEBUG(errs() << "Found alloca equal to global: " << *AI << '\n');
256 DEBUG(errs() << " memcpy = " << *TheCopy << '\n');
257 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
258 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
259 TheCopy->eraseFromParent(); // Don't mutate the global.
260 AI->eraseFromParent();
266 // Check to see if we can perform the core SROA transformation. We cannot
267 // transform the allocation instruction if it is an array allocation
268 // (allocations OF arrays are ok though), and an allocation of a scalar
269 // value cannot be decomposed at all.
270 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
272 // Do not promote [0 x %struct].
273 if (AllocaSize == 0) continue;
275 // Do not promote any struct whose size is too big.
276 if (AllocaSize > SRThreshold) continue;
278 if ((isa<StructType>(AI->getAllocatedType()) ||
279 isa<ArrayType>(AI->getAllocatedType())) &&
280 // Do not promote any struct into more than "32" separate vars.
281 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
282 // Check that all of the users of the allocation are capable of being
284 switch (isSafeAllocaToScalarRepl(AI)) {
285 default: llvm_unreachable("Unexpected value!");
286 case 0: // Not safe to scalar replace.
288 case 1: // Safe, but requires cleanup/canonicalizations first
289 CleanupAllocaUsers(AI);
291 case 3: // Safe to scalar replace.
292 DoScalarReplacement(AI, WorkList);
298 // If we can turn this aggregate value (potentially with casts) into a
299 // simple scalar value that can be mem2reg'd into a register value.
300 // IsNotTrivial tracks whether this is something that mem2reg could have
301 // promoted itself. If so, we don't want to transform it needlessly. Note
302 // that we can't just check based on the type: the alloca may be of an i32
303 // but that has pointer arithmetic to set byte 3 of it or something.
304 bool IsNotTrivial = false;
305 const Type *VectorTy = 0;
306 bool HadAVector = false;
307 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
308 0, unsigned(AllocaSize)) && IsNotTrivial) {
310 // If we were able to find a vector type that can handle this with
311 // insert/extract elements, and if there was at least one use that had
312 // a vector type, promote this to a vector. We don't want to promote
313 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
314 // we just get a lot of insert/extracts. If at least one vector is
315 // involved, then we probably really do have a union of vector/array.
316 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
317 DEBUG(errs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
318 << *VectorTy << '\n');
320 // Create and insert the vector alloca.
321 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
322 ConvertUsesToScalar(AI, NewAI, 0);
324 DEBUG(errs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
326 // Create and insert the integer alloca.
327 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
328 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
329 ConvertUsesToScalar(AI, NewAI, 0);
332 AI->eraseFromParent();
338 // Otherwise, couldn't process this alloca.
344 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
345 /// predicate, do SROA now.
346 void SROA::DoScalarReplacement(AllocaInst *AI,
347 std::vector<AllocaInst*> &WorkList) {
348 DEBUG(errs() << "Found inst to SROA: " << *AI << '\n');
349 SmallVector<AllocaInst*, 32> ElementAllocas;
350 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
351 ElementAllocas.reserve(ST->getNumContainedTypes());
352 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
353 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
355 AI->getName() + "." + Twine(i), AI);
356 ElementAllocas.push_back(NA);
357 WorkList.push_back(NA); // Add to worklist for recursive processing
360 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
361 ElementAllocas.reserve(AT->getNumElements());
362 const Type *ElTy = AT->getElementType();
363 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
364 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
365 AI->getName() + "." + Twine(i), AI);
366 ElementAllocas.push_back(NA);
367 WorkList.push_back(NA); // Add to worklist for recursive processing
371 // Now that we have created the new alloca instructions, rewrite all the
372 // uses of the old alloca.
373 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
375 // Now erase any instructions that were made dead while rewriting the alloca.
376 DeleteDeadInstructions();
377 AI->eraseFromParent();
382 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
383 /// recursively including all their operands that become trivially dead.
384 void SROA::DeleteDeadInstructions() {
385 while (!DeadInsts.empty()) {
386 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
388 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
389 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
390 // Zero out the operand and see if it becomes trivially dead.
391 // (But, don't add allocas to the dead instruction list -- they are
392 // already on the worklist and will be deleted separately.)
394 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
395 DeadInsts.push_back(U);
398 I->eraseFromParent();
402 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
403 /// performing scalar replacement of alloca AI. The results are flagged in
404 /// the Info parameter. Offset indicates the position within AI that is
405 /// referenced by this instruction.
406 void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
408 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
409 Instruction *User = cast<Instruction>(*UI);
411 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
412 isSafeForScalarRepl(BC, AI, Offset, Info);
413 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
414 uint64_t GEPOffset = Offset;
415 isSafeGEP(GEPI, AI, GEPOffset, Info);
417 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
418 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
419 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
421 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
422 UI.getOperandNo() == 1, Info);
425 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
426 if (!LI->isVolatile()) {
427 const Type *LIType = LI->getType();
428 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
429 LIType, false, Info);
432 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
433 // Store is ok if storing INTO the pointer, not storing the pointer
434 if (!SI->isVolatile() && SI->getOperand(0) != I) {
435 const Type *SIType = SI->getOperand(0)->getType();
436 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
440 } else if (isa<DbgInfoIntrinsic>(UI)) {
441 // If one user is DbgInfoIntrinsic then check if all users are
442 // DbgInfoIntrinsics.
443 if (OnlyUsedByDbgInfoIntrinsics(I)) {
444 Info.needsCleanup = true;
449 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
452 if (Info.isUnsafe) return;
456 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
457 /// replacement. It is safe when all the indices are constant, in-bounds
458 /// references, and when the resulting offset corresponds to an element within
459 /// the alloca type. The results are flagged in the Info parameter. Upon
460 /// return, Offset is adjusted as specified by the GEP indices.
461 void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
462 uint64_t &Offset, AllocaInfo &Info) {
463 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
467 // Walk through the GEP type indices, checking the types that this indexes
469 for (; GEPIt != E; ++GEPIt) {
470 // Ignore struct elements, no extra checking needed for these.
471 if (isa<StructType>(*GEPIt))
474 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
476 return MarkUnsafe(Info);
479 // Compute the offset due to this GEP and check if the alloca has a
480 // component element at that offset.
481 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
482 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
483 &Indices[0], Indices.size());
484 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
488 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
489 /// alloca or has an offset and size that corresponds to a component element
490 /// within it. The offset checked here may have been formed from a GEP with a
491 /// pointer bitcasted to a different type.
492 void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
493 const Type *MemOpType, bool isStore,
495 // Check if this is a load/store of the entire alloca.
496 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
497 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
498 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
499 // (which are essentially the same as the MemIntrinsics, especially with
500 // regard to copying padding between elements), or references using the
501 // aggregate type of the alloca.
502 if (!MemOpType || isa<IntegerType>(MemOpType) || UsesAggregateType) {
503 if (!UsesAggregateType) {
505 Info.isMemCpyDst = true;
507 Info.isMemCpySrc = true;
512 // Check if the offset/size correspond to a component within the alloca type.
513 const Type *T = AI->getAllocatedType();
514 if (TypeHasComponent(T, Offset, MemSize))
517 return MarkUnsafe(Info);
520 /// TypeHasComponent - Return true if T has a component type with the
521 /// specified offset and size. If Size is zero, do not check the size.
522 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
525 if (const StructType *ST = dyn_cast<StructType>(T)) {
526 const StructLayout *Layout = TD->getStructLayout(ST);
527 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
528 EltTy = ST->getContainedType(EltIdx);
529 EltSize = TD->getTypeAllocSize(EltTy);
530 Offset -= Layout->getElementOffset(EltIdx);
531 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
532 EltTy = AT->getElementType();
533 EltSize = TD->getTypeAllocSize(EltTy);
534 if (Offset >= AT->getNumElements() * EltSize)
540 if (Offset == 0 && (Size == 0 || EltSize == Size))
542 // Check if the component spans multiple elements.
543 if (Offset + Size > EltSize)
545 return TypeHasComponent(EltTy, Offset, Size);
548 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
549 /// the instruction I, which references it, to use the separate elements.
550 /// Offset indicates the position within AI that is referenced by this
552 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
553 SmallVector<AllocaInst*, 32> &NewElts) {
554 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
555 Instruction *User = cast<Instruction>(*UI);
557 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
558 RewriteBitCast(BC, AI, Offset, NewElts);
559 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
560 RewriteGEP(GEPI, AI, Offset, NewElts);
561 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
562 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
563 uint64_t MemSize = Length->getZExtValue();
565 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
566 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
567 // Otherwise the intrinsic can only touch a single element and the
568 // address operand will be updated, so nothing else needs to be done.
569 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
570 const Type *LIType = LI->getType();
571 if (LIType == AI->getAllocatedType()) {
573 // %res = load { i32, i32 }* %alloc
575 // %load.0 = load i32* %alloc.0
576 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
577 // %load.1 = load i32* %alloc.1
578 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
579 // (Also works for arrays instead of structs)
580 Value *Insert = UndefValue::get(LIType);
581 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
582 Value *Load = new LoadInst(NewElts[i], "load", LI);
583 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
585 LI->replaceAllUsesWith(Insert);
586 DeadInsts.push_back(LI);
587 } else if (isa<IntegerType>(LIType) &&
588 TD->getTypeAllocSize(LIType) ==
589 TD->getTypeAllocSize(AI->getAllocatedType())) {
590 // If this is a load of the entire alloca to an integer, rewrite it.
591 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
593 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
594 Value *Val = SI->getOperand(0);
595 const Type *SIType = Val->getType();
596 if (SIType == AI->getAllocatedType()) {
598 // store { i32, i32 } %val, { i32, i32 }* %alloc
600 // %val.0 = extractvalue { i32, i32 } %val, 0
601 // store i32 %val.0, i32* %alloc.0
602 // %val.1 = extractvalue { i32, i32 } %val, 1
603 // store i32 %val.1, i32* %alloc.1
604 // (Also works for arrays instead of structs)
605 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
606 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
607 new StoreInst(Extract, NewElts[i], SI);
609 DeadInsts.push_back(SI);
610 } else if (isa<IntegerType>(SIType) &&
611 TD->getTypeAllocSize(SIType) ==
612 TD->getTypeAllocSize(AI->getAllocatedType())) {
613 // If this is a store of the entire alloca from an integer, rewrite it.
614 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
620 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
621 /// and recursively continue updating all of its uses.
622 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
623 SmallVector<AllocaInst*, 32> &NewElts) {
624 RewriteForScalarRepl(BC, AI, Offset, NewElts);
625 if (BC->getOperand(0) != AI)
628 // The bitcast references the original alloca. Replace its uses with
629 // references to the first new element alloca.
630 Instruction *Val = NewElts[0];
631 if (Val->getType() != BC->getDestTy()) {
632 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
635 BC->replaceAllUsesWith(Val);
636 DeadInsts.push_back(BC);
639 /// FindElementAndOffset - Return the index of the element containing Offset
640 /// within the specified type, which must be either a struct or an array.
641 /// Sets T to the type of the element and Offset to the offset within that
642 /// element. IdxTy is set to the type of the index result to be used in a
644 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
645 const Type *&IdxTy) {
647 if (const StructType *ST = dyn_cast<StructType>(T)) {
648 const StructLayout *Layout = TD->getStructLayout(ST);
649 Idx = Layout->getElementContainingOffset(Offset);
650 T = ST->getContainedType(Idx);
651 Offset -= Layout->getElementOffset(Idx);
652 IdxTy = Type::getInt32Ty(T->getContext());
655 const ArrayType *AT = cast<ArrayType>(T);
656 T = AT->getElementType();
657 uint64_t EltSize = TD->getTypeAllocSize(T);
658 Idx = Offset / EltSize;
659 Offset -= Idx * EltSize;
660 IdxTy = Type::getInt64Ty(T->getContext());
664 /// RewriteGEP - Check if this GEP instruction moves the pointer across
665 /// elements of the alloca that are being split apart, and if so, rewrite
666 /// the GEP to be relative to the new element.
667 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
668 SmallVector<AllocaInst*, 32> &NewElts) {
669 uint64_t OldOffset = Offset;
670 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
671 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
672 &Indices[0], Indices.size());
674 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
676 const Type *T = AI->getAllocatedType();
678 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
679 if (GEPI->getOperand(0) == AI)
680 OldIdx = ~0ULL; // Force the GEP to be rewritten.
682 T = AI->getAllocatedType();
683 uint64_t EltOffset = Offset;
684 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
686 // If this GEP does not move the pointer across elements of the alloca
687 // being split, then it does not needs to be rewritten.
691 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
692 SmallVector<Value*, 8> NewArgs;
693 NewArgs.push_back(Constant::getNullValue(i32Ty));
694 while (EltOffset != 0) {
695 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
696 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
698 Instruction *Val = NewElts[Idx];
699 if (NewArgs.size() > 1) {
700 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
701 NewArgs.end(), "", GEPI);
704 if (Val->getType() != GEPI->getType())
705 Val = new BitCastInst(Val, GEPI->getType(), Val->getNameStr(), GEPI);
706 GEPI->replaceAllUsesWith(Val);
707 DeadInsts.push_back(GEPI);
710 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
711 /// Rewrite it to copy or set the elements of the scalarized memory.
712 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
714 SmallVector<AllocaInst*, 32> &NewElts) {
715 // If this is a memcpy/memmove, construct the other pointer as the
716 // appropriate type. The "Other" pointer is the pointer that goes to memory
717 // that doesn't have anything to do with the alloca that we are promoting. For
718 // memset, this Value* stays null.
720 LLVMContext &Context = MI->getContext();
721 unsigned MemAlignment = MI->getAlignment();
722 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
723 if (Inst == MTI->getRawDest())
724 OtherPtr = MTI->getRawSource();
726 assert(Inst == MTI->getRawSource());
727 OtherPtr = MTI->getRawDest();
731 // If there is an other pointer, we want to convert it to the same pointer
732 // type as AI has, so we can GEP through it safely.
735 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
736 // optimization, but it's also required to detect the corner case where
737 // both pointer operands are referencing the same memory, and where
738 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
739 // function is only called for mem intrinsics that access the whole
740 // aggregate, so non-zero GEPs are not an issue here.)
742 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
743 OtherPtr = BC->getOperand(0);
746 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
747 // All zero GEPs are effectively bitcasts.
748 if (GEP->hasAllZeroIndices()) {
749 OtherPtr = GEP->getOperand(0);
755 // If OtherPtr has already been rewritten, this intrinsic will be dead.
756 if (OtherPtr == NewElts[0])
759 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
760 if (BCE->getOpcode() == Instruction::BitCast)
761 OtherPtr = BCE->getOperand(0);
763 // If the pointer is not the right type, insert a bitcast to the right
765 if (OtherPtr->getType() != AI->getType())
766 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
770 // Process each element of the aggregate.
771 Value *TheFn = MI->getOperand(0);
772 const Type *BytePtrTy = MI->getRawDest()->getType();
773 bool SROADest = MI->getRawDest() == Inst;
775 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
777 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
778 // If this is a memcpy/memmove, emit a GEP of the other element address.
780 unsigned OtherEltAlign = MemAlignment;
782 if (OtherPtr == AI) {
783 OtherElt = NewElts[i];
785 } else if (OtherPtr) {
786 Value *Idx[2] = { Zero,
787 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
788 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
789 OtherPtr->getNameStr()+"."+Twine(i),
792 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
793 if (const StructType *ST =
794 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
795 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
798 cast<SequentialType>(OtherPtr->getType())->getElementType();
799 EltOffset = TD->getTypeAllocSize(EltTy)*i;
802 // The alignment of the other pointer is the guaranteed alignment of the
803 // element, which is affected by both the known alignment of the whole
804 // mem intrinsic and the alignment of the element. If the alignment of
805 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
806 // known alignment is just 4 bytes.
807 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
810 Value *EltPtr = NewElts[i];
811 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
813 // If we got down to a scalar, insert a load or store as appropriate.
814 if (EltTy->isSingleValueType()) {
815 if (isa<MemTransferInst>(MI)) {
817 // From Other to Alloca.
818 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
819 new StoreInst(Elt, EltPtr, MI);
821 // From Alloca to Other.
822 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
823 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
827 assert(isa<MemSetInst>(MI));
829 // If the stored element is zero (common case), just store a null
832 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
834 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
836 // If EltTy is a vector type, get the element type.
837 const Type *ValTy = EltTy->getScalarType();
839 // Construct an integer with the right value.
840 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
841 APInt OneVal(EltSize, CI->getZExtValue());
842 APInt TotalVal(OneVal);
844 for (unsigned i = 0; 8*i < EltSize; ++i) {
845 TotalVal = TotalVal.shl(8);
849 // Convert the integer value to the appropriate type.
850 StoreVal = ConstantInt::get(Context, TotalVal);
851 if (isa<PointerType>(ValTy))
852 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
853 else if (ValTy->isFloatingPoint())
854 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
855 assert(StoreVal->getType() == ValTy && "Type mismatch!");
857 // If the requested value was a vector constant, create it.
858 if (EltTy != ValTy) {
859 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
860 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
861 StoreVal = ConstantVector::get(&Elts[0], NumElts);
864 new StoreInst(StoreVal, EltPtr, MI);
867 // Otherwise, if we're storing a byte variable, use a memset call for
871 // Cast the element pointer to BytePtrTy.
872 if (EltPtr->getType() != BytePtrTy)
873 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
875 // Cast the other pointer (if we have one) to BytePtrTy.
876 if (OtherElt && OtherElt->getType() != BytePtrTy)
877 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
880 unsigned EltSize = TD->getTypeAllocSize(EltTy);
882 // Finally, insert the meminst for this element.
883 if (isa<MemTransferInst>(MI)) {
885 SROADest ? EltPtr : OtherElt, // Dest ptr
886 SROADest ? OtherElt : EltPtr, // Src ptr
887 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
889 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
891 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
893 assert(isa<MemSetInst>(MI));
895 EltPtr, MI->getOperand(2), // Dest, Value,
896 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
899 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
902 DeadInsts.push_back(MI);
905 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
906 /// overwrites the entire allocation. Extract out the pieces of the stored
907 /// integer and store them individually.
908 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
909 SmallVector<AllocaInst*, 32> &NewElts){
910 // Extract each element out of the integer according to its structure offset
911 // and store the element value to the individual alloca.
912 Value *SrcVal = SI->getOperand(0);
913 const Type *AllocaEltTy = AI->getAllocatedType();
914 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
916 // Handle tail padding by extending the operand
917 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
918 SrcVal = new ZExtInst(SrcVal,
919 IntegerType::get(SI->getContext(), AllocaSizeBits),
922 DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
925 // There are two forms here: AI could be an array or struct. Both cases
926 // have different ways to compute the element offset.
927 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
928 const StructLayout *Layout = TD->getStructLayout(EltSTy);
930 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
931 // Get the number of bits to shift SrcVal to get the value.
932 const Type *FieldTy = EltSTy->getElementType(i);
933 uint64_t Shift = Layout->getElementOffsetInBits(i);
935 if (TD->isBigEndian())
936 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
938 Value *EltVal = SrcVal;
940 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
941 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
942 "sroa.store.elt", SI);
945 // Truncate down to an integer of the right size.
946 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
948 // Ignore zero sized fields like {}, they obviously contain no data.
949 if (FieldSizeBits == 0) continue;
951 if (FieldSizeBits != AllocaSizeBits)
952 EltVal = new TruncInst(EltVal,
953 IntegerType::get(SI->getContext(), FieldSizeBits),
955 Value *DestField = NewElts[i];
956 if (EltVal->getType() == FieldTy) {
957 // Storing to an integer field of this size, just do it.
958 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
959 // Bitcast to the right element type (for fp/vector values).
960 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
962 // Otherwise, bitcast the dest pointer (for aggregates).
963 DestField = new BitCastInst(DestField,
964 PointerType::getUnqual(EltVal->getType()),
967 new StoreInst(EltVal, DestField, SI);
971 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
972 const Type *ArrayEltTy = ATy->getElementType();
973 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
974 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
978 if (TD->isBigEndian())
979 Shift = AllocaSizeBits-ElementOffset;
983 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
984 // Ignore zero sized fields like {}, they obviously contain no data.
985 if (ElementSizeBits == 0) continue;
987 Value *EltVal = SrcVal;
989 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
990 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
991 "sroa.store.elt", SI);
994 // Truncate down to an integer of the right size.
995 if (ElementSizeBits != AllocaSizeBits)
996 EltVal = new TruncInst(EltVal,
997 IntegerType::get(SI->getContext(),
998 ElementSizeBits),"",SI);
999 Value *DestField = NewElts[i];
1000 if (EltVal->getType() == ArrayEltTy) {
1001 // Storing to an integer field of this size, just do it.
1002 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1003 // Bitcast to the right element type (for fp/vector values).
1004 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1006 // Otherwise, bitcast the dest pointer (for aggregates).
1007 DestField = new BitCastInst(DestField,
1008 PointerType::getUnqual(EltVal->getType()),
1011 new StoreInst(EltVal, DestField, SI);
1013 if (TD->isBigEndian())
1014 Shift -= ElementOffset;
1016 Shift += ElementOffset;
1020 DeadInsts.push_back(SI);
1023 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1024 /// an integer. Load the individual pieces to form the aggregate value.
1025 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1026 SmallVector<AllocaInst*, 32> &NewElts) {
1027 // Extract each element out of the NewElts according to its structure offset
1028 // and form the result value.
1029 const Type *AllocaEltTy = AI->getAllocatedType();
1030 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1032 DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1035 // There are two forms here: AI could be an array or struct. Both cases
1036 // have different ways to compute the element offset.
1037 const StructLayout *Layout = 0;
1038 uint64_t ArrayEltBitOffset = 0;
1039 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1040 Layout = TD->getStructLayout(EltSTy);
1042 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1043 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1047 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1049 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1050 // Load the value from the alloca. If the NewElt is an aggregate, cast
1051 // the pointer to an integer of the same size before doing the load.
1052 Value *SrcField = NewElts[i];
1053 const Type *FieldTy =
1054 cast<PointerType>(SrcField->getType())->getElementType();
1055 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1057 // Ignore zero sized fields like {}, they obviously contain no data.
1058 if (FieldSizeBits == 0) continue;
1060 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1062 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1063 !isa<VectorType>(FieldTy))
1064 SrcField = new BitCastInst(SrcField,
1065 PointerType::getUnqual(FieldIntTy),
1067 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1069 // If SrcField is a fp or vector of the right size but that isn't an
1070 // integer type, bitcast to an integer so we can shift it.
1071 if (SrcField->getType() != FieldIntTy)
1072 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1074 // Zero extend the field to be the same size as the final alloca so that
1075 // we can shift and insert it.
1076 if (SrcField->getType() != ResultVal->getType())
1077 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1079 // Determine the number of bits to shift SrcField.
1081 if (Layout) // Struct case.
1082 Shift = Layout->getElementOffsetInBits(i);
1084 Shift = i*ArrayEltBitOffset;
1086 if (TD->isBigEndian())
1087 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1090 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1091 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1094 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1097 // Handle tail padding by truncating the result
1098 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1099 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1101 LI->replaceAllUsesWith(ResultVal);
1102 DeadInsts.push_back(LI);
1105 /// HasPadding - Return true if the specified type has any structure or
1106 /// alignment padding, false otherwise.
1107 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1108 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1109 const StructLayout *SL = TD.getStructLayout(STy);
1110 unsigned PrevFieldBitOffset = 0;
1111 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1112 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1114 // Padding in sub-elements?
1115 if (HasPadding(STy->getElementType(i), TD))
1118 // Check to see if there is any padding between this element and the
1121 unsigned PrevFieldEnd =
1122 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1123 if (PrevFieldEnd < FieldBitOffset)
1127 PrevFieldBitOffset = FieldBitOffset;
1130 // Check for tail padding.
1131 if (unsigned EltCount = STy->getNumElements()) {
1132 unsigned PrevFieldEnd = PrevFieldBitOffset +
1133 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1134 if (PrevFieldEnd < SL->getSizeInBits())
1138 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1139 return HasPadding(ATy->getElementType(), TD);
1140 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1141 return HasPadding(VTy->getElementType(), TD);
1143 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1146 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1147 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1148 /// or 1 if safe after canonicalization has been performed.
1149 int SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1150 // Loop over the use list of the alloca. We can only transform it if all of
1151 // the users are safe to transform.
1154 isSafeForScalarRepl(AI, AI, 0, Info);
1155 if (Info.isUnsafe) {
1156 DEBUG(errs() << "Cannot transform: " << *AI << '\n');
1160 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1161 // source and destination, we have to be careful. In particular, the memcpy
1162 // could be moving around elements that live in structure padding of the LLVM
1163 // types, but may actually be used. In these cases, we refuse to promote the
1165 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1166 HasPadding(AI->getAllocatedType(), *TD))
1169 // If we require cleanup, return 1, otherwise return 3.
1170 return Info.needsCleanup ? 1 : 3;
1173 /// CleanupAllocaUsers - If SROA reported that it can promote the specified
1174 /// allocation, but only if cleaned up, perform the cleanups required.
1175 void SROA::CleanupAllocaUsers(Value *V) {
1176 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
1179 Instruction *I = cast<Instruction>(U);
1180 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
1181 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
1182 // Safe to remove debug info uses.
1183 while (!DbgInUses.empty()) {
1184 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1185 DI->eraseFromParent();
1187 I->eraseFromParent();
1192 /// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1193 /// the offset specified by Offset (which is specified in bytes).
1195 /// There are two cases we handle here:
1196 /// 1) A union of vector types of the same size and potentially its elements.
1197 /// Here we turn element accesses into insert/extract element operations.
1198 /// This promotes a <4 x float> with a store of float to the third element
1199 /// into a <4 x float> that uses insert element.
1200 /// 2) A fully general blob of memory, which we turn into some (potentially
1201 /// large) integer type with extract and insert operations where the loads
1202 /// and stores would mutate the memory.
1203 static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
1204 unsigned AllocaSize, const TargetData &TD,
1205 LLVMContext &Context) {
1206 // If this could be contributing to a vector, analyze it.
1207 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
1209 // If the In type is a vector that is the same size as the alloca, see if it
1210 // matches the existing VecTy.
1211 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1212 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1213 // If we're storing/loading a vector of the right size, allow it as a
1214 // vector. If this the first vector we see, remember the type so that
1215 // we know the element size.
1220 } else if (In->isFloatTy() || In->isDoubleTy() ||
1221 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1222 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1223 // If we're accessing something that could be an element of a vector, see
1224 // if the implied vector agrees with what we already have and if Offset is
1225 // compatible with it.
1226 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1227 if (Offset % EltSize == 0 &&
1228 AllocaSize % EltSize == 0 &&
1230 cast<VectorType>(VecTy)->getElementType()
1231 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1233 VecTy = VectorType::get(In, AllocaSize/EltSize);
1239 // Otherwise, we have a case that we can't handle with an optimized vector
1240 // form. We can still turn this into a large integer.
1241 VecTy = Type::getVoidTy(Context);
1244 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
1245 /// its accesses to a single vector type, return true and set VecTy to
1246 /// the new type. If we could convert the alloca into a single promotable
1247 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1248 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1249 /// is the current offset from the base of the alloca being analyzed.
1251 /// If we see at least one access to the value that is as a vector type, set the
1253 bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1254 bool &SawVec, uint64_t Offset,
1255 unsigned AllocaSize) {
1256 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1257 Instruction *User = cast<Instruction>(*UI);
1259 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1260 // Don't break volatile loads.
1261 if (LI->isVolatile())
1263 MergeInType(LI->getType(), Offset, VecTy,
1264 AllocaSize, *TD, V->getContext());
1265 SawVec |= isa<VectorType>(LI->getType());
1269 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1270 // Storing the pointer, not into the value?
1271 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
1272 MergeInType(SI->getOperand(0)->getType(), Offset,
1273 VecTy, AllocaSize, *TD, V->getContext());
1274 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
1278 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1279 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1282 IsNotTrivial = true;
1286 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1287 // If this is a GEP with a variable indices, we can't handle it.
1288 if (!GEP->hasAllConstantIndices())
1291 // Compute the offset that this GEP adds to the pointer.
1292 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1293 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
1294 &Indices[0], Indices.size());
1295 // See if all uses can be converted.
1296 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
1299 IsNotTrivial = true;
1303 // If this is a constant sized memset of a constant value (e.g. 0) we can
1305 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1306 // Store of constant value and constant size.
1307 if (isa<ConstantInt>(MSI->getValue()) &&
1308 isa<ConstantInt>(MSI->getLength())) {
1309 IsNotTrivial = true;
1314 // If this is a memcpy or memmove into or out of the whole allocation, we
1315 // can handle it like a load or store of the scalar type.
1316 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1317 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1318 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1319 IsNotTrivial = true;
1324 // Ignore dbg intrinsic.
1325 if (isa<DbgInfoIntrinsic>(User))
1328 // Otherwise, we cannot handle this!
1335 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
1336 /// directly. This happens when we are converting an "integer union" to a
1337 /// single integer scalar, or when we are converting a "vector union" to a
1338 /// vector with insert/extractelement instructions.
1340 /// Offset is an offset from the original alloca, in bits that need to be
1341 /// shifted to the right. By the end of this, there should be no uses of Ptr.
1342 void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
1343 while (!Ptr->use_empty()) {
1344 Instruction *User = cast<Instruction>(Ptr->use_back());
1346 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
1347 ConvertUsesToScalar(CI, NewAI, Offset);
1348 CI->eraseFromParent();
1352 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1353 // Compute the offset that this GEP adds to the pointer.
1354 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1355 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getPointerOperandType(),
1356 &Indices[0], Indices.size());
1357 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
1358 GEP->eraseFromParent();
1362 IRBuilder<> Builder(User->getParent(), User);
1364 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1365 // The load is a bit extract from NewAI shifted right by Offset bits.
1366 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1368 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1369 LI->replaceAllUsesWith(NewLoadVal);
1370 LI->eraseFromParent();
1374 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1375 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1376 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
1377 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1379 Builder.CreateStore(New, NewAI);
1380 SI->eraseFromParent();
1382 // If the load we just inserted is now dead, then the inserted store
1383 // overwrote the entire thing.
1384 if (Old->use_empty())
1385 Old->eraseFromParent();
1389 // If this is a constant sized memset of a constant value (e.g. 0) we can
1390 // transform it into a store of the expanded constant value.
1391 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1392 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1393 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
1394 if (NumBytes != 0) {
1395 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1397 // Compute the value replicated the right number of times.
1398 APInt APVal(NumBytes*8, Val);
1400 // Splat the value if non-zero.
1402 for (unsigned i = 1; i != NumBytes; ++i)
1403 APVal |= APVal << 8;
1405 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
1406 Value *New = ConvertScalar_InsertValue(
1407 ConstantInt::get(User->getContext(), APVal),
1408 Old, Offset, Builder);
1409 Builder.CreateStore(New, NewAI);
1411 // If the load we just inserted is now dead, then the memset overwrote
1412 // the entire thing.
1413 if (Old->use_empty())
1414 Old->eraseFromParent();
1416 MSI->eraseFromParent();
1420 // If this is a memcpy or memmove into or out of the whole allocation, we
1421 // can handle it like a load or store of the scalar type.
1422 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1423 assert(Offset == 0 && "must be store to start of alloca");
1425 // If the source and destination are both to the same alloca, then this is
1426 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1428 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1430 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1431 // Dest must be OrigAI, change this to be a load from the original
1432 // pointer (bitcasted), then a store to our new alloca.
1433 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1434 Value *SrcPtr = MTI->getSource();
1435 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1437 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1438 SrcVal->setAlignment(MTI->getAlignment());
1439 Builder.CreateStore(SrcVal, NewAI);
1440 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1441 // Src must be OrigAI, change this to be a load from NewAI then a store
1442 // through the original dest pointer (bitcasted).
1443 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1444 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1446 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1447 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1448 NewStore->setAlignment(MTI->getAlignment());
1450 // Noop transfer. Src == Dst
1454 MTI->eraseFromParent();
1458 // If user is a dbg info intrinsic then it is safe to remove it.
1459 if (isa<DbgInfoIntrinsic>(User)) {
1460 User->eraseFromParent();
1464 llvm_unreachable("Unsupported operation!");
1468 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1469 /// or vector value FromVal, extracting the bits from the offset specified by
1470 /// Offset. This returns the value, which is of type ToType.
1472 /// This happens when we are converting an "integer union" to a single
1473 /// integer scalar, or when we are converting a "vector union" to a vector with
1474 /// insert/extractelement instructions.
1476 /// Offset is an offset from the original alloca, in bits that need to be
1477 /// shifted to the right.
1478 Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1479 uint64_t Offset, IRBuilder<> &Builder) {
1480 // If the load is of the whole new alloca, no conversion is needed.
1481 if (FromVal->getType() == ToType && Offset == 0)
1484 // If the result alloca is a vector type, this is either an element
1485 // access or a bitcast to another vector type of the same size.
1486 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1487 if (isa<VectorType>(ToType))
1488 return Builder.CreateBitCast(FromVal, ToType, "tmp");
1490 // Otherwise it must be an element access.
1493 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1494 Elt = Offset/EltSize;
1495 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
1497 // Return the element extracted out of it.
1498 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1499 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
1500 if (V->getType() != ToType)
1501 V = Builder.CreateBitCast(V, ToType, "tmp");
1505 // If ToType is a first class aggregate, extract out each of the pieces and
1506 // use insertvalue's to form the FCA.
1507 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1508 const StructLayout &Layout = *TD->getStructLayout(ST);
1509 Value *Res = UndefValue::get(ST);
1510 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1511 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
1512 Offset+Layout.getElementOffsetInBits(i),
1514 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1519 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
1520 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1521 Value *Res = UndefValue::get(AT);
1522 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1523 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1524 Offset+i*EltSize, Builder);
1525 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1530 // Otherwise, this must be a union that was converted to an integer value.
1531 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
1533 // If this is a big-endian system and the load is narrower than the
1534 // full alloca type, we need to do a shift to get the right bits.
1536 if (TD->isBigEndian()) {
1537 // On big-endian machines, the lowest bit is stored at the bit offset
1538 // from the pointer given by getTypeStoreSizeInBits. This matters for
1539 // integers with a bitwidth that is not a multiple of 8.
1540 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
1541 TD->getTypeStoreSizeInBits(ToType) - Offset;
1546 // Note: we support negative bitwidths (with shl) which are not defined.
1547 // We do this to support (f.e.) loads off the end of a structure where
1548 // only some bits are used.
1549 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
1550 FromVal = Builder.CreateLShr(FromVal,
1551 ConstantInt::get(FromVal->getType(),
1553 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
1554 FromVal = Builder.CreateShl(FromVal,
1555 ConstantInt::get(FromVal->getType(),
1558 // Finally, unconditionally truncate the integer to the right width.
1559 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
1560 if (LIBitWidth < NTy->getBitWidth())
1562 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1563 LIBitWidth), "tmp");
1564 else if (LIBitWidth > NTy->getBitWidth())
1566 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1567 LIBitWidth), "tmp");
1569 // If the result is an integer, this is a trunc or bitcast.
1570 if (isa<IntegerType>(ToType)) {
1572 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
1573 // Just do a bitcast, we know the sizes match up.
1574 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
1576 // Otherwise must be a pointer.
1577 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
1579 assert(FromVal->getType() == ToType && "Didn't convert right?");
1583 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1584 /// or vector value "Old" at the offset specified by Offset.
1586 /// This happens when we are converting an "integer union" to a
1587 /// single integer scalar, or when we are converting a "vector union" to a
1588 /// vector with insert/extractelement instructions.
1590 /// Offset is an offset from the original alloca, in bits that need to be
1591 /// shifted to the right.
1592 Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
1593 uint64_t Offset, IRBuilder<> &Builder) {
1595 // Convert the stored type to the actual type, shift it left to insert
1596 // then 'or' into place.
1597 const Type *AllocaType = Old->getType();
1598 LLVMContext &Context = Old->getContext();
1600 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
1601 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1602 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
1604 // Changing the whole vector with memset or with an access of a different
1606 if (ValSize == VecSize)
1607 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1609 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
1611 // Must be an element insertion.
1612 unsigned Elt = Offset/EltSize;
1614 if (SV->getType() != VTy->getElementType())
1615 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1617 SV = Builder.CreateInsertElement(Old, SV,
1618 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
1623 // If SV is a first-class aggregate value, insert each value recursively.
1624 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1625 const StructLayout &Layout = *TD->getStructLayout(ST);
1626 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1627 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1628 Old = ConvertScalar_InsertValue(Elt, Old,
1629 Offset+Layout.getElementOffsetInBits(i),
1635 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
1636 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
1637 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1638 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1639 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
1644 // If SV is a float, convert it to the appropriate integer type.
1645 // If it is a pointer, do the same.
1646 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1647 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1648 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1649 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1650 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
1651 SV = Builder.CreateBitCast(SV,
1652 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
1653 else if (isa<PointerType>(SV->getType()))
1654 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
1656 // Zero extend or truncate the value if needed.
1657 if (SV->getType() != AllocaType) {
1658 if (SV->getType()->getPrimitiveSizeInBits() <
1659 AllocaType->getPrimitiveSizeInBits())
1660 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
1662 // Truncation may be needed if storing more than the alloca can hold
1663 // (undefined behavior).
1664 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
1665 SrcWidth = DestWidth;
1666 SrcStoreWidth = DestStoreWidth;
1670 // If this is a big-endian system and the store is narrower than the
1671 // full alloca type, we need to do a shift to get the right bits.
1673 if (TD->isBigEndian()) {
1674 // On big-endian machines, the lowest bit is stored at the bit offset
1675 // from the pointer given by getTypeStoreSizeInBits. This matters for
1676 // integers with a bitwidth that is not a multiple of 8.
1677 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1682 // Note: we support negative bitwidths (with shr) which are not defined.
1683 // We do this to support (f.e.) stores off the end of a structure where
1684 // only some bits in the structure are set.
1685 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1686 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1687 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1690 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1691 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1693 Mask = Mask.lshr(-ShAmt);
1696 // Mask out the bits we are about to insert from the old value, and or
1698 if (SrcWidth != DestWidth) {
1699 assert(DestWidth > SrcWidth);
1700 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1701 SV = Builder.CreateOr(Old, SV, "ins");
1708 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1709 /// some part of a constant global variable. This intentionally only accepts
1710 /// constant expressions because we don't can't rewrite arbitrary instructions.
1711 static bool PointsToConstantGlobal(Value *V) {
1712 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1713 return GV->isConstant();
1714 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1715 if (CE->getOpcode() == Instruction::BitCast ||
1716 CE->getOpcode() == Instruction::GetElementPtr)
1717 return PointsToConstantGlobal(CE->getOperand(0));
1721 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1722 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1723 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1724 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1725 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1726 /// the alloca, and if the source pointer is a pointer to a constant global, we
1727 /// can optimize this.
1728 static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1730 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1731 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1732 // Ignore non-volatile loads, they are always ok.
1733 if (!LI->isVolatile())
1736 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1737 // If uses of the bitcast are ok, we are ok.
1738 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1742 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1743 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1744 // doesn't, it does.
1745 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1746 isOffset || !GEP->hasAllZeroIndices()))
1751 // If this is isn't our memcpy/memmove, reject it as something we can't
1753 if (!isa<MemTransferInst>(*UI))
1756 // If we already have seen a copy, reject the second one.
1757 if (TheCopy) return false;
1759 // If the pointer has been offset from the start of the alloca, we can't
1760 // safely handle this.
1761 if (isOffset) return false;
1763 // If the memintrinsic isn't using the alloca as the dest, reject it.
1764 if (UI.getOperandNo() != 1) return false;
1766 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1768 // If the source of the memcpy/move is not a constant global, reject it.
1769 if (!PointsToConstantGlobal(MI->getOperand(2)))
1772 // Otherwise, the transform is safe. Remember the copy instruction.
1778 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1779 /// modified by a copy from a constant global. If we can prove this, we can
1780 /// replace any uses of the alloca with uses of the global directly.
1781 Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1782 Instruction *TheCopy = 0;
1783 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))