67 #define DEBUG_TYPE "sroa"
69 STATISTIC(NumAllocasAnalyzed,
"Number of allocas analyzed for replacement");
70 STATISTIC(NumAllocaPartitions,
"Number of alloca partitions formed");
71 STATISTIC(MaxPartitionsPerAlloca,
"Maximum number of partitions per alloca");
72 STATISTIC(NumAllocaPartitionUses,
"Number of alloca partition uses rewritten");
73 STATISTIC(MaxUsesPerAllocaPartition,
"Maximum number of uses of a partition");
74 STATISTIC(NumNewAllocas,
"Number of new, smaller allocas introduced");
75 STATISTIC(NumPromoted,
"Number of allocas promoted to SSA values");
76 STATISTIC(NumLoadsSpeculated,
"Number of loads speculated to allow promotion");
77 STATISTIC(NumDeleted,
"Number of instructions deleted");
78 STATISTIC(NumVectorized,
"Number of vectorized aggregates");
123 uint64_t BeginOffset;
133 Slice() : BeginOffset(), EndOffset() {}
134 Slice(uint64_t BeginOffset, uint64_t EndOffset,
Use *U,
bool IsSplittable)
135 : BeginOffset(BeginOffset), EndOffset(EndOffset),
136 UseAndIsSplittable(U, IsSplittable) {}
138 uint64_t beginOffset()
const {
return BeginOffset; }
139 uint64_t endOffset()
const {
return EndOffset; }
141 bool isSplittable()
const {
return UseAndIsSplittable.getInt(); }
142 void makeUnsplittable() { UseAndIsSplittable.setInt(
false); }
144 Use *getUse()
const {
return UseAndIsSplittable.getPointer(); }
146 bool isDead()
const {
return getUse() ==
nullptr; }
147 void kill() { UseAndIsSplittable.setPointer(
nullptr); }
156 if (beginOffset() < RHS.beginOffset())
158 if (beginOffset() > RHS.beginOffset())
160 if (isSplittable() != RHS.isSplittable())
161 return !isSplittable();
162 if (endOffset() > RHS.endOffset())
169 uint64_t RHSOffset) {
170 return LHS.beginOffset() < RHSOffset;
174 return LHSOffset < RHS.beginOffset();
178 return isSplittable() == RHS.isSplittable() &&
179 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
187 template <>
struct isPodLike<Slice> {
static const bool value =
true; };
230 int OldSize = Slices.
size();
232 auto SliceI = Slices.
begin() + OldSize;
234 std::inplace_merge(Slices.
begin(), SliceI, Slices.
end());
239 class partition_iterator;
253 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
265 template <
typename DerivedT,
typename RetT =
void>
class BuilderBase;
269 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
327 uint64_t BeginOffset, EndOffset;
337 Partition(iterator SI) : SI(SI), SJ(SI) {}
354 assert(BeginOffset < EndOffset &&
"Partitions must span some bytes!");
355 return EndOffset - BeginOffset;
360 bool empty()
const {
return SI == SJ; }
371 iterator
begin()
const {
return SI; }
372 iterator
end()
const {
return SJ; }
406 uint64_t MaxSplitSliceEndOffset;
411 :
P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
422 assert((
P.SI != SE || !
P.SplitTails.empty()) &&
423 "Cannot advance past the end of the slices!");
426 if (!
P.SplitTails.empty()) {
427 if (
P.EndOffset >= MaxSplitSliceEndOffset) {
429 P.SplitTails.clear();
430 MaxSplitSliceEndOffset = 0;
437 [&](Slice *S) {
return S->endOffset() <=
P.EndOffset; }),
441 return S->endOffset() == MaxSplitSliceEndOffset;
443 "Could not find the current max split slice offset!");
446 return S->endOffset() <= MaxSplitSliceEndOffset;
448 "Max split slice end offset is not actually the max!");
455 assert(
P.SplitTails.empty() &&
"Failed to clear the split slices!");
465 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
466 P.SplitTails.push_back(&S);
467 MaxSplitSliceEndOffset =
468 std::max(S.endOffset(), MaxSplitSliceEndOffset);
476 P.BeginOffset = P.EndOffset;
477 P.EndOffset = MaxSplitSliceEndOffset;
484 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
485 !P.SI->isSplittable()) {
486 P.BeginOffset = P.EndOffset;
487 P.EndOffset = P.SI->beginOffset();
497 P.BeginOffset = P.SplitTails.
empty() ? P.SI->beginOffset() : P.EndOffset;
498 P.EndOffset = P.SI->endOffset();
503 if (!P.SI->isSplittable()) {
506 assert(P.BeginOffset == P.SI->beginOffset());
510 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
511 if (!P.SJ->isSplittable())
512 P.EndOffset =
std::max(P.EndOffset, P.SJ->endOffset());
524 assert(P.SI->isSplittable() &&
"Forming a splittable partition!");
527 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
528 P.SJ->isSplittable()) {
529 P.EndOffset =
std::max(P.EndOffset, P.SJ->endOffset());
536 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
537 assert(!P.SJ->isSplittable());
538 P.EndOffset = P.SJ->beginOffset();
545 "End iterators don't match between compared partition iterators!");
552 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.
empty()) {
553 assert(P.SJ == RHS.P.SJ &&
554 "Same set of slices formed two different sized partitions!");
555 assert(P.SplitTails.size() == RHS.P.SplitTails.
size() &&
556 "Same slice position with differently sized non-empty split "
580 partition_iterator(
end(),
end()));
597 if (
PHINode *PN = dyn_cast<PHINode>(&I)) {
599 return PN->hasConstantValue();
613 const uint64_t AllocSize;
625 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
629 if (VisitedDeadInsts.insert(&I).second)
630 AS.DeadUsers.push_back(&I);
634 bool IsSplittable =
false) {
637 if (Size == 0 || Offset.
uge(AllocSize)) {
638 DEBUG(
dbgs() <<
"WARNING: Ignoring " << Size <<
" byte use @" << Offset
639 <<
" which has zero size or starts outside of the "
640 << AllocSize <<
" byte alloca:\n"
641 <<
" alloca: " << AS.AI <<
"\n"
642 <<
" use: " << I <<
"\n");
643 return markAsDead(I);
647 uint64_t EndOffset = BeginOffset +
Size;
655 assert(AllocSize >= BeginOffset);
656 if (Size > AllocSize - BeginOffset) {
657 DEBUG(
dbgs() <<
"WARNING: Clamping a " << Size <<
" byte use @" << Offset
658 <<
" to remain within the " << AllocSize <<
" byte alloca:\n"
659 <<
" alloca: " << AS.AI <<
"\n"
660 <<
" use: " << I <<
"\n");
661 EndOffset = AllocSize;
664 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
669 return markAsDead(BC);
671 return Base::visitBitCastInst(BC);
676 return markAsDead(GEPI);
696 if (
StructType *STy = GTI.getStructTypeOrNull()) {
712 if (GEPOffset.
ugt(AllocSize))
713 return markAsDead(GEPI);
717 return Base::visitGetElementPtrInst(GEPI);
727 insertUse(I, Offset, Size, IsSplittable);
732 "All simple FCA loads should have been pre-split");
735 return PI.setAborted(&LI);
745 return PI.setEscapedAndAborted(&SI);
747 return PI.setAborted(&SI);
759 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
760 DEBUG(
dbgs() <<
"WARNING: Ignoring " << Size <<
" byte store @" << Offset
761 <<
" which extends past the end of the " << AllocSize
763 <<
" alloca: " << AS.AI <<
"\n"
764 <<
" use: " << SI <<
"\n");
765 return markAsDead(SI);
769 "All simple FCA stores should have been pre-split");
776 if ((Length && Length->getValue() == 0) ||
777 (IsOffsetKnown && Offset.uge(AllocSize)))
779 return markAsDead(II);
782 return PI.setAborted(&II);
784 insertUse(II, Offset, Length ? Length->getLimitedValue()
785 : AllocSize - Offset.getLimitedValue(),
791 if (Length && Length->
getValue() == 0)
793 return markAsDead(II);
797 if (VisitedDeadInsts.count(&II))
801 return PI.setAborted(&II);
808 if (Offset.uge(AllocSize)) {
810 MemTransferSliceMap.
find(&II);
811 if (MTPI != MemTransferSliceMap.
end())
812 AS.Slices[MTPI->second].kill();
813 return markAsDead(II);
816 uint64_t RawOffset = Offset.getLimitedValue();
817 uint64_t Size = Length ? Length->
getLimitedValue() : AllocSize - RawOffset;
824 return markAsDead(II);
826 return insertUse(II, Offset, Size,
false);
833 std::tie(MTPI, Inserted) =
834 MemTransferSliceMap.
insert(std::make_pair(&II, AS.Slices.size()));
835 unsigned PrevIdx = MTPI->second;
837 Slice &PrevP = AS.Slices[PrevIdx];
841 if (!II.
isVolatile() && PrevP.beginOffset() == RawOffset) {
843 return markAsDead(II);
848 PrevP.makeUnsplittable();
852 insertUse(II, Offset, Size, Inserted && Length);
855 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
856 "Map index doesn't point back to a slice with this user.");
864 return PI.setAborted(&II);
869 uint64_t Size =
std::min(AllocSize - Offset.getLimitedValue(),
871 insertUse(II, Offset, Size,
true);
875 Base::visitIntrinsicInst(II);
886 Uses.
push_back(std::make_pair(cast<Instruction>(*U), Root));
895 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
899 if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
908 if (!
GEP->hasAllZeroIndices())
910 }
else if (!isa<BitCastInst>(I) && !isa<PHINode>(
I) &&
911 !isa<SelectInst>(I)) {
916 if (Visited.
insert(cast<Instruction>(U)).second)
917 Uses.
push_back(std::make_pair(I, cast<Instruction>(U)));
918 }
while (!Uses.
empty());
924 assert(isa<PHINode>(I) || isa<SelectInst>(I));
926 return markAsDead(I);
944 AS.DeadOperands.push_back(U);
950 return PI.setAborted(&I);
953 uint64_t &Size = PHIOrSelectSizes[&
I];
956 if (
Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
957 return PI.setAborted(UnsafeI);
966 if (Offset.uge(AllocSize)) {
967 AS.DeadOperands.push_back(U);
971 insertUse(I, Offset, Size);
974 void visitPHINode(
PHINode &PN) { visitPHINodeOrSelectInst(PN); }
976 void visitSelectInst(
SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
979 void visitInstruction(
Instruction &I) { PI.setAborted(&I); }
984 #
if !defined(
NDEBUG) || defined(LLVM_ENABLE_DUMP)
987 PointerEscapingInstr(nullptr) {
989 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
990 if (PtrI.isEscaped() || PtrI.isAborted()) {
993 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
994 : PtrI.getAbortingInst();
995 assert(PointerEscapingInstr &&
"Did not track a bad instruction");
999 Slices.erase(
remove_if(Slices, [](
const Slice &S) {
return S.isDead(); }),
1004 std::mt19937 MT(static_cast<unsigned>(
1006 std::shuffle(Slices.begin(), Slices.end(), MT);
1012 std::sort(Slices.begin(), Slices.end());
1015 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1017 void AllocaSlices::print(
raw_ostream &OS, const_iterator I,
1019 printSlice(OS, I, Indent);
1021 printUse(OS, I, Indent);
1024 void AllocaSlices::printSlice(
raw_ostream &OS, const_iterator I,
1026 OS << Indent <<
"[" << I->beginOffset() <<
"," << I->endOffset() <<
")"
1027 <<
" slice #" << (I -
begin())
1028 << (I->isSplittable() ?
" (splittable)" :
"");
1031 void AllocaSlices::printUse(
raw_ostream &OS, const_iterator I,
1033 OS << Indent <<
" used by: " << *I->getUse()->getUser() <<
"\n";
1037 if (PointerEscapingInstr) {
1038 OS <<
"Can't analyze slices for alloca: " << AI <<
"\n"
1039 <<
" A pointer to this alloca escaped by:\n"
1040 <<
" " << *PointerEscapingInstr <<
"\n";
1044 OS <<
"Slices of alloca: " << AI <<
"\n";
1045 for (const_iterator I =
begin(),
E =
end(); I !=
E; ++
I)
1054 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1059 AllocaSlices::const_iterator
E,
1060 uint64_t EndOffset) {
1062 bool TyIsCommon =
true;
1067 for (AllocaSlices::const_iterator I = B; I !=
E; ++
I) {
1068 Use *U = I->getUse();
1069 if (isa<IntrinsicInst>(*U->getUser()))
1071 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1074 Type *UserTy =
nullptr;
1075 if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1077 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1081 if (
IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1086 if (UserITy->getBitWidth() % 8 != 0 ||
1087 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1092 if (!ITy || ITy->
getBitWidth() < UserITy->getBitWidth())
1098 if (!UserTy || (Ty && Ty != UserTy))
1104 return TyIsCommon ? Ty : ITy;
1131 unsigned MaxAlign = 0;
1132 bool HaveLoad =
false;
1147 if (BBI->mayWriteToMemory())
1190 DEBUG(
dbgs() <<
" original: " << PN <<
"\n");
1192 Type *LoadTy = cast<PointerType>(PN.
getType())->getElementType();
1193 IRBuilderTy PHIBuilder(&PN);
1195 PN.
getName() +
".sroa.speculated");
1217 IRBuilderTy PredBuilder(TI);
1220 InVal, (PN.
getName() +
".sroa.speculate.load." + Pred->
getName()));
1221 ++NumLoadsSpeculated;
1228 DEBUG(
dbgs() <<
" speculated to: " << *NewPN <<
"\n");
1268 DEBUG(
dbgs() <<
" original: " << SI <<
"\n");
1270 IRBuilderTy IRB(&SI);
1278 IRB.SetInsertPoint(LI);
1280 IRB.CreateLoad(TV, LI->
getName() +
".sroa.speculate.load.true");
1282 IRB.CreateLoad(FV, LI->
getName() +
".sroa.speculate.load.false");
1283 NumLoadsSpeculated += 2;
1297 LI->
getName() +
".sroa.speculated");
1299 DEBUG(
dbgs() <<
" speculated to: " << *V <<
"\n");
1312 if (Indices.
empty())
1317 if (Indices.
size() == 1 && cast<ConstantInt>(Indices.
back())->
isZero())
1320 return IRB.CreateInBoundsGEP(
nullptr, BasePtr, Indices,
1321 NamePrefix +
"sroa_idx");
1338 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1345 unsigned NumLayers = 0;
1346 Type *ElementTy = Ty;
1351 if (
ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1352 ElementTy = ArrayTy->getElementType();
1353 Indices.
push_back(IRB.getIntN(PtrSize, 0));
1354 }
else if (
VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1355 ElementTy = VectorTy->getElementType();
1357 }
else if (
StructType *STy = dyn_cast<StructType>(ElementTy)) {
1358 if (STy->element_begin() == STy->element_end())
1360 ElementTy = *STy->element_begin();
1366 }
while (ElementTy != TargetTy);
1367 if (ElementTy != TargetTy)
1368 Indices.
erase(Indices.
end() - NumLayers, Indices.
end());
1370 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1393 if (
VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1395 if (ElementSizeInBits % 8 != 0) {
1400 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1401 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1403 Offset -= NumSkippedElements * ElementSize;
1404 Indices.
push_back(IRB.getInt(NumSkippedElements));
1406 Offset, TargetTy, Indices, NamePrefix);
1409 if (
ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1410 Type *ElementTy = ArrTy->getElementType();
1412 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1413 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1416 Offset -= NumSkippedElements * ElementSize;
1417 Indices.
push_back(IRB.getInt(NumSkippedElements));
1419 Indices, NamePrefix);
1438 Indices, NamePrefix);
1466 if (ElementSize == 0)
1468 APInt NumSkippedElements = Offset.
sdiv(ElementSize);
1470 Offset -= NumSkippedElements * ElementSize;
1471 Indices.
push_back(IRB.getInt(NumSkippedElements));
1473 Indices, NamePrefix);
1502 Value *OffsetPtr =
nullptr;
1503 Value *OffsetBasePtr;
1507 Value *Int8Ptr =
nullptr;
1516 if (!
GEP->accumulateConstantOffset(DL, GEPOffset))
1518 Offset += GEPOffset;
1519 Ptr =
GEP->getPointerOperand();
1520 if (!Visited.
insert(Ptr).second)
1527 Indices, NamePrefix)) {
1531 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1532 if (
Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1533 assert(I->use_empty() &&
"Built a GEP with uses some how!");
1534 I->eraseFromParent();
1537 OffsetBasePtr =
Ptr;
1550 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1551 Ptr = cast<Operator>(
Ptr)->getOperand(0);
1552 }
else if (
GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1553 if (GA->isInterposable())
1555 Ptr = GA->getAliasee();
1560 }
while (Visited.
insert(Ptr).second);
1564 Int8Ptr = IRB.CreateBitCast(
1566 NamePrefix +
"sroa_raw_cast");
1570 OffsetPtr = Int8PtrOffset == 0
1572 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1573 IRB.getInt(Int8PtrOffset),
1574 NamePrefix +
"sroa_raw_idx");
1580 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix +
"sroa_cast");
1590 if (
auto *LI = dyn_cast<LoadInst>(I)) {
1593 }
else if (
auto *SI = dyn_cast<StoreInst>(I)) {
1603 return MinAlign(Alignment, Offset);
1619 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1622 "We can't have the same bitwidth for different int types");
1637 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1638 cast<PointerType>(OldTy)->getPointerAddressSpace();
1671 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1672 "Integer types must be the exact same to convert.");
1679 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.
getIntPtrType(NewTy)),
1684 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.
getIntPtrType(NewTy)),
1687 return IRB.CreateIntToPtr(V, NewTy);
1695 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.
getIntPtrType(OldTy)),
1700 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.
getIntPtrType(OldTy)),
1703 return IRB.CreatePtrToInt(V, NewTy);
1706 return IRB.CreateBitCast(V, NewTy);
1715 uint64_t ElementSize,
1718 uint64_t BeginOffset =
1720 uint64_t BeginIndex = BeginOffset / ElementSize;
1721 if (BeginIndex * ElementSize != BeginOffset ||
1724 uint64_t EndOffset =
1726 uint64_t EndIndex = EndOffset / ElementSize;
1727 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->
getNumElements())
1730 assert(EndIndex > BeginIndex &&
"Empty vector!");
1731 uint64_t NumElements = EndIndex - BeginIndex;
1732 Type *SliceTy = (NumElements == 1)
1737 Type::getIntNTy(Ty->
getContext(), NumElements * ElementSize * 8);
1739 Use *U = S.getUse();
1742 if (
MI->isVolatile())
1744 if (!S.isSplittable())
1746 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1750 }
else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1753 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1763 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1793 Type *CommonEltTy =
nullptr;
1794 bool HaveCommonEltTy =
true;
1795 auto CheckCandidateType = [&](
Type *Ty) {
1796 if (
auto *VTy = dyn_cast<VectorType>(Ty)) {
1799 CommonEltTy = VTy->getElementType();
1800 else if (CommonEltTy != VTy->getElementType())
1801 HaveCommonEltTy =
false;
1805 for (
const Slice &S : P)
1806 if (S.beginOffset() == P.beginOffset() &&
1807 S.endOffset() == P.endOffset()) {
1808 if (
auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1809 CheckCandidateType(LI->
getType());
1810 else if (
auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1815 if (CandidateTys.
empty())
1822 if (!HaveCommonEltTy) {
1827 CandidateTys.
end());
1830 if (CandidateTys.
empty())
1838 "Cannot have vector types of different sizes!");
1840 "All non-integer types eliminated!");
1841 assert(LHSTy->getElementType()->isIntegerTy() &&
1842 "All non-integer types eliminated!");
1847 std::unique(CandidateTys.
begin(), CandidateTys.
end(), RankVectorTypes),
1848 CandidateTys.
end());
1854 assert(VTy->getElementType() == CommonEltTy &&
1855 "Unaccounted for element type!");
1856 assert(VTy == CandidateTys[0] &&
1857 "Different vector types with the same element type!");
1860 CandidateTys.resize(1);
1864 auto CheckVectorTypeForPromotion = [&](
VectorType *VTy) {
1869 if (ElementSize % 8)
1872 "vector size not a multiple of element size?");
1875 for (
const Slice &S : P)
1879 for (
const Slice *S : P.splitSliceTails())
1886 if (CheckVectorTypeForPromotion(VTy))
1897 uint64_t AllocBeginOffset,
1900 bool &WholeAllocaOp) {
1903 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1904 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1911 Use *U = S.getUse();
1913 if (
LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1922 if (!isa<VectorType>(LI->
getType()) && RelBegin == 0 && RelEnd == Size)
1923 WholeAllocaOp =
true;
1927 }
else if (RelBegin != 0 || RelEnd != Size ||
1933 }
else if (
StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1943 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd ==
Size)
1944 WholeAllocaOp =
true;
1945 if (
IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
1948 }
else if (RelBegin != 0 || RelEnd != Size ||
1954 }
else if (
MemIntrinsic *
MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1955 if (
MI->isVolatile() || !isa<Constant>(
MI->getLength()))
1957 if (!S.isSplittable())
1959 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1980 if (SizeInBits > IntegerType::MAX_INT_BITS)
1990 Type *IntTy = Type::getIntNTy(AllocaTy->
getContext(), SizeInBits);
2002 bool WholeAllocaOp =
2005 for (
const Slice &S : P)
2010 for (
const Slice *S : P.splitSliceTails())
2015 return WholeAllocaOp;
2020 const Twine &Name) {
2021 DEBUG(
dbgs() <<
" start: " << *V <<
"\n");
2024 "Element extends past full value");
2025 uint64_t ShAmt = 8 *
Offset;
2029 V = IRB.CreateLShr(V, ShAmt, Name +
".shift");
2030 DEBUG(
dbgs() <<
" shifted: " << *V <<
"\n");
2033 "Cannot extract to a larger integer!");
2035 V = IRB.CreateTrunc(V, Ty, Name +
".trunc");
2036 DEBUG(
dbgs() <<
" trunced: " << *V <<
"\n");
2042 Value *V, uint64_t Offset,
const Twine &Name) {
2046 "Cannot insert a larger integer!");
2047 DEBUG(
dbgs() <<
" start: " << *V <<
"\n");
2049 V = IRB.CreateZExt(V, IntTy, Name +
".ext");
2050 DEBUG(
dbgs() <<
" extended: " << *V <<
"\n");
2053 "Element store outside of alloca store");
2054 uint64_t ShAmt = 8 *
Offset;
2058 V = IRB.CreateShl(V, ShAmt, Name +
".shift");
2059 DEBUG(
dbgs() <<
" shifted: " << *V <<
"\n");
2062 if (ShAmt || Ty->getBitWidth() < IntTy->
getBitWidth()) {
2064 Old = IRB.CreateAnd(Old, Mask, Name +
".mask");
2065 DEBUG(
dbgs() <<
" masked: " << *Old <<
"\n");
2066 V = IRB.CreateOr(Old, V, Name +
".insert");
2067 DEBUG(
dbgs() <<
" inserted: " << *V <<
"\n");
2073 unsigned EndIndex,
const Twine &Name) {
2075 unsigned NumElements = EndIndex - BeginIndex;
2076 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2081 if (NumElements == 1) {
2082 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2084 DEBUG(
dbgs() <<
" extract: " << *V <<
"\n");
2090 for (
unsigned i = BeginIndex; i != EndIndex; ++i)
2092 V = IRB.CreateShuffleVector(V, UndefValue::get(V->
getType()),
2093 ConstantVector::get(Mask), Name +
".extract");
2094 DEBUG(
dbgs() <<
" shuffle: " << *V <<
"\n");
2099 unsigned BeginIndex,
const Twine &Name) {
2101 assert(VecTy &&
"Can only insert a vector into a vector");
2106 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2108 DEBUG(
dbgs() <<
" insert: " << *V <<
"\n");
2113 "Too many elements!");
2127 if (i >= BeginIndex && i < EndIndex)
2128 Mask.
push_back(IRB.getInt32(i - BeginIndex));
2130 Mask.
push_back(UndefValue::get(IRB.getInt32Ty()));
2131 V = IRB.CreateShuffleVector(V, UndefValue::get(V->
getType()),
2132 ConstantVector::get(Mask), Name +
".expand");
2133 DEBUG(
dbgs() <<
" shuffle: " << *V <<
"\n");
2137 Mask.
push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2139 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name +
"blend");
2141 DEBUG(
dbgs() <<
" blend: " << *V <<
"\n");
2161 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2181 uint64_t ElementSize;
2185 uint64_t BeginOffset, EndOffset;
2188 uint64_t NewBeginOffset, NewEndOffset;
2207 uint64_t NewAllocaBeginOffset,
2208 uint64_t NewAllocaEndOffset,
bool IsIntegerPromotable,
2212 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2213 NewAllocaBeginOffset(NewAllocaBeginOffset),
2214 NewAllocaEndOffset(NewAllocaEndOffset),
2215 NewAllocaTy(NewAI.getAllocatedType()),
2216 IntTy(IsIntegerPromotable
2219 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2221 VecTy(PromotableVecTy),
2222 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2223 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2224 BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
2225 OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2229 "Only multiple-of-8 sized vector elements are viable");
2232 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2236 bool CanSROA =
true;
2237 BeginOffset = I->beginOffset();
2238 EndOffset = I->endOffset();
2239 IsSplittable = I->isSplittable();
2241 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2242 DEBUG(
dbgs() <<
" rewriting " << (IsSplit ?
"split " :
""));
2247 assert(BeginOffset < NewAllocaEndOffset);
2248 assert(EndOffset > NewAllocaBeginOffset);
2249 NewBeginOffset =
std::max(BeginOffset, NewAllocaBeginOffset);
2250 NewEndOffset =
std::min(EndOffset, NewAllocaEndOffset);
2252 SliceSize = NewEndOffset - NewBeginOffset;
2254 OldUse = I->getUse();
2255 OldPtr = cast<Instruction>(OldUse->get());
2257 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2258 IRB.SetInsertPoint(OldUserI);
2259 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2260 IRB.SetNamePrefix(
Twine(NewAI.getName()) +
"." +
Twine(BeginOffset) +
".");
2262 CanSROA &=
visit(cast<Instruction>(OldUse->getUser()));
2274 DEBUG(
dbgs() <<
" !!!! Cannot rewrite: " << I <<
"\n");
2281 assert(IsSplit || BeginOffset == NewBeginOffset);
2282 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2287 size_t LastSROAPrefix = OldName.
rfind(
".sroa.");
2289 OldName = OldName.
substr(LastSROAPrefix + strlen(
".sroa."));
2294 OldName = OldName.
substr(IndexEnd + 1);
2298 OldName = OldName.
substr(OffsetEnd + 1);
2302 OldName = OldName.
substr(0, OldName.
find(
".sroa_"));
2309 Twine(OldName) +
"."
2321 unsigned getSliceAlign(
Type *Ty =
nullptr) {
2322 unsigned NewAIAlign = NewAI.getAlignment();
2326 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2330 unsigned getIndex(uint64_t Offset) {
2331 assert(VecTy &&
"Can only call getIndex when rewriting a vector");
2332 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2333 assert(RelOffset / ElementSize < UINT32_MAX &&
"Index out of bounds");
2334 uint32_t Index = RelOffset / ElementSize;
2335 assert(Index * ElementSize == RelOffset);
2339 void deleteIfTriviallyDead(
Value *V) {
2342 Pass.DeadInsts.insert(I);
2345 Value *rewriteVectorizedLoadInst() {
2346 unsigned BeginIndex = getIndex(NewBeginOffset);
2347 unsigned EndIndex = getIndex(NewEndOffset);
2348 assert(EndIndex > BeginIndex &&
"Empty vector!");
2350 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"load");
2355 assert(IntTy &&
"We cannot insert an integer to the alloca");
2357 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"load");
2359 assert(NewBeginOffset >= NewAllocaBeginOffset &&
"Out of bounds offset");
2360 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2361 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2371 "Can only handle an extract for an overly wide load");
2373 V = IRB.CreateZExt(V, LI.
getType());
2378 DEBUG(
dbgs() <<
" original: " << LI <<
"\n");
2387 bool IsPtrAdjusted =
false;
2390 V = rewriteVectorizedLoadInst();
2392 V = rewriteIntegerLoad(LI);
2393 }
else if (NewBeginOffset == NewAllocaBeginOffset &&
2394 NewEndOffset == NewAllocaEndOffset &&
2396 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2398 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2422 if (
auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2423 if (
auto *TITy = dyn_cast<IntegerType>(TargetTy))
2424 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2425 V = IRB.CreateZExt(V, TITy,
"load.ext");
2427 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2432 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2433 getSliceAlign(TargetTy),
2439 IsPtrAdjusted =
true;
2446 "Only integer type loads and stores are split");
2448 "Split load isn't smaller than original load");
2451 "Non-byte-multiple bit width");
2458 Value *Placeholder =
2460 V =
insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2469 Pass.DeadInsts.insert(&LI);
2470 deleteIfTriviallyDead(OldOp);
2477 unsigned BeginIndex = getIndex(NewBeginOffset);
2478 unsigned EndIndex = getIndex(NewEndOffset);
2479 assert(EndIndex > BeginIndex &&
"Empty vector!");
2480 unsigned NumElements = EndIndex - BeginIndex;
2481 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2482 Type *SliceTy = (NumElements == 1)
2489 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"load");
2492 StoreInst *
Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2493 Pass.DeadInsts.insert(&SI);
2496 DEBUG(
dbgs() <<
" to: " << *Store <<
"\n");
2501 assert(IntTy &&
"We cannot extract an integer from the alloca");
2505 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"oldload");
2507 assert(BeginOffset >= NewAllocaBeginOffset &&
"Out of bounds offset");
2508 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2512 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2514 Pass.DeadInsts.insert(&SI);
2515 DEBUG(
dbgs() <<
" to: " << *Store <<
"\n");
2520 DEBUG(
dbgs() <<
" original: " << SI <<
"\n");
2530 Pass.PostPromotionWorklist.insert(AI);
2535 "Only integer type loads and stores are split");
2538 "Non-byte-multiple bit width");
2540 V =
extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2545 return rewriteVectorizedStoreInst(V, SI, OldOp);
2547 return rewriteIntegerStore(V, SI);
2551 if (NewBeginOffset == NewAllocaBeginOffset &&
2552 NewEndOffset == NewAllocaEndOffset &&
2554 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2559 if (
auto *VITy = dyn_cast<IntegerType>(V->
getType()))
2560 if (
auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2561 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2563 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2565 V = IRB.CreateTrunc(V, AITy,
"load.trunc");
2569 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2574 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->
getType()),
2580 Pass.DeadInsts.insert(&SI);
2581 deleteIfTriviallyDead(OldOp);
2583 DEBUG(
dbgs() <<
" to: " << *NewSI <<
"\n");
2584 return NewSI->getPointerOperand() == &NewAI && !SI.
isVolatile();
2596 Value *getIntegerSplat(
Value *V,
unsigned Size) {
2597 assert(Size > 0 &&
"Expected a positive number of bytes.");
2605 IRB.CreateZExt(V, SplatIntTy,
"zext"),
2615 Value *getVectorSplat(
Value *V,
unsigned NumElements) {
2616 V = IRB.CreateVectorSplat(NumElements, V,
"vsplat");
2617 DEBUG(
dbgs() <<
" splat: " << *V <<
"\n");
2622 DEBUG(
dbgs() <<
" original: " << II <<
"\n");
2629 assert(NewBeginOffset == BeginOffset);
2630 II.
setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2634 deleteIfTriviallyDead(OldPtr);
2639 Pass.DeadInsts.insert(&II);
2641 Type *AllocaTy = NewAI.getAllocatedType();
2646 if (!VecTy && !IntTy &&
2647 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2655 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.
getValue(),
Size,
2658 DEBUG(
dbgs() <<
" to: " << *New <<
"\n");
2671 assert(ElementTy == ScalarTy);
2673 unsigned BeginIndex = getIndex(NewBeginOffset);
2674 unsigned EndIndex = getIndex(NewEndOffset);
2675 assert(EndIndex > BeginIndex &&
"Empty vector!");
2676 unsigned NumElements = EndIndex - BeginIndex;
2677 assert(NumElements <= VecTy->getNumElements() &&
"Too many elements!");
2682 if (NumElements > 1)
2683 Splat = getVectorSplat(Splat, NumElements);
2686 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"oldload");
2693 uint64_t Size = NewEndOffset - NewBeginOffset;
2696 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2697 EndOffset != NewAllocaBeginOffset)) {
2699 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"oldload");
2701 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2705 "Wrong type for an alloca wide integer!");
2710 assert(NewBeginOffset == NewAllocaBeginOffset);
2711 assert(NewEndOffset == NewAllocaEndOffset);
2714 if (
VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2715 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2720 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2723 DEBUG(
dbgs() <<
" to: " << *New <<
"\n");
2731 DEBUG(
dbgs() <<
" original: " << II <<
"\n");
2737 unsigned SliceAlign = getSliceAlign();
2746 if (!IsSplittable) {
2747 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2760 deleteIfTriviallyDead(OldPtr);
2773 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2775 !NewAI.getAllocatedType()->isSingleValueType());
2780 if (EmitMemCpy && &OldAI == &NewAI) {
2782 assert(NewBeginOffset == BeginOffset);
2785 if (NewEndOffset != EndOffset)
2787 NewEndOffset - NewBeginOffset));
2791 Pass.DeadInsts.insert(&II);
2798 assert(AI != &OldAI && AI != &NewAI &&
2799 "Splittable transfers cannot reach the same alloca on both ends.");
2800 Pass.Worklist.insert(AI);
2808 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2810 OtherOffset.zextOrTrunc(64).getZExtValue());
2815 OtherPtr =
getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2818 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2823 IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
2826 DEBUG(
dbgs() <<
" to: " << *New <<
"\n");
2830 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2831 NewEndOffset == NewAllocaEndOffset;
2832 uint64_t Size = NewEndOffset - NewBeginOffset;
2833 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2834 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2835 unsigned NumElements = EndIndex - BeginIndex;
2841 if (VecTy && !IsWholeAlloca) {
2842 if (NumElements == 1)
2843 OtherPtrTy = VecTy->getElementType();
2848 }
else if (IntTy && !IsWholeAlloca) {
2855 OtherPtr->getName() +
".");
2856 unsigned SrcAlign = OtherAlign;
2857 Value *DstPtr = &NewAI;
2858 unsigned DstAlign = SliceAlign;
2865 if (VecTy && !IsWholeAlloca && !IsDest) {
2866 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"load");
2868 }
else if (IntTy && !IsWholeAlloca && !IsDest) {
2869 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"load");
2871 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2875 IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.
isVolatile(),
"copyload");
2878 if (VecTy && !IsWholeAlloca && IsDest) {
2880 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"oldload");
2882 }
else if (IntTy && !IsWholeAlloca && IsDest) {
2884 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
"oldload");
2886 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2892 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.
isVolatile()));
2894 DEBUG(
dbgs() <<
" to: " << *Store <<
"\n");
2901 DEBUG(
dbgs() <<
" original: " << II <<
"\n");
2905 Pass.DeadInsts.insert(&II);
2914 if (NewBeginOffset != NewAllocaBeginOffset ||
2915 NewEndOffset != NewAllocaEndOffset)
2920 NewEndOffset - NewBeginOffset);
2921 Value *
Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2924 New = IRB.CreateLifetimeStart(Ptr, Size);
2926 New = IRB.CreateLifetimeEnd(Ptr, Size);
2929 DEBUG(
dbgs() <<
" to: " << *New <<
"\n");
2935 DEBUG(
dbgs() <<
" original: " << PN <<
"\n");
2936 assert(BeginOffset >= NewAllocaBeginOffset &&
"PHIs are unsplittable");
2937 assert(EndOffset <= NewAllocaEndOffset &&
"PHIs are unsplittable");
2943 IRBuilderTy PtrBuilder(IRB);
2944 if (isa<PHINode>(OldPtr))
2945 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
2947 PtrBuilder.SetInsertPoint(OldPtr);
2948 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
2950 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
2955 deleteIfTriviallyDead(OldPtr);
2960 PHIUsers.insert(&PN);
2965 DEBUG(
dbgs() <<
" original: " << SI <<
"\n");
2967 "Pointer isn't an operand!");
2968 assert(BeginOffset >= NewAllocaBeginOffset &&
"Selects are unsplittable");
2969 assert(EndOffset <= NewAllocaEndOffset &&
"Selects are unsplittable");
2971 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2979 deleteIfTriviallyDead(OldPtr);
2984 SelectUsers.insert(&SI);
2995 class AggLoadStoreRewriter :
public InstVisitor<AggLoadStoreRewriter, bool> {
3013 DEBUG(
dbgs() <<
" Rewriting FCA loads and stores...\n");
3015 bool Changed =
false;
3016 while (!
Queue.empty()) {
3017 U =
Queue.pop_back_val();
3018 Changed |=
visit(cast<Instruction>(U->getUser()));
3029 Queue.push_back(&U);
3036 template <
typename Derived>
class OpSplitter {
3053 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3071 return static_cast<Derived *>(
this)->emitFunc(Ty, Agg, Name);
3073 if (
ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3074 unsigned OldSize = Indices.size();
3076 for (
unsigned Idx = 0, Size = ATy->getNumElements(); Idx !=
Size;
3078 assert(Indices.size() == OldSize &&
"Did not return to the old size");
3079 Indices.push_back(Idx);
3080 GEPIndices.push_back(IRB.getInt32(Idx));
3081 emitSplitOps(ATy->getElementType(), Agg, Name +
"." +
Twine(Idx));
3082 GEPIndices.pop_back();
3088 if (
StructType *STy = dyn_cast<StructType>(Ty)) {
3089 unsigned OldSize = Indices.size();
3091 for (
unsigned Idx = 0, Size = STy->getNumElements(); Idx !=
Size;
3093 assert(Indices.size() == OldSize &&
"Did not return to the old size");
3094 Indices.push_back(Idx);
3095 GEPIndices.push_back(IRB.getInt32(Idx));
3096 emitSplitOps(STy->getElementType(Idx), Agg, Name +
"." +
Twine(Idx));
3097 GEPIndices.pop_back();
3107 struct LoadOpSplitter :
public OpSplitter<LoadOpSplitter> {
3109 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
3117 IRB.CreateInBoundsGEP(
nullptr, Ptr, GEPIndices, Name +
".gep");
3118 Value *
Load = IRB.CreateLoad(GEP, Name +
".load");
3119 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name +
".insert");
3120 DEBUG(
dbgs() <<
" to: " << *Load <<
"\n");
3130 DEBUG(
dbgs() <<
" original: " << LI <<
"\n");
3131 LoadOpSplitter Splitter(&LI, *U);
3139 struct StoreOpSplitter :
public OpSplitter<StoreOpSplitter> {
3141 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
3151 Value *ExtractValue =
3152 IRB.CreateExtractValue(Agg, Indices, Name +
".extract");
3153 Value *InBoundsGEP =
3154 IRB.CreateInBoundsGEP(
nullptr, Ptr, GEPIndices, Name +
".gep");
3155 Value *Store = IRB.CreateStore(ExtractValue, InBoundsGEP);
3157 DEBUG(
dbgs() <<
" to: " << *Store <<
"\n");
3169 DEBUG(
dbgs() <<
" original: " << SI <<
"\n");
3170 StoreOpSplitter Splitter(&SI, *U);
3186 bool visitPHINode(
PHINode &PN) {
3211 if (
ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3212 InnerTy = ArrTy->getElementType();
3213 }
else if (
StructType *STy = dyn_cast<StructType>(Ty)) {
3216 InnerTy = STy->getElementType(Index);
3250 Type *ElementTy = SeqTy->getElementType();
3252 uint64_t NumSkippedElements = Offset / ElementSize;
3253 if (NumSkippedElements >= SeqTy->getNumElements())
3255 Offset -= NumSkippedElements * ElementSize;
3258 if (Offset > 0 || Size < ElementSize) {
3260 if ((Offset + Size) > ElementSize)
3267 if (Size == ElementSize)
3269 assert(Size > ElementSize);
3270 uint64_t NumElements = Size / ElementSize;
3271 if (NumElements * ElementSize != Size)
3273 return ArrayType::get(ElementTy, NumElements);
3283 uint64_t EndOffset = Offset +
Size;
3292 if (Offset >= ElementSize)
3296 if (Offset > 0 || Size < ElementSize) {
3297 if ((Offset + Size) > ElementSize)
3303 if (Size == ElementSize)
3308 if (EndOffset < SL->getSizeInBytes()) {
3310 if (Index == EndIndex)
3320 assert(Index < EndIndex);
3328 if (Size != SubSL->getSizeInBytes())
3365 DEBUG(
dbgs() <<
"Pre-splitting loads and stores\n");
3378 struct SplitOffsets {
3380 std::vector<uint64_t> Splits;
3397 DEBUG(
dbgs() <<
" Searching for candidate loads and stores\n");
3399 for (Slice &S : P) {
3400 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3401 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3405 if (
auto *LI = dyn_cast<LoadInst>(I))
3406 UnsplittableLoads.
insert(LI);
3407 else if (
auto *SI = dyn_cast<StoreInst>(I))
3409 UnsplittableLoads.
insert(LI);
3412 assert(P.endOffset() > S.beginOffset() &&
3413 "Empty or backwards partition!");
3416 if (
auto *LI = dyn_cast<LoadInst>(I)) {
3422 auto IsLoadSimplyStored = [](
LoadInst *LI) {
3430 if (!IsLoadSimplyStored(LI)) {
3431 UnsplittableLoads.
insert(LI);
3436 }
else if (
auto *SI = dyn_cast<StoreInst>(I)) {
3441 if (!StoredLoad || !StoredLoad->isSimple())
3452 DEBUG(
dbgs() <<
" Candidate: " << *I <<
"\n");
3453 auto &
Offsets = SplitOffsetsMap[
I];
3455 "Should not have splits the first time we see an instruction!");
3457 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3462 for (Slice *S : P.splitSliceTails()) {
3463 auto SplitOffsetsMapI =
3464 SplitOffsetsMap.
find(cast<Instruction>(S->getUse()->getUser()));
3465 if (SplitOffsetsMapI == SplitOffsetsMap.
end())
3467 auto &
Offsets = SplitOffsetsMapI->second;
3471 "Cannot have an empty set of splits on the second partition!");
3473 P.beginOffset() -
Offsets.S->beginOffset() &&
3474 "Previous split does not end where this one begins!");
3478 if (S->endOffset() > P.endOffset())
3479 Offsets.Splits.push_back(P.endOffset() -
Offsets.S->beginOffset());
3489 [&UnsplittableLoads, &SplitOffsetsMap](
StoreInst *SI) {
3495 if (UnsplittableLoads.
count(LI))
3498 auto LoadOffsetsI = SplitOffsetsMap.
find(LI);
3499 if (LoadOffsetsI == SplitOffsetsMap.
end())
3501 auto &LoadOffsets = LoadOffsetsI->second;
3504 auto &StoreOffsets = SplitOffsetsMap[SI];
3509 if (LoadOffsets.Splits == StoreOffsets.Splits)
3512 DEBUG(
dbgs() <<
" Mismatched splits for load and store:\n"
3513 <<
" " << *LI <<
"\n"
3514 <<
" " << *SI <<
"\n");
3520 UnsplittableLoads.
insert(LI);
3531 return UnsplittableLoads.
count(LI);
3537 [&UnsplittableLoads](
LoadInst *LI) {
3538 return UnsplittableLoads.
count(LI);
3549 IRBuilderTy IRB(&AI);
3567 std::vector<LoadInst *> SplitLoads;
3574 assert(LoadSize > 0 &&
"Cannot have a zero-sized integer load!");
3576 auto &
Offsets = SplitOffsetsMap[LI];
3578 "Slice size should always match load size exactly!");
3579 uint64_t BaseOffset =
Offsets.S->beginOffset();
3580 assert(BaseOffset + LoadSize > BaseOffset &&
3581 "Cannot represent alloca access size using 64-bit integers!");
3584 IRB.SetInsertPoint(LI);
3586 DEBUG(
dbgs() <<
" Splitting load: " << *LI <<
"\n");
3588 uint64_t PartOffset = 0, PartSize =
Offsets.Splits.front();
3589 int Idx = 0, Size =
Offsets.Splits.size();
3591 auto *PartTy = Type::getIntNTy(Ty->
getContext(), PartSize * 8);
3593 auto *PartPtrTy = PartTy->getPointerTo(AS);
3594 LoadInst *PLoad = IRB.CreateAlignedLoad(
3597 PartPtrTy, BasePtr->
getName() +
"."),
3600 PLoad->
copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
3604 SplitLoads.push_back(PLoad);
3608 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3611 DEBUG(
dbgs() <<
" new slice [" << NewSlices.
back().beginOffset()
3612 <<
", " << NewSlices.
back().endOffset() <<
"): " << *PLoad
3620 PartOffset =
Offsets.Splits[Idx];
3622 PartSize = (Idx < Size ?
Offsets.Splits[Idx] : LoadSize) - PartOffset;
3628 bool DeferredStores =
false;
3631 if (!Stores.
empty() && SplitOffsetsMap.
count(SI)) {
3632 DeferredStores =
true;
3633 DEBUG(
dbgs() <<
" Deferred splitting of store: " << *SI <<
"\n");
3638 IRB.SetInsertPoint(SI);
3640 DEBUG(
dbgs() <<
" Splitting store of load: " << *SI <<
"\n");
3642 for (
int Idx = 0, Size = SplitLoads.size(); Idx <
Size; ++Idx) {
3644 uint64_t PartOffset = Idx == 0 ? 0 :
Offsets.Splits[Idx - 1];
3649 StoreInst *PStore = IRB.CreateAlignedStore(
3653 PartPtrTy, StoreBasePtr->
getName() +
"."),
3655 PStore->
copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
3656 DEBUG(
dbgs() <<
" +" << PartOffset <<
":" << *PStore <<
"\n");
3663 if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3664 ResplitPromotableAllocas.
insert(OtherAI);
3665 Worklist.insert(OtherAI);
3666 }
else if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3668 Worklist.insert(OtherAI);
3672 DeadInsts.insert(SI);
3677 SplitLoadsMap.
insert(std::make_pair(LI, std::move(SplitLoads)));
3680 DeadInsts.insert(LI);
3693 assert(StoreSize > 0 &&
"Cannot have a zero-sized integer store!");
3695 auto &
Offsets = SplitOffsetsMap[SI];
3697 "Slice size should always match load size exactly!");
3698 uint64_t BaseOffset =
Offsets.S->beginOffset();
3699 assert(BaseOffset + StoreSize > BaseOffset &&
3700 "Cannot represent alloca access size using 64-bit integers!");
3705 DEBUG(
dbgs() <<
" Splitting store: " << *SI <<
"\n");
3708 auto SplitLoadsMapI = SplitLoadsMap.
find(LI);
3709 std::vector<LoadInst *> *SplitLoads =
nullptr;
3710 if (SplitLoadsMapI != SplitLoadsMap.
end()) {
3711 SplitLoads = &SplitLoadsMapI->second;
3713 "Too few split loads for the number of splits in the store!");
3715 DEBUG(
dbgs() <<
" of load: " << *LI <<
"\n");
3718 uint64_t PartOffset = 0, PartSize =
Offsets.Splits.front();
3719 int Idx = 0, Size =
Offsets.Splits.size();
3721 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3728 PLoad = (*SplitLoads)[Idx];
3730 IRB.SetInsertPoint(LI);
3732 PLoad = IRB.CreateAlignedLoad(
3735 LoadPartPtrTy, LoadBasePtr->
getName() +
"."),
3741 IRB.SetInsertPoint(SI);
3743 StoreInst *PStore = IRB.CreateAlignedStore(
3747 StorePartPtrTy, StoreBasePtr->
getName() +
"."),
3752 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3755 DEBUG(
dbgs() <<
" new slice [" << NewSlices.
back().beginOffset()
3756 <<
", " << NewSlices.
back().endOffset() <<
"): " << *PStore
3759 DEBUG(
dbgs() <<
" of split load: " << *PLoad <<
"\n");
3767 PartOffset =
Offsets.Splits[Idx];
3769 PartSize = (Idx < Size ?
Offsets.Splits[Idx] : StoreSize) - PartOffset;
3778 if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3779 assert(OtherAI != &AI &&
"We can't re-split our own alloca!");
3780 ResplitPromotableAllocas.
insert(OtherAI);
3781 Worklist.insert(OtherAI);
3782 }
else if (
AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3784 assert(OtherAI != &AI &&
"We can't re-split our own alloca!");
3785 Worklist.insert(OtherAI);
3800 DeadInsts.insert(LI);
3802 DeadInsts.insert(SI);
3807 AS.erase(
remove_if(AS, [](
const Slice &S) {
return S.isDead(); }), AS.end());
3811 AS.insert(NewSlices);
3813 DEBUG(
dbgs() <<
" Pre-split slices:\n");
3815 for (
auto I = AS.begin(),
E = AS.end(); I !=
E; ++
I)
3821 PromotableAllocas.erase(
3825 PromotableAllocas.end());
3845 Type *SliceTy =
nullptr;
3849 SliceTy = CommonUseTy;
3853 SliceTy = TypePartitionTy;
3854 if ((!SliceTy || (SliceTy->
isArrayTy() &&
3857 SliceTy = Type::getIntNTy(*
C, P.
size() * 8);
3859 SliceTy = ArrayType::get(Type::getInt8Ty(*
C), P.
size());
3876 "Non-zero begin offset but same alloca type");
3900 DEBUG(
dbgs() <<
"Rewriting alloca partition "
3902 <<
") to: " << *NewAI <<
"\n");
3907 unsigned PPWOldSize = PostPromotionWorklist.size();
3908 unsigned NumUses = 0;
3913 P.
endOffset(), IsIntegerPromotable, VecTy,
3914 PHIUsers, SelectUsers);
3915 bool Promotable =
true;
3920 for (Slice &S : P) {
3925 NumAllocaPartitionUses += NumUses;
3926 MaxUsesPerAllocaPartition.updateMax(NumUses);
3934 SelectUsers.
clear();
3942 SelectUsers.clear();
3947 if (PHIUsers.empty() && SelectUsers.empty()) {
3949 PromotableAllocas.push_back(NewAI);
3954 for (
PHINode *PHIUser : PHIUsers)
3955 SpeculatablePHIs.insert(PHIUser);
3957 SpeculatableSelects.insert(SelectUser);
3958 Worklist.insert(NewAI);
3962 while (PostPromotionWorklist.size() > PPWOldSize)
3963 PostPromotionWorklist.pop_back();
3973 Worklist.insert(NewAI);
3985 unsigned NumPartitions = 0;
3986 bool Changed =
false;
3990 Changed |= presplitLoadsAndStores(AI, AS);
3996 bool IsSorted =
true;
3997 for (Slice &S : AS) {
3998 if (!S.isSplittable())
4004 if (S.beginOffset() == 0 &&
4007 if (isa<LoadInst>(S.getUse()->getUser()) ||
4008 isa<StoreInst>(S.getUse()->getUser())) {
4009 S.makeUnsplittable();
4022 Fragment(
AllocaInst *AI, uint64_t O, uint64_t S)
4023 : Alloca(AI), Offset(O), Size(S) {}
4028 for (
auto &P : AS.partitions()) {
4029 if (
AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4032 uint64_t SizeOfByte = 8;
4035 uint64_t Size =
std::min(AllocaSize, P.size() * SizeOfByte);
4036 Fragments.
push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte,
Size));
4042 NumAllocaPartitions += NumPartitions;
4043 MaxPartitionsPerAlloca.updateMax(NumPartitions);
4048 auto *Var = DbgDecl->getVariable();
4049 auto *Expr = DbgDecl->getExpression();
4052 for (
auto Fragment : Fragments) {
4055 auto *FragmentExpr = Expr;
4056 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
4059 auto ExprFragment = Expr->getFragmentInfo();
4060 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
4061 uint64_t Start = Offset + Fragment.Offset;
4062 uint64_t Size = Fragment.Size;
4065 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
4066 if (Start >= AbsEnd)
4069 Size =
std::min(Size, AbsEnd - Start);
4071 FragmentExpr = DIB.createFragmentExpression(Start, Size);
4076 OldDDI->eraseFromParent();
4078 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
4079 DbgDecl->getDebugLoc(), &AI);
4086 void SROA::clobberUse(
Use &U) {
4089 U = UndefValue::get(OldV->
getType());
4094 if (
Instruction *OldI = dyn_cast<Instruction>(OldV))
4096 DeadInsts.insert(OldI);
4106 DEBUG(
dbgs() <<
"SROA alloca: " << AI <<
"\n");
4107 ++NumAllocasAnalyzed;
4121 bool Changed =
false;
4125 AggLoadStoreRewriter AggRewriter;
4126 Changed |= AggRewriter.rewrite(AI);
4137 for (
Use &DeadOp : DeadUser->operands())
4141 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4144 DeadInsts.insert(DeadUser);
4147 for (
Use *DeadOp : AS.getDeadOperands()) {
4148 clobberUse(*DeadOp);
4153 if (AS.begin() == AS.end())
4156 Changed |= splitAlloca(AI, AS);
4159 while (!SpeculatablePHIs.empty())
4162 DEBUG(
dbgs() <<
" Speculating Selects\n");
4163 while (!SpeculatableSelects.empty())
4178 void SROA::deleteDeadInstructions(
4180 while (!DeadInsts.empty()) {
4182 DEBUG(
dbgs() <<
"Deleting dead instruction: " << *I <<
"\n");
4187 if (
Instruction *U = dyn_cast<Instruction>(Operand)) {
4191 DeadInsts.insert(U);
4194 if (
AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4195 DeletedAllocas.
insert(AI);
4197 DbgDecl->eraseFromParent();
4210 bool SROA::promoteAllocas(
Function &
F) {
4211 if (PromotableAllocas.empty())
4214 NumPromoted += PromotableAllocas.size();
4216 DEBUG(
dbgs() <<
"Promoting allocas with mem2reg...\n");
4218 PromotableAllocas.clear();
4232 if (
AllocaInst *AI = dyn_cast<AllocaInst>(I))
4233 Worklist.insert(AI);
4236 bool Changed =
false;
4242 while (!Worklist.empty()) {
4243 Changed |= runOnAlloca(*Worklist.pop_back_val());
4244 deleteDeadInstructions(DeletedAllocas);
4248 if (!DeletedAllocas.
empty()) {
4249 auto IsInSet = [&](
AllocaInst *AI) {
return DeletedAllocas.
count(AI); };
4250 Worklist.remove_if(IsInSet);
4251 PostPromotionWorklist.remove_if(IsInSet);
4252 PromotableAllocas.erase(
remove_if(PromotableAllocas, IsInSet),
4253 PromotableAllocas.end());
4254 DeletedAllocas.
clear();
4258 Changed |= promoteAllocas(F);
4260 Worklist = PostPromotionWorklist;
4261 PostPromotionWorklist.clear();
4262 }
while (!Worklist.empty());
4265 return PreservedAnalyses::all();
4291 if (skipFunction(F))
4294 auto PA = Impl.runImpl(
4295 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4296 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4297 return !PA.areAllPreserved();
4315 "Scalar Replacement Of Aggregates",
false,
false)
unsigned getAlignment() const
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...
RetTy visitSelectInst(SelectInst &I)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
Pass interface - Implemented by all 'passes'.
static VectorType * isVectorPromotionViable(Partition &P, const DataLayout &DL)
Test whether the given alloca partitioning and range of slices can be promoted to a vector...
const Use & getOperandUse(unsigned i) const
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.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
An iterator over partitions of the alloca's slices.
RetTy visitMemSetInst(MemSetInst &I)
iterator_range< use_iterator > uses()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
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.
uint64_t getZExtValue() const
Get zero extended value.
bool isNonIntegralPointerType(PointerType *PT) const
void printUse(raw_ostream &OS, const_iterator I, StringRef Indent=" ") const
STATISTIC(NumFunctions,"Total number of functions")
bool isVolatile() const
Return true if this is a store to a volatile memory location.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
This is the interface for a simple mod/ref and alias analysis over globals.
DbgDeclareInst * FindAllocaDbgDeclare(Value *V)
Finds the llvm.dbg.declare intrinsic corresponding to an alloca, if any.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
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...
ConstantInt * getAlignmentCst() const
Value * getValue() const
Return the arguments to the instruction.
This file provides the interface for LLVM's Scalar Replacement of Aggregates pass.
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
void erase(iterator Start, iterator Stop)
Erase a range of slices.
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.
SmallVectorImpl< Slice >::iterator iterator
Support for iterating over the slices.
An immutable pass that tracks lazily created AssumptionCache objects.
gep_type_iterator gep_type_end(const User *GEP)
void insert(ArrayRef< Slice > NewSlices)
Insert new slices for this alloca.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
A cache of .assume calls within a function.
void deleteValue()
Delete a pointer to a generic Value.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
This class wraps the llvm.memset intrinsic.
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...
static void dump(StringRef Title, SpillInfo const &Spills)
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Analysis pass which computes a DominatorTree.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
An instruction for reading from memory.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
RetTy visitPHINode(PHINode &I)
Type * getElementType() const
void reserve(size_type N)
void setDest(Value *Ptr)
Set the specified arguments of the instruction.
void setAlignment(Constant *A)
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.
const Value * stripInBoundsOffsets() const
Strip off pointer casts and inbounds GEPs.
bool operator==(const partition_iterator &RHS) const
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.
Type * getPointerElementType() const
StringRef getName() const
Return a constant reference to the value's name.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
iterator begin()
Instruction iterator methods.
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
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...
element_iterator element_end() const
static Value * buildGEP(IRBuilderTy &IRB, Value *BasePtr, SmallVectorImpl< Value * > &Indices, Twine NamePrefix)
Build a GEP out of a base pointer and indices.
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1...
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.
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
std::string str() const
Return the twine contents as a std::string.
This class represents the LLVM 'select' instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
RetTy visitIntrinsicInst(IntrinsicInst &I)
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
const APInt & getValue() const
Return the constant as an APInt value reference.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
Type * getArrayElementType() const
A Use represents the edge between a Value definition and its users.
bool empty() const
Test whether this partition contains no slices, and merely spans a region occupied by split slices...
bool isEscaped() const
Test whether a pointer to the allocation escapes our analysis.
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.
static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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.
const_iterator begin() const
element_iterator element_begin() const
A partition of the slices.
ArrayRef< Slice * > splitSliceTails() const
Get the sequence of split slice tails.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
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...
LLVM_NODISCARD bool empty() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
void visit(Iterator Start, Iterator End)
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool visit(AllocaSlices::const_iterator I)
A base class for visitors over the uses of a pointer value.
ArrayRef< Use * > getDeadOperands() const
Access the dead operands referring to this alloca.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
A legacy pass for the legacy pass manager that wraps the SROA pass.
Class to represent array types.
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 class represents a no-op cast from one type to another.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
ConstantFolder - Create constants with minimum, target independent, folding.
An instruction for storing to memory.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
True if this is an instance of ArrayType.
static Constant * getUDiv(Constant *C1, Constant *C2, bool isExact=false)
RetTy visitMemTransferInst(MemTransferInst &I)
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...
Type * getElementType() const
static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy)
Test whether we can convert a value from the old to the new type.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
Class to represent pointers.
uint64_t endOffset() const
The end offset of this partition.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void printSlice(raw_ostream &OS, const_iterator I, StringRef Indent=" ") const
iterator find(const_arg_type_t< KeyT > Val)
uint64_t getElementOffset(unsigned Idx) const
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
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 ...
Scalar Replacement Of false
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
iterator_range< partition_iterator > partitions()
SmallVectorImpl< Slice >::const_iterator const_iterator
initializer< Ty > init(const Ty &Val)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
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.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
uint64_t beginOffset() const
The start offset of this partition.
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.
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()
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
bool isVectorTy() const
True if this is an instance of VectorType.
Type * getElementType(unsigned N) const
This is an important base class in LLVM.
PointerType * getType() const
Overload to return most specific pointer type.
const Value * getCondition() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isSafeSelectToSpeculate(SelectInst &SI)
Select instructions that use an alloca and are subsequently loaded can be rewritten to load both inpu...
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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).
Value * getRawDest() const
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
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.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getBitWidth() const
Return the number of bits in the APInt.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
void initializeSROALegacyPassPass(PassRegistry &)
uint64_t getNumElements() const
void print(raw_ostream &OS, const_iterator I, StringRef Indent=" ") const
FunctionPass class - This class is used to implement most global optimizations.
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Value * getOperand(unsigned i) const
Value * getPointerOperand()
unsigned getIntegerBitWidth() const
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)
RetTy visitLoadInst(LoadInst &I)
void setAlignment(unsigned Align)
static Constant * getAllOnesValue(Type *Ty)
Get the all ones value.
LLVM_NODISCARD bool empty() const
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
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.
LLVMContext & getContext() const
All values hold a context through their type.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
const Value * getTrueValue() const
LLVM_NODISCARD size_t rfind(char C, size_t From=npos) const
Search for the last character C in the string.
static Type * stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty)
Strip aggregate type wrapping.
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
This provides the default implementation of the IRBuilder 'InsertHelper' method that is called whenev...
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...
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.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
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.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
This is the shared class of boolean and integer constants.
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...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Construct the slices of a particular alloca.
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
partition_iterator & operator++()
static Value * insertVector(IRBuilderTy &IRB, Value *Old, Value *V, unsigned BeginIndex, const Twine &Name)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
uint64_t size() const
The size of the partition.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Value * getLength() const
LLVM_NODISCARD T pop_back_val()
uint64_t getSizeInBytes() const
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
unsigned getElementContainingOffset(uint64_t Offset) const
Given a valid byte offset into the structure, returns the structure index that contains it...
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.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
const BasicBlock & getEntryBlock() const
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
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.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
void clear()
Completely clear the SetVector.
A range adaptor for a pair of iterators.
Class to represent vector types.
Class for arbitrary precision integers.
bool isIntegerTy() const
True if this is an instance of IntegerType.
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()
RetTy visitStoreInst(StoreInst &I)
Represents analyses that only rely on functions' control flow.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
static Value * insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, Value *V, uint64_t Offset, const Twine &Name)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
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)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
This class wraps the llvm.memcpy/memmove intrinsics.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
StringRef getPassName() const override
getPassName - Return a nice clean name for a pass.
Visitor to rewrite instructions using p particular slice of an alloca to use a new alloca...
unsigned getAlignment() const
Return the alignment of the access that is being performed.
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
void preserveSet()
Mark an analysis set as preserved.
static void speculateSelectInstLoads(SelectInst &SI)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
FunctionPass * createSROAPass()
void setSource(Value *Ptr)
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)
const_iterator end() const
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
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.
iterator_range< iterator > range
void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB, BasicBlock::iterator InsertPt) const
Value * getRawSource() const
Return the arguments to the instruction.
static unsigned getPointerOperandIndex()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
bool operator<(int64_t V1, const APSInt &V2)
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.
APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
static bool isSafePHIToSpeculate(PHINode &PN)
PHI instructions that use an alloca and are subsequently loaded can be rewritten to load both input p...
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.
iterator_range< const_iterator > const_range
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
static void speculatePHINodeLoads(PHINode &PN)
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
This class implements an extremely fast bulk output stream that can only output to a stream...
An optimization pass providing Scalar Replacement of Aggregates.
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...
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
const Value * getFalseValue() const
StringRef - Represent a constant reference to a string, i.e.
static Expected< std::string > replace(StringRef S, StringRef From, StringRef To)
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
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)
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU...
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...
void visitInstruction(Instruction &I)
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
const Use & getRawDestUse() const
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
This represents the llvm.dbg.declare instruction.
Value * getPointerOperand()
const BasicBlock * getParent() const
A wrapper class for inspecting calls to intrinsic functions.
INITIALIZE_PASS_BEGIN(SROALegacyPass,"sroa","Scalar Replacement Of Aggregates", false, false) INITIALIZE_PASS_END(SROALegacyPass
an instruction to allocate memory on the stack
gep_type_iterator gep_type_begin(const User *GEP)
ArrayRef< Instruction * > getDeadUsers() const
Access the dead users for this alloca.
static Value * foldSelectInst(SelectInst &SI)