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 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
95 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
100 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
102 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
104 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
106 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
108 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
109 const Type *MemOpType, bool isStore, AllocaInfo &Info);
110 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
111 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
114 void DoScalarReplacement(AllocaInst *AI,
115 std::vector<AllocaInst*> &WorkList);
116 void DeleteDeadInstructions();
117 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
119 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
120 SmallVector<AllocaInst*, 32> &NewElts);
121 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
127 SmallVector<AllocaInst*, 32> &NewElts);
128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
129 SmallVector<AllocaInst*, 32> &NewElts);
130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
131 SmallVector<AllocaInst*, 32> &NewElts);
133 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
138 static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
140 // Public interface to the ScalarReplAggregates pass
141 FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
142 return new SROA(Threshold);
146 //===----------------------------------------------------------------------===//
147 // Convert To Scalar Optimization.
148 //===----------------------------------------------------------------------===//
151 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
152 /// optimization, which scans the uses of an alloca and determines if it can
153 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
154 class ConvertToScalarInfo {
155 /// AllocaSize - The size of the alloca being considered.
157 const TargetData &TD;
159 /// IsNotTrivial - This is set to true if there is some access to the object
160 /// which means that mem2reg can't promote it.
163 /// VectorTy - This tracks the type that we should promote the vector to if
164 /// it is possible to turn it into a vector. This starts out null, and if it
165 /// isn't possible to turn into a vector type, it gets set to VoidTy.
166 const Type *VectorTy;
168 /// HadAVector - True if there is at least one vector access to the alloca.
169 /// We don't want to turn random arrays into vectors and use vector element
170 /// insert/extract, but if there are element accesses to something that is
171 /// also declared as a vector, we do want to promote to a vector.
175 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
176 : AllocaSize(Size), TD(td) {
177 IsNotTrivial = false;
182 AllocaInst *TryConvert(AllocaInst *AI);
185 bool CanConvertToScalar(Value *V, uint64_t Offset);
186 void MergeInType(const Type *In, uint64_t Offset);
187 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
189 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
190 uint64_t Offset, IRBuilder<> &Builder);
191 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
192 uint64_t Offset, IRBuilder<> &Builder);
194 } // end anonymous namespace.
196 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
197 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
198 /// alloca if possible or null if not.
199 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
200 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
202 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
205 // If we were able to find a vector type that can handle this with
206 // insert/extract elements, and if there was at least one use that had
207 // a vector type, promote this to a vector. We don't want to promote
208 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
209 // we just get a lot of insert/extracts. If at least one vector is
210 // involved, then we probably really do have a union of vector/array.
212 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
213 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
214 << *VectorTy << '\n');
215 NewTy = VectorTy; // Use the vector type.
217 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
218 // Create and insert the integer alloca.
219 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
221 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
222 ConvertUsesToScalar(AI, NewAI, 0);
226 /// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
227 /// so far at the offset specified by Offset (which is specified in bytes).
229 /// There are two cases we handle here:
230 /// 1) A union of vector types of the same size and potentially its elements.
231 /// Here we turn element accesses into insert/extract element operations.
232 /// This promotes a <4 x float> with a store of float to the third element
233 /// into a <4 x float> that uses insert element.
234 /// 2) A fully general blob of memory, which we turn into some (potentially
235 /// large) integer type with extract and insert operations where the loads
236 /// and stores would mutate the memory. We mark this by setting VectorTy
238 void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
239 // If we already decided to turn this into a blob of integer memory, there is
240 // nothing to be done.
241 if (VectorTy && VectorTy->isVoidTy())
244 // If this could be contributing to a vector, analyze it.
246 // If the In type is a vector that is the same size as the alloca, see if it
247 // matches the existing VecTy.
248 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
249 // Remember if we saw a vector type.
252 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
253 // If we're storing/loading a vector of the right size, allow it as a
254 // vector. If this the first vector we see, remember the type so that
255 // we know the element size. If this is a subsequent access, ignore it
256 // even if it is a differing type but the same size. Worst case we can
257 // bitcast the resultant vectors.
262 } else if (In->isFloatTy() || In->isDoubleTy() ||
263 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
264 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
265 // If we're accessing something that could be an element of a vector, see
266 // if the implied vector agrees with what we already have and if Offset is
267 // compatible with it.
268 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
269 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
271 cast<VectorType>(VectorTy)->getElementType()
272 ->getPrimitiveSizeInBits()/8 == EltSize)) {
274 VectorTy = VectorType::get(In, AllocaSize/EltSize);
279 // Otherwise, we have a case that we can't handle with an optimized vector
280 // form. We can still turn this into a large integer.
281 VectorTy = Type::getVoidTy(In->getContext());
284 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
285 /// its accesses to a single vector type, return true and set VecTy to
286 /// the new type. If we could convert the alloca into a single promotable
287 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
288 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
289 /// is the current offset from the base of the alloca being analyzed.
291 /// If we see at least one access to the value that is as a vector type, set the
293 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
294 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
295 Instruction *User = cast<Instruction>(*UI);
297 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
298 // Don't break volatile loads.
299 if (LI->isVolatile())
301 MergeInType(LI->getType(), Offset);
305 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
306 // Storing the pointer, not into the value?
307 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
308 MergeInType(SI->getOperand(0)->getType(), Offset);
312 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
313 IsNotTrivial = true; // Can't be mem2reg'd.
314 if (!CanConvertToScalar(BCI, Offset))
319 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
320 // If this is a GEP with a variable indices, we can't handle it.
321 if (!GEP->hasAllConstantIndices())
324 // Compute the offset that this GEP adds to the pointer.
325 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
326 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
327 &Indices[0], Indices.size());
328 // See if all uses can be converted.
329 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
331 IsNotTrivial = true; // Can't be mem2reg'd.
335 // If this is a constant sized memset of a constant value (e.g. 0) we can
337 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
338 // Store of constant value and constant size.
339 if (!isa<ConstantInt>(MSI->getValue()) ||
340 !isa<ConstantInt>(MSI->getLength()))
342 IsNotTrivial = true; // Can't be mem2reg'd.
346 // If this is a memcpy or memmove into or out of the whole allocation, we
347 // can handle it like a load or store of the scalar type.
348 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
349 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
350 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
353 IsNotTrivial = true; // Can't be mem2reg'd.
357 // Otherwise, we cannot handle this!
364 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
365 /// directly. This happens when we are converting an "integer union" to a
366 /// single integer scalar, or when we are converting a "vector union" to a
367 /// vector with insert/extractelement instructions.
369 /// Offset is an offset from the original alloca, in bits that need to be
370 /// shifted to the right. By the end of this, there should be no uses of Ptr.
371 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
373 while (!Ptr->use_empty()) {
374 Instruction *User = cast<Instruction>(Ptr->use_back());
376 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
377 ConvertUsesToScalar(CI, NewAI, Offset);
378 CI->eraseFromParent();
382 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
383 // Compute the offset that this GEP adds to the pointer.
384 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
385 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
386 &Indices[0], Indices.size());
387 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
388 GEP->eraseFromParent();
392 IRBuilder<> Builder(User->getParent(), User);
394 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
395 // The load is a bit extract from NewAI shifted right by Offset bits.
396 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
398 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
399 LI->replaceAllUsesWith(NewLoadVal);
400 LI->eraseFromParent();
404 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
405 assert(SI->getOperand(0) != Ptr && "Consistency error!");
406 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
407 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
409 Builder.CreateStore(New, NewAI);
410 SI->eraseFromParent();
412 // If the load we just inserted is now dead, then the inserted store
413 // overwrote the entire thing.
414 if (Old->use_empty())
415 Old->eraseFromParent();
419 // If this is a constant sized memset of a constant value (e.g. 0) we can
420 // transform it into a store of the expanded constant value.
421 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
422 assert(MSI->getRawDest() == Ptr && "Consistency error!");
423 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
425 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
427 // Compute the value replicated the right number of times.
428 APInt APVal(NumBytes*8, Val);
430 // Splat the value if non-zero.
432 for (unsigned i = 1; i != NumBytes; ++i)
435 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
436 Value *New = ConvertScalar_InsertValue(
437 ConstantInt::get(User->getContext(), APVal),
438 Old, Offset, Builder);
439 Builder.CreateStore(New, NewAI);
441 // If the load we just inserted is now dead, then the memset overwrote
443 if (Old->use_empty())
444 Old->eraseFromParent();
446 MSI->eraseFromParent();
450 // If this is a memcpy or memmove into or out of the whole allocation, we
451 // can handle it like a load or store of the scalar type.
452 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
453 assert(Offset == 0 && "must be store to start of alloca");
455 // If the source and destination are both to the same alloca, then this is
456 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
458 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
460 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
461 // Dest must be OrigAI, change this to be a load from the original
462 // pointer (bitcasted), then a store to our new alloca.
463 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
464 Value *SrcPtr = MTI->getSource();
465 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
467 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
468 SrcVal->setAlignment(MTI->getAlignment());
469 Builder.CreateStore(SrcVal, NewAI);
470 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
471 // Src must be OrigAI, change this to be a load from NewAI then a store
472 // through the original dest pointer (bitcasted).
473 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
474 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
476 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
477 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
478 NewStore->setAlignment(MTI->getAlignment());
480 // Noop transfer. Src == Dst
483 MTI->eraseFromParent();
487 llvm_unreachable("Unsupported operation!");
491 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
492 /// or vector value FromVal, extracting the bits from the offset specified by
493 /// Offset. This returns the value, which is of type ToType.
495 /// This happens when we are converting an "integer union" to a single
496 /// integer scalar, or when we are converting a "vector union" to a vector with
497 /// insert/extractelement instructions.
499 /// Offset is an offset from the original alloca, in bits that need to be
500 /// shifted to the right.
501 Value *ConvertToScalarInfo::
502 ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
503 uint64_t Offset, IRBuilder<> &Builder) {
504 // If the load is of the whole new alloca, no conversion is needed.
505 if (FromVal->getType() == ToType && Offset == 0)
508 // If the result alloca is a vector type, this is either an element
509 // access or a bitcast to another vector type of the same size.
510 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
511 if (ToType->isVectorTy())
512 return Builder.CreateBitCast(FromVal, ToType, "tmp");
514 // Otherwise it must be an element access.
517 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
518 Elt = Offset/EltSize;
519 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
521 // Return the element extracted out of it.
522 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
523 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
524 if (V->getType() != ToType)
525 V = Builder.CreateBitCast(V, ToType, "tmp");
529 // If ToType is a first class aggregate, extract out each of the pieces and
530 // use insertvalue's to form the FCA.
531 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
532 const StructLayout &Layout = *TD.getStructLayout(ST);
533 Value *Res = UndefValue::get(ST);
534 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
535 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
536 Offset+Layout.getElementOffsetInBits(i),
538 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
543 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
544 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
545 Value *Res = UndefValue::get(AT);
546 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
547 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
548 Offset+i*EltSize, Builder);
549 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
554 // Otherwise, this must be a union that was converted to an integer value.
555 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
557 // If this is a big-endian system and the load is narrower than the
558 // full alloca type, we need to do a shift to get the right bits.
560 if (TD.isBigEndian()) {
561 // On big-endian machines, the lowest bit is stored at the bit offset
562 // from the pointer given by getTypeStoreSizeInBits. This matters for
563 // integers with a bitwidth that is not a multiple of 8.
564 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
565 TD.getTypeStoreSizeInBits(ToType) - Offset;
570 // Note: we support negative bitwidths (with shl) which are not defined.
571 // We do this to support (f.e.) loads off the end of a structure where
572 // only some bits are used.
573 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
574 FromVal = Builder.CreateLShr(FromVal,
575 ConstantInt::get(FromVal->getType(),
577 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
578 FromVal = Builder.CreateShl(FromVal,
579 ConstantInt::get(FromVal->getType(),
582 // Finally, unconditionally truncate the integer to the right width.
583 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
584 if (LIBitWidth < NTy->getBitWidth())
586 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
588 else if (LIBitWidth > NTy->getBitWidth())
590 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
593 // If the result is an integer, this is a trunc or bitcast.
594 if (ToType->isIntegerTy()) {
596 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
597 // Just do a bitcast, we know the sizes match up.
598 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
600 // Otherwise must be a pointer.
601 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
603 assert(FromVal->getType() == ToType && "Didn't convert right?");
607 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
608 /// or vector value "Old" at the offset specified by Offset.
610 /// This happens when we are converting an "integer union" to a
611 /// single integer scalar, or when we are converting a "vector union" to a
612 /// vector with insert/extractelement instructions.
614 /// Offset is an offset from the original alloca, in bits that need to be
615 /// shifted to the right.
616 Value *ConvertToScalarInfo::
617 ConvertScalar_InsertValue(Value *SV, Value *Old,
618 uint64_t Offset, IRBuilder<> &Builder) {
619 // Convert the stored type to the actual type, shift it left to insert
620 // then 'or' into place.
621 const Type *AllocaType = Old->getType();
622 LLVMContext &Context = Old->getContext();
624 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
625 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
626 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
628 // Changing the whole vector with memset or with an access of a different
630 if (ValSize == VecSize)
631 return Builder.CreateBitCast(SV, AllocaType, "tmp");
633 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
635 // Must be an element insertion.
636 unsigned Elt = Offset/EltSize;
638 if (SV->getType() != VTy->getElementType())
639 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
641 SV = Builder.CreateInsertElement(Old, SV,
642 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
647 // If SV is a first-class aggregate value, insert each value recursively.
648 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
649 const StructLayout &Layout = *TD.getStructLayout(ST);
650 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
651 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
652 Old = ConvertScalar_InsertValue(Elt, Old,
653 Offset+Layout.getElementOffsetInBits(i),
659 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
660 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
661 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
662 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
663 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
668 // If SV is a float, convert it to the appropriate integer type.
669 // If it is a pointer, do the same.
670 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
671 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
672 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
673 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
674 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
675 SV = Builder.CreateBitCast(SV,
676 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
677 else if (SV->getType()->isPointerTy())
678 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
680 // Zero extend or truncate the value if needed.
681 if (SV->getType() != AllocaType) {
682 if (SV->getType()->getPrimitiveSizeInBits() <
683 AllocaType->getPrimitiveSizeInBits())
684 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
686 // Truncation may be needed if storing more than the alloca can hold
687 // (undefined behavior).
688 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
689 SrcWidth = DestWidth;
690 SrcStoreWidth = DestStoreWidth;
694 // If this is a big-endian system and the store is narrower than the
695 // full alloca type, we need to do a shift to get the right bits.
697 if (TD.isBigEndian()) {
698 // On big-endian machines, the lowest bit is stored at the bit offset
699 // from the pointer given by getTypeStoreSizeInBits. This matters for
700 // integers with a bitwidth that is not a multiple of 8.
701 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
706 // Note: we support negative bitwidths (with shr) which are not defined.
707 // We do this to support (f.e.) stores off the end of a structure where
708 // only some bits in the structure are set.
709 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
710 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
711 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
714 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
715 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
717 Mask = Mask.lshr(-ShAmt);
720 // Mask out the bits we are about to insert from the old value, and or
722 if (SrcWidth != DestWidth) {
723 assert(DestWidth > SrcWidth);
724 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
725 SV = Builder.CreateOr(Old, SV, "ins");
731 //===----------------------------------------------------------------------===//
733 //===----------------------------------------------------------------------===//
736 bool SROA::runOnFunction(Function &F) {
737 TD = getAnalysisIfAvailable<TargetData>();
739 bool Changed = performPromotion(F);
741 // FIXME: ScalarRepl currently depends on TargetData more than it
742 // theoretically needs to. It should be refactored in order to support
743 // target-independent IR. Until this is done, just skip the actual
744 // scalar-replacement portion of this pass.
745 if (!TD) return Changed;
748 bool LocalChange = performScalarRepl(F);
749 if (!LocalChange) break; // No need to repromote if no scalarrepl
751 LocalChange = performPromotion(F);
752 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
759 bool SROA::performPromotion(Function &F) {
760 std::vector<AllocaInst*> Allocas;
761 DominatorTree &DT = getAnalysis<DominatorTree>();
762 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
764 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
766 bool Changed = false;
771 // Find allocas that are safe to promote, by looking at all instructions in
773 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
774 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
775 if (isAllocaPromotable(AI))
776 Allocas.push_back(AI);
778 if (Allocas.empty()) break;
780 PromoteMemToReg(Allocas, DT, DF);
781 NumPromoted += Allocas.size();
789 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
790 /// SROA. It must be a struct or array type with a small number of elements.
791 static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
792 const Type *T = AI->getAllocatedType();
793 // Do not promote any struct into more than 32 separate vars.
794 if (const StructType *ST = dyn_cast<StructType>(T))
795 return ST->getNumElements() <= 32;
796 // Arrays are much less likely to be safe for SROA; only consider
797 // them if they are very small.
798 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
799 return AT->getNumElements() <= 8;
804 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
805 // which runs on all of the malloc/alloca instructions in the function, removing
806 // them if they are only used by getelementptr instructions.
808 bool SROA::performScalarRepl(Function &F) {
809 std::vector<AllocaInst*> WorkList;
811 // Scan the entry basic block, adding allocas to the worklist.
812 BasicBlock &BB = F.getEntryBlock();
813 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
814 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
815 WorkList.push_back(A);
817 // Process the worklist
818 bool Changed = false;
819 while (!WorkList.empty()) {
820 AllocaInst *AI = WorkList.back();
823 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
824 // with unused elements.
825 if (AI->use_empty()) {
826 AI->eraseFromParent();
831 // If this alloca is impossible for us to promote, reject it early.
832 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
835 // Check to see if this allocation is only modified by a memcpy/memmove from
836 // a constant global. If this is the case, we can change all users to use
837 // the constant global instead. This is commonly produced by the CFE by
838 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
839 // is only subsequently read.
840 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
841 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
842 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
843 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
844 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
845 TheCopy->eraseFromParent(); // Don't mutate the global.
846 AI->eraseFromParent();
852 // Check to see if we can perform the core SROA transformation. We cannot
853 // transform the allocation instruction if it is an array allocation
854 // (allocations OF arrays are ok though), and an allocation of a scalar
855 // value cannot be decomposed at all.
856 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
858 // Do not promote [0 x %struct].
859 if (AllocaSize == 0) continue;
861 // Do not promote any struct whose size is too big.
862 if (AllocaSize > SRThreshold) continue;
864 // If the alloca looks like a good candidate for scalar replacement, and if
865 // all its users can be transformed, then split up the aggregate into its
866 // separate elements.
867 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
868 DoScalarReplacement(AI, WorkList);
873 // If we can turn this aggregate value (potentially with casts) into a
874 // simple scalar value that can be mem2reg'd into a register value.
875 // IsNotTrivial tracks whether this is something that mem2reg could have
876 // promoted itself. If so, we don't want to transform it needlessly. Note
877 // that we can't just check based on the type: the alloca may be of an i32
878 // but that has pointer arithmetic to set byte 3 of it or something.
879 if (AllocaInst *NewAI =
880 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
882 AI->eraseFromParent();
888 // Otherwise, couldn't process this alloca.
894 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
895 /// predicate, do SROA now.
896 void SROA::DoScalarReplacement(AllocaInst *AI,
897 std::vector<AllocaInst*> &WorkList) {
898 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
899 SmallVector<AllocaInst*, 32> ElementAllocas;
900 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
901 ElementAllocas.reserve(ST->getNumContainedTypes());
902 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
903 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
905 AI->getName() + "." + Twine(i), AI);
906 ElementAllocas.push_back(NA);
907 WorkList.push_back(NA); // Add to worklist for recursive processing
910 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
911 ElementAllocas.reserve(AT->getNumElements());
912 const Type *ElTy = AT->getElementType();
913 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
914 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
915 AI->getName() + "." + Twine(i), AI);
916 ElementAllocas.push_back(NA);
917 WorkList.push_back(NA); // Add to worklist for recursive processing
921 // Now that we have created the new alloca instructions, rewrite all the
922 // uses of the old alloca.
923 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
925 // Now erase any instructions that were made dead while rewriting the alloca.
926 DeleteDeadInstructions();
927 AI->eraseFromParent();
932 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
933 /// recursively including all their operands that become trivially dead.
934 void SROA::DeleteDeadInstructions() {
935 while (!DeadInsts.empty()) {
936 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
938 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
939 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
940 // Zero out the operand and see if it becomes trivially dead.
941 // (But, don't add allocas to the dead instruction list -- they are
942 // already on the worklist and will be deleted separately.)
944 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
945 DeadInsts.push_back(U);
948 I->eraseFromParent();
952 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
953 /// performing scalar replacement of alloca AI. The results are flagged in
954 /// the Info parameter. Offset indicates the position within AI that is
955 /// referenced by this instruction.
956 void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
958 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
959 Instruction *User = cast<Instruction>(*UI);
961 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
962 isSafeForScalarRepl(BC, AI, Offset, Info);
963 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
964 uint64_t GEPOffset = Offset;
965 isSafeGEP(GEPI, AI, GEPOffset, Info);
967 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
968 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
969 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
971 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
972 UI.getOperandNo() == 1, Info);
975 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
976 if (!LI->isVolatile()) {
977 const Type *LIType = LI->getType();
978 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
979 LIType, false, Info);
982 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
983 // Store is ok if storing INTO the pointer, not storing the pointer
984 if (!SI->isVolatile() && SI->getOperand(0) != I) {
985 const Type *SIType = SI->getOperand(0)->getType();
986 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
991 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
994 if (Info.isUnsafe) return;
998 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
999 /// replacement. It is safe when all the indices are constant, in-bounds
1000 /// references, and when the resulting offset corresponds to an element within
1001 /// the alloca type. The results are flagged in the Info parameter. Upon
1002 /// return, Offset is adjusted as specified by the GEP indices.
1003 void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
1004 uint64_t &Offset, AllocaInfo &Info) {
1005 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1009 // Walk through the GEP type indices, checking the types that this indexes
1011 for (; GEPIt != E; ++GEPIt) {
1012 // Ignore struct elements, no extra checking needed for these.
1013 if ((*GEPIt)->isStructTy())
1016 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1018 return MarkUnsafe(Info);
1021 // Compute the offset due to this GEP and check if the alloca has a
1022 // component element at that offset.
1023 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1024 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1025 &Indices[0], Indices.size());
1026 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1030 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1031 /// alloca or has an offset and size that corresponds to a component element
1032 /// within it. The offset checked here may have been formed from a GEP with a
1033 /// pointer bitcasted to a different type.
1034 void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
1035 const Type *MemOpType, bool isStore,
1037 // Check if this is a load/store of the entire alloca.
1038 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
1039 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
1040 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
1041 // (which are essentially the same as the MemIntrinsics, especially with
1042 // regard to copying padding between elements), or references using the
1043 // aggregate type of the alloca.
1044 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
1045 if (!UsesAggregateType) {
1047 Info.isMemCpyDst = true;
1049 Info.isMemCpySrc = true;
1054 // Check if the offset/size correspond to a component within the alloca type.
1055 const Type *T = AI->getAllocatedType();
1056 if (TypeHasComponent(T, Offset, MemSize))
1059 return MarkUnsafe(Info);
1062 /// TypeHasComponent - Return true if T has a component type with the
1063 /// specified offset and size. If Size is zero, do not check the size.
1064 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1067 if (const StructType *ST = dyn_cast<StructType>(T)) {
1068 const StructLayout *Layout = TD->getStructLayout(ST);
1069 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1070 EltTy = ST->getContainedType(EltIdx);
1071 EltSize = TD->getTypeAllocSize(EltTy);
1072 Offset -= Layout->getElementOffset(EltIdx);
1073 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1074 EltTy = AT->getElementType();
1075 EltSize = TD->getTypeAllocSize(EltTy);
1076 if (Offset >= AT->getNumElements() * EltSize)
1082 if (Offset == 0 && (Size == 0 || EltSize == Size))
1084 // Check if the component spans multiple elements.
1085 if (Offset + Size > EltSize)
1087 return TypeHasComponent(EltTy, Offset, Size);
1090 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1091 /// the instruction I, which references it, to use the separate elements.
1092 /// Offset indicates the position within AI that is referenced by this
1094 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1095 SmallVector<AllocaInst*, 32> &NewElts) {
1096 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1097 Instruction *User = cast<Instruction>(*UI);
1099 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1100 RewriteBitCast(BC, AI, Offset, NewElts);
1101 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1102 RewriteGEP(GEPI, AI, Offset, NewElts);
1103 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1104 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1105 uint64_t MemSize = Length->getZExtValue();
1107 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1108 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1109 // Otherwise the intrinsic can only touch a single element and the
1110 // address operand will be updated, so nothing else needs to be done.
1111 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1112 const Type *LIType = LI->getType();
1113 if (LIType == AI->getAllocatedType()) {
1115 // %res = load { i32, i32 }* %alloc
1117 // %load.0 = load i32* %alloc.0
1118 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1119 // %load.1 = load i32* %alloc.1
1120 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1121 // (Also works for arrays instead of structs)
1122 Value *Insert = UndefValue::get(LIType);
1123 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1124 Value *Load = new LoadInst(NewElts[i], "load", LI);
1125 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1127 LI->replaceAllUsesWith(Insert);
1128 DeadInsts.push_back(LI);
1129 } else if (LIType->isIntegerTy() &&
1130 TD->getTypeAllocSize(LIType) ==
1131 TD->getTypeAllocSize(AI->getAllocatedType())) {
1132 // If this is a load of the entire alloca to an integer, rewrite it.
1133 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1135 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1136 Value *Val = SI->getOperand(0);
1137 const Type *SIType = Val->getType();
1138 if (SIType == AI->getAllocatedType()) {
1140 // store { i32, i32 } %val, { i32, i32 }* %alloc
1142 // %val.0 = extractvalue { i32, i32 } %val, 0
1143 // store i32 %val.0, i32* %alloc.0
1144 // %val.1 = extractvalue { i32, i32 } %val, 1
1145 // store i32 %val.1, i32* %alloc.1
1146 // (Also works for arrays instead of structs)
1147 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1148 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1149 new StoreInst(Extract, NewElts[i], SI);
1151 DeadInsts.push_back(SI);
1152 } else if (SIType->isIntegerTy() &&
1153 TD->getTypeAllocSize(SIType) ==
1154 TD->getTypeAllocSize(AI->getAllocatedType())) {
1155 // If this is a store of the entire alloca from an integer, rewrite it.
1156 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1162 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1163 /// and recursively continue updating all of its uses.
1164 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1165 SmallVector<AllocaInst*, 32> &NewElts) {
1166 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1167 if (BC->getOperand(0) != AI)
1170 // The bitcast references the original alloca. Replace its uses with
1171 // references to the first new element alloca.
1172 Instruction *Val = NewElts[0];
1173 if (Val->getType() != BC->getDestTy()) {
1174 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1177 BC->replaceAllUsesWith(Val);
1178 DeadInsts.push_back(BC);
1181 /// FindElementAndOffset - Return the index of the element containing Offset
1182 /// within the specified type, which must be either a struct or an array.
1183 /// Sets T to the type of the element and Offset to the offset within that
1184 /// element. IdxTy is set to the type of the index result to be used in a
1185 /// GEP instruction.
1186 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1187 const Type *&IdxTy) {
1189 if (const StructType *ST = dyn_cast<StructType>(T)) {
1190 const StructLayout *Layout = TD->getStructLayout(ST);
1191 Idx = Layout->getElementContainingOffset(Offset);
1192 T = ST->getContainedType(Idx);
1193 Offset -= Layout->getElementOffset(Idx);
1194 IdxTy = Type::getInt32Ty(T->getContext());
1197 const ArrayType *AT = cast<ArrayType>(T);
1198 T = AT->getElementType();
1199 uint64_t EltSize = TD->getTypeAllocSize(T);
1200 Idx = Offset / EltSize;
1201 Offset -= Idx * EltSize;
1202 IdxTy = Type::getInt64Ty(T->getContext());
1206 /// RewriteGEP - Check if this GEP instruction moves the pointer across
1207 /// elements of the alloca that are being split apart, and if so, rewrite
1208 /// the GEP to be relative to the new element.
1209 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1210 SmallVector<AllocaInst*, 32> &NewElts) {
1211 uint64_t OldOffset = Offset;
1212 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1213 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1214 &Indices[0], Indices.size());
1216 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1218 const Type *T = AI->getAllocatedType();
1220 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1221 if (GEPI->getOperand(0) == AI)
1222 OldIdx = ~0ULL; // Force the GEP to be rewritten.
1224 T = AI->getAllocatedType();
1225 uint64_t EltOffset = Offset;
1226 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1228 // If this GEP does not move the pointer across elements of the alloca
1229 // being split, then it does not needs to be rewritten.
1233 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1234 SmallVector<Value*, 8> NewArgs;
1235 NewArgs.push_back(Constant::getNullValue(i32Ty));
1236 while (EltOffset != 0) {
1237 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1238 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1240 Instruction *Val = NewElts[Idx];
1241 if (NewArgs.size() > 1) {
1242 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1243 NewArgs.end(), "", GEPI);
1244 Val->takeName(GEPI);
1246 if (Val->getType() != GEPI->getType())
1247 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1248 GEPI->replaceAllUsesWith(Val);
1249 DeadInsts.push_back(GEPI);
1252 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1253 /// Rewrite it to copy or set the elements of the scalarized memory.
1254 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1256 SmallVector<AllocaInst*, 32> &NewElts) {
1257 // If this is a memcpy/memmove, construct the other pointer as the
1258 // appropriate type. The "Other" pointer is the pointer that goes to memory
1259 // that doesn't have anything to do with the alloca that we are promoting. For
1260 // memset, this Value* stays null.
1261 Value *OtherPtr = 0;
1262 unsigned MemAlignment = MI->getAlignment();
1263 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1264 if (Inst == MTI->getRawDest())
1265 OtherPtr = MTI->getRawSource();
1267 assert(Inst == MTI->getRawSource());
1268 OtherPtr = MTI->getRawDest();
1272 // If there is an other pointer, we want to convert it to the same pointer
1273 // type as AI has, so we can GEP through it safely.
1276 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1277 // optimization, but it's also required to detect the corner case where
1278 // both pointer operands are referencing the same memory, and where
1279 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1280 // function is only called for mem intrinsics that access the whole
1281 // aggregate, so non-zero GEPs are not an issue here.)
1283 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
1284 OtherPtr = BC->getOperand(0);
1287 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
1288 // All zero GEPs are effectively bitcasts.
1289 if (GEP->hasAllZeroIndices()) {
1290 OtherPtr = GEP->getOperand(0);
1296 // Copying the alloca to itself is a no-op: just delete it.
1297 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1298 // This code will run twice for a no-op memcpy -- once for each operand.
1299 // Put only one reference to MI on the DeadInsts list.
1300 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1301 E = DeadInsts.end(); I != E; ++I)
1302 if (*I == MI) return;
1303 DeadInsts.push_back(MI);
1307 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
1308 if (BCE->getOpcode() == Instruction::BitCast)
1309 OtherPtr = BCE->getOperand(0);
1311 // If the pointer is not the right type, insert a bitcast to the right
1313 if (OtherPtr->getType() != AI->getType())
1314 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
1318 // Process each element of the aggregate.
1319 Value *TheFn = MI->getCalledValue();
1320 const Type *BytePtrTy = MI->getRawDest()->getType();
1321 bool SROADest = MI->getRawDest() == Inst;
1323 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
1325 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1326 // If this is a memcpy/memmove, emit a GEP of the other element address.
1327 Value *OtherElt = 0;
1328 unsigned OtherEltAlign = MemAlignment;
1331 Value *Idx[2] = { Zero,
1332 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
1333 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
1334 OtherPtr->getName()+"."+Twine(i),
1337 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
1338 const Type *OtherTy = OtherPtrTy->getElementType();
1339 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
1340 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1342 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
1343 EltOffset = TD->getTypeAllocSize(EltTy)*i;
1346 // The alignment of the other pointer is the guaranteed alignment of the
1347 // element, which is affected by both the known alignment of the whole
1348 // mem intrinsic and the alignment of the element. If the alignment of
1349 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1350 // known alignment is just 4 bytes.
1351 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
1354 Value *EltPtr = NewElts[i];
1355 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
1357 // If we got down to a scalar, insert a load or store as appropriate.
1358 if (EltTy->isSingleValueType()) {
1359 if (isa<MemTransferInst>(MI)) {
1361 // From Other to Alloca.
1362 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1363 new StoreInst(Elt, EltPtr, MI);
1365 // From Alloca to Other.
1366 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1367 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1371 assert(isa<MemSetInst>(MI));
1373 // If the stored element is zero (common case), just store a null
1376 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
1378 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
1380 // If EltTy is a vector type, get the element type.
1381 const Type *ValTy = EltTy->getScalarType();
1383 // Construct an integer with the right value.
1384 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1385 APInt OneVal(EltSize, CI->getZExtValue());
1386 APInt TotalVal(OneVal);
1388 for (unsigned i = 0; 8*i < EltSize; ++i) {
1389 TotalVal = TotalVal.shl(8);
1393 // Convert the integer value to the appropriate type.
1394 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
1395 if (ValTy->isPointerTy())
1396 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
1397 else if (ValTy->isFloatingPointTy())
1398 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
1399 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1401 // If the requested value was a vector constant, create it.
1402 if (EltTy != ValTy) {
1403 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1404 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
1405 StoreVal = ConstantVector::get(&Elts[0], NumElts);
1408 new StoreInst(StoreVal, EltPtr, MI);
1411 // Otherwise, if we're storing a byte variable, use a memset call for
1415 // Cast the element pointer to BytePtrTy.
1416 if (EltPtr->getType() != BytePtrTy)
1417 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
1419 // Cast the other pointer (if we have one) to BytePtrTy.
1420 if (OtherElt && OtherElt->getType() != BytePtrTy) {
1421 // Preserve address space of OtherElt
1422 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
1423 const PointerType* PTy = cast<PointerType>(BytePtrTy);
1424 if (OtherPTy->getElementType() != PTy->getElementType()) {
1425 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
1426 OtherPTy->getAddressSpace());
1427 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
1428 OtherElt->getNameStr(), MI);
1432 unsigned EltSize = TD->getTypeAllocSize(EltTy);
1434 // Finally, insert the meminst for this element.
1435 if (isa<MemTransferInst>(MI)) {
1437 SROADest ? EltPtr : OtherElt, // Dest ptr
1438 SROADest ? OtherElt : EltPtr, // Src ptr
1439 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
1441 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
1442 MI->getVolatileCst()
1444 // In case we fold the address space overloaded memcpy of A to B
1445 // with memcpy of B to C, change the function to be a memcpy of A to C.
1446 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
1447 Ops[2]->getType() };
1448 Module *M = MI->getParent()->getParent()->getParent();
1449 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
1450 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
1452 assert(isa<MemSetInst>(MI));
1454 EltPtr, MI->getOperand(2), // Dest, Value,
1455 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
1457 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
1459 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
1460 Module *M = MI->getParent()->getParent()->getParent();
1461 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
1462 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
1465 DeadInsts.push_back(MI);
1468 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
1469 /// overwrites the entire allocation. Extract out the pieces of the stored
1470 /// integer and store them individually.
1471 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
1472 SmallVector<AllocaInst*, 32> &NewElts){
1473 // Extract each element out of the integer according to its structure offset
1474 // and store the element value to the individual alloca.
1475 Value *SrcVal = SI->getOperand(0);
1476 const Type *AllocaEltTy = AI->getAllocatedType();
1477 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1479 // Handle tail padding by extending the operand
1480 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
1481 SrcVal = new ZExtInst(SrcVal,
1482 IntegerType::get(SI->getContext(), AllocaSizeBits),
1485 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
1488 // There are two forms here: AI could be an array or struct. Both cases
1489 // have different ways to compute the element offset.
1490 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1491 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1493 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1494 // Get the number of bits to shift SrcVal to get the value.
1495 const Type *FieldTy = EltSTy->getElementType(i);
1496 uint64_t Shift = Layout->getElementOffsetInBits(i);
1498 if (TD->isBigEndian())
1499 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
1501 Value *EltVal = SrcVal;
1503 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1504 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1505 "sroa.store.elt", SI);
1508 // Truncate down to an integer of the right size.
1509 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1511 // Ignore zero sized fields like {}, they obviously contain no data.
1512 if (FieldSizeBits == 0) continue;
1514 if (FieldSizeBits != AllocaSizeBits)
1515 EltVal = new TruncInst(EltVal,
1516 IntegerType::get(SI->getContext(), FieldSizeBits),
1518 Value *DestField = NewElts[i];
1519 if (EltVal->getType() == FieldTy) {
1520 // Storing to an integer field of this size, just do it.
1521 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
1522 // Bitcast to the right element type (for fp/vector values).
1523 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1525 // Otherwise, bitcast the dest pointer (for aggregates).
1526 DestField = new BitCastInst(DestField,
1527 PointerType::getUnqual(EltVal->getType()),
1530 new StoreInst(EltVal, DestField, SI);
1534 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1535 const Type *ArrayEltTy = ATy->getElementType();
1536 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1537 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1541 if (TD->isBigEndian())
1542 Shift = AllocaSizeBits-ElementOffset;
1546 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1547 // Ignore zero sized fields like {}, they obviously contain no data.
1548 if (ElementSizeBits == 0) continue;
1550 Value *EltVal = SrcVal;
1552 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1553 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1554 "sroa.store.elt", SI);
1557 // Truncate down to an integer of the right size.
1558 if (ElementSizeBits != AllocaSizeBits)
1559 EltVal = new TruncInst(EltVal,
1560 IntegerType::get(SI->getContext(),
1561 ElementSizeBits),"",SI);
1562 Value *DestField = NewElts[i];
1563 if (EltVal->getType() == ArrayEltTy) {
1564 // Storing to an integer field of this size, just do it.
1565 } else if (ArrayEltTy->isFloatingPointTy() ||
1566 ArrayEltTy->isVectorTy()) {
1567 // Bitcast to the right element type (for fp/vector values).
1568 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1570 // Otherwise, bitcast the dest pointer (for aggregates).
1571 DestField = new BitCastInst(DestField,
1572 PointerType::getUnqual(EltVal->getType()),
1575 new StoreInst(EltVal, DestField, SI);
1577 if (TD->isBigEndian())
1578 Shift -= ElementOffset;
1580 Shift += ElementOffset;
1584 DeadInsts.push_back(SI);
1587 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1588 /// an integer. Load the individual pieces to form the aggregate value.
1589 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1590 SmallVector<AllocaInst*, 32> &NewElts) {
1591 // Extract each element out of the NewElts according to its structure offset
1592 // and form the result value.
1593 const Type *AllocaEltTy = AI->getAllocatedType();
1594 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1596 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1599 // There are two forms here: AI could be an array or struct. Both cases
1600 // have different ways to compute the element offset.
1601 const StructLayout *Layout = 0;
1602 uint64_t ArrayEltBitOffset = 0;
1603 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1604 Layout = TD->getStructLayout(EltSTy);
1606 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1607 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1611 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1613 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1614 // Load the value from the alloca. If the NewElt is an aggregate, cast
1615 // the pointer to an integer of the same size before doing the load.
1616 Value *SrcField = NewElts[i];
1617 const Type *FieldTy =
1618 cast<PointerType>(SrcField->getType())->getElementType();
1619 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1621 // Ignore zero sized fields like {}, they obviously contain no data.
1622 if (FieldSizeBits == 0) continue;
1624 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1626 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1627 !FieldTy->isVectorTy())
1628 SrcField = new BitCastInst(SrcField,
1629 PointerType::getUnqual(FieldIntTy),
1631 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1633 // If SrcField is a fp or vector of the right size but that isn't an
1634 // integer type, bitcast to an integer so we can shift it.
1635 if (SrcField->getType() != FieldIntTy)
1636 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1638 // Zero extend the field to be the same size as the final alloca so that
1639 // we can shift and insert it.
1640 if (SrcField->getType() != ResultVal->getType())
1641 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1643 // Determine the number of bits to shift SrcField.
1645 if (Layout) // Struct case.
1646 Shift = Layout->getElementOffsetInBits(i);
1648 Shift = i*ArrayEltBitOffset;
1650 if (TD->isBigEndian())
1651 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1654 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1655 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1658 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1661 // Handle tail padding by truncating the result
1662 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1663 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1665 LI->replaceAllUsesWith(ResultVal);
1666 DeadInsts.push_back(LI);
1669 /// HasPadding - Return true if the specified type has any structure or
1670 /// alignment padding, false otherwise.
1671 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1672 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1673 const StructLayout *SL = TD.getStructLayout(STy);
1674 unsigned PrevFieldBitOffset = 0;
1675 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1676 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1678 // Padding in sub-elements?
1679 if (HasPadding(STy->getElementType(i), TD))
1682 // Check to see if there is any padding between this element and the
1685 unsigned PrevFieldEnd =
1686 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1687 if (PrevFieldEnd < FieldBitOffset)
1691 PrevFieldBitOffset = FieldBitOffset;
1694 // Check for tail padding.
1695 if (unsigned EltCount = STy->getNumElements()) {
1696 unsigned PrevFieldEnd = PrevFieldBitOffset +
1697 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1698 if (PrevFieldEnd < SL->getSizeInBits())
1702 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1703 return HasPadding(ATy->getElementType(), TD);
1704 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1705 return HasPadding(VTy->getElementType(), TD);
1707 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1710 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1711 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1712 /// or 1 if safe after canonicalization has been performed.
1713 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1714 // Loop over the use list of the alloca. We can only transform it if all of
1715 // the users are safe to transform.
1718 isSafeForScalarRepl(AI, AI, 0, Info);
1719 if (Info.isUnsafe) {
1720 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
1724 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1725 // source and destination, we have to be careful. In particular, the memcpy
1726 // could be moving around elements that live in structure padding of the LLVM
1727 // types, but may actually be used. In these cases, we refuse to promote the
1729 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1730 HasPadding(AI->getAllocatedType(), *TD))
1738 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1739 /// some part of a constant global variable. This intentionally only accepts
1740 /// constant expressions because we don't can't rewrite arbitrary instructions.
1741 static bool PointsToConstantGlobal(Value *V) {
1742 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1743 return GV->isConstant();
1744 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1745 if (CE->getOpcode() == Instruction::BitCast ||
1746 CE->getOpcode() == Instruction::GetElementPtr)
1747 return PointsToConstantGlobal(CE->getOperand(0));
1751 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1752 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1753 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1754 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1755 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1756 /// the alloca, and if the source pointer is a pointer to a constant global, we
1757 /// can optimize this.
1758 static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
1760 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1761 User *U = cast<Instruction>(*UI);
1763 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1764 // Ignore non-volatile loads, they are always ok.
1765 if (!LI->isVolatile())
1768 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1769 // If uses of the bitcast are ok, we are ok.
1770 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1774 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
1775 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1776 // doesn't, it does.
1777 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1778 isOffset || !GEP->hasAllZeroIndices()))
1783 // If this is isn't our memcpy/memmove, reject it as something we can't
1785 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1789 // If we already have seen a copy, reject the second one.
1790 if (TheCopy) return false;
1792 // If the pointer has been offset from the start of the alloca, we can't
1793 // safely handle this.
1794 if (isOffset) return false;
1796 // If the memintrinsic isn't using the alloca as the dest, reject it.
1797 if (UI.getOperandNo() != 1) return false;
1799 // If the source of the memcpy/move is not a constant global, reject it.
1800 if (!PointsToConstantGlobal(MI->getSource()))
1803 // Otherwise, the transform is safe. Remember the copy instruction.
1809 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1810 /// modified by a copy from a constant global. If we can prove this, we can
1811 /// replace any uses of the alloca with uses of the global directly.
1812 MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1813 MemTransferInst *TheCopy = 0;
1814 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))