44 #include "llvm/Config/llvm-config.h" 102 using namespace llvm;
105 #define DEBUG_TYPE "sroa" 107 STATISTIC(NumAllocasAnalyzed,
"Number of allocas analyzed for replacement");
108 STATISTIC(NumAllocaPartitions,
"Number of alloca partitions formed");
109 STATISTIC(MaxPartitionsPerAlloca,
"Maximum number of partitions per alloca");
110 STATISTIC(NumAllocaPartitionUses,
"Number of alloca partition uses rewritten");
111 STATISTIC(MaxUsesPerAllocaPartition,
"Maximum number of uses of a partition");
112 STATISTIC(NumNewAllocas,
"Number of new, smaller allocas introduced");
113 STATISTIC(NumPromoted,
"Number of allocas promoted to SSA values");
114 STATISTIC(NumLoadsSpeculated,
"Number of loads speculated to allow promotion");
115 STATISTIC(NumDeleted,
"Number of instructions deleted");
116 STATISTIC(NumVectorized,
"Number of vectorized aggregates");
140 void SetNamePrefix(
const Twine &
P) { Prefix = P.
str(); }
161 uint64_t BeginOffset = 0;
164 uint64_t EndOffset = 0;
173 Slice(uint64_t BeginOffset, uint64_t EndOffset,
Use *U,
bool IsSplittable)
174 : BeginOffset(BeginOffset), EndOffset(EndOffset),
175 UseAndIsSplittable(U, IsSplittable) {}
177 uint64_t beginOffset()
const {
return BeginOffset; }
178 uint64_t endOffset()
const {
return EndOffset; }
180 bool isSplittable()
const {
return UseAndIsSplittable.
getInt(); }
181 void makeUnsplittable() { UseAndIsSplittable.
setInt(
false); }
183 Use *getUse()
const {
return UseAndIsSplittable.
getPointer(); }
185 bool isDead()
const {
return getUse() ==
nullptr; }
186 void kill() { UseAndIsSplittable.
setPointer(
nullptr); }
195 if (beginOffset() < RHS.beginOffset())
197 if (beginOffset() > RHS.beginOffset())
199 if (isSplittable() != RHS.isSplittable())
200 return !isSplittable();
201 if (endOffset() > RHS.endOffset())
208 uint64_t RHSOffset) {
209 return LHS.beginOffset() < RHSOffset;
213 return LHSOffset < RHS.beginOffset();
217 return isSplittable() == RHS.isSplittable() &&
218 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
267 int OldSize = Slices.size();
268 Slices.append(NewSlices.
begin(), NewSlices.
end());
269 auto SliceI = Slices.begin() + OldSize;
271 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
276 class partition_iterator;
290 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 302 template <
typename DerivedT,
typename RetT =
void>
class BuilderBase;
307 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 365 uint64_t BeginOffset = 0, EndOffset = 0;
375 Partition(iterator SI) : SI(SI), SJ(SI) {}
392 assert(BeginOffset < EndOffset &&
"Partitions must span some bytes!");
393 return EndOffset - BeginOffset;
398 bool empty()
const {
return SI == SJ; }
410 iterator
end()
const {
return SJ; }
444 uint64_t MaxSplitSliceEndOffset = 0;
461 "Cannot advance past the end of the slices!");
464 if (!P.SplitTails.
empty()) {
465 if (P.EndOffset >= MaxSplitSliceEndOffset) {
467 P.SplitTails.
clear();
468 MaxSplitSliceEndOffset = 0;
475 return S->endOffset() <=
481 return S->endOffset() == MaxSplitSliceEndOffset;
483 "Could not find the current max split slice offset!");
486 return S->endOffset() <= MaxSplitSliceEndOffset;
488 "Max split slice end offset is not actually the max!");
495 assert(P.SplitTails.
empty() &&
"Failed to clear the split slices!");
505 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
506 P.SplitTails.push_back(&S);
507 MaxSplitSliceEndOffset =
508 std::max(S.endOffset(), MaxSplitSliceEndOffset);
516 P.BeginOffset = P.EndOffset;
517 P.EndOffset = MaxSplitSliceEndOffset;
524 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
525 !P.SI->isSplittable()) {
526 P.BeginOffset = P.EndOffset;
527 P.EndOffset = P.SI->beginOffset();
537 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
538 P.EndOffset = P.SI->endOffset();
543 if (!P.SI->isSplittable()) {
546 assert(P.BeginOffset == P.SI->beginOffset());
550 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
551 if (!P.SJ->isSplittable())
552 P.EndOffset =
std::max(P.EndOffset, P.SJ->endOffset());
564 assert(P.SI->isSplittable() &&
"Forming a splittable partition!");
567 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
568 P.SJ->isSplittable()) {
569 P.EndOffset =
std::max(P.EndOffset, P.SJ->endOffset());
576 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
577 assert(!P.SJ->isSplittable());
578 P.EndOffset = P.SJ->beginOffset();
585 "End iterators don't match between compared partition iterators!");
592 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.
empty()) {
593 assert(P.SJ == RHS.P.SJ &&
594 "Same set of slices formed two different sized partitions!");
595 assert(P.SplitTails.size() == RHS.P.SplitTails.
size() &&
596 "Same slice position with differently sized non-empty split " 637 if (
PHINode *PN = dyn_cast<PHINode>(&I)) {
639 return PN->hasConstantValue();
654 const uint64_t AllocSize;
666 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
670 if (VisitedDeadInsts.
insert(&I).second)
671 AS.DeadUsers.push_back(&I);
675 bool IsSplittable =
false) {
678 if (Size == 0 || Offset.
uge(AllocSize)) {
679 LLVM_DEBUG(
dbgs() <<
"WARNING: Ignoring " << Size <<
" byte use @" 681 <<
" which has zero size or starts outside of the " 682 << AllocSize <<
" byte alloca:\n" 683 <<
" alloca: " << AS.AI <<
"\n" 684 <<
" use: " << I <<
"\n");
685 return markAsDead(I);
689 uint64_t EndOffset = BeginOffset +
Size;
697 assert(AllocSize >= BeginOffset);
698 if (Size > AllocSize - BeginOffset) {
699 LLVM_DEBUG(
dbgs() <<
"WARNING: Clamping a " << Size <<
" byte use @" 700 << Offset <<
" to remain within the " << AllocSize
702 <<
" alloca: " << AS.AI <<
"\n" 703 <<
" use: " << I <<
"\n");
704 EndOffset = AllocSize;
707 AS.Slices.
push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
712 return markAsDead(BC);
714 return Base::visitBitCastInst(BC);
719 return markAsDead(ASC);
721 return Base::visitAddrSpaceCastInst(ASC);
726 return markAsDead(GEPI);
746 if (
StructType *STy = GTI.getStructTypeOrNull()) {
762 if (GEPOffset.
ugt(AllocSize))
763 return markAsDead(GEPI);
767 return Base::visitGetElementPtrInst(GEPI);
777 insertUse(I, Offset, Size, IsSplittable);
782 "All simple FCA loads should have been pre-split");
785 return PI.setAborted(&LI);
789 return PI.setAborted(&LI);
791 uint64_t Size = DL.getTypeStoreSize(LI.
getType());
798 return PI.setEscapedAndAborted(&SI);
800 return PI.setAborted(&SI);
804 return PI.setAborted(&SI);
806 uint64_t Size = DL.getTypeStoreSize(ValOp->
getType());
815 if (Size > AllocSize || Offset.
ugt(AllocSize - Size)) {
816 LLVM_DEBUG(
dbgs() <<
"WARNING: Ignoring " << Size <<
" byte store @" 817 << Offset <<
" which extends past the end of the " 818 << AllocSize <<
" byte alloca:\n" 819 <<
" alloca: " << AS.AI <<
"\n" 820 <<
" use: " << SI <<
"\n");
821 return markAsDead(SI);
825 "All simple FCA stores should have been pre-split");
832 if ((Length && Length->getValue() == 0) ||
833 (IsOffsetKnown && Offset.
uge(AllocSize)))
835 return markAsDead(II);
838 return PI.setAborted(&II);
843 return PI.setAborted(&II);
852 if (Length && Length->
getValue() == 0)
854 return markAsDead(II);
858 if (VisitedDeadInsts.
count(&II))
862 return PI.setAborted(&II);
869 return PI.setAborted(&II);
876 if (Offset.
uge(AllocSize)) {
878 MemTransferSliceMap.
find(&II);
879 if (MTPI != MemTransferSliceMap.
end())
880 AS.Slices[MTPI->second].kill();
881 return markAsDead(II);
885 uint64_t Size = Length ? Length->
getLimitedValue() : AllocSize - RawOffset;
892 return markAsDead(II);
894 return insertUse(II, Offset, Size,
false);
901 std::tie(MTPI, Inserted) =
902 MemTransferSliceMap.
insert(std::make_pair(&II, AS.Slices.
size()));
903 unsigned PrevIdx = MTPI->second;
905 Slice &PrevP = AS.Slices[PrevIdx];
909 if (!II.
isVolatile() && PrevP.beginOffset() == RawOffset) {
911 return markAsDead(II);
916 PrevP.makeUnsplittable();
920 insertUse(II, Offset, Size, Inserted && Length);
923 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
924 "Map index doesn't point back to a slice with this user.");
932 return PI.setAborted(&II);
938 insertUse(II, Offset, Size,
true);
942 Base::visitIntrinsicInst(II);
953 Uses.
push_back(std::make_pair(cast<Instruction>(*U), Root));
962 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
967 if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
977 if (!
GEP->hasAllZeroIndices())
979 }
else if (!isa<BitCastInst>(I) && !isa<PHINode>(
I) &&
980 !isa<SelectInst>(I) && !isa<AddrSpaceCastInst>(
I)) {
985 if (Visited.
insert(cast<Instruction>(U)).second)
986 Uses.
push_back(std::make_pair(I, cast<Instruction>(U)));
987 }
while (!Uses.
empty());
993 assert(isa<PHINode>(I) || isa<SelectInst>(I));
995 return markAsDead(I);
1013 AS.DeadOperands.push_back(U);
1019 return PI.setAborted(&I);
1022 uint64_t &Size = PHIOrSelectSizes[&
I];
1025 if (
Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
1026 return PI.setAborted(UnsafeI);
1035 if (Offset.
uge(AllocSize)) {
1036 AS.DeadOperands.push_back(U);
1040 insertUse(I, Offset, Size);
1043 void visitPHINode(
PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1045 void visitSelectInst(
SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1048 void visitInstruction(
Instruction &I) { PI.setAborted(&I); }
1053 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1056 PointerEscapingInstr(
nullptr) {
1064 assert(PointerEscapingInstr &&
"Did not track a bad instruction");
1074 std::mt19937 MT(static_cast<unsigned>(
1076 std::shuffle(Slices.begin(), Slices.end(), MT);
1085 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1089 printSlice(OS, I, Indent);
1091 printUse(OS, I, Indent);
1096 OS << Indent <<
"[" << I->beginOffset() <<
"," << I->endOffset() <<
")" 1097 <<
" slice #" << (I -
begin())
1098 << (I->isSplittable() ?
" (splittable)" :
"");
1103 OS << Indent <<
" used by: " << *I->getUse()->getUser() <<
"\n";
1107 if (PointerEscapingInstr) {
1108 OS <<
"Can't analyze slices for alloca: " << AI <<
"\n" 1109 <<
" A pointer to this alloca escaped by:\n" 1110 <<
" " << *PointerEscapingInstr <<
"\n";
1114 OS <<
"Slices of alloca: " << AI <<
"\n";
1115 for (const_iterator I =
begin(),
E =
end(); I !=
E; ++
I)
1124 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1130 uint64_t EndOffset) {
1132 bool TyIsCommon =
true;
1138 Use *U = I->getUse();
1139 if (isa<IntrinsicInst>(*U->getUser()))
1141 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1144 Type *UserTy =
nullptr;
1145 if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1146 UserTy = LI->getType();
1147 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1148 UserTy = SI->getValueOperand()->getType();
1151 if (
IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1156 if (UserITy->getBitWidth() % 8 != 0 ||
1157 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1162 if (!ITy || ITy->
getBitWidth() < UserITy->getBitWidth())
1168 if (!UserTy || (Ty && Ty != UserTy))
1174 return TyIsCommon ? Ty : ITy;
1205 APInt MaxSize(APWidth, 0);
1206 bool HaveLoad =
false;
1221 if (BBI->mayWriteToMemory())
1226 MaxSize = MaxSize.
ult(Size) ?
APInt(APWidth, Size) : MaxSize;
1268 IRBuilderTy PHIBuilder(&PN);
1270 PN.
getName() +
".sroa.speculated");
1301 IRBuilderTy PredBuilder(TI);
1306 ++NumLoadsSpeculated;
1311 InjectedLoads[Pred] =
Load;
1358 IRBuilderTy IRB(&SI);
1366 IRB.SetInsertPoint(LI);
1368 LI->
getName() +
".sroa.speculate.load.true");
1370 LI->
getName() +
".sroa.speculate.load.false");
1371 NumLoadsSpeculated += 2;
1385 LI->
getName() +
".sroa.speculated");
1400 if (Indices.
empty())
1405 if (Indices.
size() == 1 && cast<ConstantInt>(Indices.
back())->
isZero())
1409 BasePtr, Indices, NamePrefix +
"sroa_idx");
1426 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1433 unsigned NumLayers = 0;
1434 Type *ElementTy = Ty;
1439 if (
ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1440 ElementTy = ArrayTy->getElementType();
1441 Indices.
push_back(IRB.getIntN(OffsetSize, 0));
1442 }
else if (
VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1443 ElementTy = VectorTy->getElementType();
1445 }
else if (
StructType *STy = dyn_cast<StructType>(ElementTy)) {
1446 if (STy->element_begin() == STy->element_end())
1448 ElementTy = *STy->element_begin();
1454 }
while (ElementTy != TargetTy);
1455 if (ElementTy != TargetTy)
1456 Indices.
erase(Indices.
end() - NumLayers, Indices.
end());
1458 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1481 if (
VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1483 if (ElementSizeInBits % 8 != 0) {
1488 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1489 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1491 Offset -= NumSkippedElements * ElementSize;
1492 Indices.
push_back(IRB.getInt(NumSkippedElements));
1494 Offset, TargetTy, Indices, NamePrefix);
1497 if (
ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1498 Type *ElementTy = ArrTy->getElementType();
1500 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1501 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1504 Offset -= NumSkippedElements * ElementSize;
1505 Indices.
push_back(IRB.getInt(NumSkippedElements));
1507 Indices, NamePrefix);
1526 Indices, NamePrefix);
1554 if (ElementSize == 0)
1556 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1558 Offset -= NumSkippedElements * ElementSize;
1559 Indices.
push_back(IRB.getInt(NumSkippedElements));
1561 Indices, NamePrefix);
1590 Value *OffsetPtr =
nullptr;
1591 Value *OffsetBasePtr;
1595 Value *Int8Ptr =
nullptr;
1599 Type *TargetTy = TargetPtrTy->getElementType();
1604 auto AS = cast<PointerType>(Ptr->
getType())->getAddressSpace();
1611 if (!
GEP->accumulateConstantOffset(DL, GEPOffset))
1613 Offset += GEPOffset;
1614 Ptr =
GEP->getPointerOperand();
1615 if (!Visited.
insert(Ptr).second)
1622 Indices, NamePrefix)) {
1626 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1627 if (
Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1628 assert(I->use_empty() &&
"Built a GEP with uses some how!");
1629 I->eraseFromParent();
1632 OffsetBasePtr = Ptr;
1646 Ptr = cast<Operator>(Ptr)->getOperand(0);
1647 }
else if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1648 if (GA->isInterposable())
1650 Ptr = GA->getAliasee();
1655 }
while (Visited.
insert(Ptr).second);
1659 Int8Ptr = IRB.CreateBitCast(
1661 NamePrefix +
"sroa_raw_cast");
1665 OffsetPtr = Int8PtrOffset == 0
1667 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1668 IRB.getInt(Int8PtrOffset),
1669 NamePrefix +
"sroa_raw_idx");
1674 if (cast<PointerType>(Ptr->
getType()) != TargetPtrTy) {
1675 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
1677 NamePrefix +
"sroa_cast");
1688 if (
auto *LI = dyn_cast<LoadInst>(I)) {
1691 }
else if (
auto *SI = dyn_cast<StoreInst>(I)) {
1693 Ty = SI->getValueOperand()->getType();
1713 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1716 "We can't have the same bitwidth for different int types");
1731 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1732 cast<PointerType>(OldTy)->getPointerAddressSpace();
1765 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1766 "Integer types must be the exact same to convert.");
1773 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.
getIntPtrType(NewTy)),
1778 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.
getIntPtrType(NewTy)),
1781 return IRB.CreateIntToPtr(V, NewTy);
1789 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.
getIntPtrType(OldTy)),
1794 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.
getIntPtrType(OldTy)),
1797 return IRB.CreatePtrToInt(V, NewTy);
1800 return IRB.CreateBitCast(V, NewTy);
1809 uint64_t ElementSize,
1812 uint64_t BeginOffset =
1814 uint64_t BeginIndex = BeginOffset / ElementSize;
1815 if (BeginIndex * ElementSize != BeginOffset ||
1818 uint64_t EndOffset =
1820 uint64_t EndIndex = EndOffset / ElementSize;
1821 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->
getNumElements())
1824 assert(EndIndex > BeginIndex &&
"Empty vector!");
1825 uint64_t NumElements = EndIndex - BeginIndex;
1826 Type *SliceTy = (NumElements == 1)
1833 Use *U = S.getUse();
1836 if (
MI->isVolatile())
1838 if (!S.isSplittable())
1840 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1841 if (!II->isLifetimeStartOrEnd())
1843 }
else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1846 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1847 if (LI->isVolatile())
1849 Type *LTy = LI->getType();
1856 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1857 if (SI->isVolatile())
1859 Type *STy = SI->getValueOperand()->getType();
1886 Type *CommonEltTy =
nullptr;
1887 bool HaveCommonEltTy =
true;
1888 auto CheckCandidateType = [&](
Type *Ty) {
1889 if (
auto *VTy = dyn_cast<VectorType>(Ty)) {
1891 if (!CandidateTys.
empty()) {
1894 CandidateTys.
clear();
1900 CommonEltTy = VTy->getElementType();
1901 else if (CommonEltTy != VTy->getElementType())
1902 HaveCommonEltTy =
false;
1906 for (
const Slice &S : P)
1907 if (S.beginOffset() == P.beginOffset() &&
1908 S.endOffset() == P.endOffset()) {
1909 if (
auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1910 CheckCandidateType(LI->getType());
1911 else if (
auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1912 CheckCandidateType(SI->getValueOperand()->getType());
1916 if (CandidateTys.
empty())
1923 if (!HaveCommonEltTy) {
1929 CandidateTys.
end());
1932 if (CandidateTys.
empty())
1940 "Cannot have vector types of different sizes!");
1942 "All non-integer types eliminated!");
1943 assert(LHSTy->getElementType()->isIntegerTy() &&
1944 "All non-integer types eliminated!");
1949 std::unique(CandidateTys.
begin(), CandidateTys.
end(), RankVectorTypes),
1950 CandidateTys.
end());
1956 assert(VTy->getElementType() == CommonEltTy &&
1957 "Unaccounted for element type!");
1958 assert(VTy == CandidateTys[0] &&
1959 "Different vector types with the same element type!");
1962 CandidateTys.resize(1);
1966 auto CheckVectorTypeForPromotion = [&](
VectorType *VTy) {
1971 if (ElementSize % 8)
1974 "vector size not a multiple of element size?");
1977 for (
const Slice &S : P)
1981 for (
const Slice *S : P.splitSliceTails())
1988 if (CheckVectorTypeForPromotion(VTy))
1999 uint64_t AllocBeginOffset,
2002 bool &WholeAllocaOp) {
2005 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2006 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2013 Use *U = S.getUse();
2015 if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2016 if (LI->isVolatile())
2023 if (S.beginOffset() < AllocBeginOffset)
2028 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
2029 WholeAllocaOp =
true;
2030 if (
IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2033 }
else if (RelBegin != 0 || RelEnd != Size ||
2039 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2040 Type *ValueTy = SI->getValueOperand()->getType();
2041 if (SI->isVolatile())
2048 if (S.beginOffset() < AllocBeginOffset)
2053 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd ==
Size)
2054 WholeAllocaOp =
true;
2055 if (
IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2058 }
else if (RelBegin != 0 || RelEnd != Size ||
2064 }
else if (
MemIntrinsic *
MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2065 if (
MI->isVolatile() || !isa<Constant>(
MI->getLength()))
2067 if (!S.isSplittable())
2069 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2070 if (!II->isLifetimeStartOrEnd())
2111 bool WholeAllocaOp =
2114 for (
const Slice &S : P)
2119 for (
const Slice *S : P.splitSliceTails())
2124 return WholeAllocaOp;
2129 const Twine &Name) {
2133 "Element extends past full value");
2134 uint64_t ShAmt = 8 *
Offset;
2138 V = IRB.CreateLShr(V, ShAmt, Name +
".shift");
2142 "Cannot extract to a larger integer!");
2144 V = IRB.CreateTrunc(V, Ty, Name +
".trunc");
2155 "Cannot insert a larger integer!");
2158 V = IRB.CreateZExt(V, IntTy, Name +
".ext");
2162 "Element store outside of alloca store");
2163 uint64_t ShAmt = 8 *
Offset;
2167 V = IRB.CreateShl(V, ShAmt, Name +
".shift");
2171 if (ShAmt || Ty->getBitWidth() < IntTy->
getBitWidth()) {
2173 Old = IRB.CreateAnd(Old, Mask, Name +
".mask");
2175 V = IRB.CreateOr(Old, V, Name +
".insert");
2182 unsigned EndIndex,
const Twine &Name) {
2184 unsigned NumElements = EndIndex - BeginIndex;
2185 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2190 if (NumElements == 1) {
2191 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2199 for (
unsigned i = BeginIndex; i != EndIndex; ++i)
2208 unsigned BeginIndex,
const Twine &Name) {
2210 assert(VecTy &&
"Can only insert a vector into a vector");
2215 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2222 "Too many elements!");
2236 if (i >= BeginIndex && i < EndIndex)
2237 Mask.
push_back(IRB.getInt32(i - BeginIndex));
2246 Mask.
push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2271 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2291 uint64_t ElementSize;
2295 uint64_t BeginOffset = 0;
2296 uint64_t EndOffset = 0;
2300 uint64_t NewBeginOffset = 0, NewEndOffset = 0;
2302 uint64_t SliceSize = 0;
2303 bool IsSplittable =
false;
2304 bool IsSplit =
false;
2305 Use *OldUse =
nullptr;
2319 uint64_t NewAllocaBeginOffset,
2320 uint64_t NewAllocaEndOffset,
bool IsIntegerPromotable,
2324 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2325 NewAllocaBeginOffset(NewAllocaBeginOffset),
2326 NewAllocaEndOffset(NewAllocaEndOffset),
2327 NewAllocaTy(NewAI.getAllocatedType()),
2328 IntTy(IsIntegerPromotable
2331 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2333 VecTy(PromotableVecTy),
2334 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2335 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2336 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2340 "Only multiple-of-8 sized vector elements are viable");
2343 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2347 bool CanSROA =
true;
2348 BeginOffset = I->beginOffset();
2349 EndOffset = I->endOffset();
2350 IsSplittable = I->isSplittable();
2352 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2353 LLVM_DEBUG(
dbgs() <<
" rewriting " << (IsSplit ?
"split " :
""));
2358 assert(BeginOffset < NewAllocaEndOffset);
2359 assert(EndOffset > NewAllocaBeginOffset);
2360 NewBeginOffset =
std::max(BeginOffset, NewAllocaBeginOffset);
2361 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2363 SliceSize = NewEndOffset - NewBeginOffset;
2365 OldUse = I->getUse();
2366 OldPtr = cast<Instruction>(OldUse->get());
2368 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2369 IRB.SetInsertPoint(OldUserI);
2370 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2373 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2392 assert(IsSplit || BeginOffset == NewBeginOffset);
2393 uint64_t
Offset = NewBeginOffset - NewAllocaBeginOffset;
2398 size_t LastSROAPrefix = OldName.
rfind(
".sroa.");
2400 OldName = OldName.
substr(LastSROAPrefix + strlen(
".sroa."));
2405 OldName = OldName.
substr(IndexEnd + 1);
2409 OldName = OldName.
substr(OffsetEnd + 1);
2413 OldName = OldName.
substr(0, OldName.
find(
".sroa_"));
2420 Twine(OldName) +
"." 2442 unsigned getIndex(uint64_t
Offset) {
2443 assert(VecTy &&
"Can only call getIndex when rewriting a vector");
2444 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2445 assert(RelOffset / ElementSize < UINT32_MAX &&
"Index out of bounds");
2447 assert(Index * ElementSize == RelOffset);
2451 void deleteIfTriviallyDead(
Value *V) {
2454 Pass.DeadInsts.insert(I);
2457 Value *rewriteVectorizedLoadInst() {
2458 unsigned BeginIndex = getIndex(NewBeginOffset);
2459 unsigned EndIndex = getIndex(NewEndOffset);
2460 assert(EndIndex > BeginIndex &&
"Empty vector!");
2468 assert(IntTy &&
"We cannot insert an integer to the alloca");
2473 assert(NewBeginOffset >= NewAllocaBeginOffset &&
"Out of bounds offset");
2474 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2475 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2485 "Can only handle an extract for an overly wide load");
2487 V = IRB.CreateZExt(V, LI.
getType());
2504 bool IsPtrAdjusted =
false;
2507 V = rewriteVectorizedLoadInst();
2509 V = rewriteIntegerLoad(LI);
2510 }
else if (NewBeginOffset == NewAllocaBeginOffset &&
2511 NewEndOffset == NewAllocaEndOffset &&
2544 if (
auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2545 if (
auto *TITy = dyn_cast<IntegerType>(TargetTy))
2546 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2547 V = IRB.CreateZExt(V, TITy,
"load.ext");
2549 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2554 LoadInst *NewLI = IRB.CreateAlignedLoad(
2555 TargetTy, getNewAllocaSlicePtr(IRB, LTy), getSliceAlign(TargetTy),
2563 IsPtrAdjusted =
true;
2570 "Only integer type loads and stores are split");
2572 "Split load isn't smaller than original load");
2574 "Non-byte-multiple bit width");
2583 V =
insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2592 Pass.DeadInsts.insert(&LI);
2593 deleteIfTriviallyDead(OldOp);
2601 unsigned BeginIndex = getIndex(NewBeginOffset);
2602 unsigned EndIndex = getIndex(NewEndOffset);
2603 assert(EndIndex > BeginIndex &&
"Empty vector!");
2604 unsigned NumElements = EndIndex - BeginIndex;
2605 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2606 Type *SliceTy = (NumElements == 1)
2620 Pass.DeadInsts.insert(&SI);
2627 assert(IntTy &&
"We cannot extract an integer from the alloca");
2633 assert(BeginOffset >= NewAllocaBeginOffset &&
"Out of bounds offset");
2634 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2639 Store->
copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2640 LLVMContext::MD_access_group});
2643 Pass.DeadInsts.insert(&SI);
2662 Pass.PostPromotionWorklist.insert(AI);
2667 "Only integer type loads and stores are split");
2669 "Non-byte-multiple bit width");
2671 V =
extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2676 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
2678 return rewriteIntegerStore(V, SI, AATags);
2682 if (NewBeginOffset == NewAllocaBeginOffset &&
2683 NewEndOffset == NewAllocaEndOffset &&
2690 if (
auto *VITy = dyn_cast<IntegerType>(V->
getType()))
2691 if (
auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2692 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2694 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2696 V = IRB.CreateTrunc(V, AITy,
"load.trunc");
2700 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.
getAlignment(),
2705 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->
getType()),
2708 NewSI->
copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2709 LLVMContext::MD_access_group});
2716 Pass.DeadInsts.insert(&SI);
2717 deleteIfTriviallyDead(OldOp);
2733 assert(Size > 0 &&
"Expected a positive number of bytes.");
2741 IRB.CreateZExt(V, SplatIntTy,
"zext"),
2751 Value *getVectorSplat(
Value *V,
unsigned NumElements) {
2752 V = IRB.CreateVectorSplat(NumElements, V,
"vsplat");
2768 assert(NewBeginOffset == BeginOffset);
2772 deleteIfTriviallyDead(OldPtr);
2777 Pass.DeadInsts.insert(&II);
2782 const bool CanContinue = [&]() {
2785 if (BeginOffset > NewAllocaBeginOffset ||
2786 EndOffset < NewAllocaEndOffset)
2789 if (
C->getBitWidth() > 64)
2791 const auto Len =
C->getZExtValue();
2821 assert(ElementTy == ScalarTy);
2823 unsigned BeginIndex = getIndex(NewBeginOffset);
2824 unsigned EndIndex = getIndex(NewEndOffset);
2825 assert(EndIndex > BeginIndex &&
"Empty vector!");
2826 unsigned NumElements = EndIndex - BeginIndex;
2827 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2832 if (NumElements > 1)
2833 Splat = getVectorSplat(Splat, NumElements);
2843 uint64_t Size = NewEndOffset - NewBeginOffset;
2846 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2847 EndOffset != NewAllocaBeginOffset)) {
2851 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2855 "Wrong type for an alloca wide integer!");
2860 assert(NewBeginOffset == NewAllocaBeginOffset);
2861 assert(NewEndOffset == NewAllocaEndOffset);
2864 if (
VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2865 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2900 if (!IsSplittable) {
2901 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
2912 deleteIfTriviallyDead(OldPtr);
2925 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2932 if (EmitMemCpy && &OldAI == &NewAI) {
2934 assert(NewBeginOffset == BeginOffset);
2937 if (NewEndOffset != EndOffset)
2939 NewEndOffset - NewBeginOffset));
2943 Pass.DeadInsts.insert(&II);
2950 assert(AI != &OldAI && AI != &NewAI &&
2951 "Splittable transfers cannot reach the same alloca on both ends.");
2952 Pass.Worklist.insert(AI);
2960 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
2969 OtherPtr =
getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2972 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
2976 Value *DestPtr, *SrcPtr;
2981 DestAlign = SliceAlign;
2983 SrcAlign = OtherAlign;
2986 DestAlign = OtherAlign;
2988 SrcAlign = SliceAlign;
2990 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2998 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2999 NewEndOffset == NewAllocaEndOffset;
3000 uint64_t Size = NewEndOffset - NewBeginOffset;
3001 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
3002 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
3003 unsigned NumElements = EndIndex - BeginIndex;
3010 if (VecTy && !IsWholeAlloca) {
3011 if (NumElements == 1)
3015 }
else if (IntTy && !IsWholeAlloca) {
3018 OtherTy = NewAllocaTy;
3025 Value *DstPtr = &NewAI;
3033 if (VecTy && !IsWholeAlloca && !IsDest) {
3037 }
else if (IntTy && !IsWholeAlloca && !IsDest) {
3041 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3044 LoadInst *
Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3051 if (VecTy && !IsWholeAlloca && IsDest) {
3055 }
else if (IntTy && !IsWholeAlloca && IsDest) {
3059 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3065 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.
isVolatile()));
3078 Pass.DeadInsts.insert(&II);
3087 if (NewBeginOffset != NewAllocaBeginOffset ||
3088 NewEndOffset != NewAllocaEndOffset)
3093 NewEndOffset - NewBeginOffset);
3097 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
3100 New = IRB.CreateLifetimeStart(Ptr, Size);
3102 New = IRB.CreateLifetimeEnd(Ptr, Size);
3121 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
3124 LI->
setAlignment(std::min(LoadAlign, getSliceAlign()));
3127 if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
3131 SI->
setAlignment(std::min(StoreAlign, getSliceAlign()));
3135 assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||
3136 isa<PHINode>(I) || isa<SelectInst>(I) ||
3137 isa<GetElementPtrInst>(I));
3139 if (Visited.
insert(cast<Instruction>(U)).second)
3141 }
while (!Uses.
empty());
3144 bool visitPHINode(
PHINode &PN) {
3146 assert(BeginOffset >= NewAllocaBeginOffset &&
"PHIs are unsplittable");
3147 assert(EndOffset <= NewAllocaEndOffset &&
"PHIs are unsplittable");
3153 IRBuilderTy PtrBuilder(IRB);
3154 if (isa<PHINode>(OldPtr))
3157 PtrBuilder.SetInsertPoint(OldPtr);
3158 PtrBuilder.SetCurrentDebugLocation(OldPtr->
getDebugLoc());
3160 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->
getType());
3165 deleteIfTriviallyDead(OldPtr);
3168 fixLoadStoreAlign(PN);
3180 "Pointer isn't an operand!");
3181 assert(BeginOffset >= NewAllocaBeginOffset &&
"Selects are unsplittable");
3182 assert(EndOffset <= NewAllocaEndOffset &&
"Selects are unsplittable");
3184 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
3192 deleteIfTriviallyDead(OldPtr);
3195 fixLoadStoreAlign(SI);
3212 class AggLoadStoreRewriter :
public InstVisitor<AggLoadStoreRewriter, bool> {
3214 friend class InstVisitor<AggLoadStoreRewriter, bool>;
3230 AggLoadStoreRewriter(
const DataLayout &DL) : DL(DL) {}
3237 bool Changed =
false;
3238 while (!Queue.empty()) {
3239 U = Queue.pop_back_val();
3240 Changed |= visit(cast<Instruction>(U->getUser()));
3251 Queue.push_back(&U);
3255 bool visitInstruction(
Instruction &I) {
return false; }
3258 template <
typename Derived>
class OpSplitter {
3289 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr),
3290 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
3309 return static_cast<Derived *
>(
this)->emitFunc(
3313 if (
ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3314 unsigned OldSize = Indices.
size();
3316 for (
unsigned Idx = 0,
Size = ATy->getNumElements(); Idx !=
Size;
3318 assert(Indices.
size() == OldSize &&
"Did not return to the old size");
3320 GEPIndices.
push_back(IRB.getInt32(Idx));
3321 emitSplitOps(ATy->getElementType(), Agg, Name +
"." +
Twine(Idx));
3328 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
3329 unsigned OldSize = Indices.
size();
3331 for (
unsigned Idx = 0,
Size = STy->getNumElements(); Idx !=
Size;
3333 assert(Indices.
size() == OldSize &&
"Did not return to the old size");
3335 GEPIndices.
push_back(IRB.getInt32(Idx));
3336 emitSplitOps(STy->getElementType(Idx), Agg, Name +
"." +
Twine(Idx));
3347 struct LoadOpSplitter :
public OpSplitter<LoadOpSplitter> {
3352 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3362 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name +
".gep");
3364 IRB.CreateAlignedLoad(Ty, GEP, Alignment.
value(), Name +
".load");
3367 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name +
".insert");
3381 LoadOpSplitter Splitter(&LI, *U, LI.
getType(), AATags,
3390 struct StoreOpSplitter :
public OpSplitter<StoreOpSplitter> {
3393 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3405 Value *ExtractValue =
3406 IRB.CreateExtractValue(Agg, Indices, Name +
".extract");
3407 Value *InBoundsGEP =
3408 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name +
".gep");
3410 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment.
value());
3428 StoreOpSplitter Splitter(&SI, *U, V->
getType(), AATags,
3450 bool visitPHINode(
PHINode &PN) {
3476 if (
ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3477 InnerTy = ArrTy->getElementType();
3478 }
else if (
StructType *STy = dyn_cast<StructType>(Ty)) {
3481 InnerTy = STy->getElementType(Index);
3515 Type *ElementTy = SeqTy->getElementType();
3517 uint64_t NumSkippedElements = Offset / ElementSize;
3518 if (NumSkippedElements >= SeqTy->getNumElements())
3520 Offset -= NumSkippedElements * ElementSize;
3523 if (Offset > 0 || Size < ElementSize) {
3525 if ((Offset + Size) > ElementSize)
3532 if (Size == ElementSize)
3534 assert(Size > ElementSize);
3535 uint64_t NumElements = Size / ElementSize;
3536 if (NumElements * ElementSize != Size)
3548 uint64_t EndOffset = Offset +
Size;
3557 if (Offset >= ElementSize)
3561 if (Offset > 0 || Size < ElementSize) {
3562 if ((Offset + Size) > ElementSize)
3568 if (Size == ElementSize)
3573 if (EndOffset < SL->getSizeInBytes()) {
3575 if (Index == EndIndex)
3585 assert(Index < EndIndex);
3593 if (Size != SubSL->getSizeInBytes())
3643 struct SplitOffsets {
3645 std::vector<uint64_t> Splits;
3662 LLVM_DEBUG(
dbgs() <<
" Searching for candidate loads and stores\n");
3664 for (Slice &S : P) {
3665 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3666 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3670 if (
auto *LI = dyn_cast<LoadInst>(I))
3671 UnsplittableLoads.
insert(LI);
3672 else if (
auto *SI = dyn_cast<StoreInst>(I))
3673 if (
auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3674 UnsplittableLoads.
insert(LI);
3677 assert(P.endOffset() > S.beginOffset() &&
3678 "Empty or backwards partition!");
3681 if (
auto *LI = dyn_cast<LoadInst>(I)) {
3682 assert(!LI->isVolatile() &&
"Cannot split volatile loads!");
3687 auto IsLoadSimplyStored = [](
LoadInst *LI) {
3690 if (!SI || !SI->isSimple())
3695 if (!IsLoadSimplyStored(LI)) {
3696 UnsplittableLoads.
insert(LI);
3701 }
else if (
auto *SI = dyn_cast<StoreInst>(I)) {
3702 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3706 if (!StoredLoad || !StoredLoad->isSimple())
3708 assert(!SI->isVolatile() &&
"Cannot split volatile stores!");
3718 auto &
Offsets = SplitOffsetsMap[
I];
3720 "Should not have splits the first time we see an instruction!");
3722 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3727 for (Slice *S : P.splitSliceTails()) {
3728 auto SplitOffsetsMapI =
3729 SplitOffsetsMap.
find(cast<Instruction>(S->getUse()->getUser()));
3730 if (SplitOffsetsMapI == SplitOffsetsMap.
end())
3732 auto &
Offsets = SplitOffsetsMapI->second;
3736 "Cannot have an empty set of splits on the second partition!");
3738 P.beginOffset() -
Offsets.S->beginOffset() &&
3739 "Previous split does not end where this one begins!");
3743 if (S->endOffset() > P.endOffset())
3744 Offsets.Splits.push_back(P.endOffset() -
Offsets.S->beginOffset());
3754 [&UnsplittableLoads, &SplitOffsetsMap](
StoreInst *SI) {
3760 if (UnsplittableLoads.
count(LI))
3763 auto LoadOffsetsI = SplitOffsetsMap.
find(LI);
3764 if (LoadOffsetsI == SplitOffsetsMap.
end())
3766 auto &LoadOffsets = LoadOffsetsI->second;
3769 auto &StoreOffsets = SplitOffsetsMap[
SI];
3774 if (LoadOffsets.Splits == StoreOffsets.Splits)
3779 <<
" Mismatched splits for load and store:\n" 3780 <<
" " << *LI <<
"\n" 3781 <<
" " << *SI <<
"\n");
3787 UnsplittableLoads.
insert(LI);
3799 return UnsplittableLoads.
count(LI);
3805 [&UnsplittableLoads](
LoadInst *LI) {
3806 return UnsplittableLoads.
count(LI);
3817 IRBuilderTy IRB(&AI);
3835 std::vector<LoadInst *> SplitLoads;
3842 assert(LoadSize > 0 &&
"Cannot have a zero-sized integer load!");
3844 auto &
Offsets = SplitOffsetsMap[LI];
3846 "Slice size should always match load size exactly!");
3847 uint64_t BaseOffset =
Offsets.S->beginOffset();
3848 assert(BaseOffset + LoadSize > BaseOffset &&
3849 "Cannot represent alloca access size using 64-bit integers!");
3852 IRB.SetInsertPoint(LI);
3856 uint64_t PartOffset = 0, PartSize =
Offsets.Splits.front();
3861 auto *PartPtrTy = PartTy->getPointerTo(AS);
3862 LoadInst *PLoad = IRB.CreateAlignedLoad(
3866 PartPtrTy, BasePtr->
getName() +
"."),
3869 PLoad->
copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3870 LLVMContext::MD_access_group});
3874 SplitLoads.push_back(PLoad);
3878 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3882 <<
", " << NewSlices.
back().endOffset()
3883 <<
"): " << *PLoad <<
"\n");
3890 PartOffset =
Offsets.Splits[Idx];
3892 PartSize = (Idx <
Size ?
Offsets.Splits[Idx] : LoadSize) - PartOffset;
3898 bool DeferredStores =
false;
3901 if (!Stores.
empty() && SplitOffsetsMap.
count(SI)) {
3902 DeferredStores =
true;
3909 IRB.SetInsertPoint(SI);
3911 LLVM_DEBUG(
dbgs() <<
" Splitting store of load: " << *SI <<
"\n");
3913 for (
int Idx = 0,
Size = SplitLoads.size(); Idx <
Size; ++Idx) {
3915 uint64_t PartOffset = Idx == 0 ? 0 :
Offsets.Splits[Idx - 1];
3920 StoreInst *PStore = IRB.CreateAlignedStore(
3924 PartPtrTy, StoreBasePtr->
getName() +
"."),
3927 PStore->
copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3928 LLVMContext::MD_access_group});
3929 LLVM_DEBUG(
dbgs() <<
" +" << PartOffset <<
":" << *PStore <<
"\n");
3936 if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3937 ResplitPromotableAllocas.
insert(OtherAI);
3938 Worklist.insert(OtherAI);
3939 }
else if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3941 Worklist.insert(OtherAI);
3945 DeadInsts.insert(SI);
3950 SplitLoadsMap.
insert(std::make_pair(LI, std::move(SplitLoads)));
3953 DeadInsts.insert(LI);
3966 assert(StoreSize > 0 &&
"Cannot have a zero-sized integer store!");
3970 "Slice size should always match load size exactly!");
3971 uint64_t BaseOffset =
Offsets.S->beginOffset();
3972 assert(BaseOffset + StoreSize > BaseOffset &&
3973 "Cannot represent alloca access size using 64-bit integers!");
3981 auto SplitLoadsMapI = SplitLoadsMap.
find(LI);
3982 std::vector<LoadInst *> *SplitLoads =
nullptr;
3983 if (SplitLoadsMapI != SplitLoadsMap.
end()) {
3984 SplitLoads = &SplitLoadsMapI->second;
3986 "Too few split loads for the number of splits in the store!");
3991 uint64_t PartOffset = 0, PartSize =
Offsets.Splits.front();
4001 PLoad = (*SplitLoads)[Idx];
4003 IRB.SetInsertPoint(LI);
4005 PLoad = IRB.CreateAlignedLoad(
4009 LoadPartPtrTy, LoadBasePtr->
getName() +
"."),
4015 IRB.SetInsertPoint(SI);
4017 StoreInst *PStore = IRB.CreateAlignedStore(
4021 StorePartPtrTy, StoreBasePtr->
getName() +
"."),
4027 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4031 <<
", " << NewSlices.
back().endOffset()
4032 <<
"): " << *PStore <<
"\n");
4042 PartOffset =
Offsets.Splits[Idx];
4044 PartSize = (Idx <
Size ?
Offsets.Splits[Idx] : StoreSize) - PartOffset;
4053 if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
4054 assert(OtherAI != &AI &&
"We can't re-split our own alloca!");
4055 ResplitPromotableAllocas.
insert(OtherAI);
4056 Worklist.insert(OtherAI);
4057 }
else if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4059 assert(OtherAI != &AI &&
"We can't re-split our own alloca!");
4060 Worklist.insert(OtherAI);
4075 DeadInsts.insert(LI);
4077 DeadInsts.insert(SI);
4091 for (
auto I = AS.
begin(),
E = AS.
end(); I !=
E; ++
I)
4097 PromotableAllocas.erase(
4101 PromotableAllocas.end());
4121 Type *SliceTy =
nullptr;
4125 SliceTy = CommonUseTy;
4129 SliceTy = TypePartitionTy;
4130 if ((!SliceTy || (SliceTy->
isArrayTy() &&
4179 <<
") to: " << *NewAI <<
"\n");
4184 unsigned PPWOldSize = PostPromotionWorklist.size();
4185 unsigned NumUses = 0;
4190 P.
endOffset(), IsIntegerPromotable, VecTy,
4191 PHIUsers, SelectUsers);
4192 bool Promotable =
true;
4197 for (Slice &S : P) {
4202 NumAllocaPartitionUses += NumUses;
4203 MaxUsesPerAllocaPartition.updateMax(NumUses);
4211 SelectUsers.
clear();
4219 SelectUsers.clear();
4224 if (PHIUsers.empty() && SelectUsers.empty()) {
4226 PromotableAllocas.push_back(NewAI);
4231 for (
PHINode *PHIUser : PHIUsers)
4232 SpeculatablePHIs.insert(PHIUser);
4234 SpeculatableSelects.insert(SelectUser);
4235 Worklist.insert(NewAI);
4239 while (PostPromotionWorklist.size() > PPWOldSize)
4240 PostPromotionWorklist.pop_back();
4250 Worklist.insert(NewAI);
4262 unsigned NumPartitions = 0;
4263 bool Changed =
false;
4267 Changed |= presplitLoadsAndStores(AI, AS);
4275 bool IsSorted =
true;
4278 const uint64_t MaxBitVectorSize = 1024;
4279 if (AllocaSize <= MaxBitVectorSize) {
4284 for (
unsigned O = S.beginOffset() + 1;
4285 O < S.endOffset() &&
O < AllocaSize;
O++)
4286 SplittableOffset.
reset(
O);
4288 for (Slice &S : AS) {
4289 if (!S.isSplittable())
4292 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4293 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4296 if (isa<LoadInst>(S.getUse()->getUser()) ||
4297 isa<StoreInst>(S.getUse()->getUser())) {
4298 S.makeUnsplittable();
4306 for (Slice &S : AS) {
4307 if (!S.isSplittable())
4310 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4313 if (isa<LoadInst>(S.getUse()->getUser()) ||
4314 isa<StoreInst>(S.getUse()->getUser())) {
4315 S.makeUnsplittable();
4337 if (
AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4340 uint64_t SizeOfByte = 8;
4343 uint64_t
Size = std::min(AllocaSize, P.
size() * SizeOfByte);
4350 NumAllocaPartitions += NumPartitions;
4351 MaxPartitionsPerAlloca.updateMax(NumPartitions);
4356 if (!DbgDeclares.
empty()) {
4359 auto VarSize = Var->getSizeInBits();
4362 for (
auto Fragment : Fragments) {
4365 auto *FragmentExpr = Expr;
4366 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
4369 auto ExprFragment = Expr->getFragmentInfo();
4370 uint64_t
Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
4371 uint64_t Start = Offset + Fragment.Offset;
4372 uint64_t
Size = Fragment.Size;
4375 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
4376 if (Start >= AbsEnd)
4379 Size = std::min(Size, AbsEnd - Start);
4382 if (
auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4383 assert(Start >= OrigFragment->OffsetInBits &&
4384 "new fragment is outside of original fragment");
4385 Start -= OrigFragment->OffsetInBits;
4390 if (Size > *VarSize)
4392 if (Size == 0 || Start + Size > *VarSize)
4397 if (!VarSize || *VarSize != Size) {
4408 OldDII->eraseFromParent();
4410 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
4418 void SROA::clobberUse(
Use &U) {
4426 if (
Instruction *OldI = dyn_cast<Instruction>(OldV))
4428 DeadInsts.insert(OldI);
4439 ++NumAllocasAnalyzed;
4453 bool Changed =
false;
4457 AggLoadStoreRewriter AggRewriter(DL);
4458 Changed |= AggRewriter.rewrite(AI);
4469 for (
Use &DeadOp : DeadUser->operands())
4476 DeadInsts.insert(DeadUser);
4480 clobberUse(*DeadOp);
4488 Changed |= splitAlloca(AI, AS);
4491 while (!SpeculatablePHIs.empty())
4495 while (!SpeculatableSelects.empty())
4510 bool SROA::deleteDeadInstructions(
4512 bool Changed =
false;
4513 while (!DeadInsts.empty()) {
4515 LLVM_DEBUG(
dbgs() <<
"Deleting dead instruction: " << *I <<
"\n");
4520 if (
AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4521 DeletedAllocas.
insert(AI);
4523 OldDII->eraseFromParent();
4529 if (
Instruction *U = dyn_cast<Instruction>(Operand)) {
4533 DeadInsts.insert(U);
4548 bool SROA::promoteAllocas(
Function &
F) {
4549 if (PromotableAllocas.empty())
4552 NumPromoted += PromotableAllocas.size();
4556 PromotableAllocas.clear();
4570 if (
AllocaInst *AI = dyn_cast<AllocaInst>(I))
4571 Worklist.insert(AI);
4574 bool Changed =
false;
4580 while (!Worklist.empty()) {
4581 Changed |= runOnAlloca(*Worklist.pop_back_val());
4582 Changed |= deleteDeadInstructions(DeletedAllocas);
4586 if (!DeletedAllocas.
empty()) {
4587 auto IsInSet = [&](
AllocaInst *AI) {
return DeletedAllocas.
count(AI); };
4588 Worklist.remove_if(IsInSet);
4589 PostPromotionWorklist.remove_if(IsInSet);
4591 PromotableAllocas.end());
4592 DeletedAllocas.
clear();
4596 Changed |= promoteAllocas(F);
4598 Worklist = PostPromotionWorklist;
4599 PostPromotionWorklist.clear();
4600 }
while (!Worklist.empty());
4632 if (skipFunction(F))
4635 auto PA = Impl.runImpl(
4636 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4637 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4656 "Scalar Replacement Of Aggregates",
false,
false)
Legacy wrapper pass to provide the GlobalsAAResult object.
static Value * getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, APInt Offset, Type *PointerTy, Twine NamePrefix)
Compute an adjusted pointer from Ptr by Offset bytes where the resulting pointer has PointerTy...
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static Align getAdjustedAlignment(Instruction *I, uint64_t Offset, const DataLayout &DL)
Compute the adjusted alignment for a load or store from an offset.
static VectorType * isVectorPromotionViable(Partition &P, const DataLayout &DL)
Test whether the given alloca partitioning and range of slices can be promoted to a vector...
static Value * getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, Type *Ty, APInt &Offset, Type *TargetTy, SmallVectorImpl< Value *> &Indices, Twine NamePrefix)
Recursively compute indices for a natural GEP.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
An iterator over partitions of the alloca's slices.
void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
iterator_range< use_iterator > uses()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
unsigned getIndexSizeInBits(unsigned AS) const
Size in bits of index used for address calculation in getelementptr.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
uint64_t getZExtValue() const
Get zero extended value.
Base class for instruction visitors.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
const Value * stripInBoundsOffsets() const
Strip off pointer casts and inbounds GEPs.
uint64_t beginOffset() const
The start offset of this partition.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
PointerTy getPointer() const
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
bool isSafeToLoadUnconditionally(Value *V, MaybeAlign Alignment, APInt &Size, const DataLayout &DL, Instruction *ScanFrom=nullptr, const DominatorTree *DT=nullptr)
Return true if we know that executing a load from this value cannot trap.
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
Type * getElementType(unsigned N) const
This is the interface for a simple mod/ref and alias analysis over globals.
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
LLVM_NODISCARD size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
void push_back(const T &Elt)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
void erase(iterator Start, iterator Stop)
Erase a range of slices.
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
This class provides information about the result of a visit.
This class represents a function call, abstracting a target machine's calling convention.
static Value * extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V, IntegerType *Ty, uint64_t Offset, const Twine &Name)
Representation of the alloca slices.
An immutable pass that tracks lazily created AssumptionCache objects.
unsigned getSourceAlignment() const
FIXME: Remove this function once transition to Align is over.
Instruction * getAbortingInst() const
Get the instruction causing the visit to abort.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
gep_type_iterator gep_type_end(const User *GEP)
const Value * getTrueValue() const
void insert(ArrayRef< Slice > NewSlices)
Insert new slices for this alloca.
A cache of @llvm.assume calls within a function.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
unsigned getSourceAddressSpace() const
LLVMContext & getContext() const
All values hold a context through their type.
void deleteValue()
Delete a pointer to a generic Value.
void setSource(Value *Ptr)
void setDest(Value *Ptr)
Set the specified arguments of the instruction.
This class wraps the llvm.memset intrinsic.
const Use & getOperandUse(unsigned i) const
Scalar Replacement Of Aggregates
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
This defines the Use class.
void reserve(size_type N)
bool typeSizeEqualsStoreSize(Type *Ty) const
Returns true if no extra padding bits are needed when storing the specified type. ...
Value * getLength() const
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
bool isEscaped() const
Test whether a pointer to the allocation escapes our analysis.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
TypeSize getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
unsigned getBitWidth() const
Return the number of bits in the APInt.
Builder for the alloca slices.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
Value * getArgOperand(unsigned i) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
MaybeAlign getAlign() const
static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S, VectorType *Ty, uint64_t ElementSize, const DataLayout &DL)
Test whether the given slice use can be promoted to a vector.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
This class represents a conversion between pointers from one address space to another.
This class represents the LLVM 'select' instruction.
Type * getPointerElementType() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
PointerType * getType() const
Overload to return most specific pointer type.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
static Type * getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset, uint64_t Size)
Try to find a partition of the aggregate type passed in for a given offset and size.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
ArrayRef< Slice * > splitSliceTails() const
Get the sequence of split slice tails.
bool isAborted() const
Did we abort the visit early?
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static Value * convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V, Type *NewTy)
Generic routine to convert an SSA value to a value of a different type.
A partition of the slices.
unsigned getDestAlignment() const
FIXME: Remove this function once transition to Align is over.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
uint64_t getNumElements() const
For scalable vectors, this will return the minimum number of elements in the vector.
Align commonAlignment(Align A, Align B)
Returns the alignment that satisfies both alignments.
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
This file implements a class to represent arbitrary precision integral constant values and operations...
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
This file provides a collection of visitors which walk the (instruction) uses of a pointer...
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
bool visit(AllocaSlices::const_iterator I)
A base class for visitors over the uses of a pointer value.
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
SmallVectorImpl< Slice >::iterator iterator
Support for iterating over the slices.
const_iterator end() const
A legacy pass for the legacy pass manager that wraps the SROA pass.
Class to represent array types.
This is the common base class for debug info intrinsics for variables.
APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
const APInt & getValue() const
Return the constant as an APInt value reference.
ConstantFolder - Create constants with minimum, target independent, folding.
An instruction for storing to memory.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Maximum number of bits that can be specified.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void printUse(raw_ostream &OS, const_iterator I, StringRef Indent=" ") const
static Constant * getUDiv(Constant *C1, Constant *C2, bool isExact=false)
uint64_t value() const
This is a hole in the type system and should not be abused.
Align getValueOrABITypeAlignment(MaybeAlign Alignment, Type *Ty) const
Helper function to return Alignment if it's set or the result of getABITypeAlignment(Ty), in any case the result is a valid alignment.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
Type::subtype_iterator element_iterator
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy)
Test whether we can convert a value from the old to the new type.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
Class to represent pointers.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
iterator find(const_arg_type_t< KeyT > Val)
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
Scalar Replacement Of false
iterator_range< partition_iterator > partitions()
initializer< Ty > init(const Ty &Val)
MaybeAlign getAlign() const
Return the alignment of the access that is being performed.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
bool areAllPreserved() const
Test whether all analyses are preserved (and none are abandoned).
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static unsigned getPointerOperandIndex()
bool ult(const APInt &RHS) const
Unsigned less than comparison.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
ArrayRef< Use * > getDeadOperands() const
Access the dead operands referring to this alloca.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
static bool isSafeSelectToSpeculate(SelectInst &SI)
Select instructions that use an alloca and are subsequently loaded can be rewritten to load both inpu...
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
LLVM_NODISCARD size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
static Value * getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, APInt Offset, Type *TargetTy, SmallVectorImpl< Value *> &Indices, Twine NamePrefix)
Get a natural GEP from a base pointer to a particular offset and resulting in a particular type...
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
element_iterator element_end() const
DIExpression * getExpression() const
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Represent the analysis usage information of a pass.
bool isLifetimeStartOrEnd() const
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
static cl::opt< bool > SROAStrictInbounds("sroa-strict-inbounds", cl::init(false), cl::Hidden)
Hidden option to experiment with completely strict handling of inbounds GEPs.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
#define LLVM_ATTRIBUTE_UNUSED
Analysis pass providing a never-invalidated alias analysis result.
static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New)
void initializeSROALegacyPassPass(PassRegistry &)
FunctionPass class - This class is used to implement most global optimizations.
Value * getPointerOperand()
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Class to represent integer types.
unsigned getIndexTypeSizeInBits(Type *Ty) const
Layout size of the index used in GEP calculation.
AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI, uint64_t NewAllocaBeginOffset, uint64_t NewAllocaEndOffset, bool IsIntegerPromotable, VectorType *PromotableVecTy, SmallSetVector< PHINode *, 8 > &PHIUsers, SmallSetVector< SelectInst *, 8 > &SelectUsers)
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
const Value * getCondition() const
static Constant * getAllOnesValue(Type *Ty)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setDestAlignment(unsigned Alignment)
FIXME: Remove this function once transition to Align is over.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
static Value * getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL, Value *BasePtr, Type *Ty, Type *TargetTy, SmallVectorImpl< Value *> &Indices, Twine NamePrefix)
Get a natural GEP off of the BasePtr walking through Ty toward TargetTy without changing the offset o...
void sort(IteratorTy Start, IteratorTy End)
void printSlice(raw_ostream &OS, const_iterator I, StringRef Indent=" ") const
static Type * stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty)
Strip aggregate type wrapping.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
This provides the default implementation of the IRBuilder 'InsertHelper' method that is called whenev...
This is the superclass of the array and vector type classes.
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
A SetVector that performs no allocations if smaller than a certain size.
print lazy value Lazy Value Info Printer Pass
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
This is the shared class of boolean and integer constants.
TinyPtrVector< DbgVariableIntrinsic * > FindDbgAddrUses(Value *V)
Finds all intrinsics declaring local variables as living in the memory that 'V' points to...
Align max(MaybeAlign Lhs, Align Rhs)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Construct the slices of a particular alloca.
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
partition_iterator & operator++()
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
void setAlignment(MaybeAlign Alignment)
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU...
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
uint64_t getSizeInBytes() const
SmallVectorImpl< Slice >::const_iterator const_iterator
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Value * getRawSource() const
Return the arguments to the instruction.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
void clear()
Completely clear the SetVector.
A range adaptor for a pair of iterators.
Class to represent vector types.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
static bool isIntegerWideningViableForSlice(const Slice &S, uint64_t AllocBeginOffset, Type *AllocaTy, const DataLayout &DL, bool &WholeAllocaOp)
Test whether a slice of an alloca is valid for integer widening.
iterator_range< user_iterator > users()
Represents analyses that only rely on functions' control flow.
void setSourceAlignment(unsigned Alignment)
FIXME: Remove this function once transition to Align is over.
const Value * getFalseValue() const
element_iterator element_begin() const
static Value * insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, Value *V, uint64_t Offset, const Twine &Name)
bool isNonIntegralPointerType(PointerType *PT) const
const_iterator begin() const
static Type * findCommonType(AllocaSlices::const_iterator B, AllocaSlices::const_iterator E, uint64_t EndOffset)
Walk the range of a partitioning looking for a common type to cover this sequence of slices...
static Value * foldPHINodeOrSelectInst(Instruction &I)
A helper that folds a PHI node or a select.
Virtual Register Rewriter
bool operator!=(uint64_t V1, const APInt &V2)
INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates", false, false) INITIALIZE_PASS_END(SROALegacyPass
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
This class wraps the llvm.memcpy/memmove intrinsics.
bool isVolatile() const
Return true if this is a store to a volatile memory location.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getDestAddressSpace() const
uint64_t getElementOffset(unsigned Idx) const
unsigned getAlignment() const
Return the alignment of the access that is being performed.
LLVM_NODISCARD bool empty() const
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
Visitor to rewrite instructions using p particular slice of an alloca to use a new alloca...
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
void preserveSet()
Mark an analysis set as preserved.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static void speculateSelectInstLoads(SelectInst &SI)
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
FunctionPass * createSROAPass()
uint64_t endOffset() const
The end offset of this partition.
Instruction * getEscapingInst() const
Get the instruction causing the pointer to escape.
void setAlignment(MaybeAlign Alignment)
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
DILocalVariable * getVariable() const
static bool rewrite(Function &F)
static Value * extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, unsigned EndIndex, const Twine &Name)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
unsigned getAlignment() const
Return the alignment of the access that is being performed FIXME: Remove this function once transitio...
std::string str() const
Return the twine contents as a std::string.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static unsigned getPointerOperandIndex()
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
bool operator<(int64_t V1, const APSInt &V2)
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
static Value * buildGEP(IRBuilderTy &IRB, Value *BasePtr, SmallVectorImpl< Value *> &Indices, Twine NamePrefix)
Build a GEP out of a base pointer and indices.
static bool isSafePHIToSpeculate(PHINode &PN)
PHI instructions that use an alloca and are subsequently loaded can be rewritten to load both input p...
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB, BasicBlock::iterator InsertPt) const
static void speculatePHINodeLoads(PHINode &PN)
This class implements an extremely fast bulk output stream that can only output to a stream...
void PromoteMemToReg(ArrayRef< AllocaInst *> Allocas, DominatorTree &DT, AssumptionCache *AC=nullptr)
Promote the specified list of alloca instructions into scalar registers, inserting PHI nodes as appro...
PtrInfo visitPtr(Instruction &I)
Recursively visit the uses of the given pointer.
An optimization pass providing Scalar Replacement of Aggregates.
Type * getElementType() const
static cl::opt< bool > SROARandomShuffleSlices("sroa-random-shuffle-slices", cl::init(false), cl::Hidden)
Hidden option to enable randomly shuffling the slices to help uncover instability in their order...
uint64_t size() const
The size of the partition.
bool hasOneUse() const
Return true if there is exactly one user of this value.
bool empty() const
Test whether this partition contains no slices, and merely spans a region occupied by split slices...
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
void print(raw_ostream &OS, const_iterator I, StringRef Indent=" ") const
Type * getArrayElementType() const
Legacy analysis pass which computes a DominatorTree.
static bool isIntegerWideningViable(Partition &P, Type *AllocaTy, const DataLayout &DL)
Test whether the given alloca partition's integer operations can be widened to promotable ones...
bool operator==(uint64_t V1, const APInt &V2)
This header defines various interfaces for pass management in LLVM.
Value * getPointerOperand()
static IntegerType * getInt8Ty(LLVMContext &C)
Value * getRawDest() const
static Constant * get(ArrayRef< Constant *> V)
Align assumeAligned(uint64_t Value)
Treats the value 0 as a 1, so Align is always at least 1.
Type * getElementType() const
const Use & getRawDestUse() const
int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef< Value *> Indices) const
Returns the offset from the beginning of the type for the specified indices.
bool isArrayTy() const
True if this is an instance of ArrayType.
static Optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
gep_type_iterator gep_type_begin(const User *GEP)
static Value * foldSelectInst(SelectInst &SI)
ArrayRef< Instruction * > getDeadUsers() const
Access the dead users for this alloca.
bool isEscaped() const
Is the pointer escaped at some point?
bool operator==(const partition_iterator &RHS) const