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 they
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 #include "llvm/Transforms/Scalar.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AssumptionTracker.h"
27 #include "llvm/Analysis/Loads.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/CallSite.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DIBuilder.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Dominators.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GetElementPtrTypeIterator.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/IR/Operator.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
52 #include "llvm/Transforms/Utils/SSAUpdater.h"
55 #define DEBUG_TYPE "scalarrepl"
57 STATISTIC(NumReplaced, "Number of allocas broken up");
58 STATISTIC(NumPromoted, "Number of allocas promoted");
59 STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
60 STATISTIC(NumConverted, "Number of aggregates converted to scalar");
63 struct SROA : public FunctionPass {
64 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
65 : FunctionPass(ID), HasDomTree(hasDT) {
71 StructMemberThreshold = 32;
73 StructMemberThreshold = ST;
75 ArrayElementThreshold = 8;
77 ArrayElementThreshold = AT;
79 // Do not limit the scalar integer load size if no threshold is given.
80 ScalarLoadThreshold = -1;
82 ScalarLoadThreshold = SLT;
85 bool runOnFunction(Function &F) override;
87 bool performScalarRepl(Function &F);
88 bool performPromotion(Function &F);
94 /// DeadInsts - Keep track of instructions we have made dead, so that
95 /// we can remove them after we are done working.
96 SmallVector<Value*, 32> DeadInsts;
98 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
99 /// information about the uses. All these fields are initialized to false
100 /// and set to true when something is learned.
102 /// The alloca to promote.
105 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
106 /// looping and avoid redundant work.
107 SmallPtrSet<PHINode*, 8> CheckedPHIs;
109 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
112 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
113 bool isMemCpySrc : 1;
115 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
116 bool isMemCpyDst : 1;
118 /// hasSubelementAccess - This is true if a subelement of the alloca is
119 /// ever accessed, or false if the alloca is only accessed with mem
120 /// intrinsics or load/store that only access the entire alloca at once.
121 bool hasSubelementAccess : 1;
123 /// hasALoadOrStore - This is true if there are any loads or stores to it.
124 /// The alloca may just be accessed with memcpy, for example, which would
126 bool hasALoadOrStore : 1;
128 explicit AllocaInfo(AllocaInst *ai)
129 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
130 hasSubelementAccess(false), hasALoadOrStore(false) {}
133 /// SRThreshold - The maximum alloca size to considered for SROA.
134 unsigned SRThreshold;
136 /// StructMemberThreshold - The maximum number of members a struct can
137 /// contain to be considered for SROA.
138 unsigned StructMemberThreshold;
140 /// ArrayElementThreshold - The maximum number of elements an array can
141 /// have to be considered for SROA.
142 unsigned ArrayElementThreshold;
144 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
145 /// converting to scalar
146 unsigned ScalarLoadThreshold;
148 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
150 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
153 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
155 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
156 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
158 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
159 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
160 Type *MemOpType, bool isStore, AllocaInfo &Info,
161 Instruction *TheAccess, bool AllowWholeAccess);
162 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size);
163 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset,
166 void DoScalarReplacement(AllocaInst *AI,
167 std::vector<AllocaInst*> &WorkList);
168 void DeleteDeadInstructions();
170 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
171 SmallVectorImpl<AllocaInst *> &NewElts);
172 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
173 SmallVectorImpl<AllocaInst *> &NewElts);
174 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
175 SmallVectorImpl<AllocaInst *> &NewElts);
176 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
178 SmallVectorImpl<AllocaInst *> &NewElts);
179 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
181 SmallVectorImpl<AllocaInst *> &NewElts);
182 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
183 SmallVectorImpl<AllocaInst *> &NewElts);
184 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
185 SmallVectorImpl<AllocaInst *> &NewElts);
186 bool ShouldAttemptScalarRepl(AllocaInst *AI);
189 // SROA_DT - SROA that uses DominatorTree.
190 struct SROA_DT : public SROA {
193 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
194 SROA(T, true, ID, ST, AT, SLT) {
195 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
198 // getAnalysisUsage - This pass does not require any passes, but we know it
199 // will not alter the CFG, so say so.
200 void getAnalysisUsage(AnalysisUsage &AU) const override {
201 AU.addRequired<AssumptionTracker>();
202 AU.addRequired<DominatorTreeWrapperPass>();
203 AU.setPreservesCFG();
207 // SROA_SSAUp - SROA that uses SSAUpdater.
208 struct SROA_SSAUp : public SROA {
211 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
212 SROA(T, false, ID, ST, AT, SLT) {
213 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
216 // getAnalysisUsage - This pass does not require any passes, but we know it
217 // will not alter the CFG, so say so.
218 void getAnalysisUsage(AnalysisUsage &AU) const override {
219 AU.addRequired<AssumptionTracker>();
220 AU.setPreservesCFG();
226 char SROA_DT::ID = 0;
227 char SROA_SSAUp::ID = 0;
229 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
230 "Scalar Replacement of Aggregates (DT)", false, false)
231 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
232 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
233 INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
234 "Scalar Replacement of Aggregates (DT)", false, false)
236 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
237 "Scalar Replacement of Aggregates (SSAUp)", false, false)
238 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
239 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
240 "Scalar Replacement of Aggregates (SSAUp)", false, false)
242 // Public interface to the ScalarReplAggregates pass
243 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
245 int StructMemberThreshold,
246 int ArrayElementThreshold,
247 int ScalarLoadThreshold) {
249 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
250 ScalarLoadThreshold);
251 return new SROA_SSAUp(Threshold, StructMemberThreshold,
252 ArrayElementThreshold, ScalarLoadThreshold);
256 //===----------------------------------------------------------------------===//
257 // Convert To Scalar Optimization.
258 //===----------------------------------------------------------------------===//
261 /// ConvertToScalarInfo - This class implements the "Convert To Scalar"
262 /// optimization, which scans the uses of an alloca and determines if it can
263 /// rewrite it in terms of a single new alloca that can be mem2reg'd.
264 class ConvertToScalarInfo {
265 /// AllocaSize - The size of the alloca being considered in bytes.
267 const DataLayout &DL;
268 unsigned ScalarLoadThreshold;
270 /// IsNotTrivial - This is set to true if there is some access to the object
271 /// which means that mem2reg can't promote it.
274 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
275 /// computed based on the uses of the alloca rather than the LLVM type system.
279 // Accesses via GEPs that are consistent with element access of a vector
280 // type. This will not be converted into a vector unless there is a later
281 // access using an actual vector type.
284 // Accesses via vector operations and GEPs that are consistent with the
285 // layout of a vector type.
288 // An integer bag-of-bits with bitwise operations for insertion and
289 // extraction. Any combination of types can be converted into this kind
294 /// VectorTy - This tracks the type that we should promote the vector to if
295 /// it is possible to turn it into a vector. This starts out null, and if it
296 /// isn't possible to turn into a vector type, it gets set to VoidTy.
297 VectorType *VectorTy;
299 /// HadNonMemTransferAccess - True if there is at least one access to the
300 /// alloca that is not a MemTransferInst. We don't want to turn structs into
301 /// large integers unless there is some potential for optimization.
302 bool HadNonMemTransferAccess;
304 /// HadDynamicAccess - True if some element of this alloca was dynamic.
305 /// We don't yet have support for turning a dynamic access into a large
307 bool HadDynamicAccess;
310 explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
312 : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
313 ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
314 HadDynamicAccess(false) { }
316 AllocaInst *TryConvert(AllocaInst *AI);
319 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
320 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
321 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
322 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
323 Value *NonConstantIdx);
325 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
326 uint64_t Offset, Value* NonConstantIdx,
327 IRBuilder<> &Builder);
328 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
329 uint64_t Offset, Value* NonConstantIdx,
330 IRBuilder<> &Builder);
332 } // end anonymous namespace.
335 /// TryConvert - Analyze the specified alloca, and if it is safe to do so,
336 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new
337 /// alloca if possible or null if not.
338 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
339 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
341 if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
344 // If an alloca has only memset / memcpy uses, it may still have an Unknown
345 // ScalarKind. Treat it as an Integer below.
346 if (ScalarKind == Unknown)
347 ScalarKind = Integer;
349 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
350 ScalarKind = Integer;
352 // If we were able to find a vector type that can handle this with
353 // insert/extract elements, and if there was at least one use that had
354 // a vector type, promote this to a vector. We don't want to promote
355 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
356 // we just get a lot of insert/extracts. If at least one vector is
357 // involved, then we probably really do have a union of vector/array.
359 if (ScalarKind == Vector) {
360 assert(VectorTy && "Missing type for vector scalar.");
361 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
362 << *VectorTy << '\n');
363 NewTy = VectorTy; // Use the vector type.
365 unsigned BitWidth = AllocaSize * 8;
367 // Do not convert to scalar integer if the alloca size exceeds the
368 // scalar load threshold.
369 if (BitWidth > ScalarLoadThreshold)
372 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
373 !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
375 // Dynamic accesses on integers aren't yet supported. They need us to shift
376 // by a dynamic amount which could be difficult to work out as we might not
377 // know whether to use a left or right shift.
378 if (ScalarKind == Integer && HadDynamicAccess)
381 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
382 // Create and insert the integer alloca.
383 NewTy = IntegerType::get(AI->getContext(), BitWidth);
385 AllocaInst *NewAI = new AllocaInst(NewTy, nullptr, "",
386 AI->getParent()->begin());
387 ConvertUsesToScalar(AI, NewAI, 0, nullptr);
391 /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
392 /// (VectorTy) so far at the offset specified by Offset (which is specified in
395 /// There are two cases we handle here:
396 /// 1) A union of vector types of the same size and potentially its elements.
397 /// Here we turn element accesses into insert/extract element operations.
398 /// This promotes a <4 x float> with a store of float to the third element
399 /// into a <4 x float> that uses insert element.
400 /// 2) A fully general blob of memory, which we turn into some (potentially
401 /// large) integer type with extract and insert operations where the loads
402 /// and stores would mutate the memory. We mark this by setting VectorTy
404 void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
406 // If we already decided to turn this into a blob of integer memory, there is
407 // nothing to be done.
408 if (ScalarKind == Integer)
411 // If this could be contributing to a vector, analyze it.
413 // If the In type is a vector that is the same size as the alloca, see if it
414 // matches the existing VecTy.
415 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
416 if (MergeInVectorType(VInTy, Offset))
418 } else if (In->isFloatTy() || In->isDoubleTy() ||
419 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
420 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
421 // Full width accesses can be ignored, because they can always be turned
423 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
424 if (EltSize == AllocaSize)
427 // If we're accessing something that could be an element of a vector, see
428 // if the implied vector agrees with what we already have and if Offset is
429 // compatible with it.
430 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
431 (!VectorTy || EltSize == VectorTy->getElementType()
432 ->getPrimitiveSizeInBits()/8)) {
434 ScalarKind = ImplicitVector;
435 VectorTy = VectorType::get(In, AllocaSize/EltSize);
441 // Otherwise, we have a case that we can't handle with an optimized vector
442 // form. We can still turn this into a large integer.
443 ScalarKind = Integer;
446 /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
447 /// returning true if the type was successfully merged and false otherwise.
448 bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
450 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
451 // If we're storing/loading a vector of the right size, allow it as a
452 // vector. If this the first vector we see, remember the type so that
453 // we know the element size. If this is a subsequent access, ignore it
454 // even if it is a differing type but the same size. Worst case we can
455 // bitcast the resultant vectors.
465 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
466 /// its accesses to a single vector type, return true and set VecTy to
467 /// the new type. If we could convert the alloca into a single promotable
468 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a
469 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
470 /// is the current offset from the base of the alloca being analyzed.
472 /// If we see at least one access to the value that is as a vector type, set the
474 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
475 Value* NonConstantIdx) {
476 for (User *U : V->users()) {
477 Instruction *UI = cast<Instruction>(U);
479 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
480 // Don't break volatile loads.
483 // Don't touch MMX operations.
484 if (LI->getType()->isX86_MMXTy())
486 HadNonMemTransferAccess = true;
487 MergeInTypeForLoadOrStore(LI->getType(), Offset);
491 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
492 // Storing the pointer, not into the value?
493 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
494 // Don't touch MMX operations.
495 if (SI->getOperand(0)->getType()->isX86_MMXTy())
497 HadNonMemTransferAccess = true;
498 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
502 if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
503 if (!onlyUsedByLifetimeMarkers(BCI))
504 IsNotTrivial = true; // Can't be mem2reg'd.
505 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
510 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
511 // If this is a GEP with a variable indices, we can't handle it.
512 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType());
516 // Compute the offset that this GEP adds to the pointer.
517 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
518 Value *GEPNonConstantIdx = nullptr;
519 if (!GEP->hasAllConstantIndices()) {
520 if (!isa<VectorType>(PtrTy->getElementType()))
524 GEPNonConstantIdx = Indices.pop_back_val();
525 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
527 HadDynamicAccess = true;
529 GEPNonConstantIdx = NonConstantIdx;
530 uint64_t GEPOffset = DL.getIndexedOffset(PtrTy,
532 // See if all uses can be converted.
533 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
535 IsNotTrivial = true; // Can't be mem2reg'd.
536 HadNonMemTransferAccess = true;
540 // If this is a constant sized memset of a constant value (e.g. 0) we can
542 if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
543 // Store to dynamic index.
546 // Store of constant value.
547 if (!isa<ConstantInt>(MSI->getValue()))
550 // Store of constant size.
551 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
555 // If the size differs from the alloca, we can only convert the alloca to
556 // an integer bag-of-bits.
557 // FIXME: This should handle all of the cases that are currently accepted
558 // as vector element insertions.
559 if (Len->getZExtValue() != AllocaSize || Offset != 0)
560 ScalarKind = Integer;
562 IsNotTrivial = true; // Can't be mem2reg'd.
563 HadNonMemTransferAccess = true;
567 // If this is a memcpy or memmove into or out of the whole allocation, we
568 // can handle it like a load or store of the scalar type.
569 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
570 // Store to dynamic index.
573 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
574 if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
577 IsNotTrivial = true; // Can't be mem2reg'd.
581 // If this is a lifetime intrinsic, we can handle it.
582 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
583 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
584 II->getIntrinsicID() == Intrinsic::lifetime_end) {
589 // Otherwise, we cannot handle this!
596 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
597 /// directly. This happens when we are converting an "integer union" to a
598 /// single integer scalar, or when we are converting a "vector union" to a
599 /// vector with insert/extractelement instructions.
601 /// Offset is an offset from the original alloca, in bits that need to be
602 /// shifted to the right. By the end of this, there should be no uses of Ptr.
603 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
605 Value* NonConstantIdx) {
606 while (!Ptr->use_empty()) {
607 Instruction *User = cast<Instruction>(Ptr->user_back());
609 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
610 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
611 CI->eraseFromParent();
615 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
616 // Compute the offset that this GEP adds to the pointer.
617 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
618 Value* GEPNonConstantIdx = nullptr;
619 if (!GEP->hasAllConstantIndices()) {
620 assert(!NonConstantIdx &&
621 "Dynamic GEP reading from dynamic GEP unsupported");
622 GEPNonConstantIdx = Indices.pop_back_val();
624 GEPNonConstantIdx = NonConstantIdx;
625 uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
627 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
628 GEP->eraseFromParent();
632 IRBuilder<> Builder(User);
634 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
635 // The load is a bit extract from NewAI shifted right by Offset bits.
636 Value *LoadedVal = Builder.CreateLoad(NewAI);
638 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
639 NonConstantIdx, Builder);
640 LI->replaceAllUsesWith(NewLoadVal);
641 LI->eraseFromParent();
645 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
646 assert(SI->getOperand(0) != Ptr && "Consistency error!");
647 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
648 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
649 NonConstantIdx, Builder);
650 Builder.CreateStore(New, NewAI);
651 SI->eraseFromParent();
653 // If the load we just inserted is now dead, then the inserted store
654 // overwrote the entire thing.
655 if (Old->use_empty())
656 Old->eraseFromParent();
660 // If this is a constant sized memset of a constant value (e.g. 0) we can
661 // transform it into a store of the expanded constant value.
662 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
663 assert(MSI->getRawDest() == Ptr && "Consistency error!");
664 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
665 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
666 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
667 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
668 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
670 // Compute the value replicated the right number of times.
671 APInt APVal(NumBytes*8, Val);
673 // Splat the value if non-zero.
675 for (unsigned i = 1; i != NumBytes; ++i)
678 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
679 Value *New = ConvertScalar_InsertValue(
680 ConstantInt::get(User->getContext(), APVal),
681 Old, Offset, nullptr, Builder);
682 Builder.CreateStore(New, NewAI);
684 // If the load we just inserted is now dead, then the memset overwrote
686 if (Old->use_empty())
687 Old->eraseFromParent();
689 MSI->eraseFromParent();
693 // If this is a memcpy or memmove into or out of the whole allocation, we
694 // can handle it like a load or store of the scalar type.
695 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
696 assert(Offset == 0 && "must be store to start of alloca");
697 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
699 // If the source and destination are both to the same alloca, then this is
700 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
702 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &DL, 0));
704 if (GetUnderlyingObject(MTI->getSource(), &DL, 0) != OrigAI) {
705 // Dest must be OrigAI, change this to be a load from the original
706 // pointer (bitcasted), then a store to our new alloca.
707 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
708 Value *SrcPtr = MTI->getSource();
709 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
710 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
711 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
712 AIPTy = PointerType::get(AIPTy->getElementType(),
713 SPTy->getAddressSpace());
715 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
717 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
718 SrcVal->setAlignment(MTI->getAlignment());
719 Builder.CreateStore(SrcVal, NewAI);
720 } else if (GetUnderlyingObject(MTI->getDest(), &DL, 0) != OrigAI) {
721 // Src must be OrigAI, change this to be a load from NewAI then a store
722 // through the original dest pointer (bitcasted).
723 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
724 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
726 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
727 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
728 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
729 AIPTy = PointerType::get(AIPTy->getElementType(),
730 DPTy->getAddressSpace());
732 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
734 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
735 NewStore->setAlignment(MTI->getAlignment());
737 // Noop transfer. Src == Dst
740 MTI->eraseFromParent();
744 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
745 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
746 II->getIntrinsicID() == Intrinsic::lifetime_end) {
747 // There's no need to preserve these, as the resulting alloca will be
748 // converted to a register anyways.
749 II->eraseFromParent();
754 llvm_unreachable("Unsupported operation!");
758 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
759 /// or vector value FromVal, extracting the bits from the offset specified by
760 /// Offset. This returns the value, which is of type ToType.
762 /// This happens when we are converting an "integer union" to a single
763 /// integer scalar, or when we are converting a "vector union" to a vector with
764 /// insert/extractelement instructions.
766 /// Offset is an offset from the original alloca, in bits that need to be
767 /// shifted to the right.
768 Value *ConvertToScalarInfo::
769 ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
770 uint64_t Offset, Value* NonConstantIdx,
771 IRBuilder<> &Builder) {
772 // If the load is of the whole new alloca, no conversion is needed.
773 Type *FromType = FromVal->getType();
774 if (FromType == ToType && Offset == 0)
777 // If the result alloca is a vector type, this is either an element
778 // access or a bitcast to another vector type of the same size.
779 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
780 unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
781 unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
782 if (FromTypeSize == ToTypeSize)
783 return Builder.CreateBitCast(FromVal, ToType);
785 // Otherwise it must be an element access.
788 unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
789 Elt = Offset/EltSize;
790 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
792 // Return the element extracted out of it.
794 if (NonConstantIdx) {
796 Idx = Builder.CreateAdd(NonConstantIdx,
797 Builder.getInt32(Elt),
800 Idx = NonConstantIdx;
802 Idx = Builder.getInt32(Elt);
803 Value *V = Builder.CreateExtractElement(FromVal, Idx);
804 if (V->getType() != ToType)
805 V = Builder.CreateBitCast(V, ToType);
809 // If ToType is a first class aggregate, extract out each of the pieces and
810 // use insertvalue's to form the FCA.
811 if (StructType *ST = dyn_cast<StructType>(ToType)) {
812 assert(!NonConstantIdx &&
813 "Dynamic indexing into struct types not supported");
814 const StructLayout &Layout = *DL.getStructLayout(ST);
815 Value *Res = UndefValue::get(ST);
816 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
817 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
818 Offset+Layout.getElementOffsetInBits(i),
820 Res = Builder.CreateInsertValue(Res, Elt, i);
825 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
826 assert(!NonConstantIdx &&
827 "Dynamic indexing into array types not supported");
828 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
829 Value *Res = UndefValue::get(AT);
830 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
831 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
832 Offset+i*EltSize, nullptr,
834 Res = Builder.CreateInsertValue(Res, Elt, i);
839 // Otherwise, this must be a union that was converted to an integer value.
840 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
842 // If this is a big-endian system and the load is narrower than the
843 // full alloca type, we need to do a shift to get the right bits.
845 if (DL.isBigEndian()) {
846 // On big-endian machines, the lowest bit is stored at the bit offset
847 // from the pointer given by getTypeStoreSizeInBits. This matters for
848 // integers with a bitwidth that is not a multiple of 8.
849 ShAmt = DL.getTypeStoreSizeInBits(NTy) -
850 DL.getTypeStoreSizeInBits(ToType) - Offset;
855 // Note: we support negative bitwidths (with shl) which are not defined.
856 // We do this to support (f.e.) loads off the end of a structure where
857 // only some bits are used.
858 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
859 FromVal = Builder.CreateLShr(FromVal,
860 ConstantInt::get(FromVal->getType(), ShAmt));
861 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
862 FromVal = Builder.CreateShl(FromVal,
863 ConstantInt::get(FromVal->getType(), -ShAmt));
865 // Finally, unconditionally truncate the integer to the right width.
866 unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
867 if (LIBitWidth < NTy->getBitWidth())
869 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
871 else if (LIBitWidth > NTy->getBitWidth())
873 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
876 // If the result is an integer, this is a trunc or bitcast.
877 if (ToType->isIntegerTy()) {
879 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
880 // Just do a bitcast, we know the sizes match up.
881 FromVal = Builder.CreateBitCast(FromVal, ToType);
883 // Otherwise must be a pointer.
884 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
886 assert(FromVal->getType() == ToType && "Didn't convert right?");
890 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
891 /// or vector value "Old" at the offset specified by Offset.
893 /// This happens when we are converting an "integer union" to a
894 /// single integer scalar, or when we are converting a "vector union" to a
895 /// vector with insert/extractelement instructions.
897 /// Offset is an offset from the original alloca, in bits that need to be
898 /// shifted to the right.
900 /// NonConstantIdx is an index value if there was a GEP with a non-constant
901 /// index value. If this is 0 then all GEPs used to find this insert address
903 Value *ConvertToScalarInfo::
904 ConvertScalar_InsertValue(Value *SV, Value *Old,
905 uint64_t Offset, Value* NonConstantIdx,
906 IRBuilder<> &Builder) {
907 // Convert the stored type to the actual type, shift it left to insert
908 // then 'or' into place.
909 Type *AllocaType = Old->getType();
910 LLVMContext &Context = Old->getContext();
912 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
913 uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
914 uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
916 // Changing the whole vector with memset or with an access of a different
918 if (ValSize == VecSize)
919 return Builder.CreateBitCast(SV, AllocaType);
921 // Must be an element insertion.
922 Type *EltTy = VTy->getElementType();
923 if (SV->getType() != EltTy)
924 SV = Builder.CreateBitCast(SV, EltTy);
925 uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
926 unsigned Elt = Offset/EltSize;
928 if (NonConstantIdx) {
930 Idx = Builder.CreateAdd(NonConstantIdx,
931 Builder.getInt32(Elt),
934 Idx = NonConstantIdx;
936 Idx = Builder.getInt32(Elt);
937 return Builder.CreateInsertElement(Old, SV, Idx);
940 // If SV is a first-class aggregate value, insert each value recursively.
941 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
942 assert(!NonConstantIdx &&
943 "Dynamic indexing into struct types not supported");
944 const StructLayout &Layout = *DL.getStructLayout(ST);
945 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
946 Value *Elt = Builder.CreateExtractValue(SV, i);
947 Old = ConvertScalar_InsertValue(Elt, Old,
948 Offset+Layout.getElementOffsetInBits(i),
954 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
955 assert(!NonConstantIdx &&
956 "Dynamic indexing into array types not supported");
957 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
958 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
959 Value *Elt = Builder.CreateExtractValue(SV, i);
960 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, nullptr,
966 // If SV is a float, convert it to the appropriate integer type.
967 // If it is a pointer, do the same.
968 unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
969 unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
970 unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
971 unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
972 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
973 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
974 else if (SV->getType()->isPointerTy())
975 SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
977 // Zero extend or truncate the value if needed.
978 if (SV->getType() != AllocaType) {
979 if (SV->getType()->getPrimitiveSizeInBits() <
980 AllocaType->getPrimitiveSizeInBits())
981 SV = Builder.CreateZExt(SV, AllocaType);
983 // Truncation may be needed if storing more than the alloca can hold
984 // (undefined behavior).
985 SV = Builder.CreateTrunc(SV, AllocaType);
986 SrcWidth = DestWidth;
987 SrcStoreWidth = DestStoreWidth;
991 // If this is a big-endian system and the store is narrower than the
992 // full alloca type, we need to do a shift to get the right bits.
994 if (DL.isBigEndian()) {
995 // On big-endian machines, the lowest bit is stored at the bit offset
996 // from the pointer given by getTypeStoreSizeInBits. This matters for
997 // integers with a bitwidth that is not a multiple of 8.
998 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1003 // Note: we support negative bitwidths (with shr) which are not defined.
1004 // We do this to support (f.e.) stores off the end of a structure where
1005 // only some bits in the structure are set.
1006 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1007 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
1008 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
1010 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
1011 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
1012 Mask = Mask.lshr(-ShAmt);
1015 // Mask out the bits we are about to insert from the old value, and or
1017 if (SrcWidth != DestWidth) {
1018 assert(DestWidth > SrcWidth);
1019 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1020 SV = Builder.CreateOr(Old, SV, "ins");
1026 //===----------------------------------------------------------------------===//
1028 //===----------------------------------------------------------------------===//
1031 bool SROA::runOnFunction(Function &F) {
1032 if (skipOptnoneFunction(F))
1035 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1036 DL = DLP ? &DLP->getDataLayout() : nullptr;
1038 bool Changed = performPromotion(F);
1040 // FIXME: ScalarRepl currently depends on DataLayout more than it
1041 // theoretically needs to. It should be refactored in order to support
1042 // target-independent IR. Until this is done, just skip the actual
1043 // scalar-replacement portion of this pass.
1044 if (!DL) return Changed;
1047 bool LocalChange = performScalarRepl(F);
1048 if (!LocalChange) break; // No need to repromote if no scalarrepl
1050 LocalChange = performPromotion(F);
1051 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1058 class AllocaPromoter : public LoadAndStorePromoter {
1061 SmallVector<DbgDeclareInst *, 4> DDIs;
1062 SmallVector<DbgValueInst *, 4> DVIs;
1064 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1066 : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
1068 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
1069 // Remember which alloca we're promoting (for isInstInList).
1071 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) {
1072 for (User *U : DebugNode->users())
1073 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1074 DDIs.push_back(DDI);
1075 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1076 DVIs.push_back(DVI);
1079 LoadAndStorePromoter::run(Insts);
1080 AI->eraseFromParent();
1081 for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
1082 E = DDIs.end(); I != E; ++I) {
1083 DbgDeclareInst *DDI = *I;
1084 DDI->eraseFromParent();
1086 for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
1087 E = DVIs.end(); I != E; ++I) {
1088 DbgValueInst *DVI = *I;
1089 DVI->eraseFromParent();
1093 bool isInstInList(Instruction *I,
1094 const SmallVectorImpl<Instruction*> &Insts) const override {
1095 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1096 return LI->getOperand(0) == AI;
1097 return cast<StoreInst>(I)->getPointerOperand() == AI;
1100 void updateDebugInfo(Instruction *Inst) const override {
1101 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
1102 E = DDIs.end(); I != E; ++I) {
1103 DbgDeclareInst *DDI = *I;
1104 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1105 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1106 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1107 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1109 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
1110 E = DVIs.end(); I != E; ++I) {
1111 DbgValueInst *DVI = *I;
1112 Value *Arg = nullptr;
1113 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1114 // If an argument is zero extended then use argument directly. The ZExt
1115 // may be zapped by an optimization pass in future.
1116 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1117 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1118 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1119 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1121 Arg = SI->getOperand(0);
1122 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1123 Arg = LI->getOperand(0);
1127 Instruction *DbgVal = DIB->insertDbgValueIntrinsic(
1128 Arg, 0, DIVariable(DVI->getVariable()),
1129 DIExpression(DVI->getExpression()), Inst);
1130 DbgVal->setDebugLoc(DVI->getDebugLoc());
1134 } // end anon namespace
1136 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1137 /// subsequently loaded can be rewritten to load both input pointers and then
1138 /// select between the result, allowing the load of the alloca to be promoted.
1140 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1141 /// %V = load i32* %P2
1143 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1144 /// %V2 = load i32* %Other
1145 /// %V = select i1 %cond, i32 %V1, i32 %V2
1147 /// We can do this to a select if its only uses are loads and if the operand to
1148 /// the select can be loaded unconditionally.
1149 static bool isSafeSelectToSpeculate(SelectInst *SI, const DataLayout *DL) {
1150 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer(DL);
1151 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer(DL);
1153 for (User *U : SI->users()) {
1154 LoadInst *LI = dyn_cast<LoadInst>(U);
1155 if (!LI || !LI->isSimple()) return false;
1157 // Both operands to the select need to be dereferencable, either absolutely
1158 // (e.g. allocas) or at this point because we can see other accesses to it.
1159 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
1160 LI->getAlignment(), DL))
1162 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
1163 LI->getAlignment(), DL))
1170 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1171 /// subsequently loaded can be rewritten to load both input pointers in the pred
1172 /// blocks and then PHI the results, allowing the load of the alloca to be
1175 /// %P2 = phi [i32* %Alloca, i32* %Other]
1176 /// %V = load i32* %P2
1178 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1180 /// %V2 = load i32* %Other
1182 /// %V = phi [i32 %V1, i32 %V2]
1184 /// We can do this to a select if its only uses are loads and if the operand to
1185 /// the select can be loaded unconditionally.
1186 static bool isSafePHIToSpeculate(PHINode *PN, const DataLayout *DL) {
1187 // For now, we can only do this promotion if the load is in the same block as
1188 // the PHI, and if there are no stores between the phi and load.
1189 // TODO: Allow recursive phi users.
1190 // TODO: Allow stores.
1191 BasicBlock *BB = PN->getParent();
1192 unsigned MaxAlign = 0;
1193 for (User *U : PN->users()) {
1194 LoadInst *LI = dyn_cast<LoadInst>(U);
1195 if (!LI || !LI->isSimple()) return false;
1197 // For now we only allow loads in the same block as the PHI. This is a
1198 // common case that happens when instcombine merges two loads through a PHI.
1199 if (LI->getParent() != BB) return false;
1201 // Ensure that there are no instructions between the PHI and the load that
1203 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
1204 if (BBI->mayWriteToMemory())
1207 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1210 // Okay, we know that we have one or more loads in the same block as the PHI.
1211 // We can transform this if it is safe to push the loads into the predecessor
1212 // blocks. The only thing to watch out for is that we can't put a possibly
1213 // trapping load in the predecessor if it is a critical edge.
1214 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1215 BasicBlock *Pred = PN->getIncomingBlock(i);
1216 Value *InVal = PN->getIncomingValue(i);
1218 // If the terminator of the predecessor has side-effects (an invoke),
1219 // there is no safe place to put a load in the predecessor.
1220 if (Pred->getTerminator()->mayHaveSideEffects())
1223 // If the value is produced by the terminator of the predecessor
1224 // (an invoke), there is no valid place to put a load in the predecessor.
1225 if (Pred->getTerminator() == InVal)
1228 // If the predecessor has a single successor, then the edge isn't critical.
1229 if (Pred->getTerminator()->getNumSuccessors() == 1)
1232 // If this pointer is always safe to load, or if we can prove that there is
1233 // already a load in the block, then we can move the load to the pred block.
1234 if (InVal->isDereferenceablePointer(DL) ||
1235 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, DL))
1245 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1246 /// direct (non-volatile) loads and stores to it. If the alloca is close but
1247 /// not quite there, this will transform the code to allow promotion. As such,
1248 /// it is a non-pure predicate.
1249 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout *DL) {
1250 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1251 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
1252 for (User *U : AI->users()) {
1253 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1254 if (!LI->isSimple())
1259 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1260 if (SI->getOperand(0) == AI || !SI->isSimple())
1261 return false; // Don't allow a store OF the AI, only INTO the AI.
1265 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1266 // If the condition being selected on is a constant, fold the select, yes
1267 // this does (rarely) happen early on.
1268 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1269 Value *Result = SI->getOperand(1+CI->isZero());
1270 SI->replaceAllUsesWith(Result);
1271 SI->eraseFromParent();
1273 // This is very rare and we just scrambled the use list of AI, start
1275 return tryToMakeAllocaBePromotable(AI, DL);
1278 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1279 // loads, then we can transform this by rewriting the select.
1280 if (!isSafeSelectToSpeculate(SI, DL))
1283 InstsToRewrite.insert(SI);
1287 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1288 if (PN->use_empty()) { // Dead PHIs can be stripped.
1289 InstsToRewrite.insert(PN);
1293 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1294 // in the pred blocks, then we can transform this by rewriting the PHI.
1295 if (!isSafePHIToSpeculate(PN, DL))
1298 InstsToRewrite.insert(PN);
1302 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1303 if (onlyUsedByLifetimeMarkers(BCI)) {
1304 InstsToRewrite.insert(BCI);
1312 // If there are no instructions to rewrite, then all uses are load/stores and
1314 if (InstsToRewrite.empty())
1317 // If we have instructions that need to be rewritten for this to be promotable
1318 // take care of it now.
1319 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
1320 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1321 // This could only be a bitcast used by nothing but lifetime intrinsics.
1322 for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
1324 cast<Instruction>(*I++)->eraseFromParent();
1325 BCI->eraseFromParent();
1329 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1330 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1331 // loads with a new select.
1332 while (!SI->use_empty()) {
1333 LoadInst *LI = cast<LoadInst>(SI->user_back());
1335 IRBuilder<> Builder(LI);
1336 LoadInst *TrueLoad =
1337 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
1338 LoadInst *FalseLoad =
1339 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
1341 // Transfer alignment and AA info if present.
1342 TrueLoad->setAlignment(LI->getAlignment());
1343 FalseLoad->setAlignment(LI->getAlignment());
1346 LI->getAAMetadata(Tags);
1348 TrueLoad->setAAMetadata(Tags);
1349 FalseLoad->setAAMetadata(Tags);
1352 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1354 LI->replaceAllUsesWith(V);
1355 LI->eraseFromParent();
1358 // Now that all the loads are gone, the select is gone too.
1359 SI->eraseFromParent();
1363 // Otherwise, we have a PHI node which allows us to push the loads into the
1365 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1366 if (PN->use_empty()) {
1367 PN->eraseFromParent();
1371 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
1372 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1373 PN->getName()+".ld", PN);
1375 // Get the AA tags and alignment to use from one of the loads. It doesn't
1376 // matter which one we get and if any differ, it doesn't matter.
1377 LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
1380 SomeLoad->getAAMetadata(AATags);
1381 unsigned Align = SomeLoad->getAlignment();
1383 // Rewrite all loads of the PN to use the new PHI.
1384 while (!PN->use_empty()) {
1385 LoadInst *LI = cast<LoadInst>(PN->user_back());
1386 LI->replaceAllUsesWith(NewPN);
1387 LI->eraseFromParent();
1390 // Inject loads into all of the pred blocks. Keep track of which blocks we
1391 // insert them into in case we have multiple edges from the same block.
1392 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
1394 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1395 BasicBlock *Pred = PN->getIncomingBlock(i);
1396 LoadInst *&Load = InsertedLoads[Pred];
1398 Load = new LoadInst(PN->getIncomingValue(i),
1399 PN->getName() + "." + Pred->getName(),
1400 Pred->getTerminator());
1401 Load->setAlignment(Align);
1402 if (AATags) Load->setAAMetadata(AATags);
1405 NewPN->addIncoming(Load, Pred);
1408 PN->eraseFromParent();
1415 bool SROA::performPromotion(Function &F) {
1416 std::vector<AllocaInst*> Allocas;
1417 DominatorTree *DT = nullptr;
1419 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1420 AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
1422 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
1423 DIBuilder DIB(*F.getParent());
1424 bool Changed = false;
1425 SmallVector<Instruction*, 64> Insts;
1429 // Find allocas that are safe to promote, by looking at all instructions in
1431 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1432 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
1433 if (tryToMakeAllocaBePromotable(AI, DL))
1434 Allocas.push_back(AI);
1436 if (Allocas.empty()) break;
1439 PromoteMemToReg(Allocas, *DT, nullptr, AT);
1442 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1443 AllocaInst *AI = Allocas[i];
1445 // Build list of instructions to promote.
1446 for (User *U : AI->users())
1447 Insts.push_back(cast<Instruction>(U));
1448 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
1452 NumPromoted += Allocas.size();
1460 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1461 /// SROA. It must be a struct or array type with a small number of elements.
1462 bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
1463 Type *T = AI->getAllocatedType();
1464 // Do not promote any struct that has too many members.
1465 if (StructType *ST = dyn_cast<StructType>(T))
1466 return ST->getNumElements() <= StructMemberThreshold;
1467 // Do not promote any array that has too many elements.
1468 if (ArrayType *AT = dyn_cast<ArrayType>(T))
1469 return AT->getNumElements() <= ArrayElementThreshold;
1473 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
1474 // which runs on all of the alloca instructions in the entry block, removing
1475 // them if they are only used by getelementptr instructions.
1477 bool SROA::performScalarRepl(Function &F) {
1478 std::vector<AllocaInst*> WorkList;
1480 // Scan the entry basic block, adding allocas to the worklist.
1481 BasicBlock &BB = F.getEntryBlock();
1482 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
1483 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
1484 WorkList.push_back(A);
1486 // Process the worklist
1487 bool Changed = false;
1488 while (!WorkList.empty()) {
1489 AllocaInst *AI = WorkList.back();
1490 WorkList.pop_back();
1492 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1493 // with unused elements.
1494 if (AI->use_empty()) {
1495 AI->eraseFromParent();
1500 // If this alloca is impossible for us to promote, reject it early.
1501 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1504 // Check to see if we can perform the core SROA transformation. We cannot
1505 // transform the allocation instruction if it is an array allocation
1506 // (allocations OF arrays are ok though), and an allocation of a scalar
1507 // value cannot be decomposed at all.
1508 uint64_t AllocaSize = DL->getTypeAllocSize(AI->getAllocatedType());
1510 // Do not promote [0 x %struct].
1511 if (AllocaSize == 0) continue;
1513 // Do not promote any struct whose size is too big.
1514 if (AllocaSize > SRThreshold) continue;
1516 // If the alloca looks like a good candidate for scalar replacement, and if
1517 // all its users can be transformed, then split up the aggregate into its
1518 // separate elements.
1519 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1520 DoScalarReplacement(AI, WorkList);
1525 // If we can turn this aggregate value (potentially with casts) into a
1526 // simple scalar value that can be mem2reg'd into a register value.
1527 // IsNotTrivial tracks whether this is something that mem2reg could have
1528 // promoted itself. If so, we don't want to transform it needlessly. Note
1529 // that we can't just check based on the type: the alloca may be of an i32
1530 // but that has pointer arithmetic to set byte 3 of it or something.
1531 if (AllocaInst *NewAI = ConvertToScalarInfo(
1532 (unsigned)AllocaSize, *DL, ScalarLoadThreshold).TryConvert(AI)) {
1533 NewAI->takeName(AI);
1534 AI->eraseFromParent();
1540 // Otherwise, couldn't process this alloca.
1546 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1547 /// predicate, do SROA now.
1548 void SROA::DoScalarReplacement(AllocaInst *AI,
1549 std::vector<AllocaInst*> &WorkList) {
1550 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
1551 SmallVector<AllocaInst*, 32> ElementAllocas;
1552 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
1553 ElementAllocas.reserve(ST->getNumContainedTypes());
1554 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
1555 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
1557 AI->getName() + "." + Twine(i), AI);
1558 ElementAllocas.push_back(NA);
1559 WorkList.push_back(NA); // Add to worklist for recursive processing
1562 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
1563 ElementAllocas.reserve(AT->getNumElements());
1564 Type *ElTy = AT->getElementType();
1565 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1566 AllocaInst *NA = new AllocaInst(ElTy, nullptr, AI->getAlignment(),
1567 AI->getName() + "." + Twine(i), AI);
1568 ElementAllocas.push_back(NA);
1569 WorkList.push_back(NA); // Add to worklist for recursive processing
1573 // Now that we have created the new alloca instructions, rewrite all the
1574 // uses of the old alloca.
1575 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
1577 // Now erase any instructions that were made dead while rewriting the alloca.
1578 DeleteDeadInstructions();
1579 AI->eraseFromParent();
1584 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1585 /// recursively including all their operands that become trivially dead.
1586 void SROA::DeleteDeadInstructions() {
1587 while (!DeadInsts.empty()) {
1588 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
1590 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1591 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1592 // Zero out the operand and see if it becomes trivially dead.
1593 // (But, don't add allocas to the dead instruction list -- they are
1594 // already on the worklist and will be deleted separately.)
1596 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1597 DeadInsts.push_back(U);
1600 I->eraseFromParent();
1604 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1605 /// performing scalar replacement of alloca AI. The results are flagged in
1606 /// the Info parameter. Offset indicates the position within AI that is
1607 /// referenced by this instruction.
1608 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
1610 for (Use &U : I->uses()) {
1611 Instruction *User = cast<Instruction>(U.getUser());
1613 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1614 isSafeForScalarRepl(BC, Offset, Info);
1615 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1616 uint64_t GEPOffset = Offset;
1617 isSafeGEP(GEPI, GEPOffset, Info);
1619 isSafeForScalarRepl(GEPI, GEPOffset, Info);
1620 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1621 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1622 if (!Length || Length->isNegative())
1623 return MarkUnsafe(Info, User);
1625 isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
1626 U.getOperandNo() == 0, Info, MI,
1627 true /*AllowWholeAccess*/);
1628 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1629 if (!LI->isSimple())
1630 return MarkUnsafe(Info, User);
1631 Type *LIType = LI->getType();
1632 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
1633 LIType, false, Info, LI, true /*AllowWholeAccess*/);
1634 Info.hasALoadOrStore = true;
1636 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1637 // Store is ok if storing INTO the pointer, not storing the pointer
1638 if (!SI->isSimple() || SI->getOperand(0) == I)
1639 return MarkUnsafe(Info, User);
1641 Type *SIType = SI->getOperand(0)->getType();
1642 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
1643 SIType, true, Info, SI, true /*AllowWholeAccess*/);
1644 Info.hasALoadOrStore = true;
1645 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1646 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1647 II->getIntrinsicID() != Intrinsic::lifetime_end)
1648 return MarkUnsafe(Info, User);
1649 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1650 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1652 return MarkUnsafe(Info, User);
1654 if (Info.isUnsafe) return;
1659 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1660 /// derived from the alloca, we can often still split the alloca into elements.
1661 /// This is useful if we have a large alloca where one element is phi'd
1662 /// together somewhere: we can SRoA and promote all the other elements even if
1663 /// we end up not being able to promote this one.
1665 /// All we require is that the uses of the PHI do not index into other parts of
1666 /// the alloca. The most important use case for this is single load and stores
1667 /// that are PHI'd together, which can happen due to code sinking.
1668 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1670 // If we've already checked this PHI, don't do it again.
1671 if (PHINode *PN = dyn_cast<PHINode>(I))
1672 if (!Info.CheckedPHIs.insert(PN))
1675 for (User *U : I->users()) {
1676 Instruction *UI = cast<Instruction>(U);
1678 if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
1679 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
1680 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
1681 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1682 // but would have to prove that we're staying inside of an element being
1684 if (!GEPI->hasAllZeroIndices())
1685 return MarkUnsafe(Info, UI);
1686 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
1687 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
1688 if (!LI->isSimple())
1689 return MarkUnsafe(Info, UI);
1690 Type *LIType = LI->getType();
1691 isSafeMemAccess(Offset, DL->getTypeAllocSize(LIType),
1692 LIType, false, Info, LI, false /*AllowWholeAccess*/);
1693 Info.hasALoadOrStore = true;
1695 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1696 // Store is ok if storing INTO the pointer, not storing the pointer
1697 if (!SI->isSimple() || SI->getOperand(0) == I)
1698 return MarkUnsafe(Info, UI);
1700 Type *SIType = SI->getOperand(0)->getType();
1701 isSafeMemAccess(Offset, DL->getTypeAllocSize(SIType),
1702 SIType, true, Info, SI, false /*AllowWholeAccess*/);
1703 Info.hasALoadOrStore = true;
1704 } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
1705 isSafePHISelectUseForScalarRepl(UI, Offset, Info);
1707 return MarkUnsafe(Info, UI);
1709 if (Info.isUnsafe) return;
1713 /// isSafeGEP - Check if a GEP instruction can be handled for scalar
1714 /// replacement. It is safe when all the indices are constant, in-bounds
1715 /// references, and when the resulting offset corresponds to an element within
1716 /// the alloca type. The results are flagged in the Info parameter. Upon
1717 /// return, Offset is adjusted as specified by the GEP indices.
1718 void SROA::isSafeGEP(GetElementPtrInst *GEPI,
1719 uint64_t &Offset, AllocaInfo &Info) {
1720 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1723 bool NonConstant = false;
1724 unsigned NonConstantIdxSize = 0;
1726 // Walk through the GEP type indices, checking the types that this indexes
1728 for (; GEPIt != E; ++GEPIt) {
1729 // Ignore struct elements, no extra checking needed for these.
1730 if ((*GEPIt)->isStructTy())
1733 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
1735 return MarkUnsafe(Info, GEPI);
1738 // Compute the offset due to this GEP and check if the alloca has a
1739 // component element at that offset.
1740 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
1741 // If this GEP is non-constant then the last operand must have been a
1742 // dynamic index into a vector. Pop this now as it has no impact on the
1743 // constant part of the offset.
1746 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1747 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset,
1748 NonConstantIdxSize))
1749 MarkUnsafe(Info, GEPI);
1752 /// isHomogeneousAggregate - Check if type T is a struct or array containing
1753 /// elements of the same type (which is always true for arrays). If so,
1754 /// return true with NumElts and EltTy set to the number of elements and the
1755 /// element type, respectively.
1756 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1758 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1759 NumElts = AT->getNumElements();
1760 EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
1763 if (StructType *ST = dyn_cast<StructType>(T)) {
1764 NumElts = ST->getNumContainedTypes();
1765 EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
1766 for (unsigned n = 1; n < NumElts; ++n) {
1767 if (ST->getContainedType(n) != EltTy)
1775 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1776 /// "homogeneous" aggregates with the same element type and number of elements.
1777 static bool isCompatibleAggregate(Type *T1, Type *T2) {
1781 unsigned NumElts1, NumElts2;
1782 Type *EltTy1, *EltTy2;
1783 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1784 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1785 NumElts1 == NumElts2 &&
1792 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1793 /// alloca or has an offset and size that corresponds to a component element
1794 /// within it. The offset checked here may have been formed from a GEP with a
1795 /// pointer bitcasted to a different type.
1797 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1798 /// unit. If false, it only allows accesses known to be in a single element.
1799 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
1800 Type *MemOpType, bool isStore,
1801 AllocaInfo &Info, Instruction *TheAccess,
1802 bool AllowWholeAccess) {
1803 // Check if this is a load/store of the entire alloca.
1804 if (Offset == 0 && AllowWholeAccess &&
1805 MemSize == DL->getTypeAllocSize(Info.AI->getAllocatedType())) {
1806 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1807 // loads/stores (which are essentially the same as the MemIntrinsics with
1808 // regard to copying padding between elements). But, if an alloca is
1809 // flagged as both a source and destination of such operations, we'll need
1810 // to check later for padding between elements.
1811 if (!MemOpType || MemOpType->isIntegerTy()) {
1813 Info.isMemCpyDst = true;
1815 Info.isMemCpySrc = true;
1818 // This is also safe for references using a type that is compatible with
1819 // the type of the alloca, so that loads/stores can be rewritten using
1820 // insertvalue/extractvalue.
1821 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
1822 Info.hasSubelementAccess = true;
1826 // Check if the offset/size correspond to a component within the alloca type.
1827 Type *T = Info.AI->getAllocatedType();
1828 if (TypeHasComponent(T, Offset, MemSize)) {
1829 Info.hasSubelementAccess = true;
1833 return MarkUnsafe(Info, TheAccess);
1836 /// TypeHasComponent - Return true if T has a component type with the
1837 /// specified offset and size. If Size is zero, do not check the size.
1838 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) {
1841 if (StructType *ST = dyn_cast<StructType>(T)) {
1842 const StructLayout *Layout = DL->getStructLayout(ST);
1843 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1844 EltTy = ST->getContainedType(EltIdx);
1845 EltSize = DL->getTypeAllocSize(EltTy);
1846 Offset -= Layout->getElementOffset(EltIdx);
1847 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
1848 EltTy = AT->getElementType();
1849 EltSize = DL->getTypeAllocSize(EltTy);
1850 if (Offset >= AT->getNumElements() * EltSize)
1853 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1854 EltTy = VT->getElementType();
1855 EltSize = DL->getTypeAllocSize(EltTy);
1856 if (Offset >= VT->getNumElements() * EltSize)
1862 if (Offset == 0 && (Size == 0 || EltSize == Size))
1864 // Check if the component spans multiple elements.
1865 if (Offset + Size > EltSize)
1867 return TypeHasComponent(EltTy, Offset, Size);
1870 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1871 /// the instruction I, which references it, to use the separate elements.
1872 /// Offset indicates the position within AI that is referenced by this
1874 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
1875 SmallVectorImpl<AllocaInst *> &NewElts) {
1876 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
1877 Use &TheUse = *UI++;
1878 Instruction *User = cast<Instruction>(TheUse.getUser());
1880 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1881 RewriteBitCast(BC, AI, Offset, NewElts);
1885 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1886 RewriteGEP(GEPI, AI, Offset, NewElts);
1890 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
1891 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1892 uint64_t MemSize = Length->getZExtValue();
1894 MemSize == DL->getTypeAllocSize(AI->getAllocatedType()))
1895 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
1896 // Otherwise the intrinsic can only touch a single element and the
1897 // address operand will be updated, so nothing else needs to be done.
1901 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1902 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1903 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1904 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1909 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1910 Type *LIType = LI->getType();
1912 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
1914 // %res = load { i32, i32 }* %alloc
1916 // %load.0 = load i32* %alloc.0
1917 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1918 // %load.1 = load i32* %alloc.1
1919 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1920 // (Also works for arrays instead of structs)
1921 Value *Insert = UndefValue::get(LIType);
1922 IRBuilder<> Builder(LI);
1923 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1924 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1925 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
1927 LI->replaceAllUsesWith(Insert);
1928 DeadInsts.push_back(LI);
1929 } else if (LIType->isIntegerTy() &&
1930 DL->getTypeAllocSize(LIType) ==
1931 DL->getTypeAllocSize(AI->getAllocatedType())) {
1932 // If this is a load of the entire alloca to an integer, rewrite it.
1933 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1938 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1939 Value *Val = SI->getOperand(0);
1940 Type *SIType = Val->getType();
1941 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
1943 // store { i32, i32 } %val, { i32, i32 }* %alloc
1945 // %val.0 = extractvalue { i32, i32 } %val, 0
1946 // store i32 %val.0, i32* %alloc.0
1947 // %val.1 = extractvalue { i32, i32 } %val, 1
1948 // store i32 %val.1, i32* %alloc.1
1949 // (Also works for arrays instead of structs)
1950 IRBuilder<> Builder(SI);
1951 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1952 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1953 Builder.CreateStore(Extract, NewElts[i]);
1955 DeadInsts.push_back(SI);
1956 } else if (SIType->isIntegerTy() &&
1957 DL->getTypeAllocSize(SIType) ==
1958 DL->getTypeAllocSize(AI->getAllocatedType())) {
1959 // If this is a store of the entire alloca from an integer, rewrite it.
1960 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1965 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
1966 // If we have a PHI user of the alloca itself (as opposed to a GEP or
1967 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1969 if (!isa<AllocaInst>(I)) continue;
1971 assert(Offset == 0 && NewElts[0] &&
1972 "Direct alloca use should have a zero offset");
1974 // If we have a use of the alloca, we know the derived uses will be
1975 // utilizing just the first element of the scalarized result. Insert a
1976 // bitcast of the first alloca before the user as required.
1977 AllocaInst *NewAI = NewElts[0];
1978 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1979 NewAI->moveBefore(BCI);
1986 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1987 /// and recursively continue updating all of its uses.
1988 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
1989 SmallVectorImpl<AllocaInst *> &NewElts) {
1990 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1991 if (BC->getOperand(0) != AI)
1994 // The bitcast references the original alloca. Replace its uses with
1995 // references to the alloca containing offset zero (which is normally at
1996 // index zero, but might not be in cases involving structs with elements
1998 Type *T = AI->getAllocatedType();
1999 uint64_t EltOffset = 0;
2001 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2002 Instruction *Val = NewElts[Idx];
2003 if (Val->getType() != BC->getDestTy()) {
2004 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2007 BC->replaceAllUsesWith(Val);
2008 DeadInsts.push_back(BC);
2011 /// FindElementAndOffset - Return the index of the element containing Offset
2012 /// within the specified type, which must be either a struct or an array.
2013 /// Sets T to the type of the element and Offset to the offset within that
2014 /// element. IdxTy is set to the type of the index result to be used in a
2015 /// GEP instruction.
2016 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset,
2019 if (StructType *ST = dyn_cast<StructType>(T)) {
2020 const StructLayout *Layout = DL->getStructLayout(ST);
2021 Idx = Layout->getElementContainingOffset(Offset);
2022 T = ST->getContainedType(Idx);
2023 Offset -= Layout->getElementOffset(Idx);
2024 IdxTy = Type::getInt32Ty(T->getContext());
2026 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2027 T = AT->getElementType();
2028 uint64_t EltSize = DL->getTypeAllocSize(T);
2029 Idx = Offset / EltSize;
2030 Offset -= Idx * EltSize;
2031 IdxTy = Type::getInt64Ty(T->getContext());
2034 VectorType *VT = cast<VectorType>(T);
2035 T = VT->getElementType();
2036 uint64_t EltSize = DL->getTypeAllocSize(T);
2037 Idx = Offset / EltSize;
2038 Offset -= Idx * EltSize;
2039 IdxTy = Type::getInt64Ty(T->getContext());
2043 /// RewriteGEP - Check if this GEP instruction moves the pointer across
2044 /// elements of the alloca that are being split apart, and if so, rewrite
2045 /// the GEP to be relative to the new element.
2046 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
2047 SmallVectorImpl<AllocaInst *> &NewElts) {
2048 uint64_t OldOffset = Offset;
2049 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
2050 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2051 // In this case, it must be the last GEP operand which is dynamic so keep that
2052 // aside until we've found the constant GEP offset then add it back in at the
2054 Value* NonConstantIdx = nullptr;
2055 if (!GEPI->hasAllConstantIndices())
2056 NonConstantIdx = Indices.pop_back_val();
2057 Offset += DL->getIndexedOffset(GEPI->getPointerOperandType(), Indices);
2059 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2061 Type *T = AI->getAllocatedType();
2063 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
2064 if (GEPI->getOperand(0) == AI)
2065 OldIdx = ~0ULL; // Force the GEP to be rewritten.
2067 T = AI->getAllocatedType();
2068 uint64_t EltOffset = Offset;
2069 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
2071 // If this GEP does not move the pointer across elements of the alloca
2072 // being split, then it does not needs to be rewritten.
2076 Type *i32Ty = Type::getInt32Ty(AI->getContext());
2077 SmallVector<Value*, 8> NewArgs;
2078 NewArgs.push_back(Constant::getNullValue(i32Ty));
2079 while (EltOffset != 0) {
2080 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
2081 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
2083 if (NonConstantIdx) {
2085 // This GEP has a dynamic index. We need to add "i32 0" to index through
2086 // any structs or arrays in the original type until we get to the vector
2088 while (!isa<VectorType>(GepTy)) {
2089 NewArgs.push_back(Constant::getNullValue(i32Ty));
2090 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2092 NewArgs.push_back(NonConstantIdx);
2094 Instruction *Val = NewElts[Idx];
2095 if (NewArgs.size() > 1) {
2096 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
2097 Val->takeName(GEPI);
2099 if (Val->getType() != GEPI->getType())
2100 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
2101 GEPI->replaceAllUsesWith(Val);
2102 DeadInsts.push_back(GEPI);
2105 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2106 /// to mark the lifetime of the scalarized memory.
2107 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2109 SmallVectorImpl<AllocaInst *> &NewElts) {
2110 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2111 // Put matching lifetime markers on everything from Offset up to
2113 Type *AIType = AI->getAllocatedType();
2114 uint64_t NewOffset = Offset;
2116 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy);
2118 IRBuilder<> Builder(II);
2119 uint64_t Size = OldSize->getLimitedValue();
2122 // Splice the first element and index 'NewOffset' bytes in. SROA will
2123 // split the alloca again later.
2124 unsigned AS = AI->getType()->getAddressSpace();
2125 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
2126 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset));
2128 IdxTy = NewElts[Idx]->getAllocatedType();
2129 uint64_t EltSize = DL->getTypeAllocSize(IdxTy) - NewOffset;
2130 if (EltSize > Size) {
2136 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2137 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2139 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2143 for (; Idx != NewElts.size() && Size; ++Idx) {
2144 IdxTy = NewElts[Idx]->getAllocatedType();
2145 uint64_t EltSize = DL->getTypeAllocSize(IdxTy);
2146 if (EltSize > Size) {
2152 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2153 Builder.CreateLifetimeStart(NewElts[Idx],
2154 Builder.getInt64(EltSize));
2156 Builder.CreateLifetimeEnd(NewElts[Idx],
2157 Builder.getInt64(EltSize));
2159 DeadInsts.push_back(II);
2162 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2163 /// Rewrite it to copy or set the elements of the scalarized memory.
2165 SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2167 SmallVectorImpl<AllocaInst *> &NewElts) {
2168 // If this is a memcpy/memmove, construct the other pointer as the
2169 // appropriate type. The "Other" pointer is the pointer that goes to memory
2170 // that doesn't have anything to do with the alloca that we are promoting. For
2171 // memset, this Value* stays null.
2172 Value *OtherPtr = nullptr;
2173 unsigned MemAlignment = MI->getAlignment();
2174 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
2175 if (Inst == MTI->getRawDest())
2176 OtherPtr = MTI->getRawSource();
2178 assert(Inst == MTI->getRawSource());
2179 OtherPtr = MTI->getRawDest();
2183 // If there is an other pointer, we want to convert it to the same pointer
2184 // type as AI has, so we can GEP through it safely.
2186 unsigned AddrSpace =
2187 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
2189 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2190 // optimization, but it's also required to detect the corner case where
2191 // both pointer operands are referencing the same memory, and where
2192 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2193 // function is only called for mem intrinsics that access the whole
2194 // aggregate, so non-zero GEPs are not an issue here.)
2195 OtherPtr = OtherPtr->stripPointerCasts();
2197 // Copying the alloca to itself is a no-op: just delete it.
2198 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2199 // This code will run twice for a no-op memcpy -- once for each operand.
2200 // Put only one reference to MI on the DeadInsts list.
2201 for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
2202 E = DeadInsts.end(); I != E; ++I)
2203 if (*I == MI) return;
2204 DeadInsts.push_back(MI);
2208 // If the pointer is not the right type, insert a bitcast to the right
2211 PointerType::get(AI->getType()->getElementType(), AddrSpace);
2213 if (OtherPtr->getType() != NewTy)
2214 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
2217 // Process each element of the aggregate.
2218 bool SROADest = MI->getRawDest() == Inst;
2220 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
2222 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2223 // If this is a memcpy/memmove, emit a GEP of the other element address.
2224 Value *OtherElt = nullptr;
2225 unsigned OtherEltAlign = MemAlignment;
2228 Value *Idx[2] = { Zero,
2229 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
2230 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
2231 OtherPtr->getName()+"."+Twine(i),
2234 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
2235 Type *OtherTy = OtherPtrTy->getElementType();
2236 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
2237 EltOffset = DL->getStructLayout(ST)->getElementOffset(i);
2239 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
2240 EltOffset = DL->getTypeAllocSize(EltTy)*i;
2243 // The alignment of the other pointer is the guaranteed alignment of the
2244 // element, which is affected by both the known alignment of the whole
2245 // mem intrinsic and the alignment of the element. If the alignment of
2246 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2247 // known alignment is just 4 bytes.
2248 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
2251 Value *EltPtr = NewElts[i];
2252 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
2254 // If we got down to a scalar, insert a load or store as appropriate.
2255 if (EltTy->isSingleValueType()) {
2256 if (isa<MemTransferInst>(MI)) {
2258 // From Other to Alloca.
2259 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
2260 new StoreInst(Elt, EltPtr, MI);
2262 // From Alloca to Other.
2263 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
2264 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
2268 assert(isa<MemSetInst>(MI));
2270 // If the stored element is zero (common case), just store a null
2273 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
2275 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
2277 // If EltTy is a vector type, get the element type.
2278 Type *ValTy = EltTy->getScalarType();
2280 // Construct an integer with the right value.
2281 unsigned EltSize = DL->getTypeSizeInBits(ValTy);
2282 APInt OneVal(EltSize, CI->getZExtValue());
2283 APInt TotalVal(OneVal);
2285 for (unsigned i = 0; 8*i < EltSize; ++i) {
2286 TotalVal = TotalVal.shl(8);
2290 // Convert the integer value to the appropriate type.
2291 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
2292 if (ValTy->isPointerTy())
2293 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
2294 else if (ValTy->isFloatingPointTy())
2295 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
2296 assert(StoreVal->getType() == ValTy && "Type mismatch!");
2298 // If the requested value was a vector constant, create it.
2299 if (EltTy->isVectorTy()) {
2300 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
2301 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
2304 new StoreInst(StoreVal, EltPtr, MI);
2307 // Otherwise, if we're storing a byte variable, use a memset call for
2311 unsigned EltSize = DL->getTypeAllocSize(EltTy);
2315 IRBuilder<> Builder(MI);
2317 // Finally, insert the meminst for this element.
2318 if (isa<MemSetInst>(MI)) {
2319 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2322 assert(isa<MemTransferInst>(MI));
2323 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2324 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
2326 if (isa<MemCpyInst>(MI))
2327 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
2329 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
2332 DeadInsts.push_back(MI);
2335 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
2336 /// overwrites the entire allocation. Extract out the pieces of the stored
2337 /// integer and store them individually.
2339 SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2340 SmallVectorImpl<AllocaInst *> &NewElts) {
2341 // Extract each element out of the integer according to its structure offset
2342 // and store the element value to the individual alloca.
2343 Value *SrcVal = SI->getOperand(0);
2344 Type *AllocaEltTy = AI->getAllocatedType();
2345 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
2347 IRBuilder<> Builder(SI);
2349 // Handle tail padding by extending the operand
2350 if (DL->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
2351 SrcVal = Builder.CreateZExt(SrcVal,
2352 IntegerType::get(SI->getContext(), AllocaSizeBits));
2354 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
2357 // There are two forms here: AI could be an array or struct. Both cases
2358 // have different ways to compute the element offset.
2359 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2360 const StructLayout *Layout = DL->getStructLayout(EltSTy);
2362 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2363 // Get the number of bits to shift SrcVal to get the value.
2364 Type *FieldTy = EltSTy->getElementType(i);
2365 uint64_t Shift = Layout->getElementOffsetInBits(i);
2367 if (DL->isBigEndian())
2368 Shift = AllocaSizeBits-Shift-DL->getTypeAllocSizeInBits(FieldTy);
2370 Value *EltVal = SrcVal;
2372 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2373 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2376 // Truncate down to an integer of the right size.
2377 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
2379 // Ignore zero sized fields like {}, they obviously contain no data.
2380 if (FieldSizeBits == 0) continue;
2382 if (FieldSizeBits != AllocaSizeBits)
2383 EltVal = Builder.CreateTrunc(EltVal,
2384 IntegerType::get(SI->getContext(), FieldSizeBits));
2385 Value *DestField = NewElts[i];
2386 if (EltVal->getType() == FieldTy) {
2387 // Storing to an integer field of this size, just do it.
2388 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
2389 // Bitcast to the right element type (for fp/vector values).
2390 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
2392 // Otherwise, bitcast the dest pointer (for aggregates).
2393 DestField = Builder.CreateBitCast(DestField,
2394 PointerType::getUnqual(EltVal->getType()));
2396 new StoreInst(EltVal, DestField, SI);
2400 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2401 Type *ArrayEltTy = ATy->getElementType();
2402 uint64_t ElementOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
2403 uint64_t ElementSizeBits = DL->getTypeSizeInBits(ArrayEltTy);
2407 if (DL->isBigEndian())
2408 Shift = AllocaSizeBits-ElementOffset;
2412 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2413 // Ignore zero sized fields like {}, they obviously contain no data.
2414 if (ElementSizeBits == 0) continue;
2416 Value *EltVal = SrcVal;
2418 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
2419 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
2422 // Truncate down to an integer of the right size.
2423 if (ElementSizeBits != AllocaSizeBits)
2424 EltVal = Builder.CreateTrunc(EltVal,
2425 IntegerType::get(SI->getContext(),
2427 Value *DestField = NewElts[i];
2428 if (EltVal->getType() == ArrayEltTy) {
2429 // Storing to an integer field of this size, just do it.
2430 } else if (ArrayEltTy->isFloatingPointTy() ||
2431 ArrayEltTy->isVectorTy()) {
2432 // Bitcast to the right element type (for fp/vector values).
2433 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
2435 // Otherwise, bitcast the dest pointer (for aggregates).
2436 DestField = Builder.CreateBitCast(DestField,
2437 PointerType::getUnqual(EltVal->getType()));
2439 new StoreInst(EltVal, DestField, SI);
2441 if (DL->isBigEndian())
2442 Shift -= ElementOffset;
2444 Shift += ElementOffset;
2448 DeadInsts.push_back(SI);
2451 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
2452 /// an integer. Load the individual pieces to form the aggregate value.
2454 SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2455 SmallVectorImpl<AllocaInst *> &NewElts) {
2456 // Extract each element out of the NewElts according to its structure offset
2457 // and form the result value.
2458 Type *AllocaEltTy = AI->getAllocatedType();
2459 uint64_t AllocaSizeBits = DL->getTypeAllocSizeInBits(AllocaEltTy);
2461 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
2464 // There are two forms here: AI could be an array or struct. Both cases
2465 // have different ways to compute the element offset.
2466 const StructLayout *Layout = nullptr;
2467 uint64_t ArrayEltBitOffset = 0;
2468 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
2469 Layout = DL->getStructLayout(EltSTy);
2471 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
2472 ArrayEltBitOffset = DL->getTypeAllocSizeInBits(ArrayEltTy);
2476 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
2478 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2479 // Load the value from the alloca. If the NewElt is an aggregate, cast
2480 // the pointer to an integer of the same size before doing the load.
2481 Value *SrcField = NewElts[i];
2483 cast<PointerType>(SrcField->getType())->getElementType();
2484 uint64_t FieldSizeBits = DL->getTypeSizeInBits(FieldTy);
2486 // Ignore zero sized fields like {}, they obviously contain no data.
2487 if (FieldSizeBits == 0) continue;
2489 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
2491 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2492 !FieldTy->isVectorTy())
2493 SrcField = new BitCastInst(SrcField,
2494 PointerType::getUnqual(FieldIntTy),
2496 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2498 // If SrcField is a fp or vector of the right size but that isn't an
2499 // integer type, bitcast to an integer so we can shift it.
2500 if (SrcField->getType() != FieldIntTy)
2501 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2503 // Zero extend the field to be the same size as the final alloca so that
2504 // we can shift and insert it.
2505 if (SrcField->getType() != ResultVal->getType())
2506 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
2508 // Determine the number of bits to shift SrcField.
2510 if (Layout) // Struct case.
2511 Shift = Layout->getElementOffsetInBits(i);
2513 Shift = i*ArrayEltBitOffset;
2515 if (DL->isBigEndian())
2516 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
2519 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
2520 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2523 // Don't create an 'or x, 0' on the first iteration.
2524 if (!isa<Constant>(ResultVal) ||
2525 !cast<Constant>(ResultVal)->isNullValue())
2526 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2528 ResultVal = SrcField;
2531 // Handle tail padding by truncating the result
2532 if (DL->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
2533 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2535 LI->replaceAllUsesWith(ResultVal);
2536 DeadInsts.push_back(LI);
2539 /// HasPadding - Return true if the specified type has any structure or
2540 /// alignment padding in between the elements that would be split apart
2541 /// by SROA; return false otherwise.
2542 static bool HasPadding(Type *Ty, const DataLayout &DL) {
2543 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2544 Ty = ATy->getElementType();
2545 return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
2548 // SROA currently handles only Arrays and Structs.
2549 StructType *STy = cast<StructType>(Ty);
2550 const StructLayout *SL = DL.getStructLayout(STy);
2551 unsigned PrevFieldBitOffset = 0;
2552 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2553 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2555 // Check to see if there is any padding between this element and the
2558 unsigned PrevFieldEnd =
2559 PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
2560 if (PrevFieldEnd < FieldBitOffset)
2563 PrevFieldBitOffset = FieldBitOffset;
2565 // Check for tail padding.
2566 if (unsigned EltCount = STy->getNumElements()) {
2567 unsigned PrevFieldEnd = PrevFieldBitOffset +
2568 DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
2569 if (PrevFieldEnd < SL->getSizeInBits())
2575 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2576 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2577 /// or 1 if safe after canonicalization has been performed.
2578 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
2579 // Loop over the use list of the alloca. We can only transform it if all of
2580 // the users are safe to transform.
2581 AllocaInfo Info(AI);
2583 isSafeForScalarRepl(AI, 0, Info);
2584 if (Info.isUnsafe) {
2585 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
2589 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2590 // source and destination, we have to be careful. In particular, the memcpy
2591 // could be moving around elements that live in structure padding of the LLVM
2592 // types, but may actually be used. In these cases, we refuse to promote the
2594 if (Info.isMemCpySrc && Info.isMemCpyDst &&
2595 HasPadding(AI->getAllocatedType(), *DL))
2598 // If the alloca never has an access to just *part* of it, but is accessed
2599 // via loads and stores, then we should use ConvertToScalarInfo to promote
2600 // the alloca instead of promoting each piece at a time and inserting fission
2602 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2603 // If the struct/array just has one element, use basic SRoA.
2604 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
2605 if (ST->getNumElements() > 1) return false;
2607 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)