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/Module.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Analysis/DominanceFrontier.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Utils/SSAUpdater.h"
39 #include "llvm/Support/CallSite.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/GetElementPtrTypeIterator.h"
43 #include "llvm/Support/IRBuilder.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/Statistic.h"
50 STATISTIC(NumReplaced, "Number of allocas broken up");
51 STATISTIC(NumPromoted, "Number of allocas promoted");
52 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
53 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
56 struct SROA : public FunctionPass {
57 SROA(int T, bool hasDF, char &ID)
58 : FunctionPass(ID), HasDomFrontiers(hasDF) {
65 bool runOnFunction(Function &F);
67 bool performScalarRepl(Function &F);
68 bool performPromotion(Function &F);
74 /// DeadInsts - Keep track of instructions we have made dead, so that
75 /// we can remove them after we are done working.
76 SmallVector<Value*, 32> DeadInsts;
78 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
79 /// information about the uses. All these fields are initialized to false
80 /// and set to true when something is learned.
82 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
85 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
88 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
92 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
97 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
99 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
101 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
103 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
105 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
106 const Type *MemOpType, bool isStore, AllocaInfo &Info);
107 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
108 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
111 void DoScalarReplacement(AllocaInst *AI,
112 std::vector<AllocaInst*> &WorkList);
113 void DeleteDeadInstructions();
115 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
116 SmallVector<AllocaInst*, 32> &NewElts);
117 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
118 SmallVector<AllocaInst*, 32> &NewElts);
119 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
120 SmallVector<AllocaInst*, 32> &NewElts);
121 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
123 SmallVector<AllocaInst*, 32> &NewElts);
124 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
125 SmallVector<AllocaInst*, 32> &NewElts);
126 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
127 SmallVector<AllocaInst*, 32> &NewElts);
129 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
132 // SROA_DF - SROA that uses DominanceFrontier.
133 struct SROA_DF : public SROA {
136 SROA_DF(int T = -1) : SROA(T, true, ID) {
137 initializeSROA_DFPass(*PassRegistry::getPassRegistry());
140 // getAnalysisUsage - This pass does not require any passes, but we know it
141 // will not alter the CFG, so say so.
142 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
143 AU.addRequired<DominatorTree>();
144 AU.addRequired<DominanceFrontier>();
145 AU.setPreservesCFG();
149 // SROA_SSAUp - SROA that uses SSAUpdater.
150 struct SROA_SSAUp : public SROA {
153 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
154 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
157 // getAnalysisUsage - This pass does not require any passes, but we know it
158 // will not alter the CFG, so say so.
159 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
160 AU.setPreservesCFG();
166 char SROA_DF::ID = 0;
167 char SROA_SSAUp::ID = 0;
169 INITIALIZE_PASS_BEGIN(SROA_DF, "scalarrepl",
170 "Scalar Replacement of Aggregates (DF)", false, false)
171 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
172 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
173 INITIALIZE_PASS_END(SROA_DF, "scalarrepl",
174 "Scalar Replacement of Aggregates (DF)", false, false)
176 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
177 "Scalar Replacement of Aggregates (SSAUp)", false, false)
178 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
179 "Scalar Replacement of Aggregates (SSAUp)", false, false)
181 // Public interface to the ScalarReplAggregates pass
182 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
183 bool UseDomFrontier) {
185 return new SROA_DF(Threshold);
186 return new SROA_SSAUp(Threshold);
190 //===----------------------------------------------------------------------===//
191 // Convert To Scalar Optimization.
192 //===----------------------------------------------------------------------===//
195 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
196 /// optimization, which scans the uses of an alloca and determines if it can
197 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
198 class ConvertToScalarInfo {
199 /// AllocaSize - The size of the alloca being considered.
201 const TargetData &TD;
203 /// IsNotTrivial - This is set to true if there is some access to the object
204 /// which means that mem2reg can't promote it.
207 /// VectorTy - This tracks the type that we should promote the vector to if
208 /// it is possible to turn it into a vector. This starts out null, and if it
209 /// isn't possible to turn into a vector type, it gets set to VoidTy.
210 const Type *VectorTy;
212 /// HadAVector - True if there is at least one vector access to the alloca.
213 /// We don't want to turn random arrays into vectors and use vector element
214 /// insert/extract, but if there are element accesses to something that is
215 /// also declared as a vector, we do want to promote to a vector.
219 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
220 : AllocaSize(Size), TD(td) {
221 IsNotTrivial = false;
226 AllocaInst *TryConvert(AllocaInst *AI);
229 bool CanConvertToScalar(Value *V, uint64_t Offset);
230 void MergeInType(const Type *In, uint64_t Offset);
231 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
233 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
234 uint64_t Offset, IRBuilder<> &Builder);
235 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
236 uint64_t Offset, IRBuilder<> &Builder);
238 } // end anonymous namespace.
241 /// IsVerbotenVectorType - Return true if this is a vector type ScalarRepl isn't
242 /// allowed to form. We do this to avoid MMX types, which is a complete hack,
243 /// but is required until the backend is fixed.
244 static bool IsVerbotenVectorType(const VectorType *VTy, const Instruction *I) {
245 StringRef Triple(I->getParent()->getParent()->getParent()->getTargetTriple());
246 if (!Triple.startswith("i386") &&
247 !Triple.startswith("x86_64"))
250 // Reject all the MMX vector types.
251 switch (VTy->getNumElements()) {
252 default: return false;
253 case 1: return VTy->getElementType()->isIntegerTy(64);
254 case 2: return VTy->getElementType()->isIntegerTy(32);
255 case 4: return VTy->getElementType()->isIntegerTy(16);
256 case 8: return VTy->getElementType()->isIntegerTy(8);
261 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
262 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
263 /// alloca if possible or null if not.
264 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
265 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
267 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
270 // If we were able to find a vector type that can handle this with
271 // insert/extract elements, and if there was at least one use that had
272 // a vector type, promote this to a vector. We don't want to promote
273 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
274 // we just get a lot of insert/extracts. If at least one vector is
275 // involved, then we probably really do have a union of vector/array.
277 if (VectorTy && VectorTy->isVectorTy() && HadAVector &&
278 !IsVerbotenVectorType(cast<VectorType>(VectorTy), AI)) {
279 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
280 << *VectorTy << '\n');
281 NewTy = VectorTy; // Use the vector type.
283 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
284 // Create and insert the integer alloca.
285 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
287 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
288 ConvertUsesToScalar(AI, NewAI, 0);
292 /// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
293 /// so far at the offset specified by Offset (which is specified in bytes).
295 /// There are two cases we handle here:
296 /// 1) A union of vector types of the same size and potentially its elements.
297 /// Here we turn element accesses into insert/extract element operations.
298 /// This promotes a <4 x float> with a store of float to the third element
299 /// into a <4 x float> that uses insert element.
300 /// 2) A fully general blob of memory, which we turn into some (potentially
301 /// large) integer type with extract and insert operations where the loads
302 /// and stores would mutate the memory. We mark this by setting VectorTy
304 void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
305 // If we already decided to turn this into a blob of integer memory, there is
306 // nothing to be done.
307 if (VectorTy && VectorTy->isVoidTy())
310 // If this could be contributing to a vector, analyze it.
312 // If the In type is a vector that is the same size as the alloca, see if it
313 // matches the existing VecTy.
314 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
315 // Remember if we saw a vector type.
318 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
319 // If we're storing/loading a vector of the right size, allow it as a
320 // vector. If this the first vector we see, remember the type so that
321 // we know the element size. If this is a subsequent access, ignore it
322 // even if it is a differing type but the same size. Worst case we can
323 // bitcast the resultant vectors.
328 } else if (In->isFloatTy() || In->isDoubleTy() ||
329 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
330 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
331 // If we're accessing something that could be an element of a vector, see
332 // if the implied vector agrees with what we already have and if Offset is
333 // compatible with it.
334 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
335 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
337 cast<VectorType>(VectorTy)->getElementType()
338 ->getPrimitiveSizeInBits()/8 == EltSize)) {
340 VectorTy = VectorType::get(In, AllocaSize/EltSize);
345 // Otherwise, we have a case that we can't handle with an optimized vector
346 // form. We can still turn this into a large integer.
347 VectorTy = Type::getVoidTy(In->getContext());
350 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
351 /// its accesses to a single vector type, return true and set VecTy to
352 /// the new type. If we could convert the alloca into a single promotable
353 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
354 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
355 /// is the current offset from the base of the alloca being analyzed.
357 /// If we see at least one access to the value that is as a vector type, set the
359 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
360 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
361 Instruction *User = cast<Instruction>(*UI);
363 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
364 // Don't break volatile loads.
365 if (LI->isVolatile())
367 // Don't touch MMX operations.
368 if (LI->getType()->isX86_MMXTy())
370 MergeInType(LI->getType(), Offset);
374 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
375 // Storing the pointer, not into the value?
376 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
377 // Don't touch MMX operations.
378 if (SI->getOperand(0)->getType()->isX86_MMXTy())
380 MergeInType(SI->getOperand(0)->getType(), Offset);
384 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
385 IsNotTrivial = true; // Can't be mem2reg'd.
386 if (!CanConvertToScalar(BCI, Offset))
391 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
392 // If this is a GEP with a variable indices, we can't handle it.
393 if (!GEP->hasAllConstantIndices())
396 // Compute the offset that this GEP adds to the pointer.
397 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
398 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
399 &Indices[0], Indices.size());
400 // See if all uses can be converted.
401 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
403 IsNotTrivial = true; // Can't be mem2reg'd.
407 // If this is a constant sized memset of a constant value (e.g. 0) we can
409 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
410 // Store of constant value and constant size.
411 if (!isa<ConstantInt>(MSI->getValue()) ||
412 !isa<ConstantInt>(MSI->getLength()))
414 IsNotTrivial = true; // Can't be mem2reg'd.
418 // If this is a memcpy or memmove into or out of the whole allocation, we
419 // can handle it like a load or store of the scalar type.
420 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
421 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
422 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
425 IsNotTrivial = true; // Can't be mem2reg'd.
429 // Otherwise, we cannot handle this!
436 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
437 /// directly. This happens when we are converting an "integer union" to a
438 /// single integer scalar, or when we are converting a "vector union" to a
439 /// vector with insert/extractelement instructions.
441 /// Offset is an offset from the original alloca, in bits that need to be
442 /// shifted to the right. By the end of this, there should be no uses of Ptr.
443 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
445 while (!Ptr->use_empty()) {
446 Instruction *User = cast<Instruction>(Ptr->use_back());
448 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
449 ConvertUsesToScalar(CI, NewAI, Offset);
450 CI->eraseFromParent();
454 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
455 // Compute the offset that this GEP adds to the pointer.
456 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
457 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
458 &Indices[0], Indices.size());
459 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
460 GEP->eraseFromParent();
464 IRBuilder<> Builder(User);
466 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
467 // The load is a bit extract from NewAI shifted right by Offset bits.
468 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
470 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
471 LI->replaceAllUsesWith(NewLoadVal);
472 LI->eraseFromParent();
476 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
477 assert(SI->getOperand(0) != Ptr && "Consistency error!");
478 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
479 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
481 Builder.CreateStore(New, NewAI);
482 SI->eraseFromParent();
484 // If the load we just inserted is now dead, then the inserted store
485 // overwrote the entire thing.
486 if (Old->use_empty())
487 Old->eraseFromParent();
491 // If this is a constant sized memset of a constant value (e.g. 0) we can
492 // transform it into a store of the expanded constant value.
493 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
494 assert(MSI->getRawDest() == Ptr && "Consistency error!");
495 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
497 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
499 // Compute the value replicated the right number of times.
500 APInt APVal(NumBytes*8, Val);
502 // Splat the value if non-zero.
504 for (unsigned i = 1; i != NumBytes; ++i)
507 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
508 Value *New = ConvertScalar_InsertValue(
509 ConstantInt::get(User->getContext(), APVal),
510 Old, Offset, Builder);
511 Builder.CreateStore(New, NewAI);
513 // If the load we just inserted is now dead, then the memset overwrote
515 if (Old->use_empty())
516 Old->eraseFromParent();
518 MSI->eraseFromParent();
522 // If this is a memcpy or memmove into or out of the whole allocation, we
523 // can handle it like a load or store of the scalar type.
524 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
525 assert(Offset == 0 && "must be store to start of alloca");
527 // If the source and destination are both to the same alloca, then this is
528 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
530 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, 0));
532 if (GetUnderlyingObject(MTI->getSource(), 0) != OrigAI) {
533 // Dest must be OrigAI, change this to be a load from the original
534 // pointer (bitcasted), then a store to our new alloca.
535 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
536 Value *SrcPtr = MTI->getSource();
537 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
538 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
539 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
540 AIPTy = PointerType::get(AIPTy->getElementType(),
541 SPTy->getAddressSpace());
543 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
545 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
546 SrcVal->setAlignment(MTI->getAlignment());
547 Builder.CreateStore(SrcVal, NewAI);
548 } else if (GetUnderlyingObject(MTI->getDest(), 0) != OrigAI) {
549 // Src must be OrigAI, change this to be a load from NewAI then a store
550 // through the original dest pointer (bitcasted).
551 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
552 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
554 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
555 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
556 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
557 AIPTy = PointerType::get(AIPTy->getElementType(),
558 DPTy->getAddressSpace());
560 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
562 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
563 NewStore->setAlignment(MTI->getAlignment());
565 // Noop transfer. Src == Dst
568 MTI->eraseFromParent();
572 llvm_unreachable("Unsupported operation!");
576 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
577 /// or vector value FromVal, extracting the bits from the offset specified by
578 /// Offset. This returns the value, which is of type ToType.
580 /// This happens when we are converting an "integer union" to a single
581 /// integer scalar, or when we are converting a "vector union" to a vector with
582 /// insert/extractelement instructions.
584 /// Offset is an offset from the original alloca, in bits that need to be
585 /// shifted to the right.
586 Value *ConvertToScalarInfo::
587 ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
588 uint64_t Offset, IRBuilder<> &Builder) {
589 // If the load is of the whole new alloca, no conversion is needed.
590 if (FromVal->getType() == ToType && Offset == 0)
593 // If the result alloca is a vector type, this is either an element
594 // access or a bitcast to another vector type of the same size.
595 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
596 if (ToType->isVectorTy())
597 return Builder.CreateBitCast(FromVal, ToType, "tmp");
599 // Otherwise it must be an element access.
602 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
603 Elt = Offset/EltSize;
604 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
606 // Return the element extracted out of it.
607 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
608 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
609 if (V->getType() != ToType)
610 V = Builder.CreateBitCast(V, ToType, "tmp");
614 // If ToType is a first class aggregate, extract out each of the pieces and
615 // use insertvalue's to form the FCA.
616 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
617 const StructLayout &Layout = *TD.getStructLayout(ST);
618 Value *Res = UndefValue::get(ST);
619 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
620 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
621 Offset+Layout.getElementOffsetInBits(i),
623 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
628 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
629 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
630 Value *Res = UndefValue::get(AT);
631 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
632 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
633 Offset+i*EltSize, Builder);
634 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
639 // Otherwise, this must be a union that was converted to an integer value.
640 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
642 // If this is a big-endian system and the load is narrower than the
643 // full alloca type, we need to do a shift to get the right bits.
645 if (TD.isBigEndian()) {
646 // On big-endian machines, the lowest bit is stored at the bit offset
647 // from the pointer given by getTypeStoreSizeInBits. This matters for
648 // integers with a bitwidth that is not a multiple of 8.
649 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
650 TD.getTypeStoreSizeInBits(ToType) - Offset;
655 // Note: we support negative bitwidths (with shl) which are not defined.
656 // We do this to support (f.e.) loads off the end of a structure where
657 // only some bits are used.
658 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
659 FromVal = Builder.CreateLShr(FromVal,
660 ConstantInt::get(FromVal->getType(),
662 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
663 FromVal = Builder.CreateShl(FromVal,
664 ConstantInt::get(FromVal->getType(),
667 // Finally, unconditionally truncate the integer to the right width.
668 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
669 if (LIBitWidth < NTy->getBitWidth())
671 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
673 else if (LIBitWidth > NTy->getBitWidth())
675 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
678 // If the result is an integer, this is a trunc or bitcast.
679 if (ToType->isIntegerTy()) {
681 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
682 // Just do a bitcast, we know the sizes match up.
683 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
685 // Otherwise must be a pointer.
686 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
688 assert(FromVal->getType() == ToType && "Didn't convert right?");
692 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
693 /// or vector value "Old" at the offset specified by Offset.
695 /// This happens when we are converting an "integer union" to a
696 /// single integer scalar, or when we are converting a "vector union" to a
697 /// vector with insert/extractelement instructions.
699 /// Offset is an offset from the original alloca, in bits that need to be
700 /// shifted to the right.
701 Value *ConvertToScalarInfo::
702 ConvertScalar_InsertValue(Value *SV, Value *Old,
703 uint64_t Offset, IRBuilder<> &Builder) {
704 // Convert the stored type to the actual type, shift it left to insert
705 // then 'or' into place.
706 const Type *AllocaType = Old->getType();
707 LLVMContext &Context = Old->getContext();
709 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
710 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
711 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
713 // Changing the whole vector with memset or with an access of a different
715 if (ValSize == VecSize)
716 return Builder.CreateBitCast(SV, AllocaType, "tmp");
718 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
720 // Must be an element insertion.
721 unsigned Elt = Offset/EltSize;
723 if (SV->getType() != VTy->getElementType())
724 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
726 SV = Builder.CreateInsertElement(Old, SV,
727 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
732 // If SV is a first-class aggregate value, insert each value recursively.
733 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
734 const StructLayout &Layout = *TD.getStructLayout(ST);
735 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
736 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
737 Old = ConvertScalar_InsertValue(Elt, Old,
738 Offset+Layout.getElementOffsetInBits(i),
744 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
745 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
746 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
747 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
748 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
753 // If SV is a float, convert it to the appropriate integer type.
754 // If it is a pointer, do the same.
755 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
756 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
757 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
758 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
759 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
760 SV = Builder.CreateBitCast(SV,
761 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
762 else if (SV->getType()->isPointerTy())
763 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
765 // Zero extend or truncate the value if needed.
766 if (SV->getType() != AllocaType) {
767 if (SV->getType()->getPrimitiveSizeInBits() <
768 AllocaType->getPrimitiveSizeInBits())
769 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
771 // Truncation may be needed if storing more than the alloca can hold
772 // (undefined behavior).
773 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
774 SrcWidth = DestWidth;
775 SrcStoreWidth = DestStoreWidth;
779 // If this is a big-endian system and the store is narrower than the
780 // full alloca type, we need to do a shift to get the right bits.
782 if (TD.isBigEndian()) {
783 // On big-endian machines, the lowest bit is stored at the bit offset
784 // from the pointer given by getTypeStoreSizeInBits. This matters for
785 // integers with a bitwidth that is not a multiple of 8.
786 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
791 // Note: we support negative bitwidths (with shr) which are not defined.
792 // We do this to support (f.e.) stores off the end of a structure where
793 // only some bits in the structure are set.
794 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
795 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
796 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
799 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
800 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
802 Mask = Mask.lshr(-ShAmt);
805 // Mask out the bits we are about to insert from the old value, and or
807 if (SrcWidth != DestWidth) {
808 assert(DestWidth > SrcWidth);
809 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
810 SV = Builder.CreateOr(Old, SV, "ins");
816 //===----------------------------------------------------------------------===//
818 //===----------------------------------------------------------------------===//
821 bool SROA::runOnFunction(Function &F) {
822 TD = getAnalysisIfAvailable<TargetData>();
824 bool Changed = performPromotion(F);
826 // FIXME: ScalarRepl currently depends on TargetData more than it
827 // theoretically needs to. It should be refactored in order to support
828 // target-independent IR. Until this is done, just skip the actual
829 // scalar-replacement portion of this pass.
830 if (!TD) return Changed;
833 bool LocalChange = performScalarRepl(F);
834 if (!LocalChange) break; // No need to repromote if no scalarrepl
836 LocalChange = performPromotion(F);
837 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
844 class AllocaPromoter : public LoadAndStorePromoter {
847 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
848 : LoadAndStorePromoter(Insts, S), AI(0) {}
850 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
851 // Remember which alloca we're promoting (for isInstInList).
853 LoadAndStorePromoter::run(Insts);
854 AI->eraseFromParent();
857 virtual bool isInstInList(Instruction *I,
858 const SmallVectorImpl<Instruction*> &Insts) const {
859 if (LoadInst *LI = dyn_cast<LoadInst>(I))
860 return LI->getOperand(0) == AI;
861 return cast<StoreInst>(I)->getPointerOperand() == AI;
864 } // end anon namespace
866 bool SROA::performPromotion(Function &F) {
867 std::vector<AllocaInst*> Allocas;
868 DominatorTree *DT = 0;
869 DominanceFrontier *DF = 0;
870 if (HasDomFrontiers) {
871 DT = &getAnalysis<DominatorTree>();
872 DF = &getAnalysis<DominanceFrontier>();
875 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
877 bool Changed = false;
878 SmallVector<Instruction*, 64> Insts;
882 // Find allocas that are safe to promote, by looking at all instructions in
884 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
885 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
886 if (isAllocaPromotable(AI))
887 Allocas.push_back(AI);
889 if (Allocas.empty()) break;
892 PromoteMemToReg(Allocas, *DT, *DF);
895 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
896 AllocaInst *AI = Allocas[i];
898 // Build list of instructions to promote.
899 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
901 Insts.push_back(cast<Instruction>(*UI));
903 AllocaPromoter(Insts, SSA).run(AI, Insts);
907 NumPromoted += Allocas.size();
915 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
916 /// SROA. It must be a struct or array type with a small number of elements.
917 static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
918 const Type *T = AI->getAllocatedType();
919 // Do not promote any struct into more than 32 separate vars.
920 if (const StructType *ST = dyn_cast<StructType>(T))
921 return ST->getNumElements() <= 32;
922 // Arrays are much less likely to be safe for SROA; only consider
923 // them if they are very small.
924 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
925 return AT->getNumElements() <= 8;
930 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
931 // which runs on all of the malloc/alloca instructions in the function, removing
932 // them if they are only used by getelementptr instructions.
934 bool SROA::performScalarRepl(Function &F) {
935 std::vector<AllocaInst*> WorkList;
937 // Scan the entry basic block, adding allocas to the worklist.
938 BasicBlock &BB = F.getEntryBlock();
939 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
940 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
941 WorkList.push_back(A);
943 // Process the worklist
944 bool Changed = false;
945 while (!WorkList.empty()) {
946 AllocaInst *AI = WorkList.back();
949 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
950 // with unused elements.
951 if (AI->use_empty()) {
952 AI->eraseFromParent();
957 // If this alloca is impossible for us to promote, reject it early.
958 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
961 // Check to see if this allocation is only modified by a memcpy/memmove from
962 // a constant global. If this is the case, we can change all users to use
963 // the constant global instead. This is commonly produced by the CFE by
964 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
965 // is only subsequently read.
966 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
967 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
968 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
969 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
970 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
971 TheCopy->eraseFromParent(); // Don't mutate the global.
972 AI->eraseFromParent();
978 // Check to see if we can perform the core SROA transformation. We cannot
979 // transform the allocation instruction if it is an array allocation
980 // (allocations OF arrays are ok though), and an allocation of a scalar
981 // value cannot be decomposed at all.
982 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
984 // Do not promote [0 x %struct].
985 if (AllocaSize == 0) continue;
987 // Do not promote any struct whose size is too big.
988 if (AllocaSize > SRThreshold) continue;
990 // If the alloca looks like a good candidate for scalar replacement, and if
991 // all its users can be transformed, then split up the aggregate into its
992 // separate elements.
993 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
994 DoScalarReplacement(AI, WorkList);
999 // If we can turn this aggregate value (potentially with casts) into a
1000 // simple scalar value that can be mem2reg'd into a register value.
1001 // IsNotTrivial tracks whether this is something that mem2reg could have
1002 // promoted itself. If so, we don't want to transform it needlessly. Note
1003 // that we can't just check based on the type: the alloca may be of an i32
1004 // but that has pointer arithmetic to set byte 3 of it or something.
1005 if (AllocaInst *NewAI =
1006 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1007 NewAI->takeName(AI);
1008 AI->eraseFromParent();
1014 // Otherwise, couldn't process this alloca.
1020 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1021 /// predicate, do SROA now.
1022 void SROA::DoScalarReplacement(AllocaInst *AI,
1023 std::vector<AllocaInst*> &WorkList) {
1024 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1025 SmallVector<AllocaInst*, 32> ElementAllocas;
1026 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1027 ElementAllocas.reserve(ST->getNumContainedTypes());
1028 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1029 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1031 AI->getName() + "." + Twine(i), AI);
1032 ElementAllocas.push_back(NA);
1033 WorkList.push_back(NA); // Add to worklist for recursive processing
1036 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1037 ElementAllocas.reserve(AT->getNumElements());
1038 const Type *ElTy = AT->getElementType();
1039 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1040 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1041 AI->getName() + "." + Twine(i), AI);
1042 ElementAllocas.push_back(NA);
1043 WorkList.push_back(NA); // Add to worklist for recursive processing
1047 // Now that we have created the new alloca instructions, rewrite all the
1048 // uses of the old alloca.
1049 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1051 // Now erase any instructions that were made dead while rewriting the alloca.
1052 DeleteDeadInstructions();
1053 AI->eraseFromParent();
1058 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1059 /// recursively including all their operands that become trivially dead.
1060 void SROA::DeleteDeadInstructions() {
1061 while (!DeadInsts.empty()) {
1062 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1064 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1065 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1066 // Zero out the operand and see if it becomes trivially dead.
1067 // (But, don't add allocas to the dead instruction list -- they are
1068 // already on the worklist and will be deleted separately.)
1070 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1071 DeadInsts.push_back(U);
1074 I->eraseFromParent();
1078 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1079 /// performing scalar replacement of alloca AI. The results are flagged in
1080 /// the Info parameter. Offset indicates the position within AI that is
1081 /// referenced by this instruction.
1082 void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1084 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1085 Instruction *User = cast<Instruction>(*UI);
1087 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1088 isSafeForScalarRepl(BC, AI, Offset, Info);
1089 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1090 uint64_t GEPOffset = Offset;
1091 isSafeGEP(GEPI, AI, GEPOffset, Info);
1093 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
1094 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1095 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1097 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
1098 UI.getOperandNo() == 0, Info);
1101 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1102 if (!LI->isVolatile()) {
1103 const Type *LIType = LI->getType();
1104 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
1105 LIType, false, Info);
1108 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1109 // Store is ok if storing INTO the pointer, not storing the pointer
1110 if (!SI->isVolatile() && SI->getOperand(0) != I) {
1111 const Type *SIType = SI->getOperand(0)->getType();
1112 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
1113 SIType, true, Info);
1117 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
1120 if (Info.isUnsafe) return;
1124 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1125 /// replacement. It is safe when all the indices are constant, in-bounds
1126 /// references, and when the resulting offset corresponds to an element within
1127 /// the alloca type. The results are flagged in the Info parameter. Upon
1128 /// return, Offset is adjusted as specified by the GEP indices.
1129 void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
1130 uint64_t &Offset, AllocaInfo &Info) {
1131 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1135 // Walk through the GEP type indices, checking the types that this indexes
1137 for (; GEPIt != E; ++GEPIt) {
1138 // Ignore struct elements, no extra checking needed for these.
1139 if ((*GEPIt)->isStructTy())
1142 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1144 return MarkUnsafe(Info);
1147 // Compute the offset due to this GEP and check if the alloca has a
1148 // component element at that offset.
1149 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1150 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1151 &Indices[0], Indices.size());
1152 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
1156 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1157 /// elements of the same type (which is always true for arrays). If so,
1158 /// return true with NumElts and EltTy set to the number of elements and the
1159 /// element type, respectively.
1160 static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1161 const Type *&EltTy) {
1162 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1163 NumElts = AT->getNumElements();
1164 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1167 if (const StructType *ST = dyn_cast<StructType>(T)) {
1168 NumElts = ST->getNumContainedTypes();
1169 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1170 for (unsigned n = 1; n < NumElts; ++n) {
1171 if (ST->getContainedType(n) != EltTy)
1179 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1180 /// "homogeneous" aggregates with the same element type and number of elements.
1181 static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1185 unsigned NumElts1, NumElts2;
1186 const Type *EltTy1, *EltTy2;
1187 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1188 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1189 NumElts1 == NumElts2 &&
1196 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1197 /// alloca or has an offset and size that corresponds to a component element
1198 /// within it. The offset checked here may have been formed from a GEP with a
1199 /// pointer bitcasted to a different type.
1200 void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
1201 const Type *MemOpType, bool isStore,
1203 // Check if this is a load/store of the entire alloca.
1204 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
1205 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1206 // loads/stores (which are essentially the same as the MemIntrinsics with
1207 // regard to copying padding between elements). But, if an alloca is
1208 // flagged as both a source and destination of such operations, we'll need
1209 // to check later for padding between elements.
1210 if (!MemOpType || MemOpType->isIntegerTy()) {
1212 Info.isMemCpyDst = true;
1214 Info.isMemCpySrc = true;
1217 // This is also safe for references using a type that is compatible with
1218 // the type of the alloca, so that loads/stores can be rewritten using
1219 // insertvalue/extractvalue.
1220 if (isCompatibleAggregate(MemOpType, AI->getAllocatedType()))
1223 // Check if the offset/size correspond to a component within the alloca type.
1224 const Type *T = AI->getAllocatedType();
1225 if (TypeHasComponent(T, Offset, MemSize))
1228 return MarkUnsafe(Info);
1231 /// TypeHasComponent - Return true if T has a component type with the
1232 /// specified offset and size. If Size is zero, do not check the size.
1233 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1236 if (const StructType *ST = dyn_cast<StructType>(T)) {
1237 const StructLayout *Layout = TD->getStructLayout(ST);
1238 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1239 EltTy = ST->getContainedType(EltIdx);
1240 EltSize = TD->getTypeAllocSize(EltTy);
1241 Offset -= Layout->getElementOffset(EltIdx);
1242 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1243 EltTy = AT->getElementType();
1244 EltSize = TD->getTypeAllocSize(EltTy);
1245 if (Offset >= AT->getNumElements() * EltSize)
1251 if (Offset == 0 && (Size == 0 || EltSize == Size))
1253 // Check if the component spans multiple elements.
1254 if (Offset + Size > EltSize)
1256 return TypeHasComponent(EltTy, Offset, Size);
1259 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1260 /// the instruction I, which references it, to use the separate elements.
1261 /// Offset indicates the position within AI that is referenced by this
1263 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1264 SmallVector<AllocaInst*, 32> &NewElts) {
1265 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1266 Instruction *User = cast<Instruction>(*UI);
1268 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1269 RewriteBitCast(BC, AI, Offset, NewElts);
1270 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1271 RewriteGEP(GEPI, AI, Offset, NewElts);
1272 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1273 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1274 uint64_t MemSize = Length->getZExtValue();
1276 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1277 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1278 // Otherwise the intrinsic can only touch a single element and the
1279 // address operand will be updated, so nothing else needs to be done.
1280 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1281 const Type *LIType = LI->getType();
1283 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1285 // %res = load { i32, i32 }* %alloc
1287 // %load.0 = load i32* %alloc.0
1288 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1289 // %load.1 = load i32* %alloc.1
1290 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1291 // (Also works for arrays instead of structs)
1292 Value *Insert = UndefValue::get(LIType);
1293 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1294 Value *Load = new LoadInst(NewElts[i], "load", LI);
1295 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1297 LI->replaceAllUsesWith(Insert);
1298 DeadInsts.push_back(LI);
1299 } else if (LIType->isIntegerTy() &&
1300 TD->getTypeAllocSize(LIType) ==
1301 TD->getTypeAllocSize(AI->getAllocatedType())) {
1302 // If this is a load of the entire alloca to an integer, rewrite it.
1303 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1305 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1306 Value *Val = SI->getOperand(0);
1307 const Type *SIType = Val->getType();
1308 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1310 // store { i32, i32 } %val, { i32, i32 }* %alloc
1312 // %val.0 = extractvalue { i32, i32 } %val, 0
1313 // store i32 %val.0, i32* %alloc.0
1314 // %val.1 = extractvalue { i32, i32 } %val, 1
1315 // store i32 %val.1, i32* %alloc.1
1316 // (Also works for arrays instead of structs)
1317 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1318 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1319 new StoreInst(Extract, NewElts[i], SI);
1321 DeadInsts.push_back(SI);
1322 } else if (SIType->isIntegerTy() &&
1323 TD->getTypeAllocSize(SIType) ==
1324 TD->getTypeAllocSize(AI->getAllocatedType())) {
1325 // If this is a store of the entire alloca from an integer, rewrite it.
1326 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1332 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1333 /// and recursively continue updating all of its uses.
1334 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1335 SmallVector<AllocaInst*, 32> &NewElts) {
1336 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1337 if (BC->getOperand(0) != AI)
1340 // The bitcast references the original alloca. Replace its uses with
1341 // references to the first new element alloca.
1342 Instruction *Val = NewElts[0];
1343 if (Val->getType() != BC->getDestTy()) {
1344 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1347 BC->replaceAllUsesWith(Val);
1348 DeadInsts.push_back(BC);
1351 /// FindElementAndOffset - Return the index of the element containing Offset
1352 /// within the specified type, which must be either a struct or an array.
1353 /// Sets T to the type of the element and Offset to the offset within that
1354 /// element. IdxTy is set to the type of the index result to be used in a
1355 /// GEP instruction.
1356 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1357 const Type *&IdxTy) {
1359 if (const StructType *ST = dyn_cast<StructType>(T)) {
1360 const StructLayout *Layout = TD->getStructLayout(ST);
1361 Idx = Layout->getElementContainingOffset(Offset);
1362 T = ST->getContainedType(Idx);
1363 Offset -= Layout->getElementOffset(Idx);
1364 IdxTy = Type::getInt32Ty(T->getContext());
1367 const ArrayType *AT = cast<ArrayType>(T);
1368 T = AT->getElementType();
1369 uint64_t EltSize = TD->getTypeAllocSize(T);
1370 Idx = Offset / EltSize;
1371 Offset -= Idx * EltSize;
1372 IdxTy = Type::getInt64Ty(T->getContext());
1376 /// RewriteGEP - Check if this GEP instruction moves the pointer across
1377 /// elements of the alloca that are being split apart, and if so, rewrite
1378 /// the GEP to be relative to the new element.
1379 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1380 SmallVector<AllocaInst*, 32> &NewElts) {
1381 uint64_t OldOffset = Offset;
1382 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1383 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1384 &Indices[0], Indices.size());
1386 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1388 const Type *T = AI->getAllocatedType();
1390 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1391 if (GEPI->getOperand(0) == AI)
1392 OldIdx = ~0ULL; // Force the GEP to be rewritten.
1394 T = AI->getAllocatedType();
1395 uint64_t EltOffset = Offset;
1396 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1398 // If this GEP does not move the pointer across elements of the alloca
1399 // being split, then it does not needs to be rewritten.
1403 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1404 SmallVector<Value*, 8> NewArgs;
1405 NewArgs.push_back(Constant::getNullValue(i32Ty));
1406 while (EltOffset != 0) {
1407 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1408 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1410 Instruction *Val = NewElts[Idx];
1411 if (NewArgs.size() > 1) {
1412 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1413 NewArgs.end(), "", GEPI);
1414 Val->takeName(GEPI);
1416 if (Val->getType() != GEPI->getType())
1417 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1418 GEPI->replaceAllUsesWith(Val);
1419 DeadInsts.push_back(GEPI);
1422 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1423 /// Rewrite it to copy or set the elements of the scalarized memory.
1424 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1426 SmallVector<AllocaInst*, 32> &NewElts) {
1427 // If this is a memcpy/memmove, construct the other pointer as the
1428 // appropriate type. The "Other" pointer is the pointer that goes to memory
1429 // that doesn't have anything to do with the alloca that we are promoting. For
1430 // memset, this Value* stays null.
1431 Value *OtherPtr = 0;
1432 unsigned MemAlignment = MI->getAlignment();
1433 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1434 if (Inst == MTI->getRawDest())
1435 OtherPtr = MTI->getRawSource();
1437 assert(Inst == MTI->getRawSource());
1438 OtherPtr = MTI->getRawDest();
1442 // If there is an other pointer, we want to convert it to the same pointer
1443 // type as AI has, so we can GEP through it safely.
1445 unsigned AddrSpace =
1446 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
1448 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1449 // optimization, but it's also required to detect the corner case where
1450 // both pointer operands are referencing the same memory, and where
1451 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1452 // function is only called for mem intrinsics that access the whole
1453 // aggregate, so non-zero GEPs are not an issue here.)
1454 OtherPtr = OtherPtr->stripPointerCasts();
1456 // Copying the alloca to itself is a no-op: just delete it.
1457 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1458 // This code will run twice for a no-op memcpy -- once for each operand.
1459 // Put only one reference to MI on the DeadInsts list.
1460 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1461 E = DeadInsts.end(); I != E; ++I)
1462 if (*I == MI) return;
1463 DeadInsts.push_back(MI);
1467 // If the pointer is not the right type, insert a bitcast to the right
1470 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1472 if (OtherPtr->getType() != NewTy)
1473 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
1476 // Process each element of the aggregate.
1477 bool SROADest = MI->getRawDest() == Inst;
1479 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
1481 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1482 // If this is a memcpy/memmove, emit a GEP of the other element address.
1483 Value *OtherElt = 0;
1484 unsigned OtherEltAlign = MemAlignment;
1487 Value *Idx[2] = { Zero,
1488 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
1489 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
1490 OtherPtr->getName()+"."+Twine(i),
1493 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
1494 const Type *OtherTy = OtherPtrTy->getElementType();
1495 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
1496 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1498 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
1499 EltOffset = TD->getTypeAllocSize(EltTy)*i;
1502 // The alignment of the other pointer is the guaranteed alignment of the
1503 // element, which is affected by both the known alignment of the whole
1504 // mem intrinsic and the alignment of the element. If the alignment of
1505 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
1506 // known alignment is just 4 bytes.
1507 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
1510 Value *EltPtr = NewElts[i];
1511 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
1513 // If we got down to a scalar, insert a load or store as appropriate.
1514 if (EltTy->isSingleValueType()) {
1515 if (isa<MemTransferInst>(MI)) {
1517 // From Other to Alloca.
1518 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
1519 new StoreInst(Elt, EltPtr, MI);
1521 // From Alloca to Other.
1522 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
1523 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
1527 assert(isa<MemSetInst>(MI));
1529 // If the stored element is zero (common case), just store a null
1532 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
1534 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
1536 // If EltTy is a vector type, get the element type.
1537 const Type *ValTy = EltTy->getScalarType();
1539 // Construct an integer with the right value.
1540 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
1541 APInt OneVal(EltSize, CI->getZExtValue());
1542 APInt TotalVal(OneVal);
1544 for (unsigned i = 0; 8*i < EltSize; ++i) {
1545 TotalVal = TotalVal.shl(8);
1549 // Convert the integer value to the appropriate type.
1550 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
1551 if (ValTy->isPointerTy())
1552 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
1553 else if (ValTy->isFloatingPointTy())
1554 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
1555 assert(StoreVal->getType() == ValTy && "Type mismatch!");
1557 // If the requested value was a vector constant, create it.
1558 if (EltTy != ValTy) {
1559 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
1560 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
1561 StoreVal = ConstantVector::get(&Elts[0], NumElts);
1564 new StoreInst(StoreVal, EltPtr, MI);
1567 // Otherwise, if we're storing a byte variable, use a memset call for
1571 unsigned EltSize = TD->getTypeAllocSize(EltTy);
1573 IRBuilder<> Builder(MI);
1575 // Finally, insert the meminst for this element.
1576 if (isa<MemSetInst>(MI)) {
1577 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
1580 assert(isa<MemTransferInst>(MI));
1581 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
1582 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
1584 if (isa<MemCpyInst>(MI))
1585 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
1587 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
1590 DeadInsts.push_back(MI);
1593 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
1594 /// overwrites the entire allocation. Extract out the pieces of the stored
1595 /// integer and store them individually.
1596 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
1597 SmallVector<AllocaInst*, 32> &NewElts){
1598 // Extract each element out of the integer according to its structure offset
1599 // and store the element value to the individual alloca.
1600 Value *SrcVal = SI->getOperand(0);
1601 const Type *AllocaEltTy = AI->getAllocatedType();
1602 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1604 // Handle tail padding by extending the operand
1605 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
1606 SrcVal = new ZExtInst(SrcVal,
1607 IntegerType::get(SI->getContext(), AllocaSizeBits),
1610 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
1613 // There are two forms here: AI could be an array or struct. Both cases
1614 // have different ways to compute the element offset.
1615 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1616 const StructLayout *Layout = TD->getStructLayout(EltSTy);
1618 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1619 // Get the number of bits to shift SrcVal to get the value.
1620 const Type *FieldTy = EltSTy->getElementType(i);
1621 uint64_t Shift = Layout->getElementOffsetInBits(i);
1623 if (TD->isBigEndian())
1624 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
1626 Value *EltVal = SrcVal;
1628 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1629 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1630 "sroa.store.elt", SI);
1633 // Truncate down to an integer of the right size.
1634 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1636 // Ignore zero sized fields like {}, they obviously contain no data.
1637 if (FieldSizeBits == 0) continue;
1639 if (FieldSizeBits != AllocaSizeBits)
1640 EltVal = new TruncInst(EltVal,
1641 IntegerType::get(SI->getContext(), FieldSizeBits),
1643 Value *DestField = NewElts[i];
1644 if (EltVal->getType() == FieldTy) {
1645 // Storing to an integer field of this size, just do it.
1646 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
1647 // Bitcast to the right element type (for fp/vector values).
1648 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
1650 // Otherwise, bitcast the dest pointer (for aggregates).
1651 DestField = new BitCastInst(DestField,
1652 PointerType::getUnqual(EltVal->getType()),
1655 new StoreInst(EltVal, DestField, SI);
1659 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1660 const Type *ArrayEltTy = ATy->getElementType();
1661 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1662 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1666 if (TD->isBigEndian())
1667 Shift = AllocaSizeBits-ElementOffset;
1671 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1672 // Ignore zero sized fields like {}, they obviously contain no data.
1673 if (ElementSizeBits == 0) continue;
1675 Value *EltVal = SrcVal;
1677 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
1678 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1679 "sroa.store.elt", SI);
1682 // Truncate down to an integer of the right size.
1683 if (ElementSizeBits != AllocaSizeBits)
1684 EltVal = new TruncInst(EltVal,
1685 IntegerType::get(SI->getContext(),
1686 ElementSizeBits), "", SI);
1687 Value *DestField = NewElts[i];
1688 if (EltVal->getType() == ArrayEltTy) {
1689 // Storing to an integer field of this size, just do it.
1690 } else if (ArrayEltTy->isFloatingPointTy() ||
1691 ArrayEltTy->isVectorTy()) {
1692 // Bitcast to the right element type (for fp/vector values).
1693 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1695 // Otherwise, bitcast the dest pointer (for aggregates).
1696 DestField = new BitCastInst(DestField,
1697 PointerType::getUnqual(EltVal->getType()),
1700 new StoreInst(EltVal, DestField, SI);
1702 if (TD->isBigEndian())
1703 Shift -= ElementOffset;
1705 Shift += ElementOffset;
1709 DeadInsts.push_back(SI);
1712 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
1713 /// an integer. Load the individual pieces to form the aggregate value.
1714 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
1715 SmallVector<AllocaInst*, 32> &NewElts) {
1716 // Extract each element out of the NewElts according to its structure offset
1717 // and form the result value.
1718 const Type *AllocaEltTy = AI->getAllocatedType();
1719 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
1721 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1724 // There are two forms here: AI could be an array or struct. Both cases
1725 // have different ways to compute the element offset.
1726 const StructLayout *Layout = 0;
1727 uint64_t ArrayEltBitOffset = 0;
1728 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1729 Layout = TD->getStructLayout(EltSTy);
1731 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
1732 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
1736 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
1738 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1739 // Load the value from the alloca. If the NewElt is an aggregate, cast
1740 // the pointer to an integer of the same size before doing the load.
1741 Value *SrcField = NewElts[i];
1742 const Type *FieldTy =
1743 cast<PointerType>(SrcField->getType())->getElementType();
1744 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1746 // Ignore zero sized fields like {}, they obviously contain no data.
1747 if (FieldSizeBits == 0) continue;
1749 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1751 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1752 !FieldTy->isVectorTy())
1753 SrcField = new BitCastInst(SrcField,
1754 PointerType::getUnqual(FieldIntTy),
1756 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1758 // If SrcField is a fp or vector of the right size but that isn't an
1759 // integer type, bitcast to an integer so we can shift it.
1760 if (SrcField->getType() != FieldIntTy)
1761 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1763 // Zero extend the field to be the same size as the final alloca so that
1764 // we can shift and insert it.
1765 if (SrcField->getType() != ResultVal->getType())
1766 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1768 // Determine the number of bits to shift SrcField.
1770 if (Layout) // Struct case.
1771 Shift = Layout->getElementOffsetInBits(i);
1773 Shift = i*ArrayEltBitOffset;
1775 if (TD->isBigEndian())
1776 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1779 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
1780 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1783 // Don't create an 'or x, 0' on the first iteration.
1784 if (!isa<Constant>(ResultVal) ||
1785 !cast<Constant>(ResultVal)->isNullValue())
1786 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1788 ResultVal = SrcField;
1791 // Handle tail padding by truncating the result
1792 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1793 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1795 LI->replaceAllUsesWith(ResultVal);
1796 DeadInsts.push_back(LI);
1799 /// HasPadding - Return true if the specified type has any structure or
1800 /// alignment padding in between the elements that would be split apart
1801 /// by SROA; return false otherwise.
1802 static bool HasPadding(const Type *Ty, const TargetData &TD) {
1803 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1804 Ty = ATy->getElementType();
1805 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
1808 // SROA currently handles only Arrays and Structs.
1809 const StructType *STy = cast<StructType>(Ty);
1810 const StructLayout *SL = TD.getStructLayout(STy);
1811 unsigned PrevFieldBitOffset = 0;
1812 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1813 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1815 // Check to see if there is any padding between this element and the
1818 unsigned PrevFieldEnd =
1819 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1820 if (PrevFieldEnd < FieldBitOffset)
1823 PrevFieldBitOffset = FieldBitOffset;
1825 // Check for tail padding.
1826 if (unsigned EltCount = STy->getNumElements()) {
1827 unsigned PrevFieldEnd = PrevFieldBitOffset +
1828 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
1829 if (PrevFieldEnd < SL->getSizeInBits())
1835 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1836 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1837 /// or 1 if safe after canonicalization has been performed.
1838 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
1839 // Loop over the use list of the alloca. We can only transform it if all of
1840 // the users are safe to transform.
1843 isSafeForScalarRepl(AI, AI, 0, Info);
1844 if (Info.isUnsafe) {
1845 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
1849 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1850 // source and destination, we have to be careful. In particular, the memcpy
1851 // could be moving around elements that live in structure padding of the LLVM
1852 // types, but may actually be used. In these cases, we refuse to promote the
1854 if (Info.isMemCpySrc && Info.isMemCpyDst &&
1855 HasPadding(AI->getAllocatedType(), *TD))
1863 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1864 /// some part of a constant global variable. This intentionally only accepts
1865 /// constant expressions because we don't can't rewrite arbitrary instructions.
1866 static bool PointsToConstantGlobal(Value *V) {
1867 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1868 return GV->isConstant();
1869 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1870 if (CE->getOpcode() == Instruction::BitCast ||
1871 CE->getOpcode() == Instruction::GetElementPtr)
1872 return PointsToConstantGlobal(CE->getOperand(0));
1876 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1877 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
1878 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
1879 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
1880 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1881 /// the alloca, and if the source pointer is a pointer to a constant global, we
1882 /// can optimize this.
1883 static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
1885 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1886 User *U = cast<Instruction>(*UI);
1888 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1889 // Ignore non-volatile loads, they are always ok.
1890 if (LI->isVolatile()) return false;
1894 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1895 // If uses of the bitcast are ok, we are ok.
1896 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1900 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
1901 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1902 // doesn't, it does.
1903 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1904 isOffset || !GEP->hasAllZeroIndices()))
1909 if (CallSite CS = U) {
1910 // If this is a readonly/readnone call site, then we know it is just a
1911 // load and we can ignore it.
1912 if (CS.onlyReadsMemory())
1915 // If this is the function being called then we treat it like a load and
1917 if (CS.isCallee(UI))
1920 // If this is being passed as a byval argument, the caller is making a
1921 // copy, so it is only a read of the alloca.
1922 unsigned ArgNo = CS.getArgumentNo(UI);
1923 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
1927 // If this is isn't our memcpy/memmove, reject it as something we can't
1929 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1933 // If the transfer is using the alloca as a source of the transfer, then
1934 // ignore it since it is a load (unless the transfer is volatile).
1935 if (UI.getOperandNo() == 1) {
1936 if (MI->isVolatile()) return false;
1940 // If we already have seen a copy, reject the second one.
1941 if (TheCopy) return false;
1943 // If the pointer has been offset from the start of the alloca, we can't
1944 // safely handle this.
1945 if (isOffset) return false;
1947 // If the memintrinsic isn't using the alloca as the dest, reject it.
1948 if (UI.getOperandNo() != 0) return false;
1950 // If the source of the memcpy/move is not a constant global, reject it.
1951 if (!PointsToConstantGlobal(MI->getSource()))
1954 // Otherwise, the transform is safe. Remember the copy instruction.
1960 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1961 /// modified by a copy from a constant global. If we can prove this, we can
1962 /// replace any uses of the alloca with uses of the global directly.
1963 MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1964 MemTransferInst *TheCopy = 0;
1965 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))