46 #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();
228 template <>
struct isPodLike<Slice> {
static const bool value =
true; };
274 int OldSize = Slices.size();
275 Slices.append(NewSlices.
begin(), NewSlices.
end());
276 auto SliceI = Slices.begin() + OldSize;
278 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
283 class partition_iterator;
297 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 309 template <
typename DerivedT,
typename RetT =
void>
class BuilderBase;
314 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 372 uint64_t BeginOffset, EndOffset;
382 Partition(iterator SI) : SI(SI), SJ(SI) {}
399 assert(BeginOffset < EndOffset &&
"Partitions must span some bytes!");
400 return EndOffset - BeginOffset;
405 bool empty()
const {
return SI == SJ; }
417 iterator
end()
const {
return SJ; }
451 uint64_t MaxSplitSliceEndOffset = 0;
468 "Cannot advance past the end of the slices!");
471 if (!P.SplitTails.
empty()) {
472 if (P.EndOffset >= MaxSplitSliceEndOffset) {
474 P.SplitTails.
clear();
475 MaxSplitSliceEndOffset = 0;
482 return S->endOffset() <=
488 return S->endOffset() == MaxSplitSliceEndOffset;
490 "Could not find the current max split slice offset!");
493 return S->endOffset() <= MaxSplitSliceEndOffset;
495 "Max split slice end offset is not actually the max!");
502 assert(P.SplitTails.
empty() &&
"Failed to clear the split slices!");
512 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
513 P.SplitTails.push_back(&S);
514 MaxSplitSliceEndOffset =
515 std::max(S.endOffset(), MaxSplitSliceEndOffset);
523 P.BeginOffset = P.EndOffset;
524 P.EndOffset = MaxSplitSliceEndOffset;
531 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
532 !P.SI->isSplittable()) {
533 P.BeginOffset = P.EndOffset;
534 P.EndOffset = P.SI->beginOffset();
544 P.BeginOffset = P.SplitTails.
empty() ? P.SI->beginOffset() : P.EndOffset;
545 P.EndOffset = P.SI->endOffset();
550 if (!P.SI->isSplittable()) {
553 assert(P.BeginOffset == P.SI->beginOffset());
557 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
558 if (!P.SJ->isSplittable())
559 P.EndOffset =
std::max(P.EndOffset, P.SJ->endOffset());
571 assert(P.SI->isSplittable() &&
"Forming a splittable partition!");
574 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
575 P.SJ->isSplittable()) {
576 P.EndOffset =
std::max(P.EndOffset, P.SJ->endOffset());
583 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
584 assert(!P.SJ->isSplittable());
585 P.EndOffset = P.SJ->beginOffset();
592 "End iterators don't match between compared partition iterators!");
599 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.
empty()) {
600 assert(P.SJ == RHS.P.SJ &&
601 "Same set of slices formed two different sized partitions!");
602 assert(P.SplitTails.size() == RHS.P.SplitTails.
size() &&
603 "Same slice position with differently sized non-empty split " 644 if (
PHINode *PN = dyn_cast<PHINode>(&I)) {
646 return PN->hasConstantValue();
661 const uint64_t AllocSize;
673 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
677 if (VisitedDeadInsts.
insert(&I).second)
678 AS.DeadUsers.push_back(&I);
682 bool IsSplittable =
false) {
685 if (Size == 0 || Offset.
uge(AllocSize)) {
686 LLVM_DEBUG(
dbgs() <<
"WARNING: Ignoring " << Size <<
" byte use @" 688 <<
" which has zero size or starts outside of the " 689 << AllocSize <<
" byte alloca:\n" 690 <<
" alloca: " << AS.AI <<
"\n" 691 <<
" use: " << I <<
"\n");
692 return markAsDead(I);
696 uint64_t EndOffset = BeginOffset +
Size;
704 assert(AllocSize >= BeginOffset);
705 if (Size > AllocSize - BeginOffset) {
706 LLVM_DEBUG(
dbgs() <<
"WARNING: Clamping a " << Size <<
" byte use @" 707 << Offset <<
" to remain within the " << AllocSize
709 <<
" alloca: " << AS.AI <<
"\n" 710 <<
" use: " << I <<
"\n");
711 EndOffset = AllocSize;
714 AS.Slices.
push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
719 return markAsDead(BC);
721 return Base::visitBitCastInst(BC);
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);
795 return PI.setEscapedAndAborted(&SI);
797 return PI.setAborted(&SI);
809 if (Size > AllocSize || Offset.
ugt(AllocSize - Size)) {
810 LLVM_DEBUG(
dbgs() <<
"WARNING: Ignoring " << Size <<
" byte store @" 811 << Offset <<
" which extends past the end of the " 812 << AllocSize <<
" byte alloca:\n" 813 <<
" alloca: " << AS.AI <<
"\n" 814 <<
" use: " << SI <<
"\n");
815 return markAsDead(SI);
819 "All simple FCA stores should have been pre-split");
826 if ((Length && Length->getValue() == 0) ||
827 (IsOffsetKnown && Offset.
uge(AllocSize)))
829 return markAsDead(II);
832 return PI.setAborted(&II);
841 if (Length && Length->
getValue() == 0)
843 return markAsDead(II);
847 if (VisitedDeadInsts.
count(&II))
851 return PI.setAborted(&II);
858 if (Offset.
uge(AllocSize)) {
860 MemTransferSliceMap.
find(&II);
861 if (MTPI != MemTransferSliceMap.
end())
862 AS.Slices[MTPI->second].kill();
863 return markAsDead(II);
867 uint64_t Size = Length ? Length->
getLimitedValue() : AllocSize - RawOffset;
874 return markAsDead(II);
876 return insertUse(II, Offset, Size,
false);
883 std::tie(MTPI, Inserted) =
884 MemTransferSliceMap.
insert(std::make_pair(&II, AS.Slices.
size()));
885 unsigned PrevIdx = MTPI->second;
887 Slice &PrevP = AS.Slices[PrevIdx];
891 if (!II.
isVolatile() && PrevP.beginOffset() == RawOffset) {
893 return markAsDead(II);
898 PrevP.makeUnsplittable();
902 insertUse(II, Offset, Size, Inserted && Length);
905 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
906 "Map index doesn't point back to a slice with this user.");
914 return PI.setAborted(&II);
921 insertUse(II, Offset, Size,
true);
925 Base::visitIntrinsicInst(II);
936 Uses.
push_back(std::make_pair(cast<Instruction>(*U), Root));
945 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
949 if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
958 if (!
GEP->hasAllZeroIndices())
960 }
else if (!isa<BitCastInst>(I) && !isa<PHINode>(
I) &&
961 !isa<SelectInst>(I)) {
966 if (Visited.
insert(cast<Instruction>(U)).second)
967 Uses.
push_back(std::make_pair(I, cast<Instruction>(U)));
968 }
while (!Uses.
empty());
974 assert(isa<PHINode>(I) || isa<SelectInst>(I));
976 return markAsDead(I);
994 AS.DeadOperands.push_back(U);
1000 return PI.setAborted(&I);
1003 uint64_t &Size = PHIOrSelectSizes[&
I];
1006 if (
Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
1007 return PI.setAborted(UnsafeI);
1016 if (Offset.
uge(AllocSize)) {
1017 AS.DeadOperands.push_back(U);
1021 insertUse(I, Offset, Size);
1024 void visitPHINode(
PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1026 void visitSelectInst(
SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1029 void visitInstruction(
Instruction &I) { PI.setAborted(&I); }
1034 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1037 PointerEscapingInstr(
nullptr) {
1045 assert(PointerEscapingInstr &&
"Did not track a bad instruction");
1055 std::mt19937 MT(static_cast<unsigned>(
1057 std::shuffle(Slices.begin(), Slices.end(), MT);
1066 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1070 printSlice(OS, I, Indent);
1072 printUse(OS, I, Indent);
1077 OS << Indent <<
"[" << I->beginOffset() <<
"," << I->endOffset() <<
")" 1078 <<
" slice #" << (I -
begin())
1079 << (I->isSplittable() ?
" (splittable)" :
"");
1084 OS << Indent <<
" used by: " << *I->getUse()->getUser() <<
"\n";
1088 if (PointerEscapingInstr) {
1089 OS <<
"Can't analyze slices for alloca: " << AI <<
"\n" 1090 <<
" A pointer to this alloca escaped by:\n" 1091 <<
" " << *PointerEscapingInstr <<
"\n";
1095 OS <<
"Slices of alloca: " << AI <<
"\n";
1096 for (const_iterator I =
begin(),
E =
end(); I !=
E; ++
I)
1105 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1111 uint64_t EndOffset) {
1113 bool TyIsCommon =
true;
1119 Use *U = I->getUse();
1120 if (isa<IntrinsicInst>(*U->getUser()))
1122 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1125 Type *UserTy =
nullptr;
1126 if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1127 UserTy = LI->getType();
1128 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1129 UserTy = SI->getValueOperand()->getType();
1132 if (
IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1137 if (UserITy->getBitWidth() % 8 != 0 ||
1138 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1143 if (!ITy || ITy->
getBitWidth() < UserITy->getBitWidth())
1149 if (!UserTy || (Ty && Ty != UserTy))
1155 return TyIsCommon ? Ty : ITy;
1182 unsigned MaxAlign = 0;
1183 bool HaveLoad =
false;
1198 if (BBI->mayWriteToMemory())
1243 Type *LoadTy = cast<PointerType>(PN.
getType())->getElementType();
1244 IRBuilderTy PHIBuilder(&PN);
1246 PN.
getName() +
".sroa.speculated");
1279 IRBuilderTy PredBuilder(TI);
1282 InVal, (PN.
getName() +
".sroa.speculate.load." + Pred->
getName()));
1283 ++NumLoadsSpeculated;
1288 InjectedLoads[Pred] =
Load;
1333 IRBuilderTy IRB(&SI);
1341 IRB.SetInsertPoint(LI);
1343 IRB.CreateLoad(TV, LI->
getName() +
".sroa.speculate.load.true");
1345 IRB.CreateLoad(FV, LI->
getName() +
".sroa.speculate.load.false");
1346 NumLoadsSpeculated += 2;
1360 LI->
getName() +
".sroa.speculated");
1375 if (Indices.
empty())
1380 if (Indices.
size() == 1 && cast<ConstantInt>(Indices.
back())->
isZero())
1383 return IRB.CreateInBoundsGEP(
nullptr, BasePtr, Indices,
1384 NamePrefix +
"sroa_idx");
1401 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1408 unsigned NumLayers = 0;
1409 Type *ElementTy = Ty;
1414 if (
ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1415 ElementTy = ArrayTy->getElementType();
1416 Indices.
push_back(IRB.getIntN(PtrSize, 0));
1417 }
else if (
VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1418 ElementTy = VectorTy->getElementType();
1420 }
else if (
StructType *STy = dyn_cast<StructType>(ElementTy)) {
1421 if (STy->element_begin() == STy->element_end())
1423 ElementTy = *STy->element_begin();
1429 }
while (ElementTy != TargetTy);
1430 if (ElementTy != TargetTy)
1431 Indices.
erase(Indices.
end() - NumLayers, Indices.
end());
1433 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1456 if (
VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1458 if (ElementSizeInBits % 8 != 0) {
1463 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1464 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1466 Offset -= NumSkippedElements * ElementSize;
1467 Indices.
push_back(IRB.getInt(NumSkippedElements));
1469 Offset, TargetTy, Indices, NamePrefix);
1472 if (
ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1473 Type *ElementTy = ArrTy->getElementType();
1475 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1476 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1479 Offset -= NumSkippedElements * ElementSize;
1480 Indices.
push_back(IRB.getInt(NumSkippedElements));
1482 Indices, NamePrefix);
1501 Indices, NamePrefix);
1529 if (ElementSize == 0)
1531 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1533 Offset -= NumSkippedElements * ElementSize;
1534 Indices.
push_back(IRB.getInt(NumSkippedElements));
1536 Indices, NamePrefix);
1565 Value *OffsetPtr =
nullptr;
1566 Value *OffsetBasePtr;
1570 Value *Int8Ptr =
nullptr;
1579 if (!
GEP->accumulateConstantOffset(DL, GEPOffset))
1581 Offset += GEPOffset;
1582 Ptr =
GEP->getPointerOperand();
1583 if (!Visited.
insert(Ptr).second)
1590 Indices, NamePrefix)) {
1594 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1595 if (
Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1596 assert(I->use_empty() &&
"Built a GEP with uses some how!");
1597 I->eraseFromParent();
1600 OffsetBasePtr =
Ptr;
1614 Ptr = cast<Operator>(
Ptr)->getOperand(0);
1615 }
else if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1616 if (GA->isInterposable())
1618 Ptr = GA->getAliasee();
1623 }
while (Visited.
insert(Ptr).second);
1627 Int8Ptr = IRB.CreateBitCast(
1629 NamePrefix +
"sroa_raw_cast");
1633 OffsetPtr = Int8PtrOffset == 0
1635 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1636 IRB.getInt(Int8PtrOffset),
1637 NamePrefix +
"sroa_raw_idx");
1643 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix +
"sroa_cast");
1653 if (
auto *LI = dyn_cast<LoadInst>(I)) {
1654 Alignment = LI->getAlignment();
1656 }
else if (
auto *SI = dyn_cast<StoreInst>(I)) {
1657 Alignment = SI->getAlignment();
1658 Ty = SI->getValueOperand()->getType();
1666 return MinAlign(Alignment, Offset);
1682 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1685 "We can't have the same bitwidth for different int types");
1700 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1701 cast<PointerType>(OldTy)->getPointerAddressSpace();
1734 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1735 "Integer types must be the exact same to convert.");
1742 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.
getIntPtrType(NewTy)),
1747 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.
getIntPtrType(NewTy)),
1750 return IRB.CreateIntToPtr(V, NewTy);
1758 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.
getIntPtrType(OldTy)),
1763 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.
getIntPtrType(OldTy)),
1766 return IRB.CreatePtrToInt(V, NewTy);
1769 return IRB.CreateBitCast(V, NewTy);
1778 uint64_t ElementSize,
1781 uint64_t BeginOffset =
1783 uint64_t BeginIndex = BeginOffset / ElementSize;
1784 if (BeginIndex * ElementSize != BeginOffset ||
1787 uint64_t EndOffset =
1789 uint64_t EndIndex = EndOffset / ElementSize;
1790 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->
getNumElements())
1793 assert(EndIndex > BeginIndex &&
"Empty vector!");
1794 uint64_t NumElements = EndIndex - BeginIndex;
1795 Type *SliceTy = (NumElements == 1)
1802 Use *U = S.getUse();
1805 if (
MI->isVolatile())
1807 if (!S.isSplittable())
1809 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1810 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1811 II->getIntrinsicID() != Intrinsic::lifetime_end)
1813 }
else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1816 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1817 if (LI->isVolatile())
1819 Type *LTy = LI->getType();
1826 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1827 if (SI->isVolatile())
1829 Type *STy = SI->getValueOperand()->getType();
1856 Type *CommonEltTy =
nullptr;
1857 bool HaveCommonEltTy =
true;
1858 auto CheckCandidateType = [&](
Type *Ty) {
1859 if (
auto *VTy = dyn_cast<VectorType>(Ty)) {
1862 CommonEltTy = VTy->getElementType();
1863 else if (CommonEltTy != VTy->getElementType())
1864 HaveCommonEltTy =
false;
1868 for (
const Slice &S : P)
1869 if (S.beginOffset() == P.beginOffset() &&
1870 S.endOffset() == P.endOffset()) {
1871 if (
auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1872 CheckCandidateType(LI->getType());
1873 else if (
auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1874 CheckCandidateType(SI->getValueOperand()->getType());
1878 if (CandidateTys.
empty())
1885 if (!HaveCommonEltTy) {
1891 CandidateTys.
end());
1894 if (CandidateTys.
empty())
1902 "Cannot have vector types of different sizes!");
1904 "All non-integer types eliminated!");
1905 assert(LHSTy->getElementType()->isIntegerTy() &&
1906 "All non-integer types eliminated!");
1911 std::unique(CandidateTys.
begin(), CandidateTys.
end(), RankVectorTypes),
1912 CandidateTys.
end());
1918 assert(VTy->getElementType() == CommonEltTy &&
1919 "Unaccounted for element type!");
1920 assert(VTy == CandidateTys[0] &&
1921 "Different vector types with the same element type!");
1924 CandidateTys.resize(1);
1928 auto CheckVectorTypeForPromotion = [&](
VectorType *VTy) {
1933 if (ElementSize % 8)
1936 "vector size not a multiple of element size?");
1939 for (
const Slice &S : P)
1943 for (
const Slice *S : P.splitSliceTails())
1950 if (CheckVectorTypeForPromotion(VTy))
1961 uint64_t AllocBeginOffset,
1964 bool &WholeAllocaOp) {
1967 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1968 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1975 Use *U = S.getUse();
1977 if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1978 if (LI->isVolatile())
1985 if (S.beginOffset() < AllocBeginOffset)
1990 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
1991 WholeAllocaOp =
true;
1992 if (
IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1995 }
else if (RelBegin != 0 || RelEnd != Size ||
2001 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2002 Type *ValueTy = SI->getValueOperand()->getType();
2003 if (SI->isVolatile())
2010 if (S.beginOffset() < AllocBeginOffset)
2015 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd ==
Size)
2016 WholeAllocaOp =
true;
2017 if (
IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2020 }
else if (RelBegin != 0 || RelEnd != Size ||
2026 }
else if (
MemIntrinsic *
MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2027 if (
MI->isVolatile() || !isa<Constant>(
MI->getLength()))
2029 if (!S.isSplittable())
2031 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2032 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2033 II->getIntrinsicID() != Intrinsic::lifetime_end)
2074 bool WholeAllocaOp =
2077 for (
const Slice &S : P)
2082 for (
const Slice *S : P.splitSliceTails())
2087 return WholeAllocaOp;
2092 const Twine &Name) {
2096 "Element extends past full value");
2097 uint64_t ShAmt = 8 *
Offset;
2101 V = IRB.CreateLShr(V, ShAmt, Name +
".shift");
2105 "Cannot extract to a larger integer!");
2107 V = IRB.CreateTrunc(V, Ty, Name +
".trunc");
2118 "Cannot insert a larger integer!");
2121 V = IRB.CreateZExt(V, IntTy, Name +
".ext");
2125 "Element store outside of alloca store");
2126 uint64_t ShAmt = 8 *
Offset;
2130 V = IRB.CreateShl(V, ShAmt, Name +
".shift");
2134 if (ShAmt || Ty->getBitWidth() < IntTy->
getBitWidth()) {
2136 Old = IRB.CreateAnd(Old, Mask, Name +
".mask");
2138 V = IRB.CreateOr(Old, V, Name +
".insert");
2145 unsigned EndIndex,
const Twine &Name) {
2147 unsigned NumElements = EndIndex - BeginIndex;
2148 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2153 if (NumElements == 1) {
2154 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2162 for (
unsigned i = BeginIndex; i != EndIndex; ++i)
2171 unsigned BeginIndex,
const Twine &Name) {
2173 assert(VecTy &&
"Can only insert a vector into a vector");
2178 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2185 "Too many elements!");
2199 if (i >= BeginIndex && i < EndIndex)
2200 Mask.
push_back(IRB.getInt32(i - BeginIndex));
2209 Mask.
push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2234 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2254 uint64_t ElementSize;
2258 uint64_t BeginOffset = 0;
2259 uint64_t EndOffset = 0;
2263 uint64_t NewBeginOffset, NewEndOffset;
2266 bool IsSplittable =
false;
2267 bool IsSplit =
false;
2268 Use *OldUse =
nullptr;
2282 uint64_t NewAllocaBeginOffset,
2283 uint64_t NewAllocaEndOffset,
bool IsIntegerPromotable,
2287 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2288 NewAllocaBeginOffset(NewAllocaBeginOffset),
2289 NewAllocaEndOffset(NewAllocaEndOffset),
2290 NewAllocaTy(NewAI.getAllocatedType()),
2291 IntTy(IsIntegerPromotable
2294 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2296 VecTy(PromotableVecTy),
2297 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2298 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2299 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2303 "Only multiple-of-8 sized vector elements are viable");
2306 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2310 bool CanSROA =
true;
2311 BeginOffset = I->beginOffset();
2312 EndOffset = I->endOffset();
2313 IsSplittable = I->isSplittable();
2315 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2316 LLVM_DEBUG(
dbgs() <<
" rewriting " << (IsSplit ?
"split " :
""));
2321 assert(BeginOffset < NewAllocaEndOffset);
2322 assert(EndOffset > NewAllocaBeginOffset);
2323 NewBeginOffset =
std::max(BeginOffset, NewAllocaBeginOffset);
2324 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2326 SliceSize = NewEndOffset - NewBeginOffset;
2328 OldUse = I->getUse();
2329 OldPtr = cast<Instruction>(OldUse->get());
2331 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2332 IRB.SetInsertPoint(OldUserI);
2333 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2336 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2355 assert(IsSplit || BeginOffset == NewBeginOffset);
2356 uint64_t
Offset = NewBeginOffset - NewAllocaBeginOffset;
2361 size_t LastSROAPrefix = OldName.
rfind(
".sroa.");
2363 OldName = OldName.
substr(LastSROAPrefix + strlen(
".sroa."));
2368 OldName = OldName.
substr(IndexEnd + 1);
2372 OldName = OldName.
substr(OffsetEnd + 1);
2376 OldName = OldName.
substr(0, OldName.
find(
".sroa_"));
2383 Twine(OldName) +
"." 2395 unsigned getSliceAlign(
Type *Ty =
nullptr) {
2400 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2404 unsigned getIndex(uint64_t
Offset) {
2405 assert(VecTy &&
"Can only call getIndex when rewriting a vector");
2406 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2407 assert(RelOffset / ElementSize < UINT32_MAX &&
"Index out of bounds");
2409 assert(Index * ElementSize == RelOffset);
2413 void deleteIfTriviallyDead(
Value *V) {
2416 Pass.DeadInsts.insert(I);
2419 Value *rewriteVectorizedLoadInst() {
2420 unsigned BeginIndex = getIndex(NewBeginOffset);
2421 unsigned EndIndex = getIndex(NewEndOffset);
2422 assert(EndIndex > BeginIndex &&
"Empty vector!");
2429 assert(IntTy &&
"We cannot insert an integer to the alloca");
2433 assert(NewBeginOffset >= NewAllocaBeginOffset &&
"Out of bounds offset");
2434 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2435 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2445 "Can only handle an extract for an overly wide load");
2447 V = IRB.CreateZExt(V, LI.
getType());
2464 bool IsPtrAdjusted =
false;
2467 V = rewriteVectorizedLoadInst();
2469 V = rewriteIntegerLoad(LI);
2470 }
else if (NewBeginOffset == NewAllocaBeginOffset &&
2471 NewEndOffset == NewAllocaEndOffset &&
2501 if (
auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2502 if (
auto *TITy = dyn_cast<IntegerType>(TargetTy))
2503 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2504 V = IRB.CreateZExt(V, TITy,
"load.ext");
2506 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2511 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2512 getSliceAlign(TargetTy),
2520 IsPtrAdjusted =
true;
2527 "Only integer type loads and stores are split");
2529 "Split load isn't smaller than original load");
2532 "Non-byte-multiple bit width");
2539 Value *Placeholder =
2541 V =
insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2550 Pass.DeadInsts.insert(&LI);
2551 deleteIfTriviallyDead(OldOp);
2559 unsigned BeginIndex = getIndex(NewBeginOffset);
2560 unsigned EndIndex = getIndex(NewEndOffset);
2561 assert(EndIndex > BeginIndex &&
"Empty vector!");
2562 unsigned NumElements = EndIndex - BeginIndex;
2563 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2564 Type *SliceTy = (NumElements == 1)
2577 Pass.DeadInsts.insert(&SI);
2584 assert(IntTy &&
"We cannot extract an integer from the alloca");
2588 IRB.CreateAlignedLoad(&NewAI, NewAI.
getAlignment(),
"oldload");
2590 assert(BeginOffset >= NewAllocaBeginOffset &&
"Out of bounds offset");
2591 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2599 Pass.DeadInsts.insert(&SI);
2618 Pass.PostPromotionWorklist.insert(AI);
2623 "Only integer type loads and stores are split");
2626 "Non-byte-multiple bit width");
2628 V =
extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2633 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
2635 return rewriteIntegerStore(V, SI, AATags);
2639 if (NewBeginOffset == NewAllocaBeginOffset &&
2640 NewEndOffset == NewAllocaEndOffset &&
2647 if (
auto *VITy = dyn_cast<IntegerType>(V->
getType()))
2648 if (
auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2649 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2651 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2653 V = IRB.CreateTrunc(V, AITy,
"load.trunc");
2657 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.
getAlignment(),
2662 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->
getType()),
2670 Pass.DeadInsts.insert(&SI);
2671 deleteIfTriviallyDead(OldOp);
2687 assert(Size > 0 &&
"Expected a positive number of bytes.");
2695 IRB.CreateZExt(V, SplatIntTy,
"zext"),
2705 Value *getVectorSplat(
Value *V,
unsigned NumElements) {
2706 V = IRB.CreateVectorSplat(NumElements, V,
"vsplat");
2722 assert(NewBeginOffset == BeginOffset);
2726 deleteIfTriviallyDead(OldPtr);
2731 Pass.DeadInsts.insert(&II);
2738 if (!VecTy && !IntTy &&
2739 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2764 assert(ElementTy == ScalarTy);
2766 unsigned BeginIndex = getIndex(NewBeginOffset);
2767 unsigned EndIndex = getIndex(NewEndOffset);
2768 assert(EndIndex > BeginIndex &&
"Empty vector!");
2769 unsigned NumElements = EndIndex - BeginIndex;
2770 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2775 if (NumElements > 1)
2776 Splat = getVectorSplat(Splat, NumElements);
2779 IRB.CreateAlignedLoad(&NewAI, NewAI.
getAlignment(),
"oldload");
2786 uint64_t Size = NewEndOffset - NewBeginOffset;
2789 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2790 EndOffset != NewAllocaBeginOffset)) {
2792 IRB.CreateAlignedLoad(&NewAI, NewAI.
getAlignment(),
"oldload");
2794 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2798 "Wrong type for an alloca wide integer!");
2803 assert(NewBeginOffset == NewAllocaBeginOffset);
2804 assert(NewEndOffset == NewAllocaEndOffset);
2807 if (
VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2808 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2834 unsigned SliceAlign = getSliceAlign();
2843 if (!IsSplittable) {
2844 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
2855 deleteIfTriviallyDead(OldPtr);
2868 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2875 if (EmitMemCpy && &OldAI == &NewAI) {
2877 assert(NewBeginOffset == BeginOffset);
2880 if (NewEndOffset != EndOffset)
2882 NewEndOffset - NewBeginOffset));
2886 Pass.DeadInsts.insert(&II);
2893 assert(AI != &OldAI && AI != &NewAI &&
2894 "Splittable transfers cannot reach the same alloca on both ends.");
2895 Pass.Worklist.insert(AI);
2903 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2904 unsigned OtherAlign =
2906 OtherAlign =
MinAlign(OtherAlign ? OtherAlign : 1,
2912 OtherPtr =
getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2915 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
2919 Value *DestPtr, *SrcPtr;
2920 unsigned DestAlign, SrcAlign;
2924 DestAlign = SliceAlign;
2926 SrcAlign = OtherAlign;
2929 DestAlign = OtherAlign;
2931 SrcAlign = SliceAlign;
2933 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2941 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2942 NewEndOffset == NewAllocaEndOffset;
2943 uint64_t Size = NewEndOffset - NewBeginOffset;
2944 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2945 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2946 unsigned NumElements = EndIndex - BeginIndex;
2952 if (VecTy && !IsWholeAlloca) {
2953 if (NumElements == 1)
2959 }
else if (IntTy && !IsWholeAlloca) {
2967 unsigned SrcAlign = OtherAlign;
2968 Value *DstPtr = &NewAI;
2969 unsigned DstAlign = SliceAlign;
2976 if (VecTy && !IsWholeAlloca && !IsDest) {
2977 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.
getAlignment(),
"load");
2979 }
else if (IntTy && !IsWholeAlloca && !IsDest) {
2980 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.
getAlignment(),
"load");
2982 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2992 if (VecTy && !IsWholeAlloca && IsDest) {
2994 IRB.CreateAlignedLoad(&NewAI, NewAI.
getAlignment(),
"oldload");
2996 }
else if (IntTy && !IsWholeAlloca && IsDest) {
2998 IRB.CreateAlignedLoad(&NewAI, NewAI.
getAlignment(),
"oldload");
3000 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3006 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.
isVolatile()));
3020 Pass.DeadInsts.insert(&II);
3029 if (NewBeginOffset != NewAllocaBeginOffset ||
3030 NewEndOffset != NewAllocaEndOffset)
3035 NewEndOffset - NewBeginOffset);
3039 New = IRB.CreateLifetimeStart(Ptr, Size);
3041 New = IRB.CreateLifetimeEnd(Ptr, Size);
3049 bool visitPHINode(
PHINode &PN) {
3051 assert(BeginOffset >= NewAllocaBeginOffset &&
"PHIs are unsplittable");
3052 assert(EndOffset <= NewAllocaEndOffset &&
"PHIs are unsplittable");
3058 IRBuilderTy PtrBuilder(IRB);
3059 if (isa<PHINode>(OldPtr))
3062 PtrBuilder.SetInsertPoint(OldPtr);
3063 PtrBuilder.SetCurrentDebugLocation(OldPtr->
getDebugLoc());
3065 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->
getType());
3070 deleteIfTriviallyDead(OldPtr);
3082 "Pointer isn't an operand!");
3083 assert(BeginOffset >= NewAllocaBeginOffset &&
"Selects are unsplittable");
3084 assert(EndOffset <= NewAllocaEndOffset &&
"Selects are unsplittable");
3086 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->
getType());
3094 deleteIfTriviallyDead(OldPtr);
3111 class AggLoadStoreRewriter :
public InstVisitor<AggLoadStoreRewriter, bool> {
3113 friend class InstVisitor<AggLoadStoreRewriter, bool>;
3131 bool Changed =
false;
3132 while (!Queue.empty()) {
3133 U = Queue.pop_back_val();
3134 Changed |= visit(cast<Instruction>(U->getUser()));
3145 Queue.push_back(&U);
3149 bool visitInstruction(
Instruction &I) {
return false; }
3152 template <
typename Derived>
class OpSplitter {
3172 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3190 return static_cast<Derived *>(
this)->emitFunc(Ty, Agg, Name);
3192 if (
ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3193 unsigned OldSize = Indices.
size();
3195 for (
unsigned Idx = 0,
Size = ATy->getNumElements(); Idx !=
Size;
3197 assert(Indices.
size() == OldSize &&
"Did not return to the old size");
3199 GEPIndices.
push_back(IRB.getInt32(Idx));
3200 emitSplitOps(ATy->getElementType(), Agg, Name +
"." +
Twine(Idx));
3207 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
3208 unsigned OldSize = Indices.
size();
3210 for (
unsigned Idx = 0,
Size = STy->getNumElements(); Idx !=
Size;
3212 assert(Indices.
size() == OldSize &&
"Did not return to the old size");
3214 GEPIndices.
push_back(IRB.getInt32(Idx));
3215 emitSplitOps(STy->getElementType(Idx), Agg, Name +
"." +
Twine(Idx));
3226 struct LoadOpSplitter :
public OpSplitter<LoadOpSplitter> {
3230 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr), AATags(AATags) {}
3238 IRB.CreateInBoundsGEP(
nullptr, Ptr, GEPIndices, Name +
".gep");
3242 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name +
".insert");
3256 LoadOpSplitter Splitter(&LI, *U, AATags);
3264 struct StoreOpSplitter :
public OpSplitter<StoreOpSplitter> {
3266 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr), AATags(AATags) {}
3277 Value *ExtractValue =
3278 IRB.CreateExtractValue(Agg, Indices, Name +
".extract");
3279 Value *InBoundsGEP =
3280 IRB.CreateInBoundsGEP(
nullptr, Ptr, GEPIndices, Name +
".gep");
3299 StoreOpSplitter Splitter(&SI, *U, AATags);
3315 bool visitPHINode(
PHINode &PN) {
3341 if (
ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3342 InnerTy = ArrTy->getElementType();
3343 }
else if (
StructType *STy = dyn_cast<StructType>(Ty)) {
3346 InnerTy = STy->getElementType(Index);
3380 Type *ElementTy = SeqTy->getElementType();
3382 uint64_t NumSkippedElements = Offset / ElementSize;
3383 if (NumSkippedElements >= SeqTy->getNumElements())
3385 Offset -= NumSkippedElements * ElementSize;
3388 if (Offset > 0 || Size < ElementSize) {
3390 if ((Offset + Size) > ElementSize)
3397 if (Size == ElementSize)
3399 assert(Size > ElementSize);
3400 uint64_t NumElements = Size / ElementSize;
3401 if (NumElements * ElementSize != Size)
3413 uint64_t EndOffset = Offset +
Size;
3422 if (Offset >= ElementSize)
3426 if (Offset > 0 || Size < ElementSize) {
3427 if ((Offset + Size) > ElementSize)
3433 if (Size == ElementSize)
3438 if (EndOffset < SL->getSizeInBytes()) {
3440 if (Index == EndIndex)
3450 assert(Index < EndIndex);
3458 if (Size != SubSL->getSizeInBytes())
3508 struct SplitOffsets {
3510 std::vector<uint64_t> Splits;
3527 LLVM_DEBUG(
dbgs() <<
" Searching for candidate loads and stores\n");
3529 for (Slice &S : P) {
3530 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3531 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3535 if (
auto *LI = dyn_cast<LoadInst>(I))
3536 UnsplittableLoads.
insert(LI);
3537 else if (
auto *SI = dyn_cast<StoreInst>(I))
3538 if (
auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3539 UnsplittableLoads.
insert(LI);
3542 assert(P.endOffset() > S.beginOffset() &&
3543 "Empty or backwards partition!");
3546 if (
auto *LI = dyn_cast<LoadInst>(I)) {
3547 assert(!LI->isVolatile() &&
"Cannot split volatile loads!");
3552 auto IsLoadSimplyStored = [](
LoadInst *LI) {
3555 if (!SI || !SI->isSimple())
3560 if (!IsLoadSimplyStored(LI)) {
3561 UnsplittableLoads.
insert(LI);
3566 }
else if (
auto *SI = dyn_cast<StoreInst>(I)) {
3567 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3571 if (!StoredLoad || !StoredLoad->isSimple())
3573 assert(!SI->isVolatile() &&
"Cannot split volatile stores!");
3583 auto &
Offsets = SplitOffsetsMap[
I];
3585 "Should not have splits the first time we see an instruction!");
3587 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3592 for (Slice *S : P.splitSliceTails()) {
3593 auto SplitOffsetsMapI =
3594 SplitOffsetsMap.
find(cast<Instruction>(S->getUse()->getUser()));
3595 if (SplitOffsetsMapI == SplitOffsetsMap.
end())
3597 auto &
Offsets = SplitOffsetsMapI->second;
3601 "Cannot have an empty set of splits on the second partition!");
3603 P.beginOffset() -
Offsets.S->beginOffset() &&
3604 "Previous split does not end where this one begins!");
3608 if (S->endOffset() > P.endOffset())
3609 Offsets.Splits.push_back(P.endOffset() -
Offsets.S->beginOffset());
3619 [&UnsplittableLoads, &SplitOffsetsMap](
StoreInst *SI) {
3625 if (UnsplittableLoads.
count(LI))
3628 auto LoadOffsetsI = SplitOffsetsMap.
find(LI);
3629 if (LoadOffsetsI == SplitOffsetsMap.
end())
3631 auto &LoadOffsets = LoadOffsetsI->second;
3634 auto &StoreOffsets = SplitOffsetsMap[
SI];
3639 if (LoadOffsets.Splits == StoreOffsets.Splits)
3644 <<
" Mismatched splits for load and store:\n" 3645 <<
" " << *LI <<
"\n" 3646 <<
" " << *SI <<
"\n");
3652 UnsplittableLoads.
insert(LI);
3664 return UnsplittableLoads.
count(LI);
3670 [&UnsplittableLoads](
LoadInst *LI) {
3671 return UnsplittableLoads.
count(LI);
3682 IRBuilderTy IRB(&AI);
3700 std::vector<LoadInst *> SplitLoads;
3707 assert(LoadSize > 0 &&
"Cannot have a zero-sized integer load!");
3709 auto &
Offsets = SplitOffsetsMap[LI];
3711 "Slice size should always match load size exactly!");
3712 uint64_t BaseOffset =
Offsets.S->beginOffset();
3713 assert(BaseOffset + LoadSize > BaseOffset &&
3714 "Cannot represent alloca access size using 64-bit integers!");
3717 IRB.SetInsertPoint(LI);
3721 uint64_t PartOffset = 0, PartSize =
Offsets.Splits.front();
3726 auto *PartPtrTy = PartTy->getPointerTo(AS);
3727 LoadInst *PLoad = IRB.CreateAlignedLoad(
3730 PartPtrTy, BasePtr->
getName() +
"."),
3737 SplitLoads.push_back(PLoad);
3741 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3745 <<
", " << NewSlices.
back().endOffset()
3746 <<
"): " << *PLoad <<
"\n");
3753 PartOffset =
Offsets.Splits[Idx];
3755 PartSize = (Idx <
Size ?
Offsets.Splits[Idx] : LoadSize) - PartOffset;
3761 bool DeferredStores =
false;
3764 if (!Stores.
empty() && SplitOffsetsMap.
count(SI)) {
3765 DeferredStores =
true;
3772 IRB.SetInsertPoint(SI);
3774 LLVM_DEBUG(
dbgs() <<
" Splitting store of load: " << *SI <<
"\n");
3776 for (
int Idx = 0,
Size = SplitLoads.size(); Idx <
Size; ++Idx) {
3778 uint64_t PartOffset = Idx == 0 ? 0 :
Offsets.Splits[Idx - 1];
3783 StoreInst *PStore = IRB.CreateAlignedStore(
3787 PartPtrTy, StoreBasePtr->
getName() +
"."),
3790 LLVM_DEBUG(
dbgs() <<
" +" << PartOffset <<
":" << *PStore <<
"\n");
3797 if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3798 ResplitPromotableAllocas.
insert(OtherAI);
3799 Worklist.insert(OtherAI);
3800 }
else if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3802 Worklist.insert(OtherAI);
3806 DeadInsts.insert(SI);
3811 SplitLoadsMap.
insert(std::make_pair(LI, std::move(SplitLoads)));
3814 DeadInsts.insert(LI);
3827 assert(StoreSize > 0 &&
"Cannot have a zero-sized integer store!");
3831 "Slice size should always match load size exactly!");
3832 uint64_t BaseOffset =
Offsets.S->beginOffset();
3833 assert(BaseOffset + StoreSize > BaseOffset &&
3834 "Cannot represent alloca access size using 64-bit integers!");
3842 auto SplitLoadsMapI = SplitLoadsMap.
find(LI);
3843 std::vector<LoadInst *> *SplitLoads =
nullptr;
3844 if (SplitLoadsMapI != SplitLoadsMap.
end()) {
3845 SplitLoads = &SplitLoadsMapI->second;
3847 "Too few split loads for the number of splits in the store!");
3852 uint64_t PartOffset = 0, PartSize =
Offsets.Splits.front();
3862 PLoad = (*SplitLoads)[Idx];
3864 IRB.SetInsertPoint(LI);
3866 PLoad = IRB.CreateAlignedLoad(
3869 LoadPartPtrTy, LoadBasePtr->
getName() +
"."),
3875 IRB.SetInsertPoint(SI);
3877 StoreInst *PStore = IRB.CreateAlignedStore(
3881 StorePartPtrTy, StoreBasePtr->
getName() +
"."),
3886 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3890 <<
", " << NewSlices.
back().endOffset()
3891 <<
"): " << *PStore <<
"\n");
3901 PartOffset =
Offsets.Splits[Idx];
3903 PartSize = (Idx <
Size ?
Offsets.Splits[Idx] : StoreSize) - PartOffset;
3912 if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3913 assert(OtherAI != &AI &&
"We can't re-split our own alloca!");
3914 ResplitPromotableAllocas.
insert(OtherAI);
3915 Worklist.insert(OtherAI);
3916 }
else if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3918 assert(OtherAI != &AI &&
"We can't re-split our own alloca!");
3919 Worklist.insert(OtherAI);
3934 DeadInsts.insert(LI);
3936 DeadInsts.insert(SI);
3950 for (
auto I = AS.
begin(),
E = AS.
end(); I !=
E; ++
I)
3956 PromotableAllocas.erase(
3960 PromotableAllocas.end());
3980 Type *SliceTy =
nullptr;
3984 SliceTy = CommonUseTy;
3988 SliceTy = TypePartitionTy;
3989 if ((!SliceTy || (SliceTy->
isArrayTy() &&
4039 <<
") to: " << *NewAI <<
"\n");
4044 unsigned PPWOldSize = PostPromotionWorklist.size();
4045 unsigned NumUses = 0;
4050 P.
endOffset(), IsIntegerPromotable, VecTy,
4051 PHIUsers, SelectUsers);
4052 bool Promotable =
true;
4057 for (Slice &S : P) {
4062 NumAllocaPartitionUses += NumUses;
4063 MaxUsesPerAllocaPartition.updateMax(NumUses);
4071 SelectUsers.
clear();
4079 SelectUsers.clear();
4084 if (PHIUsers.empty() && SelectUsers.empty()) {
4086 PromotableAllocas.push_back(NewAI);
4091 for (
PHINode *PHIUser : PHIUsers)
4092 SpeculatablePHIs.insert(PHIUser);
4094 SpeculatableSelects.insert(SelectUser);
4095 Worklist.insert(NewAI);
4099 while (PostPromotionWorklist.size() > PPWOldSize)
4100 PostPromotionWorklist.pop_back();
4110 Worklist.insert(NewAI);
4122 unsigned NumPartitions = 0;
4123 bool Changed =
false;
4127 Changed |= presplitLoadsAndStores(AI, AS);
4135 bool IsSorted =
true;
4138 const uint64_t MaxBitVectorSize = 1024;
4139 if (AllocaSize <= MaxBitVectorSize) {
4144 for (
unsigned O = S.beginOffset() + 1;
4145 O < S.endOffset() &&
O < AllocaSize;
O++)
4146 SplittableOffset.
reset(
O);
4148 for (Slice &S : AS) {
4149 if (!S.isSplittable())
4152 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4153 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4156 if (isa<LoadInst>(S.getUse()->getUser()) ||
4157 isa<StoreInst>(S.getUse()->getUser())) {
4158 S.makeUnsplittable();
4166 for (Slice &S : AS) {
4167 if (!S.isSplittable())
4170 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4173 if (isa<LoadInst>(S.getUse()->getUser()) ||
4174 isa<StoreInst>(S.getUse()->getUser())) {
4175 S.makeUnsplittable();
4197 if (
AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4200 uint64_t SizeOfByte = 8;
4203 uint64_t
Size = std::min(AllocaSize, P.
size() * SizeOfByte);
4210 NumAllocaPartitions += NumPartitions;
4211 MaxPartitionsPerAlloca.updateMax(NumPartitions);
4216 if (!DbgDeclares.
empty()) {
4219 auto VarSize = Var->getSizeInBits();
4222 for (
auto Fragment : Fragments) {
4225 auto *FragmentExpr = Expr;
4226 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
4229 auto ExprFragment = Expr->getFragmentInfo();
4230 uint64_t
Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
4231 uint64_t Start = Offset + Fragment.Offset;
4232 uint64_t
Size = Fragment.Size;
4235 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
4236 if (Start >= AbsEnd)
4239 Size = std::min(Size, AbsEnd - Start);
4242 if (
auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4243 assert(Start >= OrigFragment->OffsetInBits &&
4244 "new fragment is outside of original fragment");
4245 Start -= OrigFragment->OffsetInBits;
4250 if (Size > *VarSize)
4252 if (Size == 0 || Start + Size > *VarSize)
4257 if (!VarSize || *VarSize != Size) {
4268 OldDII->eraseFromParent();
4270 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
4278 void SROA::clobberUse(
Use &U) {
4286 if (
Instruction *OldI = dyn_cast<Instruction>(OldV))
4288 DeadInsts.insert(OldI);
4299 ++NumAllocasAnalyzed;
4313 bool Changed =
false;
4317 AggLoadStoreRewriter AggRewriter;
4318 Changed |= AggRewriter.rewrite(AI);
4329 for (
Use &DeadOp : DeadUser->operands())
4336 DeadInsts.insert(DeadUser);
4340 clobberUse(*DeadOp);
4348 Changed |= splitAlloca(AI, AS);
4351 while (!SpeculatablePHIs.empty())
4355 while (!SpeculatableSelects.empty())
4370 bool SROA::deleteDeadInstructions(
4372 bool Changed =
false;
4373 while (!DeadInsts.empty()) {
4375 LLVM_DEBUG(
dbgs() <<
"Deleting dead instruction: " << *I <<
"\n");
4380 if (
AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4381 DeletedAllocas.
insert(AI);
4383 OldDII->eraseFromParent();
4389 if (
Instruction *U = dyn_cast<Instruction>(Operand)) {
4393 DeadInsts.insert(U);
4408 bool SROA::promoteAllocas(
Function &
F) {
4409 if (PromotableAllocas.empty())
4412 NumPromoted += PromotableAllocas.size();
4416 PromotableAllocas.clear();
4430 if (
AllocaInst *AI = dyn_cast<AllocaInst>(I))
4431 Worklist.insert(AI);
4434 bool Changed =
false;
4440 while (!Worklist.empty()) {
4441 Changed |= runOnAlloca(*Worklist.pop_back_val());
4442 Changed |= deleteDeadInstructions(DeletedAllocas);
4446 if (!DeletedAllocas.
empty()) {
4447 auto IsInSet = [&](
AllocaInst *AI) {
return DeletedAllocas.
count(AI); };
4448 Worklist.remove_if(IsInSet);
4449 PostPromotionWorklist.remove_if(IsInSet);
4451 PromotableAllocas.end());
4452 DeletedAllocas.
clear();
4456 Changed |= promoteAllocas(F);
4458 Worklist = PostPromotionWorklist;
4459 PostPromotionWorklist.clear();
4460 }
while (!Worklist.empty());
4492 if (skipFunction(F))
4495 auto PA = Impl.runImpl(
4496 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4497 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4516 "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 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.
void push_back(const T &Elt)
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.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
An iterator over partitions of the alloca's slices.
Maximum number of bits that can be specified.
void setInt(IntType IntVal)
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.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
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.
Compute iterated dominance frontiers using a linear time algorithm.
PointerTy getPointer() const
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.
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.
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
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.
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...
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
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.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
An instruction for reading from memory.
APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
bool isVectorTy() const
True if this is an instance of VectorType.
This defines the Use class.
void reserve(size_type N)
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...
bool isSafeToLoadUnconditionally(Value *V, unsigned Align, const DataLayout &DL, Instruction *ScanFrom=nullptr, const DominatorTree *DT=nullptr)
Return true if we know that executing a load from this value cannot trap.
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.
static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset, const DataLayout &DL)
Compute the adjusted alignment for a load or store from an offset.
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.
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.
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)
void setPointer(PointerTy PtrVal)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
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.
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
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
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
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.
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.
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.
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
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
static Constant * getUDiv(Constant *C1, Constant *C2, bool isExact=false)
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.
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...
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
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
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)
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)
Subclasses of this class are all able to terminate a basic block.
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()
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
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...
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
Represent the analysis usage information of a pass.
static cl::opt< bool > SROAStrictInbounds("sroa-strict-inbounds", cl::init(false), cl::Hidden)
Hidden option to experiment with completely strict handling of inbounds GEPs.
DILocalVariable * getVariable() const
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass providing a never-invalidated alias analysis result.
void initializeSROALegacyPassPass(PassRegistry &)
FunctionPass class - This class is used to implement most global optimizations.
DIExpression * getExpression() const
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.
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)
void setAlignment(unsigned Align)
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.
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.
isPodLike - This is a type trait that is used to determine whether a given type can be copied around ...
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.
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)
This is the common base class for debug info intrinsics.
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()
TinyPtrVector< DbgInfoIntrinsic * > FindDbgAddrUses(Value *V)
Finds all intrinsics declaring local variables as living in the memory that 'V' points to...
Represents analyses that only rely on functions' control flow.
const Value * getFalseValue() const
#define LLVM_ATTRIBUTE_UNUSED
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...
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
static Value * foldPHINodeOrSelectInst(Instruction &I)
A helper that folds a PHI node or a select.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
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 greather than comparison.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
This class wraps the llvm.memcpy/memmove intrinsics.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
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.
uint64_t getElementOffset(unsigned Idx) const
unsigned getAlignment() const
Return the alignment of the access that is being performed.
unsigned getIntegerBitWidth() const
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...
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.
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.
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.
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()
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
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.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
static bool isSafePHIToSpeculate(PHINode &PN)
PHI instructions that use an alloca and are subsequently loaded can be rewritten to load both input p...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
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.
static VectorType * get(Type *ElementType, unsigned NumElements)
This static method is the primary way to construct an VectorType.
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.
static Expected< std::string > replace(StringRef S, StringRef From, StringRef To)
void setSourceAlignment(unsigned Align)
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)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This header defines various interfaces for pass management in LLVM.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Value * getPointerOperand()
static IntegerType * getInt8Ty(LLVMContext &C)
Value * getRawDest() const
static Constant * get(ArrayRef< Constant *> V)
Type * getElementType() const
const Use & getRawDestUse() const
void setDestAlignment(unsigned Align)
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