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 /// HadAVector - True if there is at least one access to the alloca that is
242 /// not a MemTransferInst. We don't want to turn structs into large integers
243 /// 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);
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 // If we already decided to turn this into a blob of integer memory, there is
320 // nothing to be done.
321 if (VectorTy && VectorTy->isVoidTy())
324 // If this could be contributing to a vector, analyze it.
326 // If the In type is a vector that is the same size as the alloca, see if it
327 // matches the existing VecTy.
328 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
329 if (MergeInVectorType(VInTy, Offset))
331 } else if (In->isFloatTy() || In->isDoubleTy() ||
332 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
333 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
334 // If we're accessing something that could be an element of a vector, see
335 // if the implied vector agrees with what we already have and if Offset is
336 // compatible with it.
337 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
338 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
340 cast<VectorType>(VectorTy)->getElementType()
341 ->getPrimitiveSizeInBits()/8 == EltSize)) {
343 VectorTy = VectorType::get(In, AllocaSize/EltSize);
348 // Otherwise, we have a case that we can't handle with an optimized vector
349 // form. We can still turn this into a large integer.
350 VectorTy = Type::getVoidTy(In->getContext());
353 /// MergeInVectorType - Handles the vector case of MergeInType, returning true
354 /// if the type was successfully merged and false otherwise.
355 bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy,
357 // Remember if we saw a vector type.
360 // TODO: Support nonzero offsets?
364 // Only allow vectors that are a power-of-2 away from the size of the alloca.
365 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8)))
368 // If this the first vector we see, remember the type so that we know the
375 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
376 unsigned InBitWidth = VInTy->getBitWidth();
378 // Vectors of the same size can be converted using a simple bitcast.
379 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8))
382 const Type *ElementTy = cast<VectorType>(VectorTy)->getElementType();
383 const Type *InElementTy = cast<VectorType>(VectorTy)->getElementType();
385 // Do not allow mixed integer and floating-point accesses from vectors of
387 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy())
390 if (ElementTy->isFloatingPointTy()) {
391 // Only allow floating-point vectors of different sizes if they have the
392 // same element type.
393 // TODO: This could be loosened a bit, but would anything benefit?
394 if (ElementTy != InElementTy)
397 // There are no arbitrary-precision floating-point types, which limits the
398 // number of legal vector types with larger element types that we can form
399 // to bitcast and extract a subvector.
400 // TODO: We could support some more cases with mixed fp128 and double here.
401 if (!(BitWidth == 64 || BitWidth == 128) ||
402 !(InBitWidth == 64 || InBitWidth == 128))
405 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer "
406 "or floating-point.");
407 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits();
408 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits();
410 // Do not allow integer types smaller than a byte or types whose widths are
411 // not a multiple of a byte.
412 if (BitWidth < 8 || InBitWidth < 8 ||
413 BitWidth % 8 != 0 || InBitWidth % 8 != 0)
417 // Pick the largest of the two vector types.
418 if (InBitWidth > BitWidth)
424 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
425 /// its accesses to a single vector type, return true and set VecTy to
426 /// the new type. If we could convert the alloca into a single promotable
427 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
428 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
429 /// is the current offset from the base of the alloca being analyzed.
431 /// If we see at least one access to the value that is as a vector type, set the
433 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
434 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
435 Instruction *User = cast<Instruction>(*UI);
437 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
438 // Don't break volatile loads.
439 if (LI->isVolatile())
441 // Don't touch MMX operations.
442 if (LI->getType()->isX86_MMXTy())
444 HadNonMemTransferAccess = true;
445 MergeInType(LI->getType(), Offset);
449 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
450 // Storing the pointer, not into the value?
451 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
452 // Don't touch MMX operations.
453 if (SI->getOperand(0)->getType()->isX86_MMXTy())
455 HadNonMemTransferAccess = true;
456 MergeInType(SI->getOperand(0)->getType(), Offset);
460 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
461 IsNotTrivial = true; // Can't be mem2reg'd.
462 if (!CanConvertToScalar(BCI, Offset))
467 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
468 // If this is a GEP with a variable indices, we can't handle it.
469 if (!GEP->hasAllConstantIndices())
472 // Compute the offset that this GEP adds to the pointer.
473 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
474 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
475 &Indices[0], Indices.size());
476 // See if all uses can be converted.
477 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
479 IsNotTrivial = true; // Can't be mem2reg'd.
480 HadNonMemTransferAccess = true;
484 // If this is a constant sized memset of a constant value (e.g. 0) we can
486 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
487 // Store of constant value and constant size.
488 if (!isa<ConstantInt>(MSI->getValue()) ||
489 !isa<ConstantInt>(MSI->getLength()))
491 IsNotTrivial = true; // Can't be mem2reg'd.
492 HadNonMemTransferAccess = true;
496 // If this is a memcpy or memmove into or out of the whole allocation, we
497 // can handle it like a load or store of the scalar type.
498 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
499 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
500 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0)
503 IsNotTrivial = true; // Can't be mem2reg'd.
507 // Otherwise, we cannot handle this!
514 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
515 /// directly. This happens when we are converting an "integer union" to a
516 /// single integer scalar, or when we are converting a "vector union" to a
517 /// vector with insert/extractelement instructions.
519 /// Offset is an offset from the original alloca, in bits that need to be
520 /// shifted to the right. By the end of this, there should be no uses of Ptr.
521 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
523 while (!Ptr->use_empty()) {
524 Instruction *User = cast<Instruction>(Ptr->use_back());
526 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
527 ConvertUsesToScalar(CI, NewAI, Offset);
528 CI->eraseFromParent();
532 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
533 // Compute the offset that this GEP adds to the pointer.
534 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
535 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
536 &Indices[0], Indices.size());
537 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
538 GEP->eraseFromParent();
542 IRBuilder<> Builder(User);
544 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
545 // The load is a bit extract from NewAI shifted right by Offset bits.
546 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
548 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
549 LI->replaceAllUsesWith(NewLoadVal);
550 LI->eraseFromParent();
554 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
555 assert(SI->getOperand(0) != Ptr && "Consistency error!");
556 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
557 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
559 Builder.CreateStore(New, NewAI);
560 SI->eraseFromParent();
562 // If the load we just inserted is now dead, then the inserted store
563 // overwrote the entire thing.
564 if (Old->use_empty())
565 Old->eraseFromParent();
569 // If this is a constant sized memset of a constant value (e.g. 0) we can
570 // transform it into a store of the expanded constant value.
571 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
572 assert(MSI->getRawDest() == Ptr && "Consistency error!");
573 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
575 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
577 // Compute the value replicated the right number of times.
578 APInt APVal(NumBytes*8, Val);
580 // Splat the value if non-zero.
582 for (unsigned i = 1; i != NumBytes; ++i)
585 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
586 Value *New = ConvertScalar_InsertValue(
587 ConstantInt::get(User->getContext(), APVal),
588 Old, Offset, Builder);
589 Builder.CreateStore(New, NewAI);
591 // If the load we just inserted is now dead, then the memset overwrote
593 if (Old->use_empty())
594 Old->eraseFromParent();
596 MSI->eraseFromParent();
600 // If this is a memcpy or memmove into or out of the whole allocation, we
601 // can handle it like a load or store of the scalar type.
602 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
603 assert(Offset == 0 && "must be store to start of alloca");
605 // If the source and destination are both to the same alloca, then this is
606 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
608 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0));
610 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) {
611 // Dest must be OrigAI, change this to be a load from the original
612 // pointer (bitcasted), then a store to our new alloca.
613 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
614 Value *SrcPtr = MTI->getSource();
615 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
616 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
617 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
618 AIPTy = PointerType::get(AIPTy->getElementType(),
619 SPTy->getAddressSpace());
621 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
623 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
624 SrcVal->setAlignment(MTI->getAlignment());
625 Builder.CreateStore(SrcVal, NewAI);
626 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) {
627 // Src must be OrigAI, change this to be a load from NewAI then a store
628 // through the original dest pointer (bitcasted).
629 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
630 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
632 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
633 const PointerType* AIPTy = cast<PointerType>(NewAI->getType());
634 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
635 AIPTy = PointerType::get(AIPTy->getElementType(),
636 DPTy->getAddressSpace());
638 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
640 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
641 NewStore->setAlignment(MTI->getAlignment());
643 // Noop transfer. Src == Dst
646 MTI->eraseFromParent();
650 llvm_unreachable("Unsupported operation!");
654 /// getScaledElementType - Gets a scaled element type for a partial vector
655 /// access of an alloca. The input type must be an integer or float, and
656 /// the resulting type must be an integer, float or double.
657 static const Type *getScaledElementType(const Type *OldTy, unsigned Scale) {
658 assert((OldTy->isIntegerTy() || OldTy->isFloatTy()) && "Partial vector "
659 "accesses must be scaled from integer or float elements.");
661 LLVMContext &Context = OldTy->getContext();
662 unsigned Size = OldTy->getPrimitiveSizeInBits() * Scale;
664 if (OldTy->isIntegerTy())
665 return Type::getIntNTy(Context, Size);
667 return Type::getFloatTy(Context);
669 return Type::getDoubleTy(Context);
671 llvm_unreachable("Invalid type for a partial vector access of an alloca!");
674 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
675 /// or vector value FromVal, extracting the bits from the offset specified by
676 /// Offset. This returns the value, which is of type ToType.
678 /// This happens when we are converting an "integer union" to a single
679 /// integer scalar, or when we are converting a "vector union" to a vector with
680 /// insert/extractelement instructions.
682 /// Offset is an offset from the original alloca, in bits that need to be
683 /// shifted to the right.
684 Value *ConvertToScalarInfo::
685 ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
686 uint64_t Offset, IRBuilder<> &Builder) {
687 // If the load is of the whole new alloca, no conversion is needed.
688 if (FromVal->getType() == ToType && Offset == 0)
691 // If the result alloca is a vector type, this is either an element
692 // access or a bitcast to another vector type of the same size.
693 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
694 if (ToType->isVectorTy()) {
695 unsigned ToTypeSize = TD.getTypeAllocSize(ToType);
696 if (ToTypeSize == AllocaSize)
697 return Builder.CreateBitCast(FromVal, ToType, "tmp");
699 assert(isPowerOf2_64(AllocaSize / ToTypeSize) &&
700 "Partial vector access of an alloca must have a power-of-2 size "
702 assert(Offset == 0 && "Can't extract a value of a smaller vector type "
703 "from a nonzero offset.");
705 const Type *ToElementTy = cast<VectorType>(ToType)->getElementType();
706 unsigned Scale = AllocaSize / ToTypeSize;
707 const Type *CastElementTy = getScaledElementType(ToElementTy, Scale);
708 unsigned NumCastVectorElements = VTy->getNumElements() / Scale;
710 LLVMContext &Context = FromVal->getContext();
711 const Type *CastTy = VectorType::get(CastElementTy,
712 NumCastVectorElements);
713 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp");
714 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get(
715 Type::getInt32Ty(Context), 0), "tmp");
716 return Builder.CreateBitCast(Extract, ToType, "tmp");
719 // Otherwise it must be an element access.
722 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
723 Elt = Offset/EltSize;
724 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
726 // Return the element extracted out of it.
727 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
728 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
729 if (V->getType() != ToType)
730 V = Builder.CreateBitCast(V, ToType, "tmp");
734 // If ToType is a first class aggregate, extract out each of the pieces and
735 // use insertvalue's to form the FCA.
736 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
737 const StructLayout &Layout = *TD.getStructLayout(ST);
738 Value *Res = UndefValue::get(ST);
739 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
740 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
741 Offset+Layout.getElementOffsetInBits(i),
743 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
748 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
749 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
750 Value *Res = UndefValue::get(AT);
751 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
752 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
753 Offset+i*EltSize, Builder);
754 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
759 // Otherwise, this must be a union that was converted to an integer value.
760 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
762 // If this is a big-endian system and the load is narrower than the
763 // full alloca type, we need to do a shift to get the right bits.
765 if (TD.isBigEndian()) {
766 // On big-endian machines, the lowest bit is stored at the bit offset
767 // from the pointer given by getTypeStoreSizeInBits. This matters for
768 // integers with a bitwidth that is not a multiple of 8.
769 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
770 TD.getTypeStoreSizeInBits(ToType) - Offset;
775 // Note: we support negative bitwidths (with shl) which are not defined.
776 // We do this to support (f.e.) loads off the end of a structure where
777 // only some bits are used.
778 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
779 FromVal = Builder.CreateLShr(FromVal,
780 ConstantInt::get(FromVal->getType(),
782 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
783 FromVal = Builder.CreateShl(FromVal,
784 ConstantInt::get(FromVal->getType(),
787 // Finally, unconditionally truncate the integer to the right width.
788 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
789 if (LIBitWidth < NTy->getBitWidth())
791 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
793 else if (LIBitWidth > NTy->getBitWidth())
795 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
798 // If the result is an integer, this is a trunc or bitcast.
799 if (ToType->isIntegerTy()) {
801 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
802 // Just do a bitcast, we know the sizes match up.
803 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
805 // Otherwise must be a pointer.
806 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
808 assert(FromVal->getType() == ToType && "Didn't convert right?");
812 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
813 /// or vector value "Old" at the offset specified by Offset.
815 /// This happens when we are converting an "integer union" to a
816 /// single integer scalar, or when we are converting a "vector union" to a
817 /// vector with insert/extractelement instructions.
819 /// Offset is an offset from the original alloca, in bits that need to be
820 /// shifted to the right.
821 Value *ConvertToScalarInfo::
822 ConvertScalar_InsertValue(Value *SV, Value *Old,
823 uint64_t Offset, IRBuilder<> &Builder) {
824 // Convert the stored type to the actual type, shift it left to insert
825 // then 'or' into place.
826 const Type *AllocaType = Old->getType();
827 LLVMContext &Context = Old->getContext();
829 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
830 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
831 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
833 // Changing the whole vector with memset or with an access of a different
835 if (ValSize == VecSize)
836 return Builder.CreateBitCast(SV, AllocaType, "tmp");
838 if (SV->getType()->isVectorTy() && isPowerOf2_64(VecSize / ValSize)) {
839 assert(Offset == 0 && "Can't insert a value of a smaller vector type at "
840 "a nonzero offset.");
842 const Type *ToElementTy =
843 cast<VectorType>(SV->getType())->getElementType();
844 unsigned Scale = VecSize / ValSize;
845 const Type *CastElementTy = getScaledElementType(ToElementTy, Scale);
846 unsigned NumCastVectorElements = VTy->getNumElements() / Scale;
848 LLVMContext &Context = SV->getContext();
849 const Type *OldCastTy = VectorType::get(CastElementTy,
850 NumCastVectorElements);
851 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp");
853 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp");
855 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get(
856 Type::getInt32Ty(Context), 0), "tmp");
857 return Builder.CreateBitCast(Insert, AllocaType, "tmp");
860 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
862 // Must be an element insertion.
863 unsigned Elt = Offset/EltSize;
865 if (SV->getType() != VTy->getElementType())
866 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
868 SV = Builder.CreateInsertElement(Old, SV,
869 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
874 // If SV is a first-class aggregate value, insert each value recursively.
875 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
876 const StructLayout &Layout = *TD.getStructLayout(ST);
877 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
878 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
879 Old = ConvertScalar_InsertValue(Elt, Old,
880 Offset+Layout.getElementOffsetInBits(i),
886 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
887 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
888 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
889 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
890 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
895 // If SV is a float, convert it to the appropriate integer type.
896 // If it is a pointer, do the same.
897 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
898 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
899 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
900 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
901 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
902 SV = Builder.CreateBitCast(SV,
903 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
904 else if (SV->getType()->isPointerTy())
905 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
907 // Zero extend or truncate the value if needed.
908 if (SV->getType() != AllocaType) {
909 if (SV->getType()->getPrimitiveSizeInBits() <
910 AllocaType->getPrimitiveSizeInBits())
911 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
913 // Truncation may be needed if storing more than the alloca can hold
914 // (undefined behavior).
915 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
916 SrcWidth = DestWidth;
917 SrcStoreWidth = DestStoreWidth;
921 // If this is a big-endian system and the store is narrower than the
922 // full alloca type, we need to do a shift to get the right bits.
924 if (TD.isBigEndian()) {
925 // On big-endian machines, the lowest bit is stored at the bit offset
926 // from the pointer given by getTypeStoreSizeInBits. This matters for
927 // integers with a bitwidth that is not a multiple of 8.
928 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
933 // Note: we support negative bitwidths (with shr) which are not defined.
934 // We do this to support (f.e.) stores off the end of a structure where
935 // only some bits in the structure are set.
936 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
937 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
938 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
941 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
942 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
944 Mask = Mask.lshr(-ShAmt);
947 // Mask out the bits we are about to insert from the old value, and or
949 if (SrcWidth != DestWidth) {
950 assert(DestWidth > SrcWidth);
951 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
952 SV = Builder.CreateOr(Old, SV, "ins");
958 //===----------------------------------------------------------------------===//
960 //===----------------------------------------------------------------------===//
963 bool SROA::runOnFunction(Function &F) {
964 TD = getAnalysisIfAvailable<TargetData>();
966 bool Changed = performPromotion(F);
968 // FIXME: ScalarRepl currently depends on TargetData more than it
969 // theoretically needs to. It should be refactored in order to support
970 // target-independent IR. Until this is done, just skip the actual
971 // scalar-replacement portion of this pass.
972 if (!TD) return Changed;
975 bool LocalChange = performScalarRepl(F);
976 if (!LocalChange) break; // No need to repromote if no scalarrepl
978 LocalChange = performPromotion(F);
979 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
986 class AllocaPromoter : public LoadAndStorePromoter {
989 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S)
990 : LoadAndStorePromoter(Insts, S), AI(0) {}
992 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
993 // Remember which alloca we're promoting (for isInstInList).
995 LoadAndStorePromoter::run(Insts);
996 AI->eraseFromParent();
999 virtual bool isInstInList(Instruction *I,
1000 const SmallVectorImpl<Instruction*> &Insts) const {
1001 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1002 return LI->getOperand(0) == AI;
1003 return cast<StoreInst>(I)->getPointerOperand() == AI;
1006 } // end anon namespace
1008 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1009 /// subsequently loaded can be rewritten to load both input pointers and then
1010 /// select between the result, allowing the load of the alloca to be promoted.
1012 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1013 /// %V = load i32* %P2
1015 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1016 /// %V2 = load i32* %Other
1017 /// %V = select i1 %cond, i32 %V1, i32 %V2
1019 /// We can do this to a select if its only uses are loads and if the operand to
1020 /// the select can be loaded unconditionally.
1021 static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) {
1022 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer();
1023 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer();
1025 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
1027 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1028 if (LI == 0 || LI->isVolatile()) return false;
1030 // Both operands to the select need to be dereferencable, either absolutely
1031 // (e.g. allocas) or at this point because we can see other accesses to it.
1032 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1033 LI->getAlignment(), TD))
1035 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1036 LI->getAlignment(), TD))
1043 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1044 /// subsequently loaded can be rewritten to load both input pointers in the pred
1045 /// blocks and then PHI the results, allowing the load of the alloca to be
1048 /// %P2 = phi [i32* %Alloca, i32* %Other]
1049 /// %V = load i32* %P2
1051 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1053 /// %V2 = load i32* %Other
1055 /// %V = phi [i32 %V1, i32 %V2]
1057 /// We can do this to a select if its only uses are loads and if the operand to
1058 /// the select can be loaded unconditionally.
1059 static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) {
1060 // For now, we can only do this promotion if the load is in the same block as
1061 // the PHI, and if there are no stores between the phi and load.
1062 // TODO: Allow recursive phi users.
1063 // TODO: Allow stores.
1064 BasicBlock *BB = PN->getParent();
1065 unsigned MaxAlign = 0;
1066 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1068 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1069 if (LI == 0 || LI->isVolatile()) return false;
1071 // For now we only allow loads in the same block as the PHI. This is a
1072 // common case that happens when instcombine merges two loads through a PHI.
1073 if (LI->getParent() != BB) return false;
1075 // Ensure that there are no instructions between the PHI and the load that
1077 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1078 if (BBI->mayWriteToMemory())
1081 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1084 // Okay, we know that we have one or more loads in the same block as the PHI.
1085 // We can transform this if it is safe to push the loads into the predecessor
1086 // blocks. The only thing to watch out for is that we can't put a possibly
1087 // trapping load in the predecessor if it is a critical edge.
1088 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1089 BasicBlock *Pred = PN->getIncomingBlock(i);
1091 // If the predecessor has a single successor, then the edge isn't critical.
1092 if (Pred->getTerminator()->getNumSuccessors() == 1)
1095 Value *InVal = PN->getIncomingValue(i);
1097 // If the InVal is an invoke in the pred, we can't put a load on the edge.
1098 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
1099 if (II->getParent() == Pred)
1102 // If this pointer is always safe to load, or if we can prove that there is
1103 // already a load in the block, then we can move the load to the pred block.
1104 if (InVal->isDereferenceablePointer() ||
1105 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD))
1115 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1116 /// direct (non-volatile) loads and stores to it. If the alloca is close but
1117 /// not quite there, this will transform the code to allow promotion. As such,
1118 /// it is a non-pure predicate.
1119 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) {
1120 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1121 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1123 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
1126 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1127 if (LI->isVolatile())
1132 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1133 if (SI->getOperand(0) == AI || SI->isVolatile())
1134 return false; // Don't allow a store OF the AI, only INTO the AI.
1138 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1139 // If the condition being selected on is a constant, fold the select, yes
1140 // this does (rarely) happen early on.
1141 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1142 Value *Result = SI->getOperand(1+CI->isZero());
1143 SI->replaceAllUsesWith(Result);
1144 SI->eraseFromParent();
1146 // This is very rare and we just scrambled the use list of AI, start
1148 return tryToMakeAllocaBePromotable(AI, TD);
1151 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1152 // loads, then we can transform this by rewriting the select.
1153 if (!isSafeSelectToSpeculate(SI, TD))
1156 InstsToRewrite.insert(SI);
1160 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1161 if (PN->use_empty()) { // Dead PHIs can be stripped.
1162 InstsToRewrite.insert(PN);
1166 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1167 // in the pred blocks, then we can transform this by rewriting the PHI.
1168 if (!isSafePHIToSpeculate(PN, TD))
1171 InstsToRewrite.insert(PN);
1178 // If there are no instructions to rewrite, then all uses are load/stores and
1180 if (InstsToRewrite.empty())
1183 // If we have instructions that need to be rewritten for this to be promotable
1184 // take care of it now.
1185 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1186 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1187 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1188 // loads with a new select.
1189 while (!SI->use_empty()) {
1190 LoadInst *LI = cast<LoadInst>(SI->use_back());
1192 IRBuilder<> Builder(LI);
1193 LoadInst *TrueLoad =
1194 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1195 LoadInst *FalseLoad =
1196 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t");
1198 // Transfer alignment and TBAA info if present.
1199 TrueLoad->setAlignment(LI->getAlignment());
1200 FalseLoad->setAlignment(LI->getAlignment());
1201 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1202 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1203 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1206 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1208 LI->replaceAllUsesWith(V);
1209 LI->eraseFromParent();
1212 // Now that all the loads are gone, the select is gone too.
1213 SI->eraseFromParent();
1217 // Otherwise, we have a PHI node which allows us to push the loads into the
1219 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1220 if (PN->use_empty()) {
1221 PN->eraseFromParent();
1225 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1226 PHINode *NewPN = PHINode::Create(LoadTy, PN->getName()+".ld", PN);
1228 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1229 // matter which one we get and if any differ, it doesn't matter.
1230 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back());
1231 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1232 unsigned Align = SomeLoad->getAlignment();
1234 // Rewrite all loads of the PN to use the new PHI.
1235 while (!PN->use_empty()) {
1236 LoadInst *LI = cast<LoadInst>(PN->use_back());
1237 LI->replaceAllUsesWith(NewPN);
1238 LI->eraseFromParent();
1241 // Inject loads into all of the pred blocks. Keep track of which blocks we
1242 // insert them into in case we have multiple edges from the same block.
1243 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1245 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1246 BasicBlock *Pred = PN->getIncomingBlock(i);
1247 LoadInst *&Load = InsertedLoads[Pred];
1249 Load = new LoadInst(PN->getIncomingValue(i),
1250 PN->getName() + "." + Pred->getName(),
1251 Pred->getTerminator());
1252 Load->setAlignment(Align);
1253 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1256 NewPN->addIncoming(Load, Pred);
1259 PN->eraseFromParent();
1267 bool SROA::performPromotion(Function &F) {
1268 std::vector<AllocaInst*> Allocas;
1269 DominatorTree *DT = 0;
1271 DT = &getAnalysis<DominatorTree>();
1273 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
1275 bool Changed = false;
1276 SmallVector<Instruction*, 64> Insts;
1280 // Find allocas that are safe to promote, by looking at all instructions in
1282 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1283 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
1284 if (tryToMakeAllocaBePromotable(AI, TD))
1285 Allocas.push_back(AI);
1287 if (Allocas.empty()) break;
1290 PromoteMemToReg(Allocas, *DT);
1293 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1294 AllocaInst *AI = Allocas[i];
1296 // Build list of instructions to promote.
1297 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1299 Insts.push_back(cast<Instruction>(*UI));
1301 AllocaPromoter(Insts, SSA).run(AI, Insts);
1305 NumPromoted += Allocas.size();
1313 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1314 /// SROA. It must be a struct or array type with a small number of elements.
1315 static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
1316 const Type *T = AI->getAllocatedType();
1317 // Do not promote any struct into more than 32 separate vars.
1318 if (const StructType *ST = dyn_cast<StructType>(T))
1319 return ST->getNumElements() <= 32;
1320 // Arrays are much less likely to be safe for SROA; only consider
1321 // them if they are very small.
1322 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1323 return AT->getNumElements() <= 8;
1328 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
1329 // which runs on all of the malloc/alloca instructions in the function, removing
1330 // them if they are only used by getelementptr instructions.
1332 bool SROA::performScalarRepl(Function &F) {
1333 std::vector<AllocaInst*> WorkList;
1335 // Scan the entry basic block, adding allocas to the worklist.
1336 BasicBlock &BB = F.getEntryBlock();
1337 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1338 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1339 WorkList.push_back(A);
1341 // Process the worklist
1342 bool Changed = false;
1343 while (!WorkList.empty()) {
1344 AllocaInst *AI = WorkList.back();
1345 WorkList.pop_back();
1347 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1348 // with unused elements.
1349 if (AI->use_empty()) {
1350 AI->eraseFromParent();
1355 // If this alloca is impossible for us to promote, reject it early.
1356 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1359 // Check to see if this allocation is only modified by a memcpy/memmove from
1360 // a constant global. If this is the case, we can change all users to use
1361 // the constant global instead. This is commonly produced by the CFE by
1362 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
1363 // is only subsequently read.
1364 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
1365 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
1366 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
1367 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
1368 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
1369 TheCopy->eraseFromParent(); // Don't mutate the global.
1370 AI->eraseFromParent();
1376 // Check to see if we can perform the core SROA transformation. We cannot
1377 // transform the allocation instruction if it is an array allocation
1378 // (allocations OF arrays are ok though), and an allocation of a scalar
1379 // value cannot be decomposed at all.
1380 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
1382 // Do not promote [0 x %struct].
1383 if (AllocaSize == 0) continue;
1385 // Do not promote any struct whose size is too big.
1386 if (AllocaSize > SRThreshold) continue;
1388 // If the alloca looks like a good candidate for scalar replacement, and if
1389 // all its users can be transformed, then split up the aggregate into its
1390 // separate elements.
1391 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1392 DoScalarReplacement(AI, WorkList);
1397 // If we can turn this aggregate value (potentially with casts) into a
1398 // simple scalar value that can be mem2reg'd into a register value.
1399 // IsNotTrivial tracks whether this is something that mem2reg could have
1400 // promoted itself. If so, we don't want to transform it needlessly. Note
1401 // that we can't just check based on the type: the alloca may be of an i32
1402 // but that has pointer arithmetic to set byte 3 of it or something.
1403 if (AllocaInst *NewAI =
1404 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
1405 NewAI->takeName(AI);
1406 AI->eraseFromParent();
1412 // Otherwise, couldn't process this alloca.
1418 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1419 /// predicate, do SROA now.
1420 void SROA::DoScalarReplacement(AllocaInst *AI,
1421 std::vector<AllocaInst*> &WorkList) {
1422 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1423 SmallVector<AllocaInst*, 32> ElementAllocas;
1424 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1425 ElementAllocas.reserve(ST->getNumContainedTypes());
1426 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1427 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
1429 AI->getName() + "." + Twine(i), AI);
1430 ElementAllocas.push_back(NA);
1431 WorkList.push_back(NA); // Add to worklist for recursive processing
1434 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1435 ElementAllocas.reserve(AT->getNumElements());
1436 const Type *ElTy = AT->getElementType();
1437 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1438 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
1439 AI->getName() + "." + Twine(i), AI);
1440 ElementAllocas.push_back(NA);
1441 WorkList.push_back(NA); // Add to worklist for recursive processing
1445 // Now that we have created the new alloca instructions, rewrite all the
1446 // uses of the old alloca.
1447 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1449 // Now erase any instructions that were made dead while rewriting the alloca.
1450 DeleteDeadInstructions();
1451 AI->eraseFromParent();
1456 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1457 /// recursively including all their operands that become trivially dead.
1458 void SROA::DeleteDeadInstructions() {
1459 while (!DeadInsts.empty()) {
1460 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1462 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1463 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1464 // Zero out the operand and see if it becomes trivially dead.
1465 // (But, don't add allocas to the dead instruction list -- they are
1466 // already on the worklist and will be deleted separately.)
1468 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1469 DeadInsts.push_back(U);
1472 I->eraseFromParent();
1476 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1477 /// performing scalar replacement of alloca AI. The results are flagged in
1478 /// the Info parameter. Offset indicates the position within AI that is
1479 /// referenced by this instruction.
1480 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1482 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1483 Instruction *User = cast<Instruction>(*UI);
1485 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1486 isSafeForScalarRepl(BC, Offset, Info);
1487 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1488 uint64_t GEPOffset = Offset;
1489 isSafeGEP(GEPI, GEPOffset, Info);
1491 isSafeForScalarRepl(GEPI, GEPOffset, Info);
1492 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1493 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1495 return MarkUnsafe(Info, User);
1496 isSafeMemAccess(Offset, Length->getZExtValue(), 0,
1497 UI.getOperandNo() == 0, Info, MI,
1498 true /*AllowWholeAccess*/);
1499 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1500 if (LI->isVolatile())
1501 return MarkUnsafe(Info, User);
1502 const Type *LIType = LI->getType();
1503 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1504 LIType, false, Info, LI, true /*AllowWholeAccess*/);
1505 Info.hasALoadOrStore = true;
1507 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1508 // Store is ok if storing INTO the pointer, not storing the pointer
1509 if (SI->isVolatile() || SI->getOperand(0) == I)
1510 return MarkUnsafe(Info, User);
1512 const Type *SIType = SI->getOperand(0)->getType();
1513 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1514 SIType, true, Info, SI, true /*AllowWholeAccess*/);
1515 Info.hasALoadOrStore = true;
1516 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1517 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1519 return MarkUnsafe(Info, User);
1521 if (Info.isUnsafe) return;
1526 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1527 /// derived from the alloca, we can often still split the alloca into elements.
1528 /// This is useful if we have a large alloca where one element is phi'd
1529 /// together somewhere: we can SRoA and promote all the other elements even if
1530 /// we end up not being able to promote this one.
1532 /// All we require is that the uses of the PHI do not index into other parts of
1533 /// the alloca. The most important use case for this is single load and stores
1534 /// that are PHI'd together, which can happen due to code sinking.
1535 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1537 // If we've already checked this PHI, don't do it again.
1538 if (PHINode *PN = dyn_cast<PHINode>(I))
1539 if (!Info.CheckedPHIs.insert(PN))
1542 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
1543 Instruction *User = cast<Instruction>(*UI);
1545 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1546 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1547 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1548 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1549 // but would have to prove that we're staying inside of an element being
1551 if (!GEPI->hasAllZeroIndices())
1552 return MarkUnsafe(Info, User);
1553 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1554 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1555 if (LI->isVolatile())
1556 return MarkUnsafe(Info, User);
1557 const Type *LIType = LI->getType();
1558 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType),
1559 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1560 Info.hasALoadOrStore = true;
1562 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1563 // Store is ok if storing INTO the pointer, not storing the pointer
1564 if (SI->isVolatile() || SI->getOperand(0) == I)
1565 return MarkUnsafe(Info, User);
1567 const Type *SIType = SI->getOperand(0)->getType();
1568 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType),
1569 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1570 Info.hasALoadOrStore = true;
1571 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1572 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1574 return MarkUnsafe(Info, User);
1576 if (Info.isUnsafe) return;
1580 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1581 /// replacement. It is safe when all the indices are constant, in-bounds
1582 /// references, and when the resulting offset corresponds to an element within
1583 /// the alloca type. The results are flagged in the Info parameter. Upon
1584 /// return, Offset is adjusted as specified by the GEP indices.
1585 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1586 uint64_t &Offset, AllocaInfo &Info) {
1587 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1591 // Walk through the GEP type indices, checking the types that this indexes
1593 for (; GEPIt != E; ++GEPIt) {
1594 // Ignore struct elements, no extra checking needed for these.
1595 if ((*GEPIt)->isStructTy())
1598 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1600 return MarkUnsafe(Info, GEPI);
1603 // Compute the offset due to this GEP and check if the alloca has a
1604 // component element at that offset.
1605 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1606 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1607 &Indices[0], Indices.size());
1608 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0))
1609 MarkUnsafe(Info, GEPI);
1612 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1613 /// elements of the same type (which is always true for arrays). If so,
1614 /// return true with NumElts and EltTy set to the number of elements and the
1615 /// element type, respectively.
1616 static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts,
1617 const Type *&EltTy) {
1618 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1619 NumElts = AT->getNumElements();
1620 EltTy = (NumElts == 0 ? 0 : AT->getElementType());
1623 if (const StructType *ST = dyn_cast<StructType>(T)) {
1624 NumElts = ST->getNumContainedTypes();
1625 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0));
1626 for (unsigned n = 1; n < NumElts; ++n) {
1627 if (ST->getContainedType(n) != EltTy)
1635 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1636 /// "homogeneous" aggregates with the same element type and number of elements.
1637 static bool isCompatibleAggregate(const Type *T1, const Type *T2) {
1641 unsigned NumElts1, NumElts2;
1642 const Type *EltTy1, *EltTy2;
1643 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1644 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1645 NumElts1 == NumElts2 &&
1652 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1653 /// alloca or has an offset and size that corresponds to a component element
1654 /// within it. The offset checked here may have been formed from a GEP with a
1655 /// pointer bitcasted to a different type.
1657 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1658 /// unit. If false, it only allows accesses known to be in a single element.
1659 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1660 const Type *MemOpType, bool isStore,
1661 AllocaInfo &Info, Instruction *TheAccess,
1662 bool AllowWholeAccess) {
1663 // Check if this is a load/store of the entire alloca.
1664 if (Offset == 0 && AllowWholeAccess &&
1665 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) {
1666 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1667 // loads/stores (which are essentially the same as the MemIntrinsics with
1668 // regard to copying padding between elements). But, if an alloca is
1669 // flagged as both a source and destination of such operations, we'll need
1670 // to check later for padding between elements.
1671 if (!MemOpType || MemOpType->isIntegerTy()) {
1673 Info.isMemCpyDst = true;
1675 Info.isMemCpySrc = true;
1678 // This is also safe for references using a type that is compatible with
1679 // the type of the alloca, so that loads/stores can be rewritten using
1680 // insertvalue/extractvalue.
1681 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1682 Info.hasSubelementAccess = true;
1686 // Check if the offset/size correspond to a component within the alloca type.
1687 const Type *T = Info.AI->getAllocatedType();
1688 if (TypeHasComponent(T, Offset, MemSize)) {
1689 Info.hasSubelementAccess = true;
1693 return MarkUnsafe(Info, TheAccess);
1696 /// TypeHasComponent - Return true if T has a component type with the
1697 /// specified offset and size. If Size is zero, do not check the size.
1698 bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
1701 if (const StructType *ST = dyn_cast<StructType>(T)) {
1702 const StructLayout *Layout = TD->getStructLayout(ST);
1703 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1704 EltTy = ST->getContainedType(EltIdx);
1705 EltSize = TD->getTypeAllocSize(EltTy);
1706 Offset -= Layout->getElementOffset(EltIdx);
1707 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
1708 EltTy = AT->getElementType();
1709 EltSize = TD->getTypeAllocSize(EltTy);
1710 if (Offset >= AT->getNumElements() * EltSize)
1716 if (Offset == 0 && (Size == 0 || EltSize == Size))
1718 // Check if the component spans multiple elements.
1719 if (Offset + Size > EltSize)
1721 return TypeHasComponent(EltTy, Offset, Size);
1724 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1725 /// the instruction I, which references it, to use the separate elements.
1726 /// Offset indicates the position within AI that is referenced by this
1728 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1729 SmallVector<AllocaInst*, 32> &NewElts) {
1730 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1731 Use &TheUse = UI.getUse();
1732 Instruction *User = cast<Instruction>(*UI++);
1734 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1735 RewriteBitCast(BC, AI, Offset, NewElts);
1739 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1740 RewriteGEP(GEPI, AI, Offset, NewElts);
1744 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1745 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1746 uint64_t MemSize = Length->getZExtValue();
1748 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
1749 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1750 // Otherwise the intrinsic can only touch a single element and the
1751 // address operand will be updated, so nothing else needs to be done.
1755 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1756 const Type *LIType = LI->getType();
1758 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1760 // %res = load { i32, i32 }* %alloc
1762 // %load.0 = load i32* %alloc.0
1763 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1764 // %load.1 = load i32* %alloc.1
1765 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1766 // (Also works for arrays instead of structs)
1767 Value *Insert = UndefValue::get(LIType);
1768 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1769 Value *Load = new LoadInst(NewElts[i], "load", LI);
1770 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
1772 LI->replaceAllUsesWith(Insert);
1773 DeadInsts.push_back(LI);
1774 } else if (LIType->isIntegerTy() &&
1775 TD->getTypeAllocSize(LIType) ==
1776 TD->getTypeAllocSize(AI->getAllocatedType())) {
1777 // If this is a load of the entire alloca to an integer, rewrite it.
1778 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1783 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1784 Value *Val = SI->getOperand(0);
1785 const Type *SIType = Val->getType();
1786 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1788 // store { i32, i32 } %val, { i32, i32 }* %alloc
1790 // %val.0 = extractvalue { i32, i32 } %val, 0
1791 // store i32 %val.0, i32* %alloc.0
1792 // %val.1 = extractvalue { i32, i32 } %val, 1
1793 // store i32 %val.1, i32* %alloc.1
1794 // (Also works for arrays instead of structs)
1795 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1796 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
1797 new StoreInst(Extract, NewElts[i], SI);
1799 DeadInsts.push_back(SI);
1800 } else if (SIType->isIntegerTy() &&
1801 TD->getTypeAllocSize(SIType) ==
1802 TD->getTypeAllocSize(AI->getAllocatedType())) {
1803 // If this is a store of the entire alloca from an integer, rewrite it.
1804 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1809 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1810 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1811 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1813 if (!isa<AllocaInst>(I)) continue;
1815 assert(Offset == 0 && NewElts[0] &&
1816 "Direct alloca use should have a zero offset");
1818 // If we have a use of the alloca, we know the derived uses will be
1819 // utilizing just the first element of the scalarized result. Insert a
1820 // bitcast of the first alloca before the user as required.
1821 AllocaInst *NewAI = NewElts[0];
1822 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1823 NewAI->moveBefore(BCI);
1830 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1831 /// and recursively continue updating all of its uses.
1832 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1833 SmallVector<AllocaInst*, 32> &NewElts) {
1834 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1835 if (BC->getOperand(0) != AI)
1838 // The bitcast references the original alloca. Replace its uses with
1839 // references to the first new element alloca.
1840 Instruction *Val = NewElts[0];
1841 if (Val->getType() != BC->getDestTy()) {
1842 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
1845 BC->replaceAllUsesWith(Val);
1846 DeadInsts.push_back(BC);
1849 /// FindElementAndOffset - Return the index of the element containing Offset
1850 /// within the specified type, which must be either a struct or an array.
1851 /// Sets T to the type of the element and Offset to the offset within that
1852 /// element. IdxTy is set to the type of the index result to be used in a
1853 /// GEP instruction.
1854 uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
1855 const Type *&IdxTy) {
1857 if (const StructType *ST = dyn_cast<StructType>(T)) {
1858 const StructLayout *Layout = TD->getStructLayout(ST);
1859 Idx = Layout->getElementContainingOffset(Offset);
1860 T = ST->getContainedType(Idx);
1861 Offset -= Layout->getElementOffset(Idx);
1862 IdxTy = Type::getInt32Ty(T->getContext());
1865 const ArrayType *AT = cast<ArrayType>(T);
1866 T = AT->getElementType();
1867 uint64_t EltSize = TD->getTypeAllocSize(T);
1868 Idx = Offset / EltSize;
1869 Offset -= Idx * EltSize;
1870 IdxTy = Type::getInt64Ty(T->getContext());
1874 /// RewriteGEP - Check if this GEP instruction moves the pointer across
1875 /// elements of the alloca that are being split apart, and if so, rewrite
1876 /// the GEP to be relative to the new element.
1877 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
1878 SmallVector<AllocaInst*, 32> &NewElts) {
1879 uint64_t OldOffset = Offset;
1880 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1881 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
1882 &Indices[0], Indices.size());
1884 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
1886 const Type *T = AI->getAllocatedType();
1888 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
1889 if (GEPI->getOperand(0) == AI)
1890 OldIdx = ~0ULL; // Force the GEP to be rewritten.
1892 T = AI->getAllocatedType();
1893 uint64_t EltOffset = Offset;
1894 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
1896 // If this GEP does not move the pointer across elements of the alloca
1897 // being split, then it does not needs to be rewritten.
1901 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
1902 SmallVector<Value*, 8> NewArgs;
1903 NewArgs.push_back(Constant::getNullValue(i32Ty));
1904 while (EltOffset != 0) {
1905 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
1906 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
1908 Instruction *Val = NewElts[Idx];
1909 if (NewArgs.size() > 1) {
1910 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
1911 NewArgs.end(), "", GEPI);
1912 Val->takeName(GEPI);
1914 if (Val->getType() != GEPI->getType())
1915 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
1916 GEPI->replaceAllUsesWith(Val);
1917 DeadInsts.push_back(GEPI);
1920 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
1921 /// Rewrite it to copy or set the elements of the scalarized memory.
1922 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
1924 SmallVector<AllocaInst*, 32> &NewElts) {
1925 // If this is a memcpy/memmove, construct the other pointer as the
1926 // appropriate type. The "Other" pointer is the pointer that goes to memory
1927 // that doesn't have anything to do with the alloca that we are promoting. For
1928 // memset, this Value* stays null.
1929 Value *OtherPtr = 0;
1930 unsigned MemAlignment = MI->getAlignment();
1931 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
1932 if (Inst == MTI->getRawDest())
1933 OtherPtr = MTI->getRawSource();
1935 assert(Inst == MTI->getRawSource());
1936 OtherPtr = MTI->getRawDest();
1940 // If there is an other pointer, we want to convert it to the same pointer
1941 // type as AI has, so we can GEP through it safely.
1943 unsigned AddrSpace =
1944 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
1946 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
1947 // optimization, but it's also required to detect the corner case where
1948 // both pointer operands are referencing the same memory, and where
1949 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
1950 // function is only called for mem intrinsics that access the whole
1951 // aggregate, so non-zero GEPs are not an issue here.)
1952 OtherPtr = OtherPtr->stripPointerCasts();
1954 // Copying the alloca to itself is a no-op: just delete it.
1955 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
1956 // This code will run twice for a no-op memcpy -- once for each operand.
1957 // Put only one reference to MI on the DeadInsts list.
1958 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
1959 E = DeadInsts.end(); I != E; ++I)
1960 if (*I == MI) return;
1961 DeadInsts.push_back(MI);
1965 // If the pointer is not the right type, insert a bitcast to the right
1968 PointerType::get(AI->getType()->getElementType(), AddrSpace);
1970 if (OtherPtr->getType() != NewTy)
1971 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
1974 // Process each element of the aggregate.
1975 bool SROADest = MI->getRawDest() == Inst;
1977 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
1979 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1980 // If this is a memcpy/memmove, emit a GEP of the other element address.
1981 Value *OtherElt = 0;
1982 unsigned OtherEltAlign = MemAlignment;
1985 Value *Idx[2] = { Zero,
1986 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
1987 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
1988 OtherPtr->getName()+"."+Twine(i),
1991 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
1992 const Type *OtherTy = OtherPtrTy->getElementType();
1993 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) {
1994 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
1996 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
1997 EltOffset = TD->getTypeAllocSize(EltTy)*i;
2000 // The alignment of the other pointer is the guaranteed alignment of the
2001 // element, which is affected by both the known alignment of the whole
2002 // mem intrinsic and the alignment of the element. If the alignment of
2003 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2004 // known alignment is just 4 bytes.
2005 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2008 Value *EltPtr = NewElts[i];
2009 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2011 // If we got down to a scalar, insert a load or store as appropriate.
2012 if (EltTy->isSingleValueType()) {
2013 if (isa<MemTransferInst>(MI)) {
2015 // From Other to Alloca.
2016 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2017 new StoreInst(Elt, EltPtr, MI);
2019 // From Alloca to Other.
2020 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2021 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2025 assert(isa<MemSetInst>(MI));
2027 // If the stored element is zero (common case), just store a null
2030 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2032 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
2034 // If EltTy is a vector type, get the element type.
2035 const Type *ValTy = EltTy->getScalarType();
2037 // Construct an integer with the right value.
2038 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
2039 APInt OneVal(EltSize, CI->getZExtValue());
2040 APInt TotalVal(OneVal);
2042 for (unsigned i = 0; 8*i < EltSize; ++i) {
2043 TotalVal = TotalVal.shl(8);
2047 // Convert the integer value to the appropriate type.
2048 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2049 if (ValTy->isPointerTy())
2050 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2051 else if (ValTy->isFloatingPointTy())
2052 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2053 assert(StoreVal->getType() == ValTy && "Type mismatch!");
2055 // If the requested value was a vector constant, create it.
2056 if (EltTy != ValTy) {
2057 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
2058 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
2059 StoreVal = ConstantVector::get(Elts);
2062 new StoreInst(StoreVal, EltPtr, MI);
2065 // Otherwise, if we're storing a byte variable, use a memset call for
2069 unsigned EltSize = TD->getTypeAllocSize(EltTy);
2071 IRBuilder<> Builder(MI);
2073 // Finally, insert the meminst for this element.
2074 if (isa<MemSetInst>(MI)) {
2075 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2078 assert(isa<MemTransferInst>(MI));
2079 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2080 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
2082 if (isa<MemCpyInst>(MI))
2083 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2085 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2088 DeadInsts.push_back(MI);
2091 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2092 /// overwrites the entire allocation. Extract out the pieces of the stored
2093 /// integer and store them individually.
2094 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2095 SmallVector<AllocaInst*, 32> &NewElts){
2096 // Extract each element out of the integer according to its structure offset
2097 // and store the element value to the individual alloca.
2098 Value *SrcVal = SI->getOperand(0);
2099 const Type *AllocaEltTy = AI->getAllocatedType();
2100 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2102 IRBuilder<> Builder(SI);
2104 // Handle tail padding by extending the operand
2105 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2106 SrcVal = Builder.CreateZExt(SrcVal,
2107 IntegerType::get(SI->getContext(), AllocaSizeBits));
2109 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2112 // There are two forms here: AI could be an array or struct. Both cases
2113 // have different ways to compute the element offset.
2114 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2115 const StructLayout *Layout = TD->getStructLayout(EltSTy);
2117 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2118 // Get the number of bits to shift SrcVal to get the value.
2119 const Type *FieldTy = EltSTy->getElementType(i);
2120 uint64_t Shift = Layout->getElementOffsetInBits(i);
2122 if (TD->isBigEndian())
2123 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
2125 Value *EltVal = SrcVal;
2127 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2128 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2131 // Truncate down to an integer of the right size.
2132 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2134 // Ignore zero sized fields like {}, they obviously contain no data.
2135 if (FieldSizeBits == 0) continue;
2137 if (FieldSizeBits != AllocaSizeBits)
2138 EltVal = Builder.CreateTrunc(EltVal,
2139 IntegerType::get(SI->getContext(), FieldSizeBits));
2140 Value *DestField = NewElts[i];
2141 if (EltVal->getType() == FieldTy) {
2142 // Storing to an integer field of this size, just do it.
2143 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2144 // Bitcast to the right element type (for fp/vector values).
2145 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2147 // Otherwise, bitcast the dest pointer (for aggregates).
2148 DestField = Builder.CreateBitCast(DestField,
2149 PointerType::getUnqual(EltVal->getType()));
2151 new StoreInst(EltVal, DestField, SI);
2155 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2156 const Type *ArrayEltTy = ATy->getElementType();
2157 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2158 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
2162 if (TD->isBigEndian())
2163 Shift = AllocaSizeBits-ElementOffset;
2167 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2168 // Ignore zero sized fields like {}, they obviously contain no data.
2169 if (ElementSizeBits == 0) continue;
2171 Value *EltVal = SrcVal;
2173 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2174 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2177 // Truncate down to an integer of the right size.
2178 if (ElementSizeBits != AllocaSizeBits)
2179 EltVal = Builder.CreateTrunc(EltVal,
2180 IntegerType::get(SI->getContext(),
2182 Value *DestField = NewElts[i];
2183 if (EltVal->getType() == ArrayEltTy) {
2184 // Storing to an integer field of this size, just do it.
2185 } else if (ArrayEltTy->isFloatingPointTy() ||
2186 ArrayEltTy->isVectorTy()) {
2187 // Bitcast to the right element type (for fp/vector values).
2188 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2190 // Otherwise, bitcast the dest pointer (for aggregates).
2191 DestField = Builder.CreateBitCast(DestField,
2192 PointerType::getUnqual(EltVal->getType()));
2194 new StoreInst(EltVal, DestField, SI);
2196 if (TD->isBigEndian())
2197 Shift -= ElementOffset;
2199 Shift += ElementOffset;
2203 DeadInsts.push_back(SI);
2206 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2207 /// an integer. Load the individual pieces to form the aggregate value.
2208 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2209 SmallVector<AllocaInst*, 32> &NewElts) {
2210 // Extract each element out of the NewElts according to its structure offset
2211 // and form the result value.
2212 const Type *AllocaEltTy = AI->getAllocatedType();
2213 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
2215 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2218 // There are two forms here: AI could be an array or struct. Both cases
2219 // have different ways to compute the element offset.
2220 const StructLayout *Layout = 0;
2221 uint64_t ArrayEltBitOffset = 0;
2222 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2223 Layout = TD->getStructLayout(EltSTy);
2225 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2226 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
2230 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2232 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2233 // Load the value from the alloca. If the NewElt is an aggregate, cast
2234 // the pointer to an integer of the same size before doing the load.
2235 Value *SrcField = NewElts[i];
2236 const Type *FieldTy =
2237 cast<PointerType>(SrcField->getType())->getElementType();
2238 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
2240 // Ignore zero sized fields like {}, they obviously contain no data.
2241 if (FieldSizeBits == 0) continue;
2243 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2245 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2246 !FieldTy->isVectorTy())
2247 SrcField = new BitCastInst(SrcField,
2248 PointerType::getUnqual(FieldIntTy),
2250 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2252 // If SrcField is a fp or vector of the right size but that isn't an
2253 // integer type, bitcast to an integer so we can shift it.
2254 if (SrcField->getType() != FieldIntTy)
2255 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2257 // Zero extend the field to be the same size as the final alloca so that
2258 // we can shift and insert it.
2259 if (SrcField->getType() != ResultVal->getType())
2260 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2262 // Determine the number of bits to shift SrcField.
2264 if (Layout) // Struct case.
2265 Shift = Layout->getElementOffsetInBits(i);
2267 Shift = i*ArrayEltBitOffset;
2269 if (TD->isBigEndian())
2270 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2273 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2274 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2277 // Don't create an 'or x, 0' on the first iteration.
2278 if (!isa<Constant>(ResultVal) ||
2279 !cast<Constant>(ResultVal)->isNullValue())
2280 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2282 ResultVal = SrcField;
2285 // Handle tail padding by truncating the result
2286 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2287 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2289 LI->replaceAllUsesWith(ResultVal);
2290 DeadInsts.push_back(LI);
2293 /// HasPadding - Return true if the specified type has any structure or
2294 /// alignment padding in between the elements that would be split apart
2295 /// by SROA; return false otherwise.
2296 static bool HasPadding(const Type *Ty, const TargetData &TD) {
2297 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2298 Ty = ATy->getElementType();
2299 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
2302 // SROA currently handles only Arrays and Structs.
2303 const StructType *STy = cast<StructType>(Ty);
2304 const StructLayout *SL = TD.getStructLayout(STy);
2305 unsigned PrevFieldBitOffset = 0;
2306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2307 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2309 // Check to see if there is any padding between this element and the
2312 unsigned PrevFieldEnd =
2313 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
2314 if (PrevFieldEnd < FieldBitOffset)
2317 PrevFieldBitOffset = FieldBitOffset;
2319 // Check for tail padding.
2320 if (unsigned EltCount = STy->getNumElements()) {
2321 unsigned PrevFieldEnd = PrevFieldBitOffset +
2322 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
2323 if (PrevFieldEnd < SL->getSizeInBits())
2329 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2330 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2331 /// or 1 if safe after canonicalization has been performed.
2332 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2333 // Loop over the use list of the alloca. We can only transform it if all of
2334 // the users are safe to transform.
2335 AllocaInfo Info(AI);
2337 isSafeForScalarRepl(AI, 0, Info);
2338 if (Info.isUnsafe) {
2339 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2343 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2344 // source and destination, we have to be careful. In particular, the memcpy
2345 // could be moving around elements that live in structure padding of the LLVM
2346 // types, but may actually be used. In these cases, we refuse to promote the
2348 if (Info.isMemCpySrc && Info.isMemCpyDst &&
2349 HasPadding(AI->getAllocatedType(), *TD))
2352 // If the alloca never has an access to just *part* of it, but is accessed
2353 // via loads and stores, then we should use ConvertToScalarInfo to promote
2354 // the alloca instead of promoting each piece at a time and inserting fission
2356 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2357 // If the struct/array just has one element, use basic SRoA.
2358 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2359 if (ST->getNumElements() > 1) return false;
2361 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2371 /// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
2372 /// some part of a constant global variable. This intentionally only accepts
2373 /// constant expressions because we don't can't rewrite arbitrary instructions.
2374 static bool PointsToConstantGlobal(Value *V) {
2375 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2376 return GV->isConstant();
2377 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2378 if (CE->getOpcode() == Instruction::BitCast ||
2379 CE->getOpcode() == Instruction::GetElementPtr)
2380 return PointsToConstantGlobal(CE->getOperand(0));
2384 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
2385 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
2386 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
2387 /// track of whether it moves the pointer (with isOffset) but otherwise traverse
2388 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
2389 /// the alloca, and if the source pointer is a pointer to a constant global, we
2390 /// can optimize this.
2391 static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
2393 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
2394 User *U = cast<Instruction>(*UI);
2396 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2397 // Ignore non-volatile loads, they are always ok.
2398 if (LI->isVolatile()) return false;
2402 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2403 // If uses of the bitcast are ok, we are ok.
2404 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
2408 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2409 // If the GEP has all zero indices, it doesn't offset the pointer. If it
2410 // doesn't, it does.
2411 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
2412 isOffset || !GEP->hasAllZeroIndices()))
2417 if (CallSite CS = U) {
2418 // If this is a readonly/readnone call site, then we know it is just a
2419 // load and we can ignore it.
2420 if (CS.onlyReadsMemory())
2423 // If this is the function being called then we treat it like a load and
2425 if (CS.isCallee(UI))
2428 // If this is being passed as a byval argument, the caller is making a
2429 // copy, so it is only a read of the alloca.
2430 unsigned ArgNo = CS.getArgumentNo(UI);
2431 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal))
2435 // If this is isn't our memcpy/memmove, reject it as something we can't
2437 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
2441 // If the transfer is using the alloca as a source of the transfer, then
2442 // ignore it since it is a load (unless the transfer is volatile).
2443 if (UI.getOperandNo() == 1) {
2444 if (MI->isVolatile()) return false;
2448 // If we already have seen a copy, reject the second one.
2449 if (TheCopy) return false;
2451 // If the pointer has been offset from the start of the alloca, we can't
2452 // safely handle this.
2453 if (isOffset) return false;
2455 // If the memintrinsic isn't using the alloca as the dest, reject it.
2456 if (UI.getOperandNo() != 0) return false;
2458 // If the source of the memcpy/move is not a constant global, reject it.
2459 if (!PointsToConstantGlobal(MI->getSource()))
2462 // Otherwise, the transform is safe. Remember the copy instruction.
2468 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
2469 /// modified by a copy from a constant global. If we can prove this, we can
2470 /// replace any uses of the alloca with uses of the global directly.
2471 MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
2472 MemTransferInst *TheCopy = 0;
2473 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))