72 #define DEBUG_TYPE "loop-accesses"
76 cl::desc(
"Sets the SIMD width. Zero is autoselect."),
82 cl::desc(
"Sets the vectorization interleave count. "
83 "Zero is autoselect."),
90 cl::desc(
"When performing memory disambiguation checks at runtime do not "
91 "generate more than this number of comparisons (default = 8)."),
98 cl::desc(
"Maximum number of comparisons done when trying to merge "
99 "runtime memory checks. (default = 100)"),
108 cl::desc(
"Maximum number of dependences collected by "
109 "loop-access analysis (default = 100)"),
125 cl::desc(
"Enable symbolic stride memory access versioning"));
130 "store-to-load-forwarding-conflict-detection",
cl::Hidden,
131 cl::desc(
"Enable conflict detection in loop-access analysis"),
139 if (
auto *CI = dyn_cast<CastInst>(V))
140 if (CI->getOperand(0)->getType()->isIntegerTy())
141 return CI->getOperand(0);
153 PtrToStride.
find(OrigPtr ? OrigPtr : Ptr);
154 if (SI != PtrToStride.
end()) {
155 Value *StrideVal = SI->second;
161 const auto *U = cast<SCEVUnknown>(SE->
getSCEV(StrideVal));
168 DEBUG(
dbgs() <<
"LAA: Replacing SCEV: " << *OrigSCEV <<
" by: " << *Expr
191 unsigned DepSetId,
unsigned ASId,
202 ScStart = ScEnd = Sc;
205 assert(AR &&
"Invalid addrec expression");
214 if (
const auto *CStep = dyn_cast<SCEVConstant>(Step)) {
215 if (CStep->getValue()->isNegative())
231 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, Sc);
235 RuntimePointerChecking::generateChecks()
const {
244 Checks.
push_back(std::make_pair(&CGI, &CGJ));
250 void RuntimePointerChecking::generateChecks(
253 groupChecks(DepCands, UseDependencies);
260 for (
unsigned J = 0, EJ = N.
Members.
size(); EJ != J; ++J)
307 void RuntimePointerChecking::groupChecks(
353 if (!UseDependencies) {
359 unsigned TotalComparisons = 0;
362 for (
unsigned Index = 0; Index <
Pointers.size(); ++Index)
363 PositionMap[
Pointers[Index].PointerValue] = Index;
391 unsigned Pointer = PositionMap[
MI->getPointer()];
398 for (CheckingPtrGroup &Group : Groups) {
408 if (Group.addPointer(Pointer)) {
418 Groups.push_back(CheckingPtrGroup(Pointer, *
this));
423 std::copy(Groups.begin(), Groups.end(), std::back_inserter(
CheckingGroups));
430 return (PtrToPartition[PtrIdx1] != -1 &&
431 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]);
455 unsigned Depth)
const {
457 for (
const auto &
Check : Checks) {
458 const auto &First =
Check.first->Members, &Second =
Check.second->Members;
460 OS.
indent(Depth) <<
"Check " << N++ <<
":\n";
462 OS.
indent(Depth + 2) <<
"Comparing group (" <<
Check.first <<
"):\n";
463 for (
unsigned K = 0; K < First.size(); ++K)
466 OS.
indent(Depth + 2) <<
"Against group (" <<
Check.second <<
"):\n";
467 for (
unsigned K = 0; K < Second.size(); ++K)
468 OS.
indent(Depth + 2) << *
Pointers[Second[K]].PointerValue <<
"\n";
474 OS.
indent(Depth) <<
"Run-time memory checks:\n";
477 OS.
indent(Depth) <<
"Grouped accesses:\n";
481 OS.
indent(Depth + 2) <<
"Group " << &CG <<
":\n";
482 OS.
indent(Depth + 4) <<
"(Low: " << *CG.Low <<
" High: " << *CG.High
484 for (
unsigned J = 0; J < CG.Members.size(); ++J) {
485 OS.
indent(Depth + 6) <<
"Member: " << *
Pointers[CG.Members[J]].Expr
497 class AccessAnalysis {
506 :
DL(Dl), AST(*AA), LI(LI), DepCands(DA), IsRTCheckAnalysisNeeded(
false),
513 Accesses.insert(MemAccessInfo(Ptr,
false));
515 ReadOnlyPtr.insert(Ptr);
522 Accesses.insert(MemAccessInfo(Ptr,
true));
532 bool ShouldCheckWrap =
false);
536 void buildDependenceSets() {
537 processMemAccesses();
545 bool isDependencyCheckNeeded() {
return !CheckDeps.empty(); }
553 MemAccessInfoList &getDependenciesToCheck() {
return CheckDeps; }
560 void processMemAccesses();
563 PtrAccessSet Accesses;
568 MemAccessInfoList CheckDeps;
591 bool IsRTCheckAnalysisNeeded;
630 bool ShouldCheckWrap) {
635 bool NeedRTCheck =
false;
636 if (!IsRTCheckAnalysisNeeded)
return true;
638 bool IsDepCheckNeeded = isDependencyCheckNeeded();
643 for (
auto &AS : AST) {
644 int NumReadPtrChecks = 0;
645 int NumWritePtrChecks = 0;
649 unsigned RunningDepId = 1;
653 Value *Ptr =
A.getValue();
654 bool IsWrite = Accesses.count(MemAccessInfo(Ptr,
true));
655 MemAccessInfo Access(Ptr, IsWrite);
665 (!ShouldCheckWrap ||
isNoWrap(PSE, StridesMap, Ptr, TheLoop))) {
669 if (IsDepCheckNeeded) {
671 unsigned &LeaderId = DepSetId[Leader];
673 LeaderId = RunningDepId++;
677 DepId = RunningDepId++;
679 RtCheck.
insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap, PSE);
681 DEBUG(
dbgs() <<
"LAA: Found a runtime check ptr:" << *Ptr <<
'\n');
683 DEBUG(
dbgs() <<
"LAA: Can't find bounds for ptr:" << *Ptr <<
'\n');
696 if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2))
697 NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 &&
698 NumWritePtrChecks >= 1));
708 unsigned NumPointers = RtCheck.
Pointers.size();
709 for (
unsigned i = 0; i < NumPointers; ++i) {
710 for (
unsigned j = i + 1; j < NumPointers; ++j) {
712 if (RtCheck.
Pointers[i].DependencySetId ==
713 RtCheck.
Pointers[j].DependencySetId)
725 DEBUG(
dbgs() <<
"LAA: Runtime check would require comparison between"
726 " different address spaces\n");
732 if (NeedRTCheck && CanDoRT)
736 <<
" pointer comparisons.\n");
738 RtCheck.
Need = NeedRTCheck;
740 bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT;
741 if (!CanDoRTIfNeeded)
743 return CanDoRTIfNeeded;
746 void AccessAnalysis::processMemAccesses() {
751 DEBUG(
dbgs() <<
"LAA: Processing memory accesses...\n");
753 DEBUG(
dbgs() <<
"LAA: Accesses(" << Accesses.size() <<
"):\n");
755 for (
auto A : Accesses)
756 dbgs() <<
"\t" << *
A.getPointer() <<
" (" <<
757 (
A.getInt() ?
"write" : (ReadOnlyPtr.count(
A.getPointer()) ?
758 "read-only" :
"read")) <<
")\n";
765 for (
auto &AS : AST) {
770 bool SetHasWrite =
false;
774 UnderlyingObjToAccessMap ObjToLastAccess;
777 PtrAccessSet DeferredAccesses;
781 for (
int SetIteration = 0; SetIteration < 2; ++SetIteration) {
782 bool UseDeferred = SetIteration > 0;
783 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
786 Value *Ptr = AV.getValue();
791 if (AC.getPointer() !=
Ptr)
794 bool IsWrite = AC.getInt();
798 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
799 if (UseDeferred && !IsReadOnlyPtr)
803 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite ||
804 S.count(MemAccessInfo(Ptr,
false))) &&
805 "Alias-set pointer not in the access set?");
807 MemAccessInfo Access(Ptr, IsWrite);
815 if (!UseDeferred && IsReadOnlyPtr) {
816 DeferredAccesses.insert(Access);
824 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) {
825 CheckDeps.push_back(Access);
826 IsRTCheckAnalysisNeeded =
true;
835 ValueVector TempObjects;
838 DEBUG(
dbgs() <<
"Underlying objects for pointer " << *Ptr <<
"\n");
839 for (
Value *UnderlyingObj : TempObjects) {
842 if (isa<ConstantPointerNull>(UnderlyingObj))
845 UnderlyingObjToAccessMap::iterator Prev =
846 ObjToLastAccess.find(UnderlyingObj);
847 if (Prev != ObjToLastAccess.end())
848 DepCands.
unionSets(Access, Prev->second);
850 ObjToLastAccess[UnderlyingObj] = Access;
851 DEBUG(
dbgs() <<
" " << *UnderlyingObj <<
"\n");
861 return GEP->isInBounds();
882 if (!
GEP || !
GEP->isInBounds())
886 Value *NonConstIndex =
nullptr;
888 if (!isa<ConstantInt>(Index)) {
891 NonConstIndex = Index;
899 if (
auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex))
900 if (OBO->hasNoSignedWrap() &&
903 isa<ConstantInt>(OBO->getOperand(1))) {
904 auto *OpScev = PSE.
getSCEV(OBO->getOperand(0));
906 if (
auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev))
907 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(
SCEV::FlagNSW);
916 bool Assume,
bool ShouldCheckWrap) {
921 auto *PtrTy = cast<PointerType>(Ty);
922 if (PtrTy->getElementType()->isAggregateType()) {
923 DEBUG(
dbgs() <<
"LAA: Bad stride - Not a pointer to a scalar type" << *Ptr
935 DEBUG(
dbgs() <<
"LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr
936 <<
" SCEV: " << *PtrScev <<
"\n");
942 DEBUG(
dbgs() <<
"LAA: Bad stride - Not striding over innermost loop " <<
943 *Ptr <<
" SCEV: " << *AR <<
"\n");
955 bool IsNoWrapAddRec = !ShouldCheckWrap ||
958 bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
959 if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
962 IsNoWrapAddRec =
true;
963 DEBUG(
dbgs() <<
"LAA: Pointer may wrap in the address space:\n"
964 <<
"LAA: Pointer: " << *Ptr <<
"\n"
965 <<
"LAA: SCEV: " << *AR <<
"\n"
966 <<
"LAA: Added an overflow assumption\n");
968 DEBUG(
dbgs() <<
"LAA: Bad stride - Pointer may wrap in the address space "
969 << *Ptr <<
" SCEV: " << *AR <<
"\n");
980 DEBUG(
dbgs() <<
"LAA: Bad stride - Not a constant strided " << *Ptr <<
981 " SCEV: " << *AR <<
"\n");
985 auto &
DL = Lp->
getHeader()->getModule()->getDataLayout();
996 int64_t Stride = StepVal /
Size;
997 int64_t Rem = StepVal %
Size;
1004 if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
1005 Stride != 1 && Stride != -1) {
1008 DEBUG(
dbgs() <<
"LAA: Non unit strided pointer which is not either "
1009 <<
"inbouds or in address space 0 may wrap:\n"
1010 <<
"LAA: Pointer: " << *Ptr <<
"\n"
1011 <<
"LAA: SCEV: " << *AR <<
"\n"
1012 <<
"LAA: Added an overflow assumption\n");
1024 if (
auto *LI = dyn_cast<LoadInst>(I))
1025 return LI->getPointerOperand();
1026 if (
auto *
SI = dyn_cast<StoreInst>(I))
1027 return SI->getPointerOperand();
1034 if (
LoadInst *
L = dyn_cast<LoadInst>(I))
1035 return L->getPointerAddressSpace();
1036 if (
StoreInst *S = dyn_cast<StoreInst>(I))
1037 return S->getPointerAddressSpace();
1050 if (!PtrA || !PtrB || (ASA != ASB))
1062 Type *Ty = cast<PointerType>(PtrA->
getType())->getElementType();
1065 APInt OffsetA(PtrBitWidth, 0), OffsetB(PtrBitWidth, 0);
1078 return OffsetDelta ==
Size;
1090 return X == PtrSCEVB;
1097 case BackwardVectorizable:
1101 case ForwardButPreventsForwarding:
1103 case BackwardVectorizableButPreventsForwarding:
1113 case ForwardButPreventsForwarding:
1117 case BackwardVectorizable:
1119 case BackwardVectorizableButPreventsForwarding:
1132 case ForwardButPreventsForwarding:
1137 case BackwardVectorizable:
1139 case BackwardVectorizableButPreventsForwarding:
1145 bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance,
1146 uint64_t TypeByteSize) {
1159 const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize;
1161 uint64_t MaxVFWithoutSLForwardIssues =
std::min(
1165 for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues;
1169 if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) {
1170 MaxVFWithoutSLForwardIssues = (VF >>= 1);
1175 if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) {
1176 DEBUG(
dbgs() <<
"LAA: Distance " << Distance
1177 <<
" that could cause a store-load forwarding conflict\n");
1181 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
1182 MaxVFWithoutSLForwardIssues !=
1184 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
1201 const SCEV &BackedgeTakenCount,
1202 const SCEV &Dist, uint64_t Stride,
1203 uint64_t TypeByteSize) {
1222 const uint64_t ByteStride = Stride * TypeByteSize;
1226 const SCEV *CastedDist = &Dist;
1227 const SCEV *CastedProduct = Product;
1234 if (DistTypeSize > ProductTypeSize)
1261 uint64_t TypeByteSize) {
1262 assert(Stride > 1 &&
"The stride must be greater than 1");
1263 assert(TypeByteSize > 0 &&
"The type size in byte must be non-zero");
1264 assert(Distance > 0 &&
"The distance must be non-zero");
1267 if (Distance % TypeByteSize)
1270 uint64_t ScaledDist = Distance / TypeByteSize;
1288 return ScaledDist % Stride;
1292 MemoryDepChecker::isDependent(
const MemAccessInfo &
A,
unsigned AIdx,
1293 const MemAccessInfo &
B,
unsigned BIdx,
1295 assert (AIdx < BIdx &&
"Must pass arguments in program order");
1297 Value *APtr = A.getPointer();
1298 Value *BPtr = B.getPointer();
1299 bool AIsWrite = A.getInt();
1300 bool BIsWrite = B.getInt();
1303 if (!AIsWrite && !BIsWrite)
1304 return Dependence::NoDep;
1311 int64_t StrideAPtr =
getPtrStride(PSE, APtr, InnermostLoop, Strides,
true);
1312 int64_t StrideBPtr =
getPtrStride(PSE, BPtr, InnermostLoop, Strides,
true);
1314 const SCEV *Src = PSE.getSCEV(APtr);
1315 const SCEV *
Sink = PSE.getSCEV(BPtr);
1319 if (StrideAPtr < 0) {
1327 const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src);
1329 DEBUG(
dbgs() <<
"LAA: Src Scev: " << *Src <<
"Sink Scev: " << *Sink
1330 <<
"(Induction step: " << StrideAPtr <<
")\n");
1331 DEBUG(
dbgs() <<
"LAA: Distance for " << *InstMap[AIdx] <<
" to "
1332 << *InstMap[BIdx] <<
": " << *Dist <<
"\n");
1337 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
1338 DEBUG(
dbgs() <<
"Pointer access with non-constant stride\n");
1344 auto &
DL = InnermostLoop->getHeader()->getModule()->getDataLayout();
1346 uint64_t Stride =
std::abs(StrideAPtr);
1351 *(PSE.getBackedgeTakenCount()), *Dist, Stride,
1353 return Dependence::NoDep;
1355 DEBUG(
dbgs() <<
"LAA: Dependence because of non-constant distance\n");
1356 ShouldRetryWithRuntimeCheck =
true;
1364 if (
std::abs(Distance) > 0 && Stride > 1 && ATy == BTy &&
1366 DEBUG(
dbgs() <<
"LAA: Strided accesses are independent\n");
1367 return Dependence::NoDep;
1372 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
1374 (couldPreventStoreLoadForward(Val.
abs().
getZExtValue(), TypeByteSize) ||
1376 DEBUG(
dbgs() <<
"LAA: Forward but may prevent st->ld forwarding\n");
1377 return Dependence::ForwardButPreventsForwarding;
1380 DEBUG(
dbgs() <<
"LAA: Dependence is negative\n");
1381 return Dependence::Forward;
1388 return Dependence::Forward;
1389 DEBUG(
dbgs() <<
"LAA: Zero dependence difference but different types\n");
1397 "LAA: ReadWrite-Write positive dependency with different types\n");
1407 unsigned MinNumIter =
std::max(ForcedFactor * ForcedUnroll, 2U);
1435 uint64_t MinDistanceNeeded =
1436 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize;
1437 if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) {
1438 DEBUG(
dbgs() <<
"LAA: Failure because of positive distance " << Distance
1440 return Dependence::Backward;
1444 if (MinDistanceNeeded > MaxSafeDepDistBytes) {
1445 DEBUG(
dbgs() <<
"LAA: Failure because it needs at least "
1446 << MinDistanceNeeded <<
" size in bytes");
1447 return Dependence::Backward;
1466 MaxSafeDepDistBytes =
1467 std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes);
1469 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
1471 couldPreventStoreLoadForward(Distance, TypeByteSize))
1472 return Dependence::BackwardVectorizableButPreventsForwarding;
1475 <<
" with max VF = "
1476 << MaxSafeDepDistBytes / (TypeByteSize * Stride) <<
'\n');
1478 return Dependence::BackwardVectorizable;
1485 MaxSafeDepDistBytes = -1;
1488 if (Visited.
count(CurAccess))
1507 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].
begin(),
1508 I1E = Accesses[*AI].
end(); I1 != I1E; ++I1)
1509 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].
begin(),
1510 I2E = Accesses[*OI].
end(); I2 != I2E; ++I2) {
1511 auto A = std::make_pair(&*AI, *I1);
1512 auto B = std::make_pair(&*OI, *I2);
1519 isDependent(*A.first, A.second, *B.first, B.second, Strides);
1520 SafeForVectorization &= Dependence::isSafeForVectorization(Type);
1526 if (RecordDependences) {
1527 if (Type != Dependence::NoDep)
1528 Dependences.push_back(
Dependence(A.second, B.second, Type));
1531 RecordDependences =
false;
1532 Dependences.clear();
1533 DEBUG(
dbgs() <<
"Too many dependences, stopped recording\n");
1536 if (!RecordDependences && !SafeForVectorization)
1545 DEBUG(
dbgs() <<
"Total Dependences: " << Dependences.size() <<
"\n");
1546 return SafeForVectorization;
1552 auto &IndexVector = Accesses.find(Access)->second;
1556 std::back_inserter(Insts),
1557 [&](
unsigned Idx) {
return this->InstMap[Idx]; });
1562 "NoDep",
"Unknown",
"Forward",
"ForwardButPreventsForwarding",
"Backward",
1563 "BackwardVectorizable",
"BackwardVectorizableButPreventsForwarding"};
1570 OS.
indent(Depth + 2) << *Instrs[Destination] <<
"\n";
1573 bool LoopAccessInfo::canAnalyzeLoop() {
1576 << TheLoop->
getHeader()->getParent()->getName() <<
": "
1577 << TheLoop->
getHeader()->getName() <<
'\n');
1580 if (!TheLoop->
empty()) {
1581 DEBUG(
dbgs() <<
"LAA: loop is not the innermost loop\n");
1582 recordAnalysis(
"NotInnerMostLoop") <<
"loop is not the innermost loop";
1588 DEBUG(
dbgs() <<
"LAA: loop control flow is not understood by analyzer\n");
1589 recordAnalysis(
"CFGNotUnderstood")
1590 <<
"loop control flow is not understood by analyzer";
1596 DEBUG(
dbgs() <<
"LAA: loop control flow is not understood by analyzer\n");
1597 recordAnalysis(
"CFGNotUnderstood")
1598 <<
"loop control flow is not understood by analyzer";
1606 DEBUG(
dbgs() <<
"LAA: loop control flow is not understood by analyzer\n");
1607 recordAnalysis(
"CFGNotUnderstood")
1608 <<
"loop control flow is not understood by analyzer";
1613 const SCEV *ExitCount = PSE->getBackedgeTakenCount();
1614 if (ExitCount == PSE->getSE()->getCouldNotCompute()) {
1615 recordAnalysis(
"CantComputeNumberOfIterations")
1616 <<
"could not determine number of loop iterations";
1617 DEBUG(
dbgs() <<
"LAA: SCEV could not compute the loop exit count.\n");
1634 unsigned NumReads = 0;
1635 unsigned NumReadWrites = 0;
1637 PtrRtChecking->Pointers.
clear();
1638 PtrRtChecking->Need =
false;
1649 if (
I.mayReadFromMemory()) {
1659 if (Call && !
Call->isNoBuiltin() &&
Call->getCalledFunction() &&
1664 if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) {
1665 recordAnalysis(
"NonSimpleLoad", Ld)
1666 <<
"read with atomic ordering or volatile read";
1667 DEBUG(
dbgs() <<
"LAA: Found a non-simple load.\n");
1673 DepChecker->addAccess(Ld);
1675 collectStridedAccess(Ld);
1680 if (
I.mayWriteToMemory()) {
1683 recordAnalysis(
"CantVectorizeInstruction", St)
1684 <<
"instruction cannot be vectorized";
1688 if (!St->isSimple() && !IsAnnotatedParallel) {
1689 recordAnalysis(
"NonSimpleStore", St)
1690 <<
"write with atomic ordering or volatile write";
1691 DEBUG(
dbgs() <<
"LAA: Found a non-simple store.\n");
1697 DepChecker->addAccess(St);
1699 collectStridedAccess(St);
1709 if (!Stores.
size()) {
1710 DEBUG(
dbgs() <<
"LAA: Found a read-only loop!\n");
1716 AccessAnalysis Accesses(TheLoop->
getHeader()->getModule()->getDataLayout(),
1717 AA, LI, DependentAccesses, *PSE);
1727 Value *Ptr =
ST->getPointerOperand();
1729 StoreToLoopInvariantAddress |= isUniform(Ptr);
1732 if (Seen.insert(Ptr).second) {
1739 if (blockNeedsPredication(
ST->getParent(), TheLoop, DT))
1742 Accesses.addStore(Loc);
1746 if (IsAnnotatedParallel) {
1748 <<
"LAA: A loop annotated parallel, ignore memory dependency "
1755 Value *Ptr =
LD->getPointerOperand();
1764 bool IsReadOnlyPtr =
false;
1765 if (Seen.insert(Ptr).second ||
1768 IsReadOnlyPtr =
true;
1775 if (blockNeedsPredication(
LD->getParent(), TheLoop, DT))
1778 Accesses.addLoad(Loc, IsReadOnlyPtr);
1783 if (NumReadWrites == 1 && NumReads == 0) {
1784 DEBUG(
dbgs() <<
"LAA: Found a write-only loop!\n");
1791 Accesses.buildDependenceSets();
1795 bool CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(),
1796 TheLoop, SymbolicStrides);
1797 if (!CanDoRTIfNeeded) {
1798 recordAnalysis(
"CantIdentifyArrayBounds") <<
"cannot identify array bounds";
1799 DEBUG(
dbgs() <<
"LAA: We can't vectorize because we can't find "
1800 <<
"the array bounds.\n");
1805 DEBUG(
dbgs() <<
"LAA: We can perform a memory runtime check if needed.\n");
1808 if (Accesses.isDependencyCheckNeeded()) {
1809 DEBUG(
dbgs() <<
"LAA: Checking memory dependencies\n");
1810 CanVecMem = DepChecker->areDepsSafe(
1811 DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides);
1812 MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes();
1814 if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) {
1815 DEBUG(
dbgs() <<
"LAA: Retrying with memory checks\n");
1818 Accesses.resetDepChecks(*DepChecker);
1820 PtrRtChecking->reset();
1821 PtrRtChecking->Need =
true;
1823 auto *SE = PSE->getSE();
1824 CanDoRTIfNeeded = Accesses.canCheckPtrAtRT(*PtrRtChecking, SE, TheLoop,
1825 SymbolicStrides,
true);
1828 if (!CanDoRTIfNeeded) {
1829 recordAnalysis(
"CantCheckMemDepsAtRunTime")
1830 <<
"cannot check memory dependencies at runtime";
1831 DEBUG(
dbgs() <<
"LAA: Can't vectorize with memory checks\n");
1841 DEBUG(
dbgs() <<
"LAA: No unsafe dependent memory operations in loop. We"
1842 << (PtrRtChecking->Need ?
"" :
" don't")
1843 <<
" need runtime memory checks.\n");
1845 recordAnalysis(
"UnsafeMemDep")
1846 <<
"unsafe dependent memory operations in loop. Use "
1847 "#pragma loop distribute(enable) to allow loop distribution "
1848 "to attempt to isolate the offending operations into a separate "
1850 DEBUG(
dbgs() <<
"LAA: unsafe dependent memory operations in loop\n");
1865 assert(!Report &&
"Multiple reports generated");
1878 Report = make_unique<OptimizationRemarkAnalysis>(
DEBUG_TYPE, RemarkName,
DL,
1884 auto *SE = PSE->getSE();
1911 struct PointerBounds {
1920 static PointerBounds
1934 DEBUG(
dbgs() <<
"LAA: Adding RT check for a loop invariant ptr:" << *Ptr
1945 return {NewPtr, NewPtrPlusOne};
1947 Value *Start =
nullptr, *
End =
nullptr;
1948 DEBUG(
dbgs() <<
"LAA: Adding RT check for range:\n");
1952 return {Start,
End};
1967 PointerChecks, std::back_inserter(ChecksWithBounds),
1970 First =
expandBounds(Check.first, L, Loc, Exp, SE, PtrRtChecking),
1971 Second =
expandBounds(Check.second, L, Loc, Exp, SE, PtrRtChecking);
1972 return std::make_pair(First, Second);
1975 return ChecksWithBounds;
1983 auto *SE = PSE->getSE();
1985 auto ExpandedChecks =
1986 expandBounds(PointerChecks, TheLoop, Loc, SE, Exp, *PtrRtChecking);
1992 Value *MemoryRuntimeCheck =
nullptr;
1994 for (
const auto &
Check : ExpandedChecks) {
1995 const PointerBounds &A =
Check.first, &B =
Check.second;
1998 unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
1999 unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
2001 assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
2002 (AS1 == A.End->getType()->getPointerAddressSpace()) &&
2003 "Trying to bounds check pointers with different address spaces");
2025 Value *IsConflict = ChkBuilder.
CreateAnd(Cmp0, Cmp1,
"found.conflict");
2027 if (MemoryRuntimeCheck) {
2029 ChkBuilder.
CreateOr(MemoryRuntimeCheck, IsConflict,
"conflict.rdx");
2032 MemoryRuntimeCheck = IsConflict;
2035 if (!MemoryRuntimeCheck)
2036 return std::make_pair(
nullptr,
nullptr);
2043 ChkBuilder.
Insert(Check,
"memcheck.conflict");
2045 return std::make_pair(FirstInst, Check);
2048 std::pair<Instruction *, Instruction *>
2050 if (!PtrRtChecking->Need)
2051 return std::make_pair(
nullptr,
nullptr);
2053 return addRuntimeChecks(Loc, PtrRtChecking->getChecks());
2056 void LoopAccessInfo::collectStridedAccess(
Value *MemAccess) {
2057 Value *Ptr =
nullptr;
2058 if (
LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
2059 Ptr = LI->getPointerOperand();
2060 else if (
StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
2061 Ptr =
SI->getPointerOperand();
2069 DEBUG(
dbgs() <<
"LAA: Found a strided access that we can version");
2070 DEBUG(
dbgs() <<
" Ptr: " << *Ptr <<
" Stride: " << *Stride <<
"\n");
2071 SymbolicStrides[
Ptr] = Stride;
2072 StrideSet.insert(Stride);
2081 NumLoads(0), NumStores(0), MaxSafeDepDistBytes(-1), CanVecMem(
false),
2082 StoreToLoopInvariantAddress(
false) {
2083 if (canAnalyzeLoop())
2084 analyzeLoop(AA, LI, TLI, DT);
2089 OS.
indent(Depth) <<
"Memory dependences are safe";
2090 if (MaxSafeDepDistBytes != -1ULL)
2091 OS <<
" with a maximum dependence distance of " << MaxSafeDepDistBytes
2093 if (PtrRtChecking->Need)
2094 OS <<
" with run-time checks";
2099 OS.
indent(Depth) <<
"Report: " << Report->getMsg() <<
"\n";
2101 if (
auto *Dependences = DepChecker->getDependences()) {
2102 OS.
indent(Depth) <<
"Dependences:\n";
2103 for (
auto &Dep : *Dependences) {
2104 Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions());
2108 OS.
indent(Depth) <<
"Too many dependences, not recorded\n";
2111 PtrRtChecking->print(OS, Depth);
2114 OS.
indent(Depth) <<
"Store to invariant address was "
2115 << (StoreToLoopInvariantAddress ?
"" :
"not ")
2116 <<
"found in loop.\n";
2118 OS.
indent(Depth) <<
"SCEV assumptions:\n";
2119 PSE->getUnionPredicate().print(OS, Depth);
2123 OS.
indent(Depth) <<
"Expressions re-written:\n";
2124 PSE->print(OS, Depth);
2128 auto &LAI = LoopAccessInfoMap[
L];
2131 LAI = llvm::make_unique<LoopAccessInfo>(
L, SE, TLI, AA, DT, LI);
2139 for (
Loop *TopLevelLoop : *LI)
2148 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2149 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2150 TLI = TLIP ? &TLIP->getTLI() :
nullptr;
2151 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2152 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2153 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2169 #define LAA_NAME "loop-accesses"
2182 return LoopAccessInfo(&L, &AR.SE, &AR.TLI, &AR.AA, &AR.DT, &AR.LI);
NoWrapFlags getNoWrapFlags(NoWrapFlags Mask=NoWrapMask) const
static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE, const SCEV &BackedgeTakenCount, const SCEV &Dist, uint64_t Stride, uint64_t TypeByteSize)
Given a non-constant (unknown) dependence-distance Dist between two memory accesses, that have the same stride whose absolute value is given in Stride, and that have the same type size TypeByteSize, in a loop whose takenCount is BackedgeTakenCount, check if it is possible to prove statically that the dependence distance is larger than the range that the accesses will travel through the execution of the loop.
bool isPossiblyBackward() const
May be a lexically backward dependence type (includes Unknown).
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
void print(raw_ostream &OS, unsigned Depth, const SmallVectorImpl< Instruction * > &Instrs) const
Print the dependence.
Pass interface - Implemented by all 'passes'.
void print(raw_ostream &OS, unsigned Depth=0) const
Print the information about the memory accesses in the loop.
static unsigned RuntimeMemoryCheckThreshold
\brief When performing memory disambiguation checks at runtime do not make more than this number of c...
static bool Check(DecodeStatus &Out, DecodeStatus In)
static const char laa_name[]
Value * getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp)
Get the stride of a pointer access in a loop.
const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
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.
SmallVector< CheckingPtrGroup, 2 > CheckingGroups
Holds a partitioning of pointers into "check groups".
void print(raw_ostream &OS, unsigned Depth=0) const
Print the list run-time memory checks necessary.
void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Proves that V doesn't overflow by adding SCEV predicate.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
uint64_t getZExtValue() const
Get zero extended value.
const SCEV * getConstant(ConstantInt *V)
static bool isInBoundsGep(Value *Ptr)
MDNode * TBAA
The tag for type-based alias analysis.
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
A Module instance is used to store all the information related to an LLVM module. ...
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
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
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
The main scalar evolution driver.
This class represents a function call, abstracting a target machine's calling convention.
int64_t getPtrStride(PredicatedScalarEvolution &PSE, Value *Ptr, const Loop *Lp, const ValueToValueMap &StridesMap=ValueToValueMap(), bool Assume=false, bool ShouldCheckWrap=true)
If the pointer has a constant stride return it in units of its element size.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
bool IsWritePtr
Holds the information if this pointer is used for writing to memory.
std::pair< Instruction *, Instruction * > addRuntimeChecks(Instruction *Loc) const
Add code that checks at runtime if the accessed arrays overlap.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void reset()
Reset the state of the pointer runtime information.
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
An instruction for reading from memory.
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
union - Merge the two equivalence sets for the specified values, inserting them if they do not alread...
void GetUnderlyingObjects(Value *V, SmallVectorImpl< Value * > &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
Checks memory dependences among accesses to the same underlying object to determine whether there vec...
static unsigned VectorizationFactor
VF as overridden by the user.
member_iterator member_begin(iterator I) const
BlockT * getHeader() const
static cl::opt< unsigned > MaxDependences("max-dependences", cl::Hidden, cl::desc("Maximum number of dependences collected by ""loop-access analysis (default = 100)"), cl::init(100))
We collect dependences up to this threshold.
static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride, uint64_t TypeByteSize)
Check the dependence for two accesses with the same stride Stride.
Type * getPointerElementType() const
const SCEV * getStart() const
Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
void printChecks(raw_ostream &OS, const SmallVectorImpl< PointerCheck > &Checks, unsigned Depth=0) const
Print Checks.
bool isNegative() const
Determine sign of this APInt.
void insert(Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId, unsigned ASId, const ValueToValueMap &Strides, PredicatedScalarEvolution &PSE)
Insert a pointer and calculate the start and end SCEVs.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
static const unsigned MaxVectorWidth
Maximum SIMD width.
static bool arePointersInSamePartition(const SmallVectorImpl< int > &PtrToPartition, unsigned PtrIdx1, unsigned PtrIdx2)
Check if pointers are in the same partition.
member_iterator member_end() const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
This file implements a class to represent arbitrary precision integral constant values and operations...
static const char * DepName[]
String version of the types.
LLVM_NODISCARD bool empty() const
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
iterator findValue(const ElemTy &V) const
findValue - Return an iterator to the specified value.
This node represents a polynomial recurrence on the trip count of the specified loop.
static cl::opt< bool > EnableForwardingConflictDetection("store-to-load-forwarding-conflict-detection", cl::Hidden, cl::desc("Enable conflict detection in loop-access analysis"), cl::init(true))
Enable store-to-load forwarding conflict detection.
iterator insert(const ElemTy &Data)
insert - Insert a new value into the union/find set, ignoring the request if the value already exists...
const SCEV * getMulExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
const SCEVAddRecExpr * getAsAddRec(Value *V)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
This header provides classes for managing per-loop analyses.
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
An instruction for storing to memory.
static Instruction * getFirstInst(Instruction *FirstInst, Value *V, Instruction *Loc)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
iterator_range< block_iterator > blocks() const
const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
iterator find(const_arg_type_t< KeyT > Val)
bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Function Alias Analysis false
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
initializer< Ty > init(const Ty &Val)
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
Type * getType() const
Return the LLVM type of this SCEV expression.
Value handle that tracks a Value across RAUW.
This analysis provides dependence information for the memory accesses of a loop.
int64_t getSExtValue() const
Get sign extended value.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool addPointer(unsigned Index)
Tries to add the pointer recorded in RtCheck at index Index to this pointer checking group...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallVector< Instruction *, 4 > getInstructionsForAccess(Value *Ptr, bool isWrite) const
Find the set of instructions that read or write via Ptr.
EquivalenceClasses - This represents a collection of equivalence classes and supports three efficient...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
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.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
static const unsigned End
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
const SCEV * replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, const ValueToValueMap &PtrToStride, Value *Ptr, Value *OrigPtr=nullptr)
Return the SCEV corresponding to a pointer with the symbolic stride replaced with constant one...
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
const APInt & getAPInt() const
bool isPointerTy() const
True if this is an instance of PointerType.
static bool hasComputableBounds(PredicatedScalarEvolution &PSE, const ValueToValueMap &Strides, Value *Ptr, Loop *L)
Check whether a pointer can participate in a runtime bounds check.
LLVMContext & getContext() const
All values hold a context through their type.
std::pair< const CheckingPtrGroup *, const CheckingPtrGroup * > PointerCheck
A memcheck which made up of a pair of grouped pointers.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Value * stripIntegerCast(Value *V)
unsigned AliasSetId
Holds the id of the disjoint alias set to which this pointer belongs.
DepType
The type of the dependence.
SmallVector< unsigned, 2 > Members
Indices of all the pointers that constitute this grouping.
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
const Value * Ptr
The address of the start of the location.
Representation for a specific memory location.
bool areDepsSafe(DepCandidates &AccessSets, MemAccessInfoList &CheckDeps, const ValueToValueMap &Strides)
Check whether the dependencies between the accesses are safe.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've proved that V doesn't wrap by means of a SCEV predicate.
static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR, PredicatedScalarEvolution &PSE, const Loop *L)
Return true if an AddRec pointer Ptr is unsigned non-wrapping, i.e.
bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
bool isBackward() const
Lexically backward dependence.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
bool isUniform(Value *V) const
Returns true if the value V is uniform within the loop.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
static const SCEV * getMinFromExprs(const SCEV *I, const SCEV *J, ScalarEvolution *SE)
Compare I and J and return the minimum.
Provides information about what library functions are available for the current target.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
bool isForward() const
Lexically forward dependence.
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
const SCEV * Low
The SCEV expression which represents the lower bound of all the pointers in this group.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Drive the analysis of memory accesses in the loop.
ConstantInt * getValue() const
const SCEV * getUMaxExpr(const SCEV *LHS, const SCEV *RHS)
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
const LoopAccessInfo & getInfo(Loop *L)
Query the result of the loop access information for the loop L.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
void generateChecks(MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies)
Generate the checks and store it.
void setPreservesAll()
Set by analyses that do not transform their input at all.
This class uses information about analyze scalars to rewrite expressions in canonical form...
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
static bool isSafeForVectorization(DepType Type)
Dependence types that don't prevent vectorization.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
unsigned getNumberOfChecks() const
Returns the number of run-time checks required according to needsChecking.
llvm_unreachable("Unknown RegBank!")
const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
This analysis provides dependence information for the memory accesses of a loop.
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
static PointerBounds expandBounds(const RuntimePointerChecking::CheckingPtrGroup *CG, Loop *TheLoop, Instruction *Loc, SCEVExpander &Exp, ScalarEvolution *SE, const RuntimePointerChecking &PtrRtChecking)
Expand code for the lower and upper bound of the pointer group CG in TheLoop.
Dependece between memory access instructions.
This class represents an analyzed expression in the program.
const SCEV * High
The SCEV expression which represents the upper bound of all the pointers in this group.
static cl::opt< bool > EnableMemAccessVersioning("enable-mem-access-versioning", cl::init(true), cl::Hidden, cl::desc("Enable symbolic stride memory access versioning"))
This enables versioning on the strides of symbolically striding memory accesses in code like the foll...
bool isFunctionVectorizable(StringRef F, unsigned VF) const
Represents a single loop in the control flow graph.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
This file provides utility analysis objects describing memory locations.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
APFloat abs(APFloat X)
Returns the absolute value of the argument.
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
SmallVector< PointerInfo, 2 > Pointers
Information about the pointers that may require checking.
static cl::opt< unsigned, true > VectorizationFactor("force-vector-width", cl::Hidden, cl::desc("Sets the SIMD width. Zero is autoselect."), cl::location(VectorizerParams::VectorizationFactor))
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static Value * getPointerOperand(Value *I)
Take the pointer operand from the Load/Store instruction.
const Loop * getLoop() const
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
static unsigned getAddressSpaceOperand(Value *I)
Take the address space operand from the Load/Store instruction.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
iterator_range< df_iterator< T > > depth_first(const T &G)
typename std::set< ECValue >::const_iterator iterator
iterator* - Provides a way to iterate over all values in the set.
static cl::opt< unsigned, true > VectorizationInterleave("force-vector-interleave", cl::Hidden, cl::desc("Sets the vectorization interleave count. ""Zero is autoselect."), cl::location(VectorizerParams::VectorizationInterleave))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const SCEV * getUMinExpr(const SCEV *LHS, const SCEV *RHS)
RuntimePointerChecking & RtCheck
Constitutes the context of this pointer checking group.
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM Value Representation.
const ElemTy & getLeaderValue(const ElemTy &V) const
getLeaderValue - Return the leader for the specified value that is in the set.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
A vector that has set insertion semantics.
static bool blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, DominatorTree *DT)
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
bool needsChecking(const CheckingPtrGroup &M, const CheckingPtrGroup &N) const
Decide if we need to add a check between two groups of pointers, according to needsChecking.
This class implements an extremely fast bulk output stream that can only output to a stream...
The legacy pass manager's analysis pass to compute loop information.
static unsigned VectorizationInterleave
Interleave factor as overridden by the user.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV * > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
APInt abs() const
Get the absolute value;.
This header defines various interfaces for pass management in LLVM.
static bool isInterleaveForced()
True if force-vector-interleave was specified by the user.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
A special type used by analysis passes to provide an address that identifies that particular analysis...
LocationClass< Ty > location(Ty &L)
const BasicBlock * getParent() const
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
Accumulate offsets from stripInBoundsConstantOffsets().
void print(raw_ostream &OS, const Module *M=nullptr) const override
Print the result of the analysis when invoked with -analyze.
static cl::opt< unsigned > MemoryCheckMergeThreshold("memory-check-merge-threshold", cl::Hidden, cl::desc("Maximum number of comparisons done when trying to merge ""runtime memory checks. (default = 100)"), cl::init(100))
The maximum iterations used to merge memory checks.
unsigned DependencySetId
Holds the id of the set of pointers that could be dependent because of a shared underlying object...
static cl::opt< unsigned, true > RuntimeMemoryCheckThreshold("runtime-memory-check-threshold", cl::Hidden, cl::desc("When performing memory disambiguation checks at runtime do not ""generate more than this number of comparisons (default = 8)."), cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8))
static bool isNoWrap(PredicatedScalarEvolution &PSE, const ValueToValueMap &Strides, Value *Ptr, Loop *L)
Check whether a pointer address cannot wrap.
This class represents a constant integer value.
bool Need
This flag indicates if we need to add the runtime check.
LoopAccessInfo(Loop *L, ScalarEvolution *SE, const TargetLibraryInfo *TLI, AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI)