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/Dominators.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Utils/SSAUpdater.h"
40 #include "llvm/Support/CallSite.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/GetElementPtrTypeIterator.h"
44 #include "llvm/Support/IRBuilder.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/ADT/SetVector.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/ADT/Statistic.h"
52 STATISTIC(NumReplaced, "Number of allocas broken up");
53 STATISTIC(NumPromoted, "Number of allocas promoted");
54 STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
55 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
56 STATISTIC(NumGlobals, "Number of allocas copied from constant global");
59 struct SROA : public FunctionPass {
60 SROA(int T, bool hasDT, char &ID)
61 : FunctionPass(ID), HasDomTree(hasDT) {
68 bool runOnFunction(Function &F);
70 bool performScalarRepl(Function &F);
71 bool performPromotion(Function &F);
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 /// The alloca to promote.
88 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
89 /// looping and avoid redundant work.
90 SmallPtrSet<PHINode*, 8> CheckedPHIs;
92 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
95 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
98 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
101 /// hasSubelementAccess - This is true if a subelement of the alloca is
102 /// ever accessed, or false if the alloca is only accessed with mem
103 /// intrinsics or load/store that only access the entire alloca at once.
104 bool hasSubelementAccess : 1;
106 /// hasALoadOrStore - This is true if there are any loads or stores to it.
107 /// The alloca may just be accessed with memcpy, for example, which would
109 bool hasALoadOrStore : 1;
111 explicit AllocaInfo(AllocaInst *ai)
112 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
113 hasSubelementAccess(false), hasALoadOrStore(false) {}
116 unsigned SRThreshold;
118 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
120 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
123 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
125 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
126 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
128 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
129 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
130 const Type *MemOpType, bool isStore, AllocaInfo &Info,
131 Instruction *TheAccess, bool AllowWholeAccess);
132 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
133 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
136 void DoScalarReplacement(AllocaInst *AI,
137 std::vector<AllocaInst*> &WorkList);
138 void DeleteDeadInstructions();
140 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
141 SmallVector<AllocaInst*, 32> &NewElts);
142 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
143 SmallVector<AllocaInst*, 32> &NewElts);
144 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
145 SmallVector<AllocaInst*, 32> &NewElts);
146 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
148 SmallVector<AllocaInst*, 32> &NewElts);
149 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
150 SmallVector<AllocaInst*, 32> &NewElts);
151 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
152 SmallVector<AllocaInst*, 32> &NewElts);
154 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
157 // SROA_DT - SROA that uses DominatorTree.
158 struct SROA_DT : public SROA {
161 SROA_DT(int T = -1) : SROA(T, true, ID) {
162 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
165 // getAnalysisUsage - This pass does not require any passes, but we know it
166 // will not alter the CFG, so say so.
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequired<DominatorTree>();
169 AU.setPreservesCFG();
173 // SROA_SSAUp - SROA that uses SSAUpdater.
174 struct SROA_SSAUp : public SROA {
177 SROA_SSAUp(int T = -1) : SROA(T, false, ID) {
178 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
181 // getAnalysisUsage - This pass does not require any passes, but we know it
182 // will not alter the CFG, so say so.
183 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
184 AU.setPreservesCFG();
190 char SROA_DT::ID = 0;
191 char SROA_SSAUp::ID = 0;
193 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
194 "Scalar Replacement of Aggregates (DT)", false, false)
195 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
196 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
197 "Scalar Replacement of Aggregates (DT)", false, false)
199 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
200 "Scalar Replacement of Aggregates (SSAUp)", false, false)
201 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
202 "Scalar Replacement of Aggregates (SSAUp)", false, false)
204 // Public interface to the ScalarReplAggregates pass
205 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
208 return new SROA_DT(Threshold);
209 return new SROA_SSAUp(Threshold);
213 //===----------------------------------------------------------------------===//
214 // Convert To Scalar Optimization.
215 //===----------------------------------------------------------------------===//
218 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
219 /// optimization, which scans the uses of an alloca and determines if it can
220 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
221 class ConvertToScalarInfo {
222 /// AllocaSize - The size of the alloca being considered in bytes.
224 const TargetData &TD;
226 /// IsNotTrivial - This is set to true if there is some access to the object
227 /// which means that mem2reg can't promote it.
230 /// VectorTy - This tracks the type that we should promote the vector to if
231 /// it is possible to turn it into a vector. This starts out null, and if it
232 /// isn't possible to turn into a vector type, it gets set to VoidTy.
233 const Type *VectorTy;
235 /// HadAVector - True if there is at least one vector access to the alloca.
236 /// We don't want to turn random arrays into vectors and use vector element
237 /// insert/extract, but if there are element accesses to something that is
238 /// also declared as a vector, we do want to promote to a vector.
241 /// HadNonMemTransferAccess - True if there is at least one access to the
242 /// alloca that is not a MemTransferInst. We don't want to turn structs into
243 /// large integers unless there is some potential for optimization.
244 bool HadNonMemTransferAccess;
247 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
248 : AllocaSize(Size), TD(td), IsNotTrivial(false), VectorTy(0),
249 HadAVector(false), HadNonMemTransferAccess(false) { }
251 AllocaInst *TryConvert(AllocaInst *AI);
254 bool CanConvertToScalar(Value *V, uint64_t Offset);
255 void MergeInType(const Type *In, uint64_t Offset, bool IsLoadOrStore);
256 bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset);
257 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
259 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
260 uint64_t Offset, IRBuilder<> &Builder);
261 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
262 uint64_t Offset, IRBuilder<> &Builder);
264 } // end anonymous namespace.
267 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
268 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
269 /// alloca if possible or null if not.
270 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
271 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
273 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
276 // If we were able to find a vector type that can handle this with
277 // insert/extract elements, and if there was at least one use that had
278 // a vector type, promote this to a vector. We don't want to promote
279 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
280 // we just get a lot of insert/extracts. If at least one vector is
281 // involved, then we probably really do have a union of vector/array.
283 if (VectorTy && VectorTy->isVectorTy() && HadAVector) {
284 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
285 << *VectorTy << '\n');
286 NewTy = VectorTy; // Use the vector type.
288 unsigned BitWidth = AllocaSize * 8;
289 if (!HadAVector && !HadNonMemTransferAccess &&
290 !TD.fitsInLegalInteger(BitWidth))
293 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
294 // Create and insert the integer alloca.
295 NewTy = IntegerType::get(AI->getContext(), BitWidth);
297 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
298 ConvertUsesToScalar(AI, NewAI, 0);
302 /// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy)
303 /// so far at the offset specified by Offset (which is specified in bytes).
305 /// There are three cases we handle here:
306 /// 1) A union of vector types of the same size and potentially its elements.
307 /// Here we turn element accesses into insert/extract element operations.
308 /// This promotes a <4 x float> with a store of float to the third element
309 /// into a <4 x float> that uses insert element.
310 /// 2) A union of vector types with power-of-2 size differences, e.g. a float,
311 /// <2 x float> and <4 x float>. Here we turn element accesses into insert
312 /// and extract element operations, and <2 x float> accesses into a cast to
313 /// <2 x double>, an extract, and a cast back to <2 x float>.
314 /// 3) A fully general blob of memory, which we turn into some (potentially
315 /// large) integer type with extract and insert operations where the loads
316 /// and stores would mutate the memory. We mark this by setting VectorTy
318 void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset,
319 bool IsLoadOrStore) {
320 // If we already decided to turn this into a blob of integer memory, there is
321 // nothing to be done.
322 if (VectorTy && VectorTy->isVoidTy())
325 // If this could be contributing to a vector, analyze it.
327 // If the In type is a vector that is the same size as the alloca, see if it
328 // matches the existing VecTy.
329 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
330 if (MergeInVectorType(VInTy, Offset))
332 } else if (In->isFloatTy() || In->isDoubleTy() ||
333 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
334 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
335 // Full width accesses can be ignored, because they can always be turned
337 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
338 if (IsLoadOrStore && EltSize == AllocaSize)
341 // If we're accessing something that could be an element of a vector, see
342 // if the implied vector agrees with what we already have and if Offset is
343 // compatible with it.
344 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0) {
346 VectorTy = VectorType::get(In, AllocaSize/EltSize);
350 unsigned CurrentEltSize = cast<VectorType>(VectorTy)->getElementType()
351 ->getPrimitiveSizeInBits()/8;
352 if (EltSize == CurrentEltSize)
355 if (In->isIntegerTy() && isPowerOf2_32(AllocaSize / EltSize))
360 // Otherwise, we have a case that we can't handle with an optimized vector
361 // form. We can still turn this into a large integer.
362 VectorTy = Type::getVoidTy(In->getContext());
365 /// MergeInVectorType - Handles the vector case of MergeInType, returning true
366 /// if the type was successfully merged and false otherwise.
367 bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
369 // Remember if we saw a vector type.
372 // TODO: Support nonzero offsets?
376 // Only allow vectors that are a power-of-2 away from the size of the alloca.
377 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
380 // If this the first vector we see, remember the type so that we know the
387 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
388 unsigned InBitWidth = VInTy->getBitWidth();
390 // Vectors of the same size can be converted using a simple bitcast.
391 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8))
394 const Type *ElementTy = cast<VectorType>(VectorTy)->getElementType();
395 const Type *InElementTy = cast<VectorType>(VInTy)->getElementType();
397 // Do not allow mixed integer and floating-point accesses from vectors of
399 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
402 if (ElementTy->isFloatingPointTy()) {
403 // Only allow floating-point vectors of different sizes if they have the
404 // same element type.
405 // TODO: This could be loosened a bit, but would anything benefit?
406 if (ElementTy != InElementTy)
409 // There are no arbitrary-precision floating-point types, which limits the
410 // number of legal vector types with larger element types that we can form
411 // to bitcast and extract a subvector.
412 // TODO: We could support some more cases with mixed fp128 and double here.
413 if (!(BitWidth == 64 || BitWidth == 128) ||
414 !(InBitWidth == 64 || InBitWidth == 128))
417 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
418 "or floating-point.");
419 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
420 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
422 // Do not allow integer types smaller than a byte or types whose widths are
423 // not a multiple of a byte.
424 if (BitWidth < 8 || InBitWidth < 8 ||
425 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
429 // Pick the largest of the two vector types.
430 if (InBitWidth > BitWidth)
436 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
437 /// its accesses to a single vector type, return true and set VecTy to
438 /// the new type. If we could convert the alloca into a single promotable
439 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
440 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
441 /// is the current offset from the base of the alloca being analyzed.
443 /// If we see at least one access to the value that is as a vector type, set the
445 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
446 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
447 Instruction *User = cast<Instruction>(*UI);
449 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
450 // Don't break volatile loads.
451 if (LI->isVolatile())
453 // Don't touch MMX operations.
454 if (LI->getType()->isX86_MMXTy())
456 HadNonMemTransferAccess = true;
457 MergeInType(LI->getType(), Offset, true);
461 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
462 // Storing the pointer, not into the value?
463 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
464 // Don't touch MMX operations.
465 if (SI->getOperand(0)->getType()->isX86_MMXTy())
467 HadNonMemTransferAccess = true;
468 MergeInType(SI->getOperand(0)->getType(), Offset, true);
472 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
473 IsNotTrivial = true; // Can't be mem2reg'd.
474 if (!CanConvertToScalar(BCI, Offset))
479 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
480 // If this is a GEP with a variable indices, we can't handle it.
481 if (!GEP->hasAllConstantIndices())
484 // Compute the offset that this GEP adds to the pointer.
485 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
486 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
487 &Indices[0], Indices.size());
488 // See if all uses can be converted.
489 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
491 IsNotTrivial = true; // Can't be mem2reg'd.
492 HadNonMemTransferAccess = true;
496 // If this is a constant sized memset of a constant value (e.g. 0) we can
498 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
499 // Store of constant value and constant size.
500 if (!isa<ConstantInt>(MSI->getValue()) ||
501 !isa<ConstantInt>(MSI->getLength()))
503 IsNotTrivial = true; // Can't be mem2reg'd.
504 HadNonMemTransferAccess = true;
508 // If this is a memcpy or memmove into or out of the whole allocation, we
509 // can handle it like a load or store of the scalar type.
510 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
511 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
512 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
515 IsNotTrivial = true; // Can't be mem2reg'd.
519 // Otherwise, we cannot handle this!
526 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
527 /// directly. This happens when we are converting an "integer union" to a
528 /// single integer scalar, or when we are converting a "vector union" to a
529 /// vector with insert/extractelement instructions.
531 /// Offset is an offset from the original alloca, in bits that need to be
532 /// shifted to the right. By the end of this, there should be no uses of Ptr.
533 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
535 while (!Ptr->use_empty()) {
536 Instruction *User = cast<Instruction>(Ptr->use_back());
538 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
539 ConvertUsesToScalar(CI, NewAI, Offset);
540 CI->eraseFromParent();
544 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
545 // Compute the offset that this GEP adds to the pointer.
546 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
547 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
548 &Indices[0], Indices.size());
549 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
550 GEP->eraseFromParent();
554 IRBuilder<> Builder(User);
556 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
557 // The load is a bit extract from NewAI shifted right by Offset bits.
558 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
560 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
561 LI->replaceAllUsesWith(NewLoadVal);
562 LI->eraseFromParent();
566 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
567 assert(SI->getOperand(0) != Ptr && "Consistency error!");
568 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
569 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
571 Builder.CreateStore(New, NewAI);
572 SI->eraseFromParent();
574 // If the load we just inserted is now dead, then the inserted store
575 // overwrote the entire thing.
576 if (Old->use_empty())
577 Old->eraseFromParent();
581 // If this is a constant sized memset of a constant value (e.g. 0) we can
582 // transform it into a store of the expanded constant value.
583 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
584 assert(MSI->getRawDest() == Ptr && "Consistency error!");
585 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
587 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
589 // Compute the value replicated the right number of times.
590 APInt APVal(NumBytes*8, Val);
592 // Splat the value if non-zero.
594 for (unsigned i = 1; i != NumBytes; ++i)
597 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
598 Value *New = ConvertScalar_InsertValue(
599 ConstantInt::get(User->getContext(), APVal),
600 Old, Offset, Builder);
601 Builder.CreateStore(New, NewAI);
603 // If the load we just inserted is now dead, then the memset overwrote
605 if (Old->use_empty())
606 Old->eraseFromParent();
608 MSI->eraseFromParent();
612 // If this is a memcpy or memmove into or out of the whole allocation, we
613 // can handle it like a load or store of the scalar type.
614 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
615 assert(Offset == 0 && "must be store to start of alloca");
617 // If the source and destination are both to the same alloca, then this is
618 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
620 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
622 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
623 // Dest must be OrigAI, change this to be a load from the original
624 // pointer (bitcasted), then a store to our new alloca.
625 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
626 Value *SrcPtr = MTI->getSource();
627 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
628 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
629 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
630 AIPTy = PointerType::get(AIPTy->getElementType(),
631 SPTy->getAddressSpace());
633 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
635 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
636 SrcVal->setAlignment(MTI->getAlignment());
637 Builder.CreateStore(SrcVal, NewAI);
638 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
639 // Src must be OrigAI, change this to be a load from NewAI then a store
640 // through the original dest pointer (bitcasted).
641 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
642 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
644 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
645 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
646 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
647 AIPTy = PointerType::get(AIPTy->getElementType(),
648 DPTy->getAddressSpace());
650 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
652 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
653 NewStore->setAlignment(MTI->getAlignment());
655 // Noop transfer. Src == Dst
658 MTI->eraseFromParent();
662 llvm_unreachable("Unsupported operation!");
666 /// getScaledElementType - Gets a scaled element type for a partial vector
667 /// access of an alloca. The input types must be integer or floating-point
668 /// scalar or vector types, and the resulting type is an integer, float or
670 static const Type *getScaledElementType(const Type *Ty1, const Type *Ty2,
671 unsigned NewBitWidth) {
672 bool IsFP1 = Ty1->isFloatingPointTy() ||
673 (Ty1->isVectorTy() &&
674 cast<VectorType>(Ty1)->getElementType()->isFloatingPointTy());
675 bool IsFP2 = Ty2->isFloatingPointTy() ||
676 (Ty2->isVectorTy() &&
677 cast<VectorType>(Ty2)->getElementType()->isFloatingPointTy());
679 LLVMContext &Context = Ty1->getContext();
681 // Prefer floating-point types over integer types, as integer types may have
682 // been created by earlier scalar replacement.
683 if (IsFP1 || IsFP2) {
684 if (NewBitWidth == 32)
685 return Type::getFloatTy(Context);
686 if (NewBitWidth == 64)
687 return Type::getDoubleTy(Context);
690 return Type::getIntNTy(Context, NewBitWidth);
693 /// CreateShuffleVectorCast - Creates a shuffle vector to convert one vector
694 /// to another vector of the same element type which has the same allocation
695 /// size but different primitive sizes (e.g. <3 x i32> and <4 x i32>).
696 static Value *CreateShuffleVectorCast(Value *FromVal, const Type *ToType,
697 IRBuilder<> &Builder) {
698 const Type *FromType = FromVal->getType();
699 const VectorType *FromVTy = cast<VectorType>(FromType);
700 const VectorType *ToVTy = cast<VectorType>(ToType);
701 assert((ToVTy->getElementType() == FromVTy->getElementType()) &&
702 "Vectors must have the same element type");
703 Value *UnV = UndefValue::get(FromType);
704 unsigned numEltsFrom = FromVTy->getNumElements();
705 unsigned numEltsTo = ToVTy->getNumElements();
707 SmallVector<Constant*, 3> Args;
708 const Type* Int32Ty = Builder.getInt32Ty();
709 unsigned minNumElts = std::min(numEltsFrom, numEltsTo);
711 for (i=0; i != minNumElts; ++i)
712 Args.push_back(ConstantInt::get(Int32Ty, i));
715 Constant* UnC = UndefValue::get(Int32Ty);
716 for (; i != numEltsTo; ++i)
719 Constant *Mask = ConstantVector::get(Args);
720 return Builder.CreateShuffleVector(FromVal, UnV, Mask, "tmpV");
723 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
724 /// or vector value FromVal, extracting the bits from the offset specified by
725 /// Offset. This returns the value, which is of type ToType.
727 /// This happens when we are converting an "integer union" to a single
728 /// integer scalar, or when we are converting a "vector union" to a vector with
729 /// insert/extractelement instructions.
731 /// Offset is an offset from the original alloca, in bits that need to be
732 /// shifted to the right.
733 Value *ConvertToScalarInfo::
734 ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
735 uint64_t Offset, IRBuilder<> &Builder) {
736 // If the load is of the whole new alloca, no conversion is needed.
737 const Type *FromType = FromVal->getType();
738 if (FromType == ToType && Offset == 0)
741 // If the result alloca is a vector type, this is either an element
742 // access or a bitcast to another vector type of the same size.
743 if (const VectorType *VTy = dyn_cast<VectorType>(FromType)) {
744 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
745 if (ToTypeSize == AllocaSize) {
746 // If the two types have the same primitive size, use a bit cast.
747 // Otherwise, it is two vectors with the same element type that has
748 // the same allocation size but different number of elements so use
750 if (FromType->getPrimitiveSizeInBits() ==
751 ToType->getPrimitiveSizeInBits())
752 return Builder.CreateBitCast(FromVal, ToType, "tmp");
754 return CreateShuffleVectorCast(FromVal, ToType, Builder);
757 if (isPowerOf2_64(AllocaSize / ToTypeSize)) {
758 assert(!(ToType->isVectorTy() && Offset != 0) && "Can't extract a value "
759 "of a smaller vector type at a nonzero offset.");
761 const Type *CastElementTy = getScaledElementType(FromType, ToType,
763 unsigned NumCastVectorElements = AllocaSize / ToTypeSize;
765 LLVMContext &Context = FromVal->getContext();
766 const Type *CastTy = VectorType::get(CastElementTy,
767 NumCastVectorElements);
768 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
770 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
771 unsigned Elt = Offset/EltSize;
772 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
773 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
774 Type::getInt32Ty(Context), Elt), "tmp");
775 return Builder.CreateBitCast(Extract, ToType, "tmp");
778 // Otherwise it must be an element access.
781 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
782 Elt = Offset/EltSize;
783 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
785 // Return the element extracted out of it.
786 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
787 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
788 if (V->getType() != ToType)
789 V = Builder.CreateBitCast(V, ToType, "tmp");
793 // If ToType is a first class aggregate, extract out each of the pieces and
794 // use insertvalue's to form the FCA.
795 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
796 const StructLayout &Layout = *TD.getStructLayout(ST);
797 Value *Res = UndefValue::get(ST);
798 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
799 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
800 Offset+Layout.getElementOffsetInBits(i),
802 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
807 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
808 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
809 Value *Res = UndefValue::get(AT);
810 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
811 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
812 Offset+i*EltSize, Builder);
813 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
818 // Otherwise, this must be a union that was converted to an integer value.
819 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
821 // If this is a big-endian system and the load is narrower than the
822 // full alloca type, we need to do a shift to get the right bits.
824 if (TD.isBigEndian()) {
825 // On big-endian machines, the lowest bit is stored at the bit offset
826 // from the pointer given by getTypeStoreSizeInBits. This matters for
827 // integers with a bitwidth that is not a multiple of 8.
828 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
829 TD.getTypeStoreSizeInBits(ToType) - Offset;
834 // Note: we support negative bitwidths (with shl) which are not defined.
835 // We do this to support (f.e.) loads off the end of a structure where
836 // only some bits are used.
837 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
838 FromVal = Builder.CreateLShr(FromVal,
839 ConstantInt::get(FromVal->getType(),
841 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
842 FromVal = Builder.CreateShl(FromVal,
843 ConstantInt::get(FromVal->getType(),
846 // Finally, unconditionally truncate the integer to the right width.
847 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
848 if (LIBitWidth < NTy->getBitWidth())
850 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
852 else if (LIBitWidth > NTy->getBitWidth())
854 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
857 // If the result is an integer, this is a trunc or bitcast.
858 if (ToType->isIntegerTy()) {
860 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
861 // Just do a bitcast, we know the sizes match up.
862 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
864 // Otherwise must be a pointer.
865 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
867 assert(FromVal->getType() == ToType && "Didn't convert right?");
871 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
872 /// or vector value "Old" at the offset specified by Offset.
874 /// This happens when we are converting an "integer union" to a
875 /// single integer scalar, or when we are converting a "vector union" to a
876 /// vector with insert/extractelement instructions.
878 /// Offset is an offset from the original alloca, in bits that need to be
879 /// shifted to the right.
880 Value *ConvertToScalarInfo::
881 ConvertScalar_InsertValue(Value *SV, Value *Old,
882 uint64_t Offset, IRBuilder<> &Builder) {
883 // Convert the stored type to the actual type, shift it left to insert
884 // then 'or' into place.
885 const Type *AllocaType = Old->getType();
886 LLVMContext &Context = Old->getContext();
888 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
889 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
890 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
892 // Changing the whole vector with memset or with an access of a different
894 if (ValSize == VecSize) {
895 // If the two types have the same primitive size, use a bit cast.
896 // Otherwise, it is two vectors with the same element type that has
897 // the same allocation size but different number of elements so use
899 if (VTy->getPrimitiveSizeInBits() ==
900 SV->getType()->getPrimitiveSizeInBits())
901 return Builder.CreateBitCast(SV, AllocaType, "tmp");
903 return CreateShuffleVectorCast(SV, VTy, Builder);
906 if (isPowerOf2_64(VecSize / ValSize)) {
907 assert(!(SV->getType()->isVectorTy() && Offset != 0) && "Can't insert a "
908 "value of a smaller vector type at a nonzero offset.");
910 const Type *CastElementTy = getScaledElementType(VTy, SV->getType(),
912 unsigned NumCastVectorElements = VecSize / ValSize;
914 LLVMContext &Context = SV->getContext();
915 const Type *OldCastTy = VectorType::get(CastElementTy,
916 NumCastVectorElements);
917 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
919 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
921 unsigned EltSize = TD.getTypeAllocSizeInBits(CastElementTy);
922 unsigned Elt = Offset/EltSize;
923 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
925 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
926 Type::getInt32Ty(Context), Elt), "tmp");
927 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
930 // Must be an element insertion.
931 assert(SV->getType() == VTy->getElementType());
932 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
933 unsigned Elt = Offset/EltSize;
934 return Builder.CreateInsertElement(Old, SV,
935 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
939 // If SV is a first-class aggregate value, insert each value recursively.
940 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
941 const StructLayout &Layout = *TD.getStructLayout(ST);
942 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
943 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
944 Old = ConvertScalar_InsertValue(Elt, Old,
945 Offset+Layout.getElementOffsetInBits(i),
951 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
952 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
953 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
954 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
955 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
960 // If SV is a float, convert it to the appropriate integer type.
961 // If it is a pointer, do the same.
962 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
963 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
964 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
965 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
966 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
967 SV = Builder.CreateBitCast(SV,
968 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
969 else if (SV->getType()->isPointerTy())
970 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
972 // Zero extend or truncate the value if needed.
973 if (SV->getType() != AllocaType) {
974 if (SV->getType()->getPrimitiveSizeInBits() <
975 AllocaType->getPrimitiveSizeInBits())
976 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
978 // Truncation may be needed if storing more than the alloca can hold
979 // (undefined behavior).
980 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
981 SrcWidth = DestWidth;
982 SrcStoreWidth = DestStoreWidth;
986 // If this is a big-endian system and the store is narrower than the
987 // full alloca type, we need to do a shift to get the right bits.
989 if (TD.isBigEndian()) {
990 // On big-endian machines, the lowest bit is stored at the bit offset
991 // from the pointer given by getTypeStoreSizeInBits. This matters for
992 // integers with a bitwidth that is not a multiple of 8.
993 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
998 // Note: we support negative bitwidths (with shr) which are not defined.
999 // We do this to support (f.e.) stores off the end of a structure where
1000 // only some bits in the structure are set.
1001 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1002 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1003 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
1006 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1007 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
1009 Mask = Mask.lshr(-ShAmt);
1012 // Mask out the bits we are about to insert from the old value, and or
1014 if (SrcWidth != DestWidth) {
1015 assert(DestWidth > SrcWidth);
1016 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1017 SV = Builder.CreateOr(Old, SV, "ins");
1023 //===----------------------------------------------------------------------===//
1025 //===----------------------------------------------------------------------===//
1028 bool SROA::runOnFunction(Function &F) {
1029 TD = getAnalysisIfAvailable<TargetData>();
1031 bool Changed = performPromotion(F);
1033 // FIXME: ScalarRepl currently depends on TargetData more than it
1034 // theoretically needs to. It should be refactored in order to support
1035 // target-independent IR. Until this is done, just skip the actual
1036 // scalar-replacement portion of this pass.
1037 if (!TD) return Changed;
1040 bool LocalChange = performScalarRepl(F);
1041 if (!LocalChange) break; // No need to repromote if no scalarrepl
1043 LocalChange = performPromotion(F);
1044 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1051 class AllocaPromoter : public LoadAndStorePromoter {
1054 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
1055 : LoadAndStorePromoter(Insts, S), AI(0) {}
1057 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
1058 // Remember which alloca we're promoting (for isInstInList).
1060 LoadAndStorePromoter::run(Insts);
1061 AI->eraseFromParent();
1064 virtual bool isInstInList(Instruction *I,
1065 const SmallVectorImpl<Instruction*> &Insts) const {
1066 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1067 return LI->getOperand(0) == AI;
1068 return cast<StoreInst>(I)->getPointerOperand() == AI;
1071 } // end anon namespace
1073 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1074 /// subsequently loaded can be rewritten to load both input pointers and then
1075 /// select between the result, allowing the load of the alloca to be promoted.
1077 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1078 /// %V = load i32* %P2
1080 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1081 /// %V2 = load i32* %Other
1082 /// %V = select i1 %cond, i32 %V1, i32 %V2
1084 /// We can do this to a select if its only uses are loads and if the operand to
1085 /// the select can be loaded unconditionally.
1086 static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1087 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1088 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1090 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1092 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1093 if (LI == 0 || LI->isVolatile()) return false;
1095 // Both operands to the select need to be dereferencable, either absolutely
1096 // (e.g. allocas) or at this point because we can see other accesses to it.
1097 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1098 LI->getAlignment(), TD))
1100 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1101 LI->getAlignment(), TD))
1108 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1109 /// subsequently loaded can be rewritten to load both input pointers in the pred
1110 /// blocks and then PHI the results, allowing the load of the alloca to be
1113 /// %P2 = phi [i32* %Alloca, i32* %Other]
1114 /// %V = load i32* %P2
1116 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1118 /// %V2 = load i32* %Other
1120 /// %V = phi [i32 %V1, i32 %V2]
1122 /// We can do this to a select if its only uses are loads and if the operand to
1123 /// the select can be loaded unconditionally.
1124 static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1125 // For now, we can only do this promotion if the load is in the same block as
1126 // the PHI, and if there are no stores between the phi and load.
1127 // TODO: Allow recursive phi users.
1128 // TODO: Allow stores.
1129 BasicBlock *BB = PN->getParent();
1130 unsigned MaxAlign = 0;
1131 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1133 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1134 if (LI == 0 || LI->isVolatile()) return false;
1136 // For now we only allow loads in the same block as the PHI. This is a
1137 // common case that happens when instcombine merges two loads through a PHI.
1138 if (LI->getParent() != BB) return false;
1140 // Ensure that there are no instructions between the PHI and the load that
1142 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1143 if (BBI->mayWriteToMemory())
1146 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1149 // Okay, we know that we have one or more loads in the same block as the PHI.
1150 // We can transform this if it is safe to push the loads into the predecessor
1151 // blocks. The only thing to watch out for is that we can't put a possibly
1152 // trapping load in the predecessor if it is a critical edge.
1153 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1154 BasicBlock *Pred = PN->getIncomingBlock(i);
1156 // If the predecessor has a single successor, then the edge isn't critical.
1157 if (Pred->getTerminator()->getNumSuccessors() == 1)
1160 Value *InVal = PN->getIncomingValue(i);
1162 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1163 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1164 if (II->getParent() == Pred)
1167 // If this pointer is always safe to load, or if we can prove that there is
1168 // already a load in the block, then we can move the load to the pred block.
1169 if (InVal->isDereferenceablePointer() ||
1170 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1180 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1181 /// direct (non-volatile) loads and stores to it. If the alloca is close but
1182 /// not quite there, this will transform the code to allow promotion. As such,
1183 /// it is a non-pure predicate.
1184 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1185 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1186 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1188 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1191 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1192 if (LI->isVolatile())
1197 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1198 if (SI->getOperand(0) == AI || SI->isVolatile())
1199 return false; // Don't allow a store OF the AI, only INTO the AI.
1203 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1204 // If the condition being selected on is a constant, fold the select, yes
1205 // this does (rarely) happen early on.
1206 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1207 Value *Result = SI->getOperand(1+CI->isZero());
1208 SI->replaceAllUsesWith(Result);
1209 SI->eraseFromParent();
1211 // This is very rare and we just scrambled the use list of AI, start
1213 return tryToMakeAllocaBePromotable(AI, TD);
1216 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1217 // loads, then we can transform this by rewriting the select.
1218 if (!isSafeSelectToSpeculate(SI, TD))
1221 InstsToRewrite.insert(SI);
1225 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1226 if (PN->use_empty()) { // Dead PHIs can be stripped.
1227 InstsToRewrite.insert(PN);
1231 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1232 // in the pred blocks, then we can transform this by rewriting the PHI.
1233 if (!isSafePHIToSpeculate(PN, TD))
1236 InstsToRewrite.insert(PN);
1243 // If there are no instructions to rewrite, then all uses are load/stores and
1245 if (InstsToRewrite.empty())
1248 // If we have instructions that need to be rewritten for this to be promotable
1249 // take care of it now.
1250 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1251 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1252 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1253 // loads with a new select.
1254 while (!SI->use_empty()) {
1255 LoadInst *LI = cast<LoadInst>(SI->use_back());
1257 IRBuilder<> Builder(LI);
1258 LoadInst *TrueLoad =
1259 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1260 LoadInst *FalseLoad =
1261 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1263 // Transfer alignment and TBAA info if present.
1264 TrueLoad->setAlignment(LI->getAlignment());
1265 FalseLoad->setAlignment(LI->getAlignment());
1266 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1267 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1268 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1271 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1273 LI->replaceAllUsesWith(V);
1274 LI->eraseFromParent();
1277 // Now that all the loads are gone, the select is gone too.
1278 SI->eraseFromParent();
1282 // Otherwise, we have a PHI node which allows us to push the loads into the
1284 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1285 if (PN->use_empty()) {
1286 PN->eraseFromParent();
1290 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1291 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1292 PN->getName()+".ld", PN);
1294 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1295 // matter which one we get and if any differ, it doesn't matter.
1296 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1297 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1298 unsigned Align = SomeLoad->getAlignment();
1300 // Rewrite all loads of the PN to use the new PHI.
1301 while (!PN->use_empty()) {
1302 LoadInst *LI = cast<LoadInst>(PN->use_back());
1303 LI->replaceAllUsesWith(NewPN);
1304 LI->eraseFromParent();
1307 // Inject loads into all of the pred blocks. Keep track of which blocks we
1308 // insert them into in case we have multiple edges from the same block.
1309 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1311 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1312 BasicBlock *Pred = PN->getIncomingBlock(i);
1313 LoadInst *&Load = InsertedLoads[Pred];
1315 Load = new LoadInst(PN->getIncomingValue(i),
1316 PN->getName() + "." + Pred->getName(),
1317 Pred->getTerminator());
1318 Load->setAlignment(Align);
1319 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1322 NewPN->addIncoming(Load, Pred);
1325 PN->eraseFromParent();
1333 bool SROA::performPromotion(Function &F) {
1334 std::vector<AllocaInst*> Allocas;
1335 DominatorTree *DT = 0;
1337 DT = &getAnalysis<DominatorTree>();
1339 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
1341 bool Changed = false;
1342 SmallVector<Instruction*, 64> Insts;
1346 // Find allocas that are safe to promote, by looking at all instructions in
1348 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1349 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
1350 if (tryToMakeAllocaBePromotable(AI, TD))
1351 Allocas.push_back(AI);
1353 if (Allocas.empty()) break;
1356 PromoteMemToReg(Allocas, *DT);
1359 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1360 AllocaInst *AI = Allocas[i];
1362 // Build list of instructions to promote.
1363 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1365 Insts.push_back(cast<Instruction>(*UI));
1367 AllocaPromoter(Insts, SSA).run(AI, Insts);
1371 NumPromoted += Allocas.size();
1379 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1380 /// SROA. It must be a struct or array type with a small number of elements.
1381 static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1382 const Type *T = AI->getAllocatedType();
1383 // Do not promote any struct into more than 32 separate vars.
1384 if (const StructType *ST = dyn_cast<StructType>(T))
1385 return ST->getNumElements() <= 32;
1386 // Arrays are much less likely to be safe for SROA; only consider
1387 // them if they are very small.
1388 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1389 return AT->getNumElements() <= 8;
1394 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
1395 // which runs on all of the malloc/alloca instructions in the function, removing
1396 // them if they are only used by getelementptr instructions.
1398 bool SROA::performScalarRepl(Function &F) {
1399 std::vector<AllocaInst*> WorkList;
1401 // Scan the entry basic block, adding allocas to the worklist.
1402 BasicBlock &BB = F.getEntryBlock();
1403 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1404 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1405 WorkList.push_back(A);
1407 // Process the worklist
1408 bool Changed = false;
1409 while (!WorkList.empty()) {
1410 AllocaInst *AI = WorkList.back();
1411 WorkList.pop_back();
1413 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1414 // with unused elements.
1415 if (AI->use_empty()) {
1416 AI->eraseFromParent();
1421 // If this alloca is impossible for us to promote, reject it early.
1422 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1425 // Check to see if this allocation is only modified by a memcpy/memmove from
1426 // a constant global. If this is the case, we can change all users to use
1427 // the constant global instead. This is commonly produced by the CFE by
1428 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1429 // is only subsequently read.
1430 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
1431 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1432 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
1433 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
1434 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1435 TheCopy->eraseFromParent(); // Don't mutate the global.
1436 AI->eraseFromParent();
1442 // Check to see if we can perform the core SROA transformation. We cannot
1443 // transform the allocation instruction if it is an array allocation
1444 // (allocations OF arrays are ok though), and an allocation of a scalar
1445 // value cannot be decomposed at all.
1446 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1448 // Do not promote [0 x %struct].
1449 if (AllocaSize == 0) continue;
1451 // Do not promote any struct whose size is too big.
1452 if (AllocaSize > SRThreshold) continue;
1454 // If the alloca looks like a good candidate for scalar replacement, and if
1455 // all its users can be transformed, then split up the aggregate into its
1456 // separate elements.
1457 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1458 DoScalarReplacement(AI, WorkList);
1463 // If we can turn this aggregate value (potentially with casts) into a
1464 // simple scalar value that can be mem2reg'd into a register value.
1465 // IsNotTrivial tracks whether this is something that mem2reg could have
1466 // promoted itself. If so, we don't want to transform it needlessly. Note
1467 // that we can't just check based on the type: the alloca may be of an i32
1468 // but that has pointer arithmetic to set byte 3 of it or something.
1469 if (AllocaInst *NewAI =
1470 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1471 NewAI->takeName(AI);
1472 AI->eraseFromParent();
1478 // Otherwise, couldn't process this alloca.
1484 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1485 /// predicate, do SROA now.
1486 void SROA::DoScalarReplacement(AllocaInst *AI,
1487 std::vector<AllocaInst*> &WorkList) {
1488 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1489 SmallVector<AllocaInst*, 32> ElementAllocas;
1490 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1491 ElementAllocas.reserve(ST->getNumContainedTypes());
1492 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1493 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1495 AI->getName() + "." + Twine(i), AI);
1496 ElementAllocas.push_back(NA);
1497 WorkList.push_back(NA); // Add to worklist for recursive processing
1500 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1501 ElementAllocas.reserve(AT->getNumElements());
1502 const Type *ElTy = AT->getElementType();
1503 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1504 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1505 AI->getName() + "." + Twine(i), AI);
1506 ElementAllocas.push_back(NA);
1507 WorkList.push_back(NA); // Add to worklist for recursive processing
1511 // Now that we have created the new alloca instructions, rewrite all the
1512 // uses of the old alloca.
1513 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1515 // Now erase any instructions that were made dead while rewriting the alloca.
1516 DeleteDeadInstructions();
1517 AI->eraseFromParent();
1522 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1523 /// recursively including all their operands that become trivially dead.
1524 void SROA::DeleteDeadInstructions() {
1525 while (!DeadInsts.empty()) {
1526 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1528 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1529 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1530 // Zero out the operand and see if it becomes trivially dead.
1531 // (But, don't add allocas to the dead instruction list -- they are
1532 // already on the worklist and will be deleted separately.)
1534 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1535 DeadInsts.push_back(U);
1538 I->eraseFromParent();
1542 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1543 /// performing scalar replacement of alloca AI. The results are flagged in
1544 /// the Info parameter. Offset indicates the position within AI that is
1545 /// referenced by this instruction.
1546 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1548 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1549 Instruction *User = cast<Instruction>(*UI);
1551 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1552 isSafeForScalarRepl(BC, Offset, Info);
1553 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1554 uint64_t GEPOffset = Offset;
1555 isSafeGEP(GEPI, GEPOffset, Info);
1557 isSafeForScalarRepl(GEPI, GEPOffset, Info);
1558 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1559 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1561 return MarkUnsafe(Info, User);
1562 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1563 UI.getOperandNo() == 0, Info, MI,
1564 true /*AllowWholeAccess*/);
1565 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1566 if (LI->isVolatile())
1567 return MarkUnsafe(Info, User);
1568 const Type *LIType = LI->getType();
1569 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1570 LIType, false, Info, LI, true /*AllowWholeAccess*/);
1571 Info.hasALoadOrStore = true;
1573 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1574 // Store is ok if storing INTO the pointer, not storing the pointer
1575 if (SI->isVolatile() || SI->getOperand(0) == I)
1576 return MarkUnsafe(Info, User);
1578 const Type *SIType = SI->getOperand(0)->getType();
1579 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1580 SIType, true, Info, SI, true /*AllowWholeAccess*/);
1581 Info.hasALoadOrStore = true;
1582 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1583 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1585 return MarkUnsafe(Info, User);
1587 if (Info.isUnsafe) return;
1592 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1593 /// derived from the alloca, we can often still split the alloca into elements.
1594 /// This is useful if we have a large alloca where one element is phi'd
1595 /// together somewhere: we can SRoA and promote all the other elements even if
1596 /// we end up not being able to promote this one.
1598 /// All we require is that the uses of the PHI do not index into other parts of
1599 /// the alloca. The most important use case for this is single load and stores
1600 /// that are PHI'd together, which can happen due to code sinking.
1601 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1603 // If we've already checked this PHI, don't do it again.
1604 if (PHINode *PN = dyn_cast<PHINode>(I))
1605 if (!Info.CheckedPHIs.insert(PN))
1608 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1609 Instruction *User = cast<Instruction>(*UI);
1611 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1612 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1613 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1614 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1615 // but would have to prove that we're staying inside of an element being
1617 if (!GEPI->hasAllZeroIndices())
1618 return MarkUnsafe(Info, User);
1619 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1620 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1621 if (LI->isVolatile())
1622 return MarkUnsafe(Info, User);
1623 const Type *LIType = LI->getType();
1624 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1625 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1626 Info.hasALoadOrStore = true;
1628 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1629 // Store is ok if storing INTO the pointer, not storing the pointer
1630 if (SI->isVolatile() || SI->getOperand(0) == I)
1631 return MarkUnsafe(Info, User);
1633 const Type *SIType = SI->getOperand(0)->getType();
1634 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1635 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1636 Info.hasALoadOrStore = true;
1637 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1638 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1640 return MarkUnsafe(Info, User);
1642 if (Info.isUnsafe) return;
1646 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1647 /// replacement. It is safe when all the indices are constant, in-bounds
1648 /// references, and when the resulting offset corresponds to an element within
1649 /// the alloca type. The results are flagged in the Info parameter. Upon
1650 /// return, Offset is adjusted as specified by the GEP indices.
1651 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1652 uint64_t &Offset, AllocaInfo &Info) {
1653 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1657 // Walk through the GEP type indices, checking the types that this indexes
1659 for (; GEPIt != E; ++GEPIt) {
1660 // Ignore struct elements, no extra checking needed for these.
1661 if ((*GEPIt)->isStructTy())
1664 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1666 return MarkUnsafe(Info, GEPI);
1669 // Compute the offset due to this GEP and check if the alloca has a
1670 // component element at that offset.
1671 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1672 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1673 &Indices[0], Indices.size());
1674 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
1675 MarkUnsafe(Info, GEPI);
1678 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1679 /// elements of the same type (which is always true for arrays). If so,
1680 /// return true with NumElts and EltTy set to the number of elements and the
1681 /// element type, respectively.
1682 static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1683 const Type *&EltTy) {
1684 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1685 NumElts = AT->getNumElements();
1686 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1689 if (const StructType *ST = dyn_cast<StructType>(T)) {
1690 NumElts = ST->getNumContainedTypes();
1691 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1692 for (unsigned n = 1; n < NumElts; ++n) {
1693 if (ST->getContainedType(n) != EltTy)
1701 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1702 /// "homogeneous" aggregates with the same element type and number of elements.
1703 static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1707 unsigned NumElts1, NumElts2;
1708 const Type *EltTy1, *EltTy2;
1709 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1710 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1711 NumElts1 == NumElts2 &&
1718 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1719 /// alloca or has an offset and size that corresponds to a component element
1720 /// within it. The offset checked here may have been formed from a GEP with a
1721 /// pointer bitcasted to a different type.
1723 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1724 /// unit. If false, it only allows accesses known to be in a single element.
1725 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1726 const Type *MemOpType, bool isStore,
1727 AllocaInfo &Info, Instruction *TheAccess,
1728 bool AllowWholeAccess) {
1729 // Check if this is a load/store of the entire alloca.
1730 if (Offset == 0 && AllowWholeAccess &&
1731 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1732 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1733 // loads/stores (which are essentially the same as the MemIntrinsics with
1734 // regard to copying padding between elements). But, if an alloca is
1735 // flagged as both a source and destination of such operations, we'll need
1736 // to check later for padding between elements.
1737 if (!MemOpType || MemOpType->isIntegerTy()) {
1739 Info.isMemCpyDst = true;
1741 Info.isMemCpySrc = true;
1744 // This is also safe for references using a type that is compatible with
1745 // the type of the alloca, so that loads/stores can be rewritten using
1746 // insertvalue/extractvalue.
1747 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1748 Info.hasSubelementAccess = true;
1752 // Check if the offset/size correspond to a component within the alloca type.
1753 const Type *T = Info.AI->getAllocatedType();
1754 if (TypeHasComponent(T, Offset, MemSize)) {
1755 Info.hasSubelementAccess = true;
1759 return MarkUnsafe(Info, TheAccess);
1762 /// TypeHasComponent - Return true if T has a component type with the
1763 /// specified offset and size. If Size is zero, do not check the size.
1764 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1767 if (const StructType *ST = dyn_cast<StructType>(T)) {
1768 const StructLayout *Layout = TD->getStructLayout(ST);
1769 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1770 EltTy = ST->getContainedType(EltIdx);
1771 EltSize = TD->getTypeAllocSize(EltTy);
1772 Offset -= Layout->getElementOffset(EltIdx);
1773 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1774 EltTy = AT->getElementType();
1775 EltSize = TD->getTypeAllocSize(EltTy);
1776 if (Offset >= AT->getNumElements() * EltSize)
1782 if (Offset == 0 && (Size == 0 || EltSize == Size))
1784 // Check if the component spans multiple elements.
1785 if (Offset + Size > EltSize)
1787 return TypeHasComponent(EltTy, Offset, Size);
1790 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1791 /// the instruction I, which references it, to use the separate elements.
1792 /// Offset indicates the position within AI that is referenced by this
1794 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1795 SmallVector<AllocaInst*, 32> &NewElts) {
1796 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1797 Use &TheUse = UI.getUse();
1798 Instruction *User = cast<Instruction>(*UI++);
1800 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1801 RewriteBitCast(BC, AI, Offset, NewElts);
1805 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1806 RewriteGEP(GEPI, AI, Offset, NewElts);
1810 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1811 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1812 uint64_t MemSize = Length->getZExtValue();
1814 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1815 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1816 // Otherwise the intrinsic can only touch a single element and the
1817 // address operand will be updated, so nothing else needs to be done.
1821 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1822 const Type *LIType = LI->getType();
1824 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1826 // %res = load { i32, i32 }* %alloc
1828 // %load.0 = load i32* %alloc.0
1829 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1830 // %load.1 = load i32* %alloc.1
1831 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1832 // (Also works for arrays instead of structs)
1833 Value *Insert = UndefValue::get(LIType);
1834 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1835 Value *Load = new LoadInst(NewElts[i], "load", LI);
1836 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1838 LI->replaceAllUsesWith(Insert);
1839 DeadInsts.push_back(LI);
1840 } else if (LIType->isIntegerTy() &&
1841 TD->getTypeAllocSize(LIType) ==
1842 TD->getTypeAllocSize(AI->getAllocatedType())) {
1843 // If this is a load of the entire alloca to an integer, rewrite it.
1844 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1849 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1850 Value *Val = SI->getOperand(0);
1851 const Type *SIType = Val->getType();
1852 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1854 // store { i32, i32 } %val, { i32, i32 }* %alloc
1856 // %val.0 = extractvalue { i32, i32 } %val, 0
1857 // store i32 %val.0, i32* %alloc.0
1858 // %val.1 = extractvalue { i32, i32 } %val, 1
1859 // store i32 %val.1, i32* %alloc.1
1860 // (Also works for arrays instead of structs)
1861 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1862 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1863 new StoreInst(Extract, NewElts[i], SI);
1865 DeadInsts.push_back(SI);
1866 } else if (SIType->isIntegerTy() &&
1867 TD->getTypeAllocSize(SIType) ==
1868 TD->getTypeAllocSize(AI->getAllocatedType())) {
1869 // If this is a store of the entire alloca from an integer, rewrite it.
1870 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1875 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1876 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1877 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1879 if (!isa<AllocaInst>(I)) continue;
1881 assert(Offset == 0 && NewElts[0] &&
1882 "Direct alloca use should have a zero offset");
1884 // If we have a use of the alloca, we know the derived uses will be
1885 // utilizing just the first element of the scalarized result. Insert a
1886 // bitcast of the first alloca before the user as required.
1887 AllocaInst *NewAI = NewElts[0];
1888 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1889 NewAI->moveBefore(BCI);
1896 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1897 /// and recursively continue updating all of its uses.
1898 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1899 SmallVector<AllocaInst*, 32> &NewElts) {
1900 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1901 if (BC->getOperand(0) != AI)
1904 // The bitcast references the original alloca. Replace its uses with
1905 // references to the first new element alloca.
1906 Instruction *Val = NewElts[0];
1907 if (Val->getType() != BC->getDestTy()) {
1908 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1911 BC->replaceAllUsesWith(Val);
1912 DeadInsts.push_back(BC);
1915 /// FindElementAndOffset - Return the index of the element containing Offset
1916 /// within the specified type, which must be either a struct or an array.
1917 /// Sets T to the type of the element and Offset to the offset within that
1918 /// element. IdxTy is set to the type of the index result to be used in a
1919 /// GEP instruction.
1920 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1921 const Type *&IdxTy) {
1923 if (const StructType *ST = dyn_cast<StructType>(T)) {
1924 const StructLayout *Layout = TD->getStructLayout(ST);
1925 Idx = Layout->getElementContainingOffset(Offset);
1926 T = ST->getContainedType(Idx);
1927 Offset -= Layout->getElementOffset(Idx);
1928 IdxTy = Type::getInt32Ty(T->getContext());
1931 const ArrayType *AT = cast<ArrayType>(T);
1932 T = AT->getElementType();
1933 uint64_t EltSize = TD->getTypeAllocSize(T);
1934 Idx = Offset / EltSize;
1935 Offset -= Idx * EltSize;
1936 IdxTy = Type::getInt64Ty(T->getContext());
1940 /// RewriteGEP - Check if this GEP instruction moves the pointer across
1941 /// elements of the alloca that are being split apart, and if so, rewrite
1942 /// the GEP to be relative to the new element.
1943 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1944 SmallVector<AllocaInst*, 32> &NewElts) {
1945 uint64_t OldOffset = Offset;
1946 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1947 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1948 &Indices[0], Indices.size());
1950 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1952 const Type *T = AI->getAllocatedType();
1954 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1955 if (GEPI->getOperand(0) == AI)
1956 OldIdx = ~0ULL; // Force the GEP to be rewritten.
1958 T = AI->getAllocatedType();
1959 uint64_t EltOffset = Offset;
1960 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1962 // If this GEP does not move the pointer across elements of the alloca
1963 // being split, then it does not needs to be rewritten.
1967 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1968 SmallVector<Value*, 8> NewArgs;
1969 NewArgs.push_back(Constant::getNullValue(i32Ty));
1970 while (EltOffset != 0) {
1971 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1972 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1974 Instruction *Val = NewElts[Idx];
1975 if (NewArgs.size() > 1) {
1976 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1977 NewArgs.end(), "", GEPI);
1978 Val->takeName(GEPI);
1980 if (Val->getType() != GEPI->getType())
1981 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1982 GEPI->replaceAllUsesWith(Val);
1983 DeadInsts.push_back(GEPI);
1986 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1987 /// Rewrite it to copy or set the elements of the scalarized memory.
1988 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1990 SmallVector<AllocaInst*, 32> &NewElts) {
1991 // If this is a memcpy/memmove, construct the other pointer as the
1992 // appropriate type. The "Other" pointer is the pointer that goes to memory
1993 // that doesn't have anything to do with the alloca that we are promoting. For
1994 // memset, this Value* stays null.
1995 Value *OtherPtr = 0;
1996 unsigned MemAlignment = MI->getAlignment();
1997 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1998 if (Inst == MTI->getRawDest())
1999 OtherPtr = MTI->getRawSource();
2001 assert(Inst == MTI->getRawSource());
2002 OtherPtr = MTI->getRawDest();
2006 // If there is an other pointer, we want to convert it to the same pointer
2007 // type as AI has, so we can GEP through it safely.
2009 unsigned AddrSpace =
2010 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2012 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2013 // optimization, but it's also required to detect the corner case where
2014 // both pointer operands are referencing the same memory, and where
2015 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2016 // function is only called for mem intrinsics that access the whole
2017 // aggregate, so non-zero GEPs are not an issue here.)
2018 OtherPtr = OtherPtr->stripPointerCasts();
2020 // Copying the alloca to itself is a no-op: just delete it.
2021 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2022 // This code will run twice for a no-op memcpy -- once for each operand.
2023 // Put only one reference to MI on the DeadInsts list.
2024 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
2025 E = DeadInsts.end(); I != E; ++I)
2026 if (*I == MI) return;
2027 DeadInsts.push_back(MI);
2031 // If the pointer is not the right type, insert a bitcast to the right
2034 PointerType::get(AI->getType()->getElementType(), AddrSpace);
2036 if (OtherPtr->getType() != NewTy)
2037 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2040 // Process each element of the aggregate.
2041 bool SROADest = MI->getRawDest() == Inst;
2043 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2045 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2046 // If this is a memcpy/memmove, emit a GEP of the other element address.
2047 Value *OtherElt = 0;
2048 unsigned OtherEltAlign = MemAlignment;
2051 Value *Idx[2] = { Zero,
2052 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2053 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
2054 OtherPtr->getName()+"."+Twine(i),
2057 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2058 const Type *OtherTy = OtherPtrTy->getElementType();
2059 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
2060 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
2062 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2063 EltOffset = TD->getTypeAllocSize(EltTy)*i;
2066 // The alignment of the other pointer is the guaranteed alignment of the
2067 // element, which is affected by both the known alignment of the whole
2068 // mem intrinsic and the alignment of the element. If the alignment of
2069 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2070 // known alignment is just 4 bytes.
2071 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2074 Value *EltPtr = NewElts[i];
2075 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2077 // If we got down to a scalar, insert a load or store as appropriate.
2078 if (EltTy->isSingleValueType()) {
2079 if (isa<MemTransferInst>(MI)) {
2081 // From Other to Alloca.
2082 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2083 new StoreInst(Elt, EltPtr, MI);
2085 // From Alloca to Other.
2086 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2087 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2091 assert(isa<MemSetInst>(MI));
2093 // If the stored element is zero (common case), just store a null
2096 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2098 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
2100 // If EltTy is a vector type, get the element type.
2101 const Type *ValTy = EltTy->getScalarType();
2103 // Construct an integer with the right value.
2104 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2105 APInt OneVal(EltSize, CI->getZExtValue());
2106 APInt TotalVal(OneVal);
2108 for (unsigned i = 0; 8*i < EltSize; ++i) {
2109 TotalVal = TotalVal.shl(8);
2113 // Convert the integer value to the appropriate type.
2114 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2115 if (ValTy->isPointerTy())
2116 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2117 else if (ValTy->isFloatingPointTy())
2118 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2119 assert(StoreVal->getType() == ValTy && "Type mismatch!");
2121 // If the requested value was a vector constant, create it.
2122 if (EltTy != ValTy) {
2123 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2124 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
2125 StoreVal = ConstantVector::get(Elts);
2128 new StoreInst(StoreVal, EltPtr, MI);
2131 // Otherwise, if we're storing a byte variable, use a memset call for
2135 unsigned EltSize = TD->getTypeAllocSize(EltTy);
2137 IRBuilder<> Builder(MI);
2139 // Finally, insert the meminst for this element.
2140 if (isa<MemSetInst>(MI)) {
2141 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2144 assert(isa<MemTransferInst>(MI));
2145 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2146 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
2148 if (isa<MemCpyInst>(MI))
2149 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2151 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2154 DeadInsts.push_back(MI);
2157 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2158 /// overwrites the entire allocation. Extract out the pieces of the stored
2159 /// integer and store them individually.
2160 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2161 SmallVector<AllocaInst*, 32> &NewElts){
2162 // Extract each element out of the integer according to its structure offset
2163 // and store the element value to the individual alloca.
2164 Value *SrcVal = SI->getOperand(0);
2165 const Type *AllocaEltTy = AI->getAllocatedType();
2166 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2168 IRBuilder<> Builder(SI);
2170 // Handle tail padding by extending the operand
2171 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2172 SrcVal = Builder.CreateZExt(SrcVal,
2173 IntegerType::get(SI->getContext(), AllocaSizeBits));
2175 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2178 // There are two forms here: AI could be an array or struct. Both cases
2179 // have different ways to compute the element offset.
2180 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2181 const StructLayout *Layout = TD->getStructLayout(EltSTy);
2183 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2184 // Get the number of bits to shift SrcVal to get the value.
2185 const Type *FieldTy = EltSTy->getElementType(i);
2186 uint64_t Shift = Layout->getElementOffsetInBits(i);
2188 if (TD->isBigEndian())
2189 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2191 Value *EltVal = SrcVal;
2193 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2194 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2197 // Truncate down to an integer of the right size.
2198 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2200 // Ignore zero sized fields like {}, they obviously contain no data.
2201 if (FieldSizeBits == 0) continue;
2203 if (FieldSizeBits != AllocaSizeBits)
2204 EltVal = Builder.CreateTrunc(EltVal,
2205 IntegerType::get(SI->getContext(), FieldSizeBits));
2206 Value *DestField = NewElts[i];
2207 if (EltVal->getType() == FieldTy) {
2208 // Storing to an integer field of this size, just do it.
2209 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2210 // Bitcast to the right element type (for fp/vector values).
2211 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2213 // Otherwise, bitcast the dest pointer (for aggregates).
2214 DestField = Builder.CreateBitCast(DestField,
2215 PointerType::getUnqual(EltVal->getType()));
2217 new StoreInst(EltVal, DestField, SI);
2221 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2222 const Type *ArrayEltTy = ATy->getElementType();
2223 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2224 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2228 if (TD->isBigEndian())
2229 Shift = AllocaSizeBits-ElementOffset;
2233 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2234 // Ignore zero sized fields like {}, they obviously contain no data.
2235 if (ElementSizeBits == 0) continue;
2237 Value *EltVal = SrcVal;
2239 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2240 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2243 // Truncate down to an integer of the right size.
2244 if (ElementSizeBits != AllocaSizeBits)
2245 EltVal = Builder.CreateTrunc(EltVal,
2246 IntegerType::get(SI->getContext(),
2248 Value *DestField = NewElts[i];
2249 if (EltVal->getType() == ArrayEltTy) {
2250 // Storing to an integer field of this size, just do it.
2251 } else if (ArrayEltTy->isFloatingPointTy() ||
2252 ArrayEltTy->isVectorTy()) {
2253 // Bitcast to the right element type (for fp/vector values).
2254 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2256 // Otherwise, bitcast the dest pointer (for aggregates).
2257 DestField = Builder.CreateBitCast(DestField,
2258 PointerType::getUnqual(EltVal->getType()));
2260 new StoreInst(EltVal, DestField, SI);
2262 if (TD->isBigEndian())
2263 Shift -= ElementOffset;
2265 Shift += ElementOffset;
2269 DeadInsts.push_back(SI);
2272 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2273 /// an integer. Load the individual pieces to form the aggregate value.
2274 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2275 SmallVector<AllocaInst*, 32> &NewElts) {
2276 // Extract each element out of the NewElts according to its structure offset
2277 // and form the result value.
2278 const Type *AllocaEltTy = AI->getAllocatedType();
2279 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2281 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2284 // There are two forms here: AI could be an array or struct. Both cases
2285 // have different ways to compute the element offset.
2286 const StructLayout *Layout = 0;
2287 uint64_t ArrayEltBitOffset = 0;
2288 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2289 Layout = TD->getStructLayout(EltSTy);
2291 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2292 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2296 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2298 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2299 // Load the value from the alloca. If the NewElt is an aggregate, cast
2300 // the pointer to an integer of the same size before doing the load.
2301 Value *SrcField = NewElts[i];
2302 const Type *FieldTy =
2303 cast<PointerType>(SrcField->getType())->getElementType();
2304 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2306 // Ignore zero sized fields like {}, they obviously contain no data.
2307 if (FieldSizeBits == 0) continue;
2309 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2311 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2312 !FieldTy->isVectorTy())
2313 SrcField = new BitCastInst(SrcField,
2314 PointerType::getUnqual(FieldIntTy),
2316 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2318 // If SrcField is a fp or vector of the right size but that isn't an
2319 // integer type, bitcast to an integer so we can shift it.
2320 if (SrcField->getType() != FieldIntTy)
2321 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2323 // Zero extend the field to be the same size as the final alloca so that
2324 // we can shift and insert it.
2325 if (SrcField->getType() != ResultVal->getType())
2326 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2328 // Determine the number of bits to shift SrcField.
2330 if (Layout) // Struct case.
2331 Shift = Layout->getElementOffsetInBits(i);
2333 Shift = i*ArrayEltBitOffset;
2335 if (TD->isBigEndian())
2336 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2339 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2340 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2343 // Don't create an 'or x, 0' on the first iteration.
2344 if (!isa<Constant>(ResultVal) ||
2345 !cast<Constant>(ResultVal)->isNullValue())
2346 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2348 ResultVal = SrcField;
2351 // Handle tail padding by truncating the result
2352 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2353 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2355 LI->replaceAllUsesWith(ResultVal);
2356 DeadInsts.push_back(LI);
2359 /// HasPadding - Return true if the specified type has any structure or
2360 /// alignment padding in between the elements that would be split apart
2361 /// by SROA; return false otherwise.
2362 static bool HasPadding(const Type *Ty, const TargetData &TD) {
2363 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2364 Ty = ATy->getElementType();
2365 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2368 // SROA currently handles only Arrays and Structs.
2369 const StructType *STy = cast<StructType>(Ty);
2370 const StructLayout *SL = TD.getStructLayout(STy);
2371 unsigned PrevFieldBitOffset = 0;
2372 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2373 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2375 // Check to see if there is any padding between this element and the
2378 unsigned PrevFieldEnd =
2379 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2380 if (PrevFieldEnd < FieldBitOffset)
2383 PrevFieldBitOffset = FieldBitOffset;
2385 // Check for tail padding.
2386 if (unsigned EltCount = STy->getNumElements()) {
2387 unsigned PrevFieldEnd = PrevFieldBitOffset +
2388 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2389 if (PrevFieldEnd < SL->getSizeInBits())
2395 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2396 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2397 /// or 1 if safe after canonicalization has been performed.
2398 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2399 // Loop over the use list of the alloca. We can only transform it if all of
2400 // the users are safe to transform.
2401 AllocaInfo Info(AI);
2403 isSafeForScalarRepl(AI, 0, Info);
2404 if (Info.isUnsafe) {
2405 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2409 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2410 // source and destination, we have to be careful. In particular, the memcpy
2411 // could be moving around elements that live in structure padding of the LLVM
2412 // types, but may actually be used. In these cases, we refuse to promote the
2414 if (Info.isMemCpySrc && Info.isMemCpyDst &&
2415 HasPadding(AI->getAllocatedType(), *TD))
2418 // If the alloca never has an access to just *part* of it, but is accessed
2419 // via loads and stores, then we should use ConvertToScalarInfo to promote
2420 // the alloca instead of promoting each piece at a time and inserting fission
2422 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2423 // If the struct/array just has one element, use basic SRoA.
2424 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2425 if (ST->getNumElements() > 1) return false;
2427 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2437 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2438 /// some part of a constant global variable. This intentionally only accepts
2439 /// constant expressions because we don't can't rewrite arbitrary instructions.
2440 static bool PointsToConstantGlobal(Value *V) {
2441 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2442 return GV->isConstant();
2443 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2444 if (CE->getOpcode() == Instruction::BitCast ||
2445 CE->getOpcode() == Instruction::GetElementPtr)
2446 return PointsToConstantGlobal(CE->getOperand(0));
2450 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2451 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
2452 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
2453 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
2454 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
2455 /// the alloca, and if the source pointer is a pointer to a constant global, we
2456 /// can optimize this.
2457 static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2459 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
2460 User *U = cast<Instruction>(*UI);
2462 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2463 // Ignore non-volatile loads, they are always ok.
2464 if (LI->isVolatile()) return false;
2468 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2469 // If uses of the bitcast are ok, we are ok.
2470 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2474 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2475 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2476 // doesn't, it does.
2477 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2478 isOffset || !GEP->hasAllZeroIndices()))
2483 if (CallSite CS = U) {
2484 // If this is a readonly/readnone call site, then we know it is just a
2485 // load and we can ignore it.
2486 if (CS.onlyReadsMemory())
2489 // If this is the function being called then we treat it like a load and
2491 if (CS.isCallee(UI))
2494 // If this is being passed as a byval argument, the caller is making a
2495 // copy, so it is only a read of the alloca.
2496 unsigned ArgNo = CS.getArgumentNo(UI);
2497 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2501 // If this is isn't our memcpy/memmove, reject it as something we can't
2503 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2507 // If the transfer is using the alloca as a source of the transfer, then
2508 // ignore it since it is a load (unless the transfer is volatile).
2509 if (UI.getOperandNo() == 1) {
2510 if (MI->isVolatile()) return false;
2514 // If we already have seen a copy, reject the second one.
2515 if (TheCopy) return false;
2517 // If the pointer has been offset from the start of the alloca, we can't
2518 // safely handle this.
2519 if (isOffset) return false;
2521 // If the memintrinsic isn't using the alloca as the dest, reject it.
2522 if (UI.getOperandNo() != 0) return false;
2524 // If the source of the memcpy/move is not a constant global, reject it.
2525 if (!PointsToConstantGlobal(MI->getSource()))
2528 // Otherwise, the transform is safe. Remember the copy instruction.
2534 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2535 /// modified by a copy from a constant global. If we can prove this, we can
2536 /// replace any uses of the alloca with uses of the global directly.
2537 MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2538 MemTransferInst *TheCopy = 0;
2539 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))