1 //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // The implementation for the loop memory dependence that was originally 10 // developed for the loop vectorizer. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Analysis/LoopAccessAnalysis.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/ADT/DepthFirstIterator.h" 18 #include "llvm/ADT/EquivalenceClasses.h" 19 #include "llvm/ADT/PointerIntPair.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/iterator_range.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/AliasSetTracker.h" 28 #include "llvm/Analysis/LoopAnalysisManager.h" 29 #include "llvm/Analysis/LoopInfo.h" 30 #include "llvm/Analysis/MemoryLocation.h" 31 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 32 #include "llvm/Analysis/ScalarEvolution.h" 33 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 34 #include "llvm/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/Analysis/VectorUtils.h" 37 #include "llvm/IR/BasicBlock.h" 38 #include "llvm/IR/Constants.h" 39 #include "llvm/IR/DataLayout.h" 40 #include "llvm/IR/DebugLoc.h" 41 #include "llvm/IR/DerivedTypes.h" 42 #include "llvm/IR/DiagnosticInfo.h" 43 #include "llvm/IR/Dominators.h" 44 #include "llvm/IR/Function.h" 45 #include "llvm/IR/InstrTypes.h" 46 #include "llvm/IR/Instruction.h" 47 #include "llvm/IR/Instructions.h" 48 #include "llvm/IR/Operator.h" 49 #include "llvm/IR/PassManager.h" 50 #include "llvm/IR/PatternMatch.h" 51 #include "llvm/IR/Type.h" 52 #include "llvm/IR/Value.h" 53 #include "llvm/IR/ValueHandle.h" 54 #include "llvm/InitializePasses.h" 55 #include "llvm/Pass.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CommandLine.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/ErrorHandling.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include <algorithm> 62 #include <cassert> 63 #include <cstdint> 64 #include <iterator> 65 #include <utility> 66 #include <vector> 67 68 using namespace llvm; 69 using namespace llvm::PatternMatch; 70 71 #define DEBUG_TYPE "loop-accesses" 72 73 static cl::opt<unsigned, true> 74 VectorizationFactor("force-vector-width", cl::Hidden, 75 cl::desc("Sets the SIMD width. Zero is autoselect."), 76 cl::location(VectorizerParams::VectorizationFactor)); 77 unsigned VectorizerParams::VectorizationFactor; 78 79 static cl::opt<unsigned, true> 80 VectorizationInterleave("force-vector-interleave", cl::Hidden, 81 cl::desc("Sets the vectorization interleave count. " 82 "Zero is autoselect."), 83 cl::location( 84 VectorizerParams::VectorizationInterleave)); 85 unsigned VectorizerParams::VectorizationInterleave; 86 87 static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold( 88 "runtime-memory-check-threshold", cl::Hidden, 89 cl::desc("When performing memory disambiguation checks at runtime do not " 90 "generate more than this number of comparisons (default = 8)."), 91 cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8)); 92 unsigned VectorizerParams::RuntimeMemoryCheckThreshold; 93 94 /// The maximum iterations used to merge memory checks 95 static cl::opt<unsigned> MemoryCheckMergeThreshold( 96 "memory-check-merge-threshold", cl::Hidden, 97 cl::desc("Maximum number of comparisons done when trying to merge " 98 "runtime memory checks. (default = 100)"), 99 cl::init(100)); 100 101 /// Maximum SIMD width. 102 const unsigned VectorizerParams::MaxVectorWidth = 64; 103 104 /// We collect dependences up to this threshold. 105 static cl::opt<unsigned> 106 MaxDependences("max-dependences", cl::Hidden, 107 cl::desc("Maximum number of dependences collected by " 108 "loop-access analysis (default = 100)"), 109 cl::init(100)); 110 111 /// This enables versioning on the strides of symbolically striding memory 112 /// accesses in code like the following. 113 /// for (i = 0; i < N; ++i) 114 /// A[i * Stride1] += B[i * Stride2] ... 115 /// 116 /// Will be roughly translated to 117 /// if (Stride1 == 1 && Stride2 == 1) { 118 /// for (i = 0; i < N; i+=4) 119 /// A[i:i+3] += ... 120 /// } else 121 /// ... 122 static cl::opt<bool> EnableMemAccessVersioning( 123 "enable-mem-access-versioning", cl::init(true), cl::Hidden, 124 cl::desc("Enable symbolic stride memory access versioning")); 125 126 /// Enable store-to-load forwarding conflict detection. This option can 127 /// be disabled for correctness testing. 128 static cl::opt<bool> EnableForwardingConflictDetection( 129 "store-to-load-forwarding-conflict-detection", cl::Hidden, 130 cl::desc("Enable conflict detection in loop-access analysis"), 131 cl::init(true)); 132 133 static cl::opt<unsigned> MaxForkedSCEVDepth( 134 "max-forked-scev-depth", cl::Hidden, 135 cl::desc("Maximum recursion depth when finding forked SCEVs (default = 5)"), 136 cl::init(5)); 137 138 bool VectorizerParams::isInterleaveForced() { 139 return ::VectorizationInterleave.getNumOccurrences() > 0; 140 } 141 142 Value *llvm::stripIntegerCast(Value *V) { 143 if (auto *CI = dyn_cast<CastInst>(V)) 144 if (CI->getOperand(0)->getType()->isIntegerTy()) 145 return CI->getOperand(0); 146 return V; 147 } 148 149 const SCEV *llvm::replaceSymbolicStrideSCEV(PredicatedScalarEvolution &PSE, 150 const ValueToValueMap &PtrToStride, 151 Value *Ptr) { 152 const SCEV *OrigSCEV = PSE.getSCEV(Ptr); 153 154 // If there is an entry in the map return the SCEV of the pointer with the 155 // symbolic stride replaced by one. 156 ValueToValueMap::const_iterator SI = PtrToStride.find(Ptr); 157 if (SI == PtrToStride.end()) 158 // For a non-symbolic stride, just return the original expression. 159 return OrigSCEV; 160 161 Value *StrideVal = stripIntegerCast(SI->second); 162 163 ScalarEvolution *SE = PSE.getSE(); 164 const auto *U = cast<SCEVUnknown>(SE->getSCEV(StrideVal)); 165 const auto *CT = 166 static_cast<const SCEVConstant *>(SE->getOne(StrideVal->getType())); 167 168 PSE.addPredicate(*SE->getEqualPredicate(U, CT)); 169 auto *Expr = PSE.getSCEV(Ptr); 170 171 LLVM_DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV 172 << " by: " << *Expr << "\n"); 173 return Expr; 174 } 175 176 RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup( 177 unsigned Index, RuntimePointerChecking &RtCheck) 178 : High(RtCheck.Pointers[Index].End), Low(RtCheck.Pointers[Index].Start), 179 AddressSpace(RtCheck.Pointers[Index] 180 .PointerValue->getType() 181 ->getPointerAddressSpace()), 182 NeedsFreeze(RtCheck.Pointers[Index].NeedsFreeze) { 183 Members.push_back(Index); 184 } 185 186 /// Calculate Start and End points of memory access. 187 /// Let's assume A is the first access and B is a memory access on N-th loop 188 /// iteration. Then B is calculated as: 189 /// B = A + Step*N . 190 /// Step value may be positive or negative. 191 /// N is a calculated back-edge taken count: 192 /// N = (TripCount > 0) ? RoundDown(TripCount -1 , VF) : 0 193 /// Start and End points are calculated in the following way: 194 /// Start = UMIN(A, B) ; End = UMAX(A, B) + SizeOfElt, 195 /// where SizeOfElt is the size of single memory access in bytes. 196 /// 197 /// There is no conflict when the intervals are disjoint: 198 /// NoConflict = (P2.Start >= P1.End) || (P1.Start >= P2.End) 199 void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr, 200 Type *AccessTy, bool WritePtr, 201 unsigned DepSetId, unsigned ASId, 202 PredicatedScalarEvolution &PSE, 203 bool NeedsFreeze) { 204 ScalarEvolution *SE = PSE.getSE(); 205 206 const SCEV *ScStart; 207 const SCEV *ScEnd; 208 209 if (SE->isLoopInvariant(PtrExpr, Lp)) { 210 ScStart = ScEnd = PtrExpr; 211 } else { 212 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrExpr); 213 assert(AR && "Invalid addrec expression"); 214 const SCEV *Ex = PSE.getBackedgeTakenCount(); 215 216 ScStart = AR->getStart(); 217 ScEnd = AR->evaluateAtIteration(Ex, *SE); 218 const SCEV *Step = AR->getStepRecurrence(*SE); 219 220 // For expressions with negative step, the upper bound is ScStart and the 221 // lower bound is ScEnd. 222 if (const auto *CStep = dyn_cast<SCEVConstant>(Step)) { 223 if (CStep->getValue()->isNegative()) 224 std::swap(ScStart, ScEnd); 225 } else { 226 // Fallback case: the step is not constant, but we can still 227 // get the upper and lower bounds of the interval by using min/max 228 // expressions. 229 ScStart = SE->getUMinExpr(ScStart, ScEnd); 230 ScEnd = SE->getUMaxExpr(AR->getStart(), ScEnd); 231 } 232 } 233 // Add the size of the pointed element to ScEnd. 234 auto &DL = Lp->getHeader()->getModule()->getDataLayout(); 235 Type *IdxTy = DL.getIndexType(Ptr->getType()); 236 const SCEV *EltSizeSCEV = SE->getStoreSizeOfExpr(IdxTy, AccessTy); 237 ScEnd = SE->getAddExpr(ScEnd, EltSizeSCEV); 238 239 Pointers.emplace_back(Ptr, ScStart, ScEnd, WritePtr, DepSetId, ASId, PtrExpr, 240 NeedsFreeze); 241 } 242 243 void RuntimePointerChecking::tryToCreateDiffCheck( 244 const RuntimeCheckingPtrGroup &CGI, const RuntimeCheckingPtrGroup &CGJ) { 245 if (!CanUseDiffCheck) 246 return; 247 248 // If either group contains multiple different pointers, bail out. 249 // TODO: Support multiple pointers by using the minimum or maximum pointer, 250 // depending on src & sink. 251 if (CGI.Members.size() != 1 || CGJ.Members.size() != 1) { 252 CanUseDiffCheck = false; 253 return; 254 } 255 256 PointerInfo *Src = &Pointers[CGI.Members[0]]; 257 PointerInfo *Sink = &Pointers[CGJ.Members[0]]; 258 259 // If either pointer is read and written, multiple checks may be needed. Bail 260 // out. 261 if (!DC.getOrderForAccess(Src->PointerValue, !Src->IsWritePtr).empty() || 262 !DC.getOrderForAccess(Sink->PointerValue, !Sink->IsWritePtr).empty()) { 263 CanUseDiffCheck = false; 264 return; 265 } 266 267 ArrayRef<unsigned> AccSrc = 268 DC.getOrderForAccess(Src->PointerValue, Src->IsWritePtr); 269 ArrayRef<unsigned> AccSink = 270 DC.getOrderForAccess(Sink->PointerValue, Sink->IsWritePtr); 271 // If either pointer is accessed multiple times, there may not be a clear 272 // src/sink relation. Bail out for now. 273 if (AccSrc.size() != 1 || AccSink.size() != 1) { 274 CanUseDiffCheck = false; 275 return; 276 } 277 // If the sink is accessed before src, swap src/sink. 278 if (AccSink[0] < AccSrc[0]) 279 std::swap(Src, Sink); 280 281 auto *SrcAR = dyn_cast<SCEVAddRecExpr>(Src->Expr); 282 auto *SinkAR = dyn_cast<SCEVAddRecExpr>(Sink->Expr); 283 if (!SrcAR || !SinkAR) { 284 CanUseDiffCheck = false; 285 return; 286 } 287 288 const DataLayout &DL = 289 SinkAR->getLoop()->getHeader()->getModule()->getDataLayout(); 290 SmallVector<Instruction *, 4> SrcInsts = 291 DC.getInstructionsForAccess(Src->PointerValue, Src->IsWritePtr); 292 SmallVector<Instruction *, 4> SinkInsts = 293 DC.getInstructionsForAccess(Sink->PointerValue, Sink->IsWritePtr); 294 Type *SrcTy = getLoadStoreType(SrcInsts[0]); 295 Type *DstTy = getLoadStoreType(SinkInsts[0]); 296 if (isa<ScalableVectorType>(SrcTy) || isa<ScalableVectorType>(DstTy)) 297 return; 298 unsigned AllocSize = 299 std::max(DL.getTypeAllocSize(SrcTy), DL.getTypeAllocSize(DstTy)); 300 IntegerType *IntTy = 301 IntegerType::get(Src->PointerValue->getContext(), 302 DL.getPointerSizeInBits(CGI.AddressSpace)); 303 304 // Only matching constant steps matching the AllocSize are supported at the 305 // moment. This simplifies the difference computation. Can be extended in the 306 // future. 307 auto *Step = dyn_cast<SCEVConstant>(SinkAR->getStepRecurrence(*SE)); 308 if (!Step || Step != SrcAR->getStepRecurrence(*SE) || 309 Step->getAPInt().abs() != AllocSize) { 310 CanUseDiffCheck = false; 311 return; 312 } 313 314 // When counting down, the dependence distance needs to be swapped. 315 if (Step->getValue()->isNegative()) 316 std::swap(SinkAR, SrcAR); 317 318 const SCEV *SinkStartInt = SE->getPtrToIntExpr(SinkAR->getStart(), IntTy); 319 const SCEV *SrcStartInt = SE->getPtrToIntExpr(SrcAR->getStart(), IntTy); 320 if (isa<SCEVCouldNotCompute>(SinkStartInt) || 321 isa<SCEVCouldNotCompute>(SrcStartInt)) { 322 CanUseDiffCheck = false; 323 return; 324 } 325 DiffChecks.emplace_back(SrcStartInt, SinkStartInt, AllocSize, 326 Src->NeedsFreeze || Sink->NeedsFreeze); 327 } 328 329 SmallVector<RuntimePointerCheck, 4> RuntimePointerChecking::generateChecks() { 330 SmallVector<RuntimePointerCheck, 4> Checks; 331 332 for (unsigned I = 0; I < CheckingGroups.size(); ++I) { 333 for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) { 334 const RuntimeCheckingPtrGroup &CGI = CheckingGroups[I]; 335 const RuntimeCheckingPtrGroup &CGJ = CheckingGroups[J]; 336 337 if (needsChecking(CGI, CGJ)) { 338 tryToCreateDiffCheck(CGI, CGJ); 339 Checks.push_back(std::make_pair(&CGI, &CGJ)); 340 } 341 } 342 } 343 return Checks; 344 } 345 346 void RuntimePointerChecking::generateChecks( 347 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) { 348 assert(Checks.empty() && "Checks is not empty"); 349 groupChecks(DepCands, UseDependencies); 350 Checks = generateChecks(); 351 } 352 353 bool RuntimePointerChecking::needsChecking( 354 const RuntimeCheckingPtrGroup &M, const RuntimeCheckingPtrGroup &N) const { 355 for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I) 356 for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J) 357 if (needsChecking(M.Members[I], N.Members[J])) 358 return true; 359 return false; 360 } 361 362 /// Compare \p I and \p J and return the minimum. 363 /// Return nullptr in case we couldn't find an answer. 364 static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J, 365 ScalarEvolution *SE) { 366 const SCEV *Diff = SE->getMinusSCEV(J, I); 367 const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff); 368 369 if (!C) 370 return nullptr; 371 if (C->getValue()->isNegative()) 372 return J; 373 return I; 374 } 375 376 bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, 377 RuntimePointerChecking &RtCheck) { 378 return addPointer( 379 Index, RtCheck.Pointers[Index].Start, RtCheck.Pointers[Index].End, 380 RtCheck.Pointers[Index].PointerValue->getType()->getPointerAddressSpace(), 381 RtCheck.Pointers[Index].NeedsFreeze, *RtCheck.SE); 382 } 383 384 bool RuntimeCheckingPtrGroup::addPointer(unsigned Index, const SCEV *Start, 385 const SCEV *End, unsigned AS, 386 bool NeedsFreeze, 387 ScalarEvolution &SE) { 388 assert(AddressSpace == AS && 389 "all pointers in a checking group must be in the same address space"); 390 391 // Compare the starts and ends with the known minimum and maximum 392 // of this set. We need to know how we compare against the min/max 393 // of the set in order to be able to emit memchecks. 394 const SCEV *Min0 = getMinFromExprs(Start, Low, &SE); 395 if (!Min0) 396 return false; 397 398 const SCEV *Min1 = getMinFromExprs(End, High, &SE); 399 if (!Min1) 400 return false; 401 402 // Update the low bound expression if we've found a new min value. 403 if (Min0 == Start) 404 Low = Start; 405 406 // Update the high bound expression if we've found a new max value. 407 if (Min1 != End) 408 High = End; 409 410 Members.push_back(Index); 411 this->NeedsFreeze |= NeedsFreeze; 412 return true; 413 } 414 415 void RuntimePointerChecking::groupChecks( 416 MemoryDepChecker::DepCandidates &DepCands, bool UseDependencies) { 417 // We build the groups from dependency candidates equivalence classes 418 // because: 419 // - We know that pointers in the same equivalence class share 420 // the same underlying object and therefore there is a chance 421 // that we can compare pointers 422 // - We wouldn't be able to merge two pointers for which we need 423 // to emit a memcheck. The classes in DepCands are already 424 // conveniently built such that no two pointers in the same 425 // class need checking against each other. 426 427 // We use the following (greedy) algorithm to construct the groups 428 // For every pointer in the equivalence class: 429 // For each existing group: 430 // - if the difference between this pointer and the min/max bounds 431 // of the group is a constant, then make the pointer part of the 432 // group and update the min/max bounds of that group as required. 433 434 CheckingGroups.clear(); 435 436 // If we need to check two pointers to the same underlying object 437 // with a non-constant difference, we shouldn't perform any pointer 438 // grouping with those pointers. This is because we can easily get 439 // into cases where the resulting check would return false, even when 440 // the accesses are safe. 441 // 442 // The following example shows this: 443 // for (i = 0; i < 1000; ++i) 444 // a[5000 + i * m] = a[i] + a[i + 9000] 445 // 446 // Here grouping gives a check of (5000, 5000 + 1000 * m) against 447 // (0, 10000) which is always false. However, if m is 1, there is no 448 // dependence. Not grouping the checks for a[i] and a[i + 9000] allows 449 // us to perform an accurate check in this case. 450 // 451 // The above case requires that we have an UnknownDependence between 452 // accesses to the same underlying object. This cannot happen unless 453 // FoundNonConstantDistanceDependence is set, and therefore UseDependencies 454 // is also false. In this case we will use the fallback path and create 455 // separate checking groups for all pointers. 456 457 // If we don't have the dependency partitions, construct a new 458 // checking pointer group for each pointer. This is also required 459 // for correctness, because in this case we can have checking between 460 // pointers to the same underlying object. 461 if (!UseDependencies) { 462 for (unsigned I = 0; I < Pointers.size(); ++I) 463 CheckingGroups.push_back(RuntimeCheckingPtrGroup(I, *this)); 464 return; 465 } 466 467 unsigned TotalComparisons = 0; 468 469 DenseMap<Value *, SmallVector<unsigned>> PositionMap; 470 for (unsigned Index = 0; Index < Pointers.size(); ++Index) { 471 auto Iter = PositionMap.insert({Pointers[Index].PointerValue, {}}); 472 Iter.first->second.push_back(Index); 473 } 474 475 // We need to keep track of what pointers we've already seen so we 476 // don't process them twice. 477 SmallSet<unsigned, 2> Seen; 478 479 // Go through all equivalence classes, get the "pointer check groups" 480 // and add them to the overall solution. We use the order in which accesses 481 // appear in 'Pointers' to enforce determinism. 482 for (unsigned I = 0; I < Pointers.size(); ++I) { 483 // We've seen this pointer before, and therefore already processed 484 // its equivalence class. 485 if (Seen.count(I)) 486 continue; 487 488 MemoryDepChecker::MemAccessInfo Access(Pointers[I].PointerValue, 489 Pointers[I].IsWritePtr); 490 491 SmallVector<RuntimeCheckingPtrGroup, 2> Groups; 492 auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access)); 493 494 // Because DepCands is constructed by visiting accesses in the order in 495 // which they appear in alias sets (which is deterministic) and the 496 // iteration order within an equivalence class member is only dependent on 497 // the order in which unions and insertions are performed on the 498 // equivalence class, the iteration order is deterministic. 499 for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end(); 500 MI != ME; ++MI) { 501 auto PointerI = PositionMap.find(MI->getPointer()); 502 assert(PointerI != PositionMap.end() && 503 "pointer in equivalence class not found in PositionMap"); 504 for (unsigned Pointer : PointerI->second) { 505 bool Merged = false; 506 // Mark this pointer as seen. 507 Seen.insert(Pointer); 508 509 // Go through all the existing sets and see if we can find one 510 // which can include this pointer. 511 for (RuntimeCheckingPtrGroup &Group : Groups) { 512 // Don't perform more than a certain amount of comparisons. 513 // This should limit the cost of grouping the pointers to something 514 // reasonable. If we do end up hitting this threshold, the algorithm 515 // will create separate groups for all remaining pointers. 516 if (TotalComparisons > MemoryCheckMergeThreshold) 517 break; 518 519 TotalComparisons++; 520 521 if (Group.addPointer(Pointer, *this)) { 522 Merged = true; 523 break; 524 } 525 } 526 527 if (!Merged) 528 // We couldn't add this pointer to any existing set or the threshold 529 // for the number of comparisons has been reached. Create a new group 530 // to hold the current pointer. 531 Groups.push_back(RuntimeCheckingPtrGroup(Pointer, *this)); 532 } 533 } 534 535 // We've computed the grouped checks for this partition. 536 // Save the results and continue with the next one. 537 llvm::copy(Groups, std::back_inserter(CheckingGroups)); 538 } 539 } 540 541 bool RuntimePointerChecking::arePointersInSamePartition( 542 const SmallVectorImpl<int> &PtrToPartition, unsigned PtrIdx1, 543 unsigned PtrIdx2) { 544 return (PtrToPartition[PtrIdx1] != -1 && 545 PtrToPartition[PtrIdx1] == PtrToPartition[PtrIdx2]); 546 } 547 548 bool RuntimePointerChecking::needsChecking(unsigned I, unsigned J) const { 549 const PointerInfo &PointerI = Pointers[I]; 550 const PointerInfo &PointerJ = Pointers[J]; 551 552 // No need to check if two readonly pointers intersect. 553 if (!PointerI.IsWritePtr && !PointerJ.IsWritePtr) 554 return false; 555 556 // Only need to check pointers between two different dependency sets. 557 if (PointerI.DependencySetId == PointerJ.DependencySetId) 558 return false; 559 560 // Only need to check pointers in the same alias set. 561 if (PointerI.AliasSetId != PointerJ.AliasSetId) 562 return false; 563 564 return true; 565 } 566 567 void RuntimePointerChecking::printChecks( 568 raw_ostream &OS, const SmallVectorImpl<RuntimePointerCheck> &Checks, 569 unsigned Depth) const { 570 unsigned N = 0; 571 for (const auto &Check : Checks) { 572 const auto &First = Check.first->Members, &Second = Check.second->Members; 573 574 OS.indent(Depth) << "Check " << N++ << ":\n"; 575 576 OS.indent(Depth + 2) << "Comparing group (" << Check.first << "):\n"; 577 for (unsigned K = 0; K < First.size(); ++K) 578 OS.indent(Depth + 2) << *Pointers[First[K]].PointerValue << "\n"; 579 580 OS.indent(Depth + 2) << "Against group (" << Check.second << "):\n"; 581 for (unsigned K = 0; K < Second.size(); ++K) 582 OS.indent(Depth + 2) << *Pointers[Second[K]].PointerValue << "\n"; 583 } 584 } 585 586 void RuntimePointerChecking::print(raw_ostream &OS, unsigned Depth) const { 587 588 OS.indent(Depth) << "Run-time memory checks:\n"; 589 printChecks(OS, Checks, Depth); 590 591 OS.indent(Depth) << "Grouped accesses:\n"; 592 for (unsigned I = 0; I < CheckingGroups.size(); ++I) { 593 const auto &CG = CheckingGroups[I]; 594 595 OS.indent(Depth + 2) << "Group " << &CG << ":\n"; 596 OS.indent(Depth + 4) << "(Low: " << *CG.Low << " High: " << *CG.High 597 << ")\n"; 598 for (unsigned J = 0; J < CG.Members.size(); ++J) { 599 OS.indent(Depth + 6) << "Member: " << *Pointers[CG.Members[J]].Expr 600 << "\n"; 601 } 602 } 603 } 604 605 namespace { 606 607 /// Analyses memory accesses in a loop. 608 /// 609 /// Checks whether run time pointer checks are needed and builds sets for data 610 /// dependence checking. 611 class AccessAnalysis { 612 public: 613 /// Read or write access location. 614 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; 615 typedef SmallVector<MemAccessInfo, 8> MemAccessInfoList; 616 617 AccessAnalysis(Loop *TheLoop, AAResults *AA, LoopInfo *LI, 618 MemoryDepChecker::DepCandidates &DA, 619 PredicatedScalarEvolution &PSE) 620 : TheLoop(TheLoop), AST(*AA), LI(LI), DepCands(DA), PSE(PSE) {} 621 622 /// Register a load and whether it is only read from. 623 void addLoad(MemoryLocation &Loc, Type *AccessTy, bool IsReadOnly) { 624 Value *Ptr = const_cast<Value*>(Loc.Ptr); 625 AST.add(Ptr, LocationSize::beforeOrAfterPointer(), Loc.AATags); 626 Accesses[MemAccessInfo(Ptr, false)].insert(AccessTy); 627 if (IsReadOnly) 628 ReadOnlyPtr.insert(Ptr); 629 } 630 631 /// Register a store. 632 void addStore(MemoryLocation &Loc, Type *AccessTy) { 633 Value *Ptr = const_cast<Value*>(Loc.Ptr); 634 AST.add(Ptr, LocationSize::beforeOrAfterPointer(), Loc.AATags); 635 Accesses[MemAccessInfo(Ptr, true)].insert(AccessTy); 636 } 637 638 /// Check if we can emit a run-time no-alias check for \p Access. 639 /// 640 /// Returns true if we can emit a run-time no alias check for \p Access. 641 /// If we can check this access, this also adds it to a dependence set and 642 /// adds a run-time to check for it to \p RtCheck. If \p Assume is true, 643 /// we will attempt to use additional run-time checks in order to get 644 /// the bounds of the pointer. 645 bool createCheckForAccess(RuntimePointerChecking &RtCheck, 646 MemAccessInfo Access, Type *AccessTy, 647 const ValueToValueMap &Strides, 648 DenseMap<Value *, unsigned> &DepSetId, 649 Loop *TheLoop, unsigned &RunningDepId, 650 unsigned ASId, bool ShouldCheckStride, bool Assume); 651 652 /// Check whether we can check the pointers at runtime for 653 /// non-intersection. 654 /// 655 /// Returns true if we need no check or if we do and we can generate them 656 /// (i.e. the pointers have computable bounds). 657 bool canCheckPtrAtRT(RuntimePointerChecking &RtCheck, ScalarEvolution *SE, 658 Loop *TheLoop, const ValueToValueMap &Strides, 659 Value *&UncomputablePtr, bool ShouldCheckWrap = false); 660 661 /// Goes over all memory accesses, checks whether a RT check is needed 662 /// and builds sets of dependent accesses. 663 void buildDependenceSets() { 664 processMemAccesses(); 665 } 666 667 /// Initial processing of memory accesses determined that we need to 668 /// perform dependency checking. 669 /// 670 /// Note that this can later be cleared if we retry memcheck analysis without 671 /// dependency checking (i.e. FoundNonConstantDistanceDependence). 672 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); } 673 674 /// We decided that no dependence analysis would be used. Reset the state. 675 void resetDepChecks(MemoryDepChecker &DepChecker) { 676 CheckDeps.clear(); 677 DepChecker.clearDependences(); 678 } 679 680 MemAccessInfoList &getDependenciesToCheck() { return CheckDeps; } 681 682 private: 683 typedef MapVector<MemAccessInfo, SmallSetVector<Type *, 1>> PtrAccessMap; 684 685 /// Go over all memory access and check whether runtime pointer checks 686 /// are needed and build sets of dependency check candidates. 687 void processMemAccesses(); 688 689 /// Map of all accesses. Values are the types used to access memory pointed to 690 /// by the pointer. 691 PtrAccessMap Accesses; 692 693 /// The loop being checked. 694 const Loop *TheLoop; 695 696 /// List of accesses that need a further dependence check. 697 MemAccessInfoList CheckDeps; 698 699 /// Set of pointers that are read only. 700 SmallPtrSet<Value*, 16> ReadOnlyPtr; 701 702 /// An alias set tracker to partition the access set by underlying object and 703 //intrinsic property (such as TBAA metadata). 704 AliasSetTracker AST; 705 706 LoopInfo *LI; 707 708 /// Sets of potentially dependent accesses - members of one set share an 709 /// underlying pointer. The set "CheckDeps" identfies which sets really need a 710 /// dependence check. 711 MemoryDepChecker::DepCandidates &DepCands; 712 713 /// Initial processing of memory accesses determined that we may need 714 /// to add memchecks. Perform the analysis to determine the necessary checks. 715 /// 716 /// Note that, this is different from isDependencyCheckNeeded. When we retry 717 /// memcheck analysis without dependency checking 718 /// (i.e. FoundNonConstantDistanceDependence), isDependencyCheckNeeded is 719 /// cleared while this remains set if we have potentially dependent accesses. 720 bool IsRTCheckAnalysisNeeded = false; 721 722 /// The SCEV predicate containing all the SCEV-related assumptions. 723 PredicatedScalarEvolution &PSE; 724 }; 725 726 } // end anonymous namespace 727 728 /// Check whether a pointer can participate in a runtime bounds check. 729 /// If \p Assume, try harder to prove that we can compute the bounds of \p Ptr 730 /// by adding run-time checks (overflow checks) if necessary. 731 static bool hasComputableBounds(PredicatedScalarEvolution &PSE, Value *Ptr, 732 const SCEV *PtrScev, Loop *L, bool Assume) { 733 // The bounds for loop-invariant pointer is trivial. 734 if (PSE.getSE()->isLoopInvariant(PtrScev, L)) 735 return true; 736 737 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 738 739 if (!AR && Assume) 740 AR = PSE.getAsAddRec(Ptr); 741 742 if (!AR) 743 return false; 744 745 return AR->isAffine(); 746 } 747 748 /// Check whether a pointer address cannot wrap. 749 static bool isNoWrap(PredicatedScalarEvolution &PSE, 750 const ValueToValueMap &Strides, Value *Ptr, Type *AccessTy, 751 Loop *L) { 752 const SCEV *PtrScev = PSE.getSCEV(Ptr); 753 if (PSE.getSE()->isLoopInvariant(PtrScev, L)) 754 return true; 755 756 int64_t Stride = getPtrStride(PSE, AccessTy, Ptr, L, Strides); 757 if (Stride == 1 || PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW)) 758 return true; 759 760 return false; 761 } 762 763 static void visitPointers(Value *StartPtr, const Loop &InnermostLoop, 764 function_ref<void(Value *)> AddPointer) { 765 SmallPtrSet<Value *, 8> Visited; 766 SmallVector<Value *> WorkList; 767 WorkList.push_back(StartPtr); 768 769 while (!WorkList.empty()) { 770 Value *Ptr = WorkList.pop_back_val(); 771 if (!Visited.insert(Ptr).second) 772 continue; 773 auto *PN = dyn_cast<PHINode>(Ptr); 774 // SCEV does not look through non-header PHIs inside the loop. Such phis 775 // can be analyzed by adding separate accesses for each incoming pointer 776 // value. 777 if (PN && InnermostLoop.contains(PN->getParent()) && 778 PN->getParent() != InnermostLoop.getHeader()) { 779 for (const Use &Inc : PN->incoming_values()) 780 WorkList.push_back(Inc); 781 } else 782 AddPointer(Ptr); 783 } 784 } 785 786 // Walk back through the IR for a pointer, looking for a select like the 787 // following: 788 // 789 // %offset = select i1 %cmp, i64 %a, i64 %b 790 // %addr = getelementptr double, double* %base, i64 %offset 791 // %ld = load double, double* %addr, align 8 792 // 793 // We won't be able to form a single SCEVAddRecExpr from this since the 794 // address for each loop iteration depends on %cmp. We could potentially 795 // produce multiple valid SCEVAddRecExprs, though, and check all of them for 796 // memory safety/aliasing if needed. 797 // 798 // If we encounter some IR we don't yet handle, or something obviously fine 799 // like a constant, then we just add the SCEV for that term to the list passed 800 // in by the caller. If we have a node that may potentially yield a valid 801 // SCEVAddRecExpr then we decompose it into parts and build the SCEV terms 802 // ourselves before adding to the list. 803 static void 804 findForkedSCEVs(ScalarEvolution *SE, const Loop *L, Value *Ptr, 805 SmallVectorImpl<std::pair<const SCEV *, bool>> &ScevList, 806 unsigned Depth) { 807 // If our Value is a SCEVAddRecExpr, loop invariant, not an instruction, or 808 // we've exceeded our limit on recursion, just return whatever we have 809 // regardless of whether it can be used for a forked pointer or not, along 810 // with an indication of whether it might be a poison or undef value. 811 const SCEV *Scev = SE->getSCEV(Ptr); 812 if (isa<SCEVAddRecExpr>(Scev) || L->isLoopInvariant(Ptr) || 813 !isa<Instruction>(Ptr) || Depth == 0) { 814 ScevList.push_back( 815 std::make_pair(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr))); 816 return; 817 } 818 819 Depth--; 820 821 auto UndefPoisonCheck = [](std::pair<const SCEV *, bool> S) -> bool { 822 return S.second; 823 }; 824 825 Instruction *I = cast<Instruction>(Ptr); 826 unsigned Opcode = I->getOpcode(); 827 switch (Opcode) { 828 case Instruction::GetElementPtr: { 829 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I); 830 Type *SourceTy = GEP->getSourceElementType(); 831 // We only handle base + single offset GEPs here for now. 832 // Not dealing with preexisting gathers yet, so no vectors. 833 if (I->getNumOperands() != 2 || SourceTy->isVectorTy()) { 834 ScevList.push_back( 835 std::make_pair(Scev, !isGuaranteedNotToBeUndefOrPoison(GEP))); 836 break; 837 } 838 SmallVector<std::pair<const SCEV *, bool>, 2> BaseScevs; 839 SmallVector<std::pair<const SCEV *, bool>, 2> OffsetScevs; 840 findForkedSCEVs(SE, L, I->getOperand(0), BaseScevs, Depth); 841 findForkedSCEVs(SE, L, I->getOperand(1), OffsetScevs, Depth); 842 843 // See if we need to freeze our fork... 844 bool NeedsFreeze = any_of(BaseScevs, UndefPoisonCheck) || 845 any_of(OffsetScevs, UndefPoisonCheck); 846 847 // Check that we only have a single fork, on either the base or the offset. 848 // Copy the SCEV across for the one without a fork in order to generate 849 // the full SCEV for both sides of the GEP. 850 if (OffsetScevs.size() == 2 && BaseScevs.size() == 1) 851 BaseScevs.push_back(BaseScevs[0]); 852 else if (BaseScevs.size() == 2 && OffsetScevs.size() == 1) 853 OffsetScevs.push_back(OffsetScevs[0]); 854 else { 855 ScevList.push_back(std::make_pair(Scev, NeedsFreeze)); 856 break; 857 } 858 859 // Find the pointer type we need to extend to. 860 Type *IntPtrTy = SE->getEffectiveSCEVType( 861 SE->getSCEV(GEP->getPointerOperand())->getType()); 862 863 // Find the size of the type being pointed to. We only have a single 864 // index term (guarded above) so we don't need to index into arrays or 865 // structures, just get the size of the scalar value. 866 const SCEV *Size = SE->getSizeOfExpr(IntPtrTy, SourceTy); 867 868 // Scale up the offsets by the size of the type, then add to the bases. 869 const SCEV *Scaled1 = SE->getMulExpr( 870 Size, SE->getTruncateOrSignExtend(OffsetScevs[0].first, IntPtrTy)); 871 const SCEV *Scaled2 = SE->getMulExpr( 872 Size, SE->getTruncateOrSignExtend(OffsetScevs[1].first, IntPtrTy)); 873 ScevList.push_back(std::make_pair( 874 SE->getAddExpr(BaseScevs[0].first, Scaled1), NeedsFreeze)); 875 ScevList.push_back(std::make_pair( 876 SE->getAddExpr(BaseScevs[1].first, Scaled2), NeedsFreeze)); 877 break; 878 } 879 case Instruction::Select: { 880 SmallVector<std::pair<const SCEV *, bool>, 2> ChildScevs; 881 // A select means we've found a forked pointer, but we currently only 882 // support a single select per pointer so if there's another behind this 883 // then we just bail out and return the generic SCEV. 884 findForkedSCEVs(SE, L, I->getOperand(1), ChildScevs, Depth); 885 findForkedSCEVs(SE, L, I->getOperand(2), ChildScevs, Depth); 886 if (ChildScevs.size() == 2) { 887 ScevList.push_back(ChildScevs[0]); 888 ScevList.push_back(ChildScevs[1]); 889 } else 890 ScevList.push_back( 891 std::make_pair(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr))); 892 break; 893 } 894 default: 895 // Just return the current SCEV if we haven't handled the instruction yet. 896 LLVM_DEBUG(dbgs() << "ForkedPtr unhandled instruction: " << *I << "\n"); 897 ScevList.push_back( 898 std::make_pair(Scev, !isGuaranteedNotToBeUndefOrPoison(Ptr))); 899 break; 900 } 901 902 return; 903 } 904 905 static SmallVector<std::pair<const SCEV *, bool>> 906 findForkedPointer(PredicatedScalarEvolution &PSE, 907 const ValueToValueMap &StridesMap, Value *Ptr, 908 const Loop *L) { 909 ScalarEvolution *SE = PSE.getSE(); 910 assert(SE->isSCEVable(Ptr->getType()) && "Value is not SCEVable!"); 911 SmallVector<std::pair<const SCEV *, bool>> Scevs; 912 findForkedSCEVs(SE, L, Ptr, Scevs, MaxForkedSCEVDepth); 913 914 // For now, we will only accept a forked pointer with two possible SCEVs. 915 if (Scevs.size() == 2) 916 return Scevs; 917 918 return { 919 std::make_pair(replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false)}; 920 } 921 922 bool AccessAnalysis::createCheckForAccess(RuntimePointerChecking &RtCheck, 923 MemAccessInfo Access, Type *AccessTy, 924 const ValueToValueMap &StridesMap, 925 DenseMap<Value *, unsigned> &DepSetId, 926 Loop *TheLoop, unsigned &RunningDepId, 927 unsigned ASId, bool ShouldCheckWrap, 928 bool Assume) { 929 Value *Ptr = Access.getPointer(); 930 931 SmallVector<std::pair<const SCEV *, bool>> TranslatedPtrs = 932 findForkedPointer(PSE, StridesMap, Ptr, TheLoop); 933 934 for (auto &P : TranslatedPtrs) { 935 const SCEV *PtrExpr = P.first; 936 if (!hasComputableBounds(PSE, Ptr, PtrExpr, TheLoop, Assume)) 937 return false; 938 939 // When we run after a failing dependency check we have to make sure 940 // we don't have wrapping pointers. 941 if (ShouldCheckWrap) { 942 // Skip wrap checking when translating pointers. 943 if (TranslatedPtrs.size() > 1) 944 return false; 945 946 if (!isNoWrap(PSE, StridesMap, Ptr, AccessTy, TheLoop)) { 947 auto *Expr = PSE.getSCEV(Ptr); 948 if (!Assume || !isa<SCEVAddRecExpr>(Expr)) 949 return false; 950 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW); 951 } 952 } 953 // If there's only one option for Ptr, look it up after bounds and wrap 954 // checking, because assumptions might have been added to PSE. 955 if (TranslatedPtrs.size() == 1) 956 TranslatedPtrs[0] = std::make_pair( 957 replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr), false); 958 } 959 960 for (auto &P : TranslatedPtrs) { 961 const SCEV *PtrExpr = P.first; 962 963 // The id of the dependence set. 964 unsigned DepId; 965 966 if (isDependencyCheckNeeded()) { 967 Value *Leader = DepCands.getLeaderValue(Access).getPointer(); 968 unsigned &LeaderId = DepSetId[Leader]; 969 if (!LeaderId) 970 LeaderId = RunningDepId++; 971 DepId = LeaderId; 972 } else 973 // Each access has its own dependence set. 974 DepId = RunningDepId++; 975 976 bool IsWrite = Access.getInt(); 977 RtCheck.insert(TheLoop, Ptr, PtrExpr, AccessTy, IsWrite, DepId, ASId, PSE, 978 P.second); 979 LLVM_DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n'); 980 } 981 982 return true; 983 } 984 985 bool AccessAnalysis::canCheckPtrAtRT(RuntimePointerChecking &RtCheck, 986 ScalarEvolution *SE, Loop *TheLoop, 987 const ValueToValueMap &StridesMap, 988 Value *&UncomputablePtr, bool ShouldCheckWrap) { 989 // Find pointers with computable bounds. We are going to use this information 990 // to place a runtime bound check. 991 bool CanDoRT = true; 992 993 bool MayNeedRTCheck = false; 994 if (!IsRTCheckAnalysisNeeded) return true; 995 996 bool IsDepCheckNeeded = isDependencyCheckNeeded(); 997 998 // We assign a consecutive id to access from different alias sets. 999 // Accesses between different groups doesn't need to be checked. 1000 unsigned ASId = 0; 1001 for (auto &AS : AST) { 1002 int NumReadPtrChecks = 0; 1003 int NumWritePtrChecks = 0; 1004 bool CanDoAliasSetRT = true; 1005 ++ASId; 1006 1007 // We assign consecutive id to access from different dependence sets. 1008 // Accesses within the same set don't need a runtime check. 1009 unsigned RunningDepId = 1; 1010 DenseMap<Value *, unsigned> DepSetId; 1011 1012 SmallVector<MemAccessInfo, 4> Retries; 1013 1014 // First, count how many write and read accesses are in the alias set. Also 1015 // collect MemAccessInfos for later. 1016 SmallVector<MemAccessInfo, 4> AccessInfos; 1017 for (const auto &A : AS) { 1018 Value *Ptr = A.getValue(); 1019 bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true)); 1020 1021 if (IsWrite) 1022 ++NumWritePtrChecks; 1023 else 1024 ++NumReadPtrChecks; 1025 AccessInfos.emplace_back(Ptr, IsWrite); 1026 } 1027 1028 // We do not need runtime checks for this alias set, if there are no writes 1029 // or a single write and no reads. 1030 if (NumWritePtrChecks == 0 || 1031 (NumWritePtrChecks == 1 && NumReadPtrChecks == 0)) { 1032 assert((AS.size() <= 1 || 1033 all_of(AS, 1034 [this](auto AC) { 1035 MemAccessInfo AccessWrite(AC.getValue(), true); 1036 return DepCands.findValue(AccessWrite) == DepCands.end(); 1037 })) && 1038 "Can only skip updating CanDoRT below, if all entries in AS " 1039 "are reads or there is at most 1 entry"); 1040 continue; 1041 } 1042 1043 for (auto &Access : AccessInfos) { 1044 for (const auto &AccessTy : Accesses[Access]) { 1045 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap, 1046 DepSetId, TheLoop, RunningDepId, ASId, 1047 ShouldCheckWrap, false)) { 1048 LLVM_DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" 1049 << *Access.getPointer() << '\n'); 1050 Retries.push_back(Access); 1051 CanDoAliasSetRT = false; 1052 } 1053 } 1054 } 1055 1056 // Note that this function computes CanDoRT and MayNeedRTCheck 1057 // independently. For example CanDoRT=false, MayNeedRTCheck=false means that 1058 // we have a pointer for which we couldn't find the bounds but we don't 1059 // actually need to emit any checks so it does not matter. 1060 // 1061 // We need runtime checks for this alias set, if there are at least 2 1062 // dependence sets (in which case RunningDepId > 2) or if we need to re-try 1063 // any bound checks (because in that case the number of dependence sets is 1064 // incomplete). 1065 bool NeedsAliasSetRTCheck = RunningDepId > 2 || !Retries.empty(); 1066 1067 // We need to perform run-time alias checks, but some pointers had bounds 1068 // that couldn't be checked. 1069 if (NeedsAliasSetRTCheck && !CanDoAliasSetRT) { 1070 // Reset the CanDoSetRt flag and retry all accesses that have failed. 1071 // We know that we need these checks, so we can now be more aggressive 1072 // and add further checks if required (overflow checks). 1073 CanDoAliasSetRT = true; 1074 for (auto Access : Retries) { 1075 for (const auto &AccessTy : Accesses[Access]) { 1076 if (!createCheckForAccess(RtCheck, Access, AccessTy, StridesMap, 1077 DepSetId, TheLoop, RunningDepId, ASId, 1078 ShouldCheckWrap, /*Assume=*/true)) { 1079 CanDoAliasSetRT = false; 1080 UncomputablePtr = Access.getPointer(); 1081 break; 1082 } 1083 } 1084 } 1085 } 1086 1087 CanDoRT &= CanDoAliasSetRT; 1088 MayNeedRTCheck |= NeedsAliasSetRTCheck; 1089 ++ASId; 1090 } 1091 1092 // If the pointers that we would use for the bounds comparison have different 1093 // address spaces, assume the values aren't directly comparable, so we can't 1094 // use them for the runtime check. We also have to assume they could 1095 // overlap. In the future there should be metadata for whether address spaces 1096 // are disjoint. 1097 unsigned NumPointers = RtCheck.Pointers.size(); 1098 for (unsigned i = 0; i < NumPointers; ++i) { 1099 for (unsigned j = i + 1; j < NumPointers; ++j) { 1100 // Only need to check pointers between two different dependency sets. 1101 if (RtCheck.Pointers[i].DependencySetId == 1102 RtCheck.Pointers[j].DependencySetId) 1103 continue; 1104 // Only need to check pointers in the same alias set. 1105 if (RtCheck.Pointers[i].AliasSetId != RtCheck.Pointers[j].AliasSetId) 1106 continue; 1107 1108 Value *PtrI = RtCheck.Pointers[i].PointerValue; 1109 Value *PtrJ = RtCheck.Pointers[j].PointerValue; 1110 1111 unsigned ASi = PtrI->getType()->getPointerAddressSpace(); 1112 unsigned ASj = PtrJ->getType()->getPointerAddressSpace(); 1113 if (ASi != ASj) { 1114 LLVM_DEBUG( 1115 dbgs() << "LAA: Runtime check would require comparison between" 1116 " different address spaces\n"); 1117 return false; 1118 } 1119 } 1120 } 1121 1122 if (MayNeedRTCheck && CanDoRT) 1123 RtCheck.generateChecks(DepCands, IsDepCheckNeeded); 1124 1125 LLVM_DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks() 1126 << " pointer comparisons.\n"); 1127 1128 // If we can do run-time checks, but there are no checks, no runtime checks 1129 // are needed. This can happen when all pointers point to the same underlying 1130 // object for example. 1131 RtCheck.Need = CanDoRT ? RtCheck.getNumberOfChecks() != 0 : MayNeedRTCheck; 1132 1133 bool CanDoRTIfNeeded = !RtCheck.Need || CanDoRT; 1134 if (!CanDoRTIfNeeded) 1135 RtCheck.reset(); 1136 return CanDoRTIfNeeded; 1137 } 1138 1139 void AccessAnalysis::processMemAccesses() { 1140 // We process the set twice: first we process read-write pointers, last we 1141 // process read-only pointers. This allows us to skip dependence tests for 1142 // read-only pointers. 1143 1144 LLVM_DEBUG(dbgs() << "LAA: Processing memory accesses...\n"); 1145 LLVM_DEBUG(dbgs() << " AST: "; AST.dump()); 1146 LLVM_DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n"); 1147 LLVM_DEBUG({ 1148 for (auto A : Accesses) 1149 dbgs() << "\t" << *A.first.getPointer() << " (" 1150 << (A.first.getInt() 1151 ? "write" 1152 : (ReadOnlyPtr.count(A.first.getPointer()) ? "read-only" 1153 : "read")) 1154 << ")\n"; 1155 }); 1156 1157 // The AliasSetTracker has nicely partitioned our pointers by metadata 1158 // compatibility and potential for underlying-object overlap. As a result, we 1159 // only need to check for potential pointer dependencies within each alias 1160 // set. 1161 for (const auto &AS : AST) { 1162 // Note that both the alias-set tracker and the alias sets themselves used 1163 // linked lists internally and so the iteration order here is deterministic 1164 // (matching the original instruction order within each set). 1165 1166 bool SetHasWrite = false; 1167 1168 // Map of pointers to last access encountered. 1169 typedef DenseMap<const Value*, MemAccessInfo> UnderlyingObjToAccessMap; 1170 UnderlyingObjToAccessMap ObjToLastAccess; 1171 1172 // Set of access to check after all writes have been processed. 1173 PtrAccessMap DeferredAccesses; 1174 1175 // Iterate over each alias set twice, once to process read/write pointers, 1176 // and then to process read-only pointers. 1177 for (int SetIteration = 0; SetIteration < 2; ++SetIteration) { 1178 bool UseDeferred = SetIteration > 0; 1179 PtrAccessMap &S = UseDeferred ? DeferredAccesses : Accesses; 1180 1181 for (const auto &AV : AS) { 1182 Value *Ptr = AV.getValue(); 1183 1184 // For a single memory access in AliasSetTracker, Accesses may contain 1185 // both read and write, and they both need to be handled for CheckDeps. 1186 for (const auto &AC : S) { 1187 if (AC.first.getPointer() != Ptr) 1188 continue; 1189 1190 bool IsWrite = AC.first.getInt(); 1191 1192 // If we're using the deferred access set, then it contains only 1193 // reads. 1194 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite; 1195 if (UseDeferred && !IsReadOnlyPtr) 1196 continue; 1197 // Otherwise, the pointer must be in the PtrAccessSet, either as a 1198 // read or a write. 1199 assert(((IsReadOnlyPtr && UseDeferred) || IsWrite || 1200 S.count(MemAccessInfo(Ptr, false))) && 1201 "Alias-set pointer not in the access set?"); 1202 1203 MemAccessInfo Access(Ptr, IsWrite); 1204 DepCands.insert(Access); 1205 1206 // Memorize read-only pointers for later processing and skip them in 1207 // the first round (they need to be checked after we have seen all 1208 // write pointers). Note: we also mark pointer that are not 1209 // consecutive as "read-only" pointers (so that we check 1210 // "a[b[i]] +="). Hence, we need the second check for "!IsWrite". 1211 if (!UseDeferred && IsReadOnlyPtr) { 1212 // We only use the pointer keys, the types vector values don't 1213 // matter. 1214 DeferredAccesses.insert({Access, {}}); 1215 continue; 1216 } 1217 1218 // If this is a write - check other reads and writes for conflicts. If 1219 // this is a read only check other writes for conflicts (but only if 1220 // there is no other write to the ptr - this is an optimization to 1221 // catch "a[i] = a[i] + " without having to do a dependence check). 1222 if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) { 1223 CheckDeps.push_back(Access); 1224 IsRTCheckAnalysisNeeded = true; 1225 } 1226 1227 if (IsWrite) 1228 SetHasWrite = true; 1229 1230 // Create sets of pointers connected by a shared alias set and 1231 // underlying object. 1232 typedef SmallVector<const Value *, 16> ValueVector; 1233 ValueVector TempObjects; 1234 1235 getUnderlyingObjects(Ptr, TempObjects, LI); 1236 LLVM_DEBUG(dbgs() 1237 << "Underlying objects for pointer " << *Ptr << "\n"); 1238 for (const Value *UnderlyingObj : TempObjects) { 1239 // nullptr never alias, don't join sets for pointer that have "null" 1240 // in their UnderlyingObjects list. 1241 if (isa<ConstantPointerNull>(UnderlyingObj) && 1242 !NullPointerIsDefined( 1243 TheLoop->getHeader()->getParent(), 1244 UnderlyingObj->getType()->getPointerAddressSpace())) 1245 continue; 1246 1247 UnderlyingObjToAccessMap::iterator Prev = 1248 ObjToLastAccess.find(UnderlyingObj); 1249 if (Prev != ObjToLastAccess.end()) 1250 DepCands.unionSets(Access, Prev->second); 1251 1252 ObjToLastAccess[UnderlyingObj] = Access; 1253 LLVM_DEBUG(dbgs() << " " << *UnderlyingObj << "\n"); 1254 } 1255 } 1256 } 1257 } 1258 } 1259 } 1260 1261 static bool isInBoundsGep(Value *Ptr) { 1262 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) 1263 return GEP->isInBounds(); 1264 return false; 1265 } 1266 1267 /// Return true if an AddRec pointer \p Ptr is unsigned non-wrapping, 1268 /// i.e. monotonically increasing/decreasing. 1269 static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR, 1270 PredicatedScalarEvolution &PSE, const Loop *L) { 1271 // FIXME: This should probably only return true for NUW. 1272 if (AR->getNoWrapFlags(SCEV::NoWrapMask)) 1273 return true; 1274 1275 // Scalar evolution does not propagate the non-wrapping flags to values that 1276 // are derived from a non-wrapping induction variable because non-wrapping 1277 // could be flow-sensitive. 1278 // 1279 // Look through the potentially overflowing instruction to try to prove 1280 // non-wrapping for the *specific* value of Ptr. 1281 1282 // The arithmetic implied by an inbounds GEP can't overflow. 1283 auto *GEP = dyn_cast<GetElementPtrInst>(Ptr); 1284 if (!GEP || !GEP->isInBounds()) 1285 return false; 1286 1287 // Make sure there is only one non-const index and analyze that. 1288 Value *NonConstIndex = nullptr; 1289 for (Value *Index : GEP->indices()) 1290 if (!isa<ConstantInt>(Index)) { 1291 if (NonConstIndex) 1292 return false; 1293 NonConstIndex = Index; 1294 } 1295 if (!NonConstIndex) 1296 // The recurrence is on the pointer, ignore for now. 1297 return false; 1298 1299 // The index in GEP is signed. It is non-wrapping if it's derived from a NSW 1300 // AddRec using a NSW operation. 1301 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex)) 1302 if (OBO->hasNoSignedWrap() && 1303 // Assume constant for other the operand so that the AddRec can be 1304 // easily found. 1305 isa<ConstantInt>(OBO->getOperand(1))) { 1306 auto *OpScev = PSE.getSCEV(OBO->getOperand(0)); 1307 1308 if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev)) 1309 return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW); 1310 } 1311 1312 return false; 1313 } 1314 1315 /// Check whether the access through \p Ptr has a constant stride. 1316 int64_t llvm::getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, 1317 Value *Ptr, const Loop *Lp, 1318 const ValueToValueMap &StridesMap, bool Assume, 1319 bool ShouldCheckWrap) { 1320 Type *Ty = Ptr->getType(); 1321 assert(Ty->isPointerTy() && "Unexpected non-ptr"); 1322 1323 if (isa<ScalableVectorType>(AccessTy)) { 1324 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Scalable object: " << *AccessTy 1325 << "\n"); 1326 return 0; 1327 } 1328 1329 const SCEV *PtrScev = replaceSymbolicStrideSCEV(PSE, StridesMap, Ptr); 1330 1331 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 1332 if (Assume && !AR) 1333 AR = PSE.getAsAddRec(Ptr); 1334 1335 if (!AR) { 1336 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " << *Ptr 1337 << " SCEV: " << *PtrScev << "\n"); 1338 return 0; 1339 } 1340 1341 // The access function must stride over the innermost loop. 1342 if (Lp != AR->getLoop()) { 1343 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " 1344 << *Ptr << " SCEV: " << *AR << "\n"); 1345 return 0; 1346 } 1347 1348 // The address calculation must not wrap. Otherwise, a dependence could be 1349 // inverted. 1350 // An inbounds getelementptr that is a AddRec with a unit stride 1351 // cannot wrap per definition. The unit stride requirement is checked later. 1352 // An getelementptr without an inbounds attribute and unit stride would have 1353 // to access the pointer value "0" which is undefined behavior in address 1354 // space 0, therefore we can also vectorize this case. 1355 unsigned AddrSpace = Ty->getPointerAddressSpace(); 1356 bool IsInBoundsGEP = isInBoundsGep(Ptr); 1357 bool IsNoWrapAddRec = !ShouldCheckWrap || 1358 PSE.hasNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW) || 1359 isNoWrapAddRec(Ptr, AR, PSE, Lp); 1360 if (!IsNoWrapAddRec && !IsInBoundsGEP && 1361 NullPointerIsDefined(Lp->getHeader()->getParent(), AddrSpace)) { 1362 if (Assume) { 1363 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW); 1364 IsNoWrapAddRec = true; 1365 LLVM_DEBUG(dbgs() << "LAA: Pointer may wrap in the address space:\n" 1366 << "LAA: Pointer: " << *Ptr << "\n" 1367 << "LAA: SCEV: " << *AR << "\n" 1368 << "LAA: Added an overflow assumption\n"); 1369 } else { 1370 LLVM_DEBUG( 1371 dbgs() << "LAA: Bad stride - Pointer may wrap in the address space " 1372 << *Ptr << " SCEV: " << *AR << "\n"); 1373 return 0; 1374 } 1375 } 1376 1377 // Check the step is constant. 1378 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE()); 1379 1380 // Calculate the pointer stride and check if it is constant. 1381 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 1382 if (!C) { 1383 LLVM_DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr 1384 << " SCEV: " << *AR << "\n"); 1385 return 0; 1386 } 1387 1388 auto &DL = Lp->getHeader()->getModule()->getDataLayout(); 1389 TypeSize AllocSize = DL.getTypeAllocSize(AccessTy); 1390 int64_t Size = AllocSize.getFixedSize(); 1391 const APInt &APStepVal = C->getAPInt(); 1392 1393 // Huge step value - give up. 1394 if (APStepVal.getBitWidth() > 64) 1395 return 0; 1396 1397 int64_t StepVal = APStepVal.getSExtValue(); 1398 1399 // Strided access. 1400 int64_t Stride = StepVal / Size; 1401 int64_t Rem = StepVal % Size; 1402 if (Rem) 1403 return 0; 1404 1405 // If the SCEV could wrap but we have an inbounds gep with a unit stride we 1406 // know we can't "wrap around the address space". In case of address space 1407 // zero we know that this won't happen without triggering undefined behavior. 1408 if (!IsNoWrapAddRec && Stride != 1 && Stride != -1 && 1409 (IsInBoundsGEP || !NullPointerIsDefined(Lp->getHeader()->getParent(), 1410 AddrSpace))) { 1411 if (Assume) { 1412 // We can avoid this case by adding a run-time check. 1413 LLVM_DEBUG(dbgs() << "LAA: Non unit strided pointer which is not either " 1414 << "inbounds or in address space 0 may wrap:\n" 1415 << "LAA: Pointer: " << *Ptr << "\n" 1416 << "LAA: SCEV: " << *AR << "\n" 1417 << "LAA: Added an overflow assumption\n"); 1418 PSE.setNoOverflow(Ptr, SCEVWrapPredicate::IncrementNUSW); 1419 } else 1420 return 0; 1421 } 1422 1423 return Stride; 1424 } 1425 1426 Optional<int> llvm::getPointersDiff(Type *ElemTyA, Value *PtrA, Type *ElemTyB, 1427 Value *PtrB, const DataLayout &DL, 1428 ScalarEvolution &SE, bool StrictCheck, 1429 bool CheckType) { 1430 assert(PtrA && PtrB && "Expected non-nullptr pointers."); 1431 assert(cast<PointerType>(PtrA->getType()) 1432 ->isOpaqueOrPointeeTypeMatches(ElemTyA) && "Wrong PtrA type"); 1433 assert(cast<PointerType>(PtrB->getType()) 1434 ->isOpaqueOrPointeeTypeMatches(ElemTyB) && "Wrong PtrB type"); 1435 1436 // Make sure that A and B are different pointers. 1437 if (PtrA == PtrB) 1438 return 0; 1439 1440 // Make sure that the element types are the same if required. 1441 if (CheckType && ElemTyA != ElemTyB) 1442 return None; 1443 1444 unsigned ASA = PtrA->getType()->getPointerAddressSpace(); 1445 unsigned ASB = PtrB->getType()->getPointerAddressSpace(); 1446 1447 // Check that the address spaces match. 1448 if (ASA != ASB) 1449 return None; 1450 unsigned IdxWidth = DL.getIndexSizeInBits(ASA); 1451 1452 APInt OffsetA(IdxWidth, 0), OffsetB(IdxWidth, 0); 1453 Value *PtrA1 = PtrA->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetA); 1454 Value *PtrB1 = PtrB->stripAndAccumulateInBoundsConstantOffsets(DL, OffsetB); 1455 1456 int Val; 1457 if (PtrA1 == PtrB1) { 1458 // Retrieve the address space again as pointer stripping now tracks through 1459 // `addrspacecast`. 1460 ASA = cast<PointerType>(PtrA1->getType())->getAddressSpace(); 1461 ASB = cast<PointerType>(PtrB1->getType())->getAddressSpace(); 1462 // Check that the address spaces match and that the pointers are valid. 1463 if (ASA != ASB) 1464 return None; 1465 1466 IdxWidth = DL.getIndexSizeInBits(ASA); 1467 OffsetA = OffsetA.sextOrTrunc(IdxWidth); 1468 OffsetB = OffsetB.sextOrTrunc(IdxWidth); 1469 1470 OffsetB -= OffsetA; 1471 Val = OffsetB.getSExtValue(); 1472 } else { 1473 // Otherwise compute the distance with SCEV between the base pointers. 1474 const SCEV *PtrSCEVA = SE.getSCEV(PtrA); 1475 const SCEV *PtrSCEVB = SE.getSCEV(PtrB); 1476 const auto *Diff = 1477 dyn_cast<SCEVConstant>(SE.getMinusSCEV(PtrSCEVB, PtrSCEVA)); 1478 if (!Diff) 1479 return None; 1480 Val = Diff->getAPInt().getSExtValue(); 1481 } 1482 int Size = DL.getTypeStoreSize(ElemTyA); 1483 int Dist = Val / Size; 1484 1485 // Ensure that the calculated distance matches the type-based one after all 1486 // the bitcasts removal in the provided pointers. 1487 if (!StrictCheck || Dist * Size == Val) 1488 return Dist; 1489 return None; 1490 } 1491 1492 bool llvm::sortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy, 1493 const DataLayout &DL, ScalarEvolution &SE, 1494 SmallVectorImpl<unsigned> &SortedIndices) { 1495 assert(llvm::all_of( 1496 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && 1497 "Expected list of pointer operands."); 1498 // Walk over the pointers, and map each of them to an offset relative to 1499 // first pointer in the array. 1500 Value *Ptr0 = VL[0]; 1501 1502 using DistOrdPair = std::pair<int64_t, int>; 1503 auto Compare = [](const DistOrdPair &L, const DistOrdPair &R) { 1504 return L.first < R.first; 1505 }; 1506 std::set<DistOrdPair, decltype(Compare)> Offsets(Compare); 1507 Offsets.emplace(0, 0); 1508 int Cnt = 1; 1509 bool IsConsecutive = true; 1510 for (auto *Ptr : VL.drop_front()) { 1511 Optional<int> Diff = getPointersDiff(ElemTy, Ptr0, ElemTy, Ptr, DL, SE, 1512 /*StrictCheck=*/true); 1513 if (!Diff) 1514 return false; 1515 1516 // Check if the pointer with the same offset is found. 1517 int64_t Offset = *Diff; 1518 auto Res = Offsets.emplace(Offset, Cnt); 1519 if (!Res.second) 1520 return false; 1521 // Consecutive order if the inserted element is the last one. 1522 IsConsecutive = IsConsecutive && std::next(Res.first) == Offsets.end(); 1523 ++Cnt; 1524 } 1525 SortedIndices.clear(); 1526 if (!IsConsecutive) { 1527 // Fill SortedIndices array only if it is non-consecutive. 1528 SortedIndices.resize(VL.size()); 1529 Cnt = 0; 1530 for (const std::pair<int64_t, int> &Pair : Offsets) { 1531 SortedIndices[Cnt] = Pair.second; 1532 ++Cnt; 1533 } 1534 } 1535 return true; 1536 } 1537 1538 /// Returns true if the memory operations \p A and \p B are consecutive. 1539 bool llvm::isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, 1540 ScalarEvolution &SE, bool CheckType) { 1541 Value *PtrA = getLoadStorePointerOperand(A); 1542 Value *PtrB = getLoadStorePointerOperand(B); 1543 if (!PtrA || !PtrB) 1544 return false; 1545 Type *ElemTyA = getLoadStoreType(A); 1546 Type *ElemTyB = getLoadStoreType(B); 1547 Optional<int> Diff = getPointersDiff(ElemTyA, PtrA, ElemTyB, PtrB, DL, SE, 1548 /*StrictCheck=*/true, CheckType); 1549 return Diff && *Diff == 1; 1550 } 1551 1552 void MemoryDepChecker::addAccess(StoreInst *SI) { 1553 visitPointers(SI->getPointerOperand(), *InnermostLoop, 1554 [this, SI](Value *Ptr) { 1555 Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx); 1556 InstMap.push_back(SI); 1557 ++AccessIdx; 1558 }); 1559 } 1560 1561 void MemoryDepChecker::addAccess(LoadInst *LI) { 1562 visitPointers(LI->getPointerOperand(), *InnermostLoop, 1563 [this, LI](Value *Ptr) { 1564 Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx); 1565 InstMap.push_back(LI); 1566 ++AccessIdx; 1567 }); 1568 } 1569 1570 MemoryDepChecker::VectorizationSafetyStatus 1571 MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) { 1572 switch (Type) { 1573 case NoDep: 1574 case Forward: 1575 case BackwardVectorizable: 1576 return VectorizationSafetyStatus::Safe; 1577 1578 case Unknown: 1579 return VectorizationSafetyStatus::PossiblySafeWithRtChecks; 1580 case ForwardButPreventsForwarding: 1581 case Backward: 1582 case BackwardVectorizableButPreventsForwarding: 1583 return VectorizationSafetyStatus::Unsafe; 1584 } 1585 llvm_unreachable("unexpected DepType!"); 1586 } 1587 1588 bool MemoryDepChecker::Dependence::isBackward() const { 1589 switch (Type) { 1590 case NoDep: 1591 case Forward: 1592 case ForwardButPreventsForwarding: 1593 case Unknown: 1594 return false; 1595 1596 case BackwardVectorizable: 1597 case Backward: 1598 case BackwardVectorizableButPreventsForwarding: 1599 return true; 1600 } 1601 llvm_unreachable("unexpected DepType!"); 1602 } 1603 1604 bool MemoryDepChecker::Dependence::isPossiblyBackward() const { 1605 return isBackward() || Type == Unknown; 1606 } 1607 1608 bool MemoryDepChecker::Dependence::isForward() const { 1609 switch (Type) { 1610 case Forward: 1611 case ForwardButPreventsForwarding: 1612 return true; 1613 1614 case NoDep: 1615 case Unknown: 1616 case BackwardVectorizable: 1617 case Backward: 1618 case BackwardVectorizableButPreventsForwarding: 1619 return false; 1620 } 1621 llvm_unreachable("unexpected DepType!"); 1622 } 1623 1624 bool MemoryDepChecker::couldPreventStoreLoadForward(uint64_t Distance, 1625 uint64_t TypeByteSize) { 1626 // If loads occur at a distance that is not a multiple of a feasible vector 1627 // factor store-load forwarding does not take place. 1628 // Positive dependences might cause troubles because vectorizing them might 1629 // prevent store-load forwarding making vectorized code run a lot slower. 1630 // a[i] = a[i-3] ^ a[i-8]; 1631 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and 1632 // hence on your typical architecture store-load forwarding does not take 1633 // place. Vectorizing in such cases does not make sense. 1634 // Store-load forwarding distance. 1635 1636 // After this many iterations store-to-load forwarding conflicts should not 1637 // cause any slowdowns. 1638 const uint64_t NumItersForStoreLoadThroughMemory = 8 * TypeByteSize; 1639 // Maximum vector factor. 1640 uint64_t MaxVFWithoutSLForwardIssues = std::min( 1641 VectorizerParams::MaxVectorWidth * TypeByteSize, MaxSafeDepDistBytes); 1642 1643 // Compute the smallest VF at which the store and load would be misaligned. 1644 for (uint64_t VF = 2 * TypeByteSize; VF <= MaxVFWithoutSLForwardIssues; 1645 VF *= 2) { 1646 // If the number of vector iteration between the store and the load are 1647 // small we could incur conflicts. 1648 if (Distance % VF && Distance / VF < NumItersForStoreLoadThroughMemory) { 1649 MaxVFWithoutSLForwardIssues = (VF >> 1); 1650 break; 1651 } 1652 } 1653 1654 if (MaxVFWithoutSLForwardIssues < 2 * TypeByteSize) { 1655 LLVM_DEBUG( 1656 dbgs() << "LAA: Distance " << Distance 1657 << " that could cause a store-load forwarding conflict\n"); 1658 return true; 1659 } 1660 1661 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes && 1662 MaxVFWithoutSLForwardIssues != 1663 VectorizerParams::MaxVectorWidth * TypeByteSize) 1664 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues; 1665 return false; 1666 } 1667 1668 void MemoryDepChecker::mergeInStatus(VectorizationSafetyStatus S) { 1669 if (Status < S) 1670 Status = S; 1671 } 1672 1673 /// Given a non-constant (unknown) dependence-distance \p Dist between two 1674 /// memory accesses, that have the same stride whose absolute value is given 1675 /// in \p Stride, and that have the same type size \p TypeByteSize, 1676 /// in a loop whose takenCount is \p BackedgeTakenCount, check if it is 1677 /// possible to prove statically that the dependence distance is larger 1678 /// than the range that the accesses will travel through the execution of 1679 /// the loop. If so, return true; false otherwise. This is useful for 1680 /// example in loops such as the following (PR31098): 1681 /// for (i = 0; i < D; ++i) { 1682 /// = out[i]; 1683 /// out[i+D] = 1684 /// } 1685 static bool isSafeDependenceDistance(const DataLayout &DL, ScalarEvolution &SE, 1686 const SCEV &BackedgeTakenCount, 1687 const SCEV &Dist, uint64_t Stride, 1688 uint64_t TypeByteSize) { 1689 1690 // If we can prove that 1691 // (**) |Dist| > BackedgeTakenCount * Step 1692 // where Step is the absolute stride of the memory accesses in bytes, 1693 // then there is no dependence. 1694 // 1695 // Rationale: 1696 // We basically want to check if the absolute distance (|Dist/Step|) 1697 // is >= the loop iteration count (or > BackedgeTakenCount). 1698 // This is equivalent to the Strong SIV Test (Practical Dependence Testing, 1699 // Section 4.2.1); Note, that for vectorization it is sufficient to prove 1700 // that the dependence distance is >= VF; This is checked elsewhere. 1701 // But in some cases we can prune unknown dependence distances early, and 1702 // even before selecting the VF, and without a runtime test, by comparing 1703 // the distance against the loop iteration count. Since the vectorized code 1704 // will be executed only if LoopCount >= VF, proving distance >= LoopCount 1705 // also guarantees that distance >= VF. 1706 // 1707 const uint64_t ByteStride = Stride * TypeByteSize; 1708 const SCEV *Step = SE.getConstant(BackedgeTakenCount.getType(), ByteStride); 1709 const SCEV *Product = SE.getMulExpr(&BackedgeTakenCount, Step); 1710 1711 const SCEV *CastedDist = &Dist; 1712 const SCEV *CastedProduct = Product; 1713 uint64_t DistTypeSizeBits = DL.getTypeSizeInBits(Dist.getType()); 1714 uint64_t ProductTypeSizeBits = DL.getTypeSizeInBits(Product->getType()); 1715 1716 // The dependence distance can be positive/negative, so we sign extend Dist; 1717 // The multiplication of the absolute stride in bytes and the 1718 // backedgeTakenCount is non-negative, so we zero extend Product. 1719 if (DistTypeSizeBits > ProductTypeSizeBits) 1720 CastedProduct = SE.getZeroExtendExpr(Product, Dist.getType()); 1721 else 1722 CastedDist = SE.getNoopOrSignExtend(&Dist, Product->getType()); 1723 1724 // Is Dist - (BackedgeTakenCount * Step) > 0 ? 1725 // (If so, then we have proven (**) because |Dist| >= Dist) 1726 const SCEV *Minus = SE.getMinusSCEV(CastedDist, CastedProduct); 1727 if (SE.isKnownPositive(Minus)) 1728 return true; 1729 1730 // Second try: Is -Dist - (BackedgeTakenCount * Step) > 0 ? 1731 // (If so, then we have proven (**) because |Dist| >= -1*Dist) 1732 const SCEV *NegDist = SE.getNegativeSCEV(CastedDist); 1733 Minus = SE.getMinusSCEV(NegDist, CastedProduct); 1734 if (SE.isKnownPositive(Minus)) 1735 return true; 1736 1737 return false; 1738 } 1739 1740 /// Check the dependence for two accesses with the same stride \p Stride. 1741 /// \p Distance is the positive distance and \p TypeByteSize is type size in 1742 /// bytes. 1743 /// 1744 /// \returns true if they are independent. 1745 static bool areStridedAccessesIndependent(uint64_t Distance, uint64_t Stride, 1746 uint64_t TypeByteSize) { 1747 assert(Stride > 1 && "The stride must be greater than 1"); 1748 assert(TypeByteSize > 0 && "The type size in byte must be non-zero"); 1749 assert(Distance > 0 && "The distance must be non-zero"); 1750 1751 // Skip if the distance is not multiple of type byte size. 1752 if (Distance % TypeByteSize) 1753 return false; 1754 1755 uint64_t ScaledDist = Distance / TypeByteSize; 1756 1757 // No dependence if the scaled distance is not multiple of the stride. 1758 // E.g. 1759 // for (i = 0; i < 1024 ; i += 4) 1760 // A[i+2] = A[i] + 1; 1761 // 1762 // Two accesses in memory (scaled distance is 2, stride is 4): 1763 // | A[0] | | | | A[4] | | | | 1764 // | | | A[2] | | | | A[6] | | 1765 // 1766 // E.g. 1767 // for (i = 0; i < 1024 ; i += 3) 1768 // A[i+4] = A[i] + 1; 1769 // 1770 // Two accesses in memory (scaled distance is 4, stride is 3): 1771 // | A[0] | | | A[3] | | | A[6] | | | 1772 // | | | | | A[4] | | | A[7] | | 1773 return ScaledDist % Stride; 1774 } 1775 1776 MemoryDepChecker::Dependence::DepType 1777 MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx, 1778 const MemAccessInfo &B, unsigned BIdx, 1779 const ValueToValueMap &Strides) { 1780 assert (AIdx < BIdx && "Must pass arguments in program order"); 1781 1782 Value *APtr = A.getPointer(); 1783 Value *BPtr = B.getPointer(); 1784 bool AIsWrite = A.getInt(); 1785 bool BIsWrite = B.getInt(); 1786 Type *ATy = getLoadStoreType(InstMap[AIdx]); 1787 Type *BTy = getLoadStoreType(InstMap[BIdx]); 1788 1789 // Two reads are independent. 1790 if (!AIsWrite && !BIsWrite) 1791 return Dependence::NoDep; 1792 1793 // We cannot check pointers in different address spaces. 1794 if (APtr->getType()->getPointerAddressSpace() != 1795 BPtr->getType()->getPointerAddressSpace()) 1796 return Dependence::Unknown; 1797 1798 int64_t StrideAPtr = 1799 getPtrStride(PSE, ATy, APtr, InnermostLoop, Strides, true); 1800 int64_t StrideBPtr = 1801 getPtrStride(PSE, BTy, BPtr, InnermostLoop, Strides, true); 1802 1803 const SCEV *Src = PSE.getSCEV(APtr); 1804 const SCEV *Sink = PSE.getSCEV(BPtr); 1805 1806 // If the induction step is negative we have to invert source and sink of the 1807 // dependence. 1808 if (StrideAPtr < 0) { 1809 std::swap(APtr, BPtr); 1810 std::swap(ATy, BTy); 1811 std::swap(Src, Sink); 1812 std::swap(AIsWrite, BIsWrite); 1813 std::swap(AIdx, BIdx); 1814 std::swap(StrideAPtr, StrideBPtr); 1815 } 1816 1817 const SCEV *Dist = PSE.getSE()->getMinusSCEV(Sink, Src); 1818 1819 LLVM_DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink 1820 << "(Induction step: " << StrideAPtr << ")\n"); 1821 LLVM_DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to " 1822 << *InstMap[BIdx] << ": " << *Dist << "\n"); 1823 1824 // Need accesses with constant stride. We don't want to vectorize 1825 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in 1826 // the address space. 1827 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){ 1828 LLVM_DEBUG(dbgs() << "Pointer access with non-constant stride\n"); 1829 return Dependence::Unknown; 1830 } 1831 1832 auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout(); 1833 uint64_t TypeByteSize = DL.getTypeAllocSize(ATy); 1834 bool HasSameSize = 1835 DL.getTypeStoreSizeInBits(ATy) == DL.getTypeStoreSizeInBits(BTy); 1836 uint64_t Stride = std::abs(StrideAPtr); 1837 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist); 1838 if (!C) { 1839 if (!isa<SCEVCouldNotCompute>(Dist) && HasSameSize && 1840 isSafeDependenceDistance(DL, *(PSE.getSE()), 1841 *(PSE.getBackedgeTakenCount()), *Dist, Stride, 1842 TypeByteSize)) 1843 return Dependence::NoDep; 1844 1845 LLVM_DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n"); 1846 FoundNonConstantDistanceDependence = true; 1847 return Dependence::Unknown; 1848 } 1849 1850 const APInt &Val = C->getAPInt(); 1851 int64_t Distance = Val.getSExtValue(); 1852 1853 // Attempt to prove strided accesses independent. 1854 if (std::abs(Distance) > 0 && Stride > 1 && HasSameSize && 1855 areStridedAccessesIndependent(std::abs(Distance), Stride, TypeByteSize)) { 1856 LLVM_DEBUG(dbgs() << "LAA: Strided accesses are independent\n"); 1857 return Dependence::NoDep; 1858 } 1859 1860 // Negative distances are not plausible dependencies. 1861 if (Val.isNegative()) { 1862 bool IsTrueDataDependence = (AIsWrite && !BIsWrite); 1863 if (IsTrueDataDependence && EnableForwardingConflictDetection && 1864 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) || 1865 !HasSameSize)) { 1866 LLVM_DEBUG(dbgs() << "LAA: Forward but may prevent st->ld forwarding\n"); 1867 return Dependence::ForwardButPreventsForwarding; 1868 } 1869 1870 LLVM_DEBUG(dbgs() << "LAA: Dependence is negative\n"); 1871 return Dependence::Forward; 1872 } 1873 1874 // Write to the same location with the same size. 1875 if (Val == 0) { 1876 if (HasSameSize) 1877 return Dependence::Forward; 1878 LLVM_DEBUG( 1879 dbgs() << "LAA: Zero dependence difference but different type sizes\n"); 1880 return Dependence::Unknown; 1881 } 1882 1883 assert(Val.isStrictlyPositive() && "Expect a positive value"); 1884 1885 if (!HasSameSize) { 1886 LLVM_DEBUG(dbgs() << "LAA: ReadWrite-Write positive dependency with " 1887 "different type sizes\n"); 1888 return Dependence::Unknown; 1889 } 1890 1891 // Bail out early if passed-in parameters make vectorization not feasible. 1892 unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ? 1893 VectorizerParams::VectorizationFactor : 1); 1894 unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ? 1895 VectorizerParams::VectorizationInterleave : 1); 1896 // The minimum number of iterations for a vectorized/unrolled version. 1897 unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U); 1898 1899 // It's not vectorizable if the distance is smaller than the minimum distance 1900 // needed for a vectroized/unrolled version. Vectorizing one iteration in 1901 // front needs TypeByteSize * Stride. Vectorizing the last iteration needs 1902 // TypeByteSize (No need to plus the last gap distance). 1903 // 1904 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes. 1905 // foo(int *A) { 1906 // int *B = (int *)((char *)A + 14); 1907 // for (i = 0 ; i < 1024 ; i += 2) 1908 // B[i] = A[i] + 1; 1909 // } 1910 // 1911 // Two accesses in memory (stride is 2): 1912 // | A[0] | | A[2] | | A[4] | | A[6] | | 1913 // | B[0] | | B[2] | | B[4] | 1914 // 1915 // Distance needs for vectorizing iterations except the last iteration: 1916 // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4. 1917 // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4. 1918 // 1919 // If MinNumIter is 2, it is vectorizable as the minimum distance needed is 1920 // 12, which is less than distance. 1921 // 1922 // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4), 1923 // the minimum distance needed is 28, which is greater than distance. It is 1924 // not safe to do vectorization. 1925 uint64_t MinDistanceNeeded = 1926 TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize; 1927 if (MinDistanceNeeded > static_cast<uint64_t>(Distance)) { 1928 LLVM_DEBUG(dbgs() << "LAA: Failure because of positive distance " 1929 << Distance << '\n'); 1930 return Dependence::Backward; 1931 } 1932 1933 // Unsafe if the minimum distance needed is greater than max safe distance. 1934 if (MinDistanceNeeded > MaxSafeDepDistBytes) { 1935 LLVM_DEBUG(dbgs() << "LAA: Failure because it needs at least " 1936 << MinDistanceNeeded << " size in bytes"); 1937 return Dependence::Backward; 1938 } 1939 1940 // Positive distance bigger than max vectorization factor. 1941 // FIXME: Should use max factor instead of max distance in bytes, which could 1942 // not handle different types. 1943 // E.g. Assume one char is 1 byte in memory and one int is 4 bytes. 1944 // void foo (int *A, char *B) { 1945 // for (unsigned i = 0; i < 1024; i++) { 1946 // A[i+2] = A[i] + 1; 1947 // B[i+2] = B[i] + 1; 1948 // } 1949 // } 1950 // 1951 // This case is currently unsafe according to the max safe distance. If we 1952 // analyze the two accesses on array B, the max safe dependence distance 1953 // is 2. Then we analyze the accesses on array A, the minimum distance needed 1954 // is 8, which is less than 2 and forbidden vectorization, But actually 1955 // both A and B could be vectorized by 2 iterations. 1956 MaxSafeDepDistBytes = 1957 std::min(static_cast<uint64_t>(Distance), MaxSafeDepDistBytes); 1958 1959 bool IsTrueDataDependence = (!AIsWrite && BIsWrite); 1960 if (IsTrueDataDependence && EnableForwardingConflictDetection && 1961 couldPreventStoreLoadForward(Distance, TypeByteSize)) 1962 return Dependence::BackwardVectorizableButPreventsForwarding; 1963 1964 uint64_t MaxVF = MaxSafeDepDistBytes / (TypeByteSize * Stride); 1965 LLVM_DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() 1966 << " with max VF = " << MaxVF << '\n'); 1967 uint64_t MaxVFInBits = MaxVF * TypeByteSize * 8; 1968 MaxSafeVectorWidthInBits = std::min(MaxSafeVectorWidthInBits, MaxVFInBits); 1969 return Dependence::BackwardVectorizable; 1970 } 1971 1972 bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets, 1973 MemAccessInfoList &CheckDeps, 1974 const ValueToValueMap &Strides) { 1975 1976 MaxSafeDepDistBytes = -1; 1977 SmallPtrSet<MemAccessInfo, 8> Visited; 1978 for (MemAccessInfo CurAccess : CheckDeps) { 1979 if (Visited.count(CurAccess)) 1980 continue; 1981 1982 // Get the relevant memory access set. 1983 EquivalenceClasses<MemAccessInfo>::iterator I = 1984 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess)); 1985 1986 // Check accesses within this set. 1987 EquivalenceClasses<MemAccessInfo>::member_iterator AI = 1988 AccessSets.member_begin(I); 1989 EquivalenceClasses<MemAccessInfo>::member_iterator AE = 1990 AccessSets.member_end(); 1991 1992 // Check every access pair. 1993 while (AI != AE) { 1994 Visited.insert(*AI); 1995 bool AIIsWrite = AI->getInt(); 1996 // Check loads only against next equivalent class, but stores also against 1997 // other stores in the same equivalence class - to the same address. 1998 EquivalenceClasses<MemAccessInfo>::member_iterator OI = 1999 (AIIsWrite ? AI : std::next(AI)); 2000 while (OI != AE) { 2001 // Check every accessing instruction pair in program order. 2002 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(), 2003 I1E = Accesses[*AI].end(); I1 != I1E; ++I1) 2004 // Scan all accesses of another equivalence class, but only the next 2005 // accesses of the same equivalent class. 2006 for (std::vector<unsigned>::iterator 2007 I2 = (OI == AI ? std::next(I1) : Accesses[*OI].begin()), 2008 I2E = (OI == AI ? I1E : Accesses[*OI].end()); 2009 I2 != I2E; ++I2) { 2010 auto A = std::make_pair(&*AI, *I1); 2011 auto B = std::make_pair(&*OI, *I2); 2012 2013 assert(*I1 != *I2); 2014 if (*I1 > *I2) 2015 std::swap(A, B); 2016 2017 Dependence::DepType Type = 2018 isDependent(*A.first, A.second, *B.first, B.second, Strides); 2019 mergeInStatus(Dependence::isSafeForVectorization(Type)); 2020 2021 // Gather dependences unless we accumulated MaxDependences 2022 // dependences. In that case return as soon as we find the first 2023 // unsafe dependence. This puts a limit on this quadratic 2024 // algorithm. 2025 if (RecordDependences) { 2026 if (Type != Dependence::NoDep) 2027 Dependences.push_back(Dependence(A.second, B.second, Type)); 2028 2029 if (Dependences.size() >= MaxDependences) { 2030 RecordDependences = false; 2031 Dependences.clear(); 2032 LLVM_DEBUG(dbgs() 2033 << "Too many dependences, stopped recording\n"); 2034 } 2035 } 2036 if (!RecordDependences && !isSafeForVectorization()) 2037 return false; 2038 } 2039 ++OI; 2040 } 2041 AI++; 2042 } 2043 } 2044 2045 LLVM_DEBUG(dbgs() << "Total Dependences: " << Dependences.size() << "\n"); 2046 return isSafeForVectorization(); 2047 } 2048 2049 SmallVector<Instruction *, 4> 2050 MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const { 2051 MemAccessInfo Access(Ptr, isWrite); 2052 auto &IndexVector = Accesses.find(Access)->second; 2053 2054 SmallVector<Instruction *, 4> Insts; 2055 transform(IndexVector, 2056 std::back_inserter(Insts), 2057 [&](unsigned Idx) { return this->InstMap[Idx]; }); 2058 return Insts; 2059 } 2060 2061 const char *MemoryDepChecker::Dependence::DepName[] = { 2062 "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward", 2063 "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"}; 2064 2065 void MemoryDepChecker::Dependence::print( 2066 raw_ostream &OS, unsigned Depth, 2067 const SmallVectorImpl<Instruction *> &Instrs) const { 2068 OS.indent(Depth) << DepName[Type] << ":\n"; 2069 OS.indent(Depth + 2) << *Instrs[Source] << " -> \n"; 2070 OS.indent(Depth + 2) << *Instrs[Destination] << "\n"; 2071 } 2072 2073 bool LoopAccessInfo::canAnalyzeLoop() { 2074 // We need to have a loop header. 2075 LLVM_DEBUG(dbgs() << "LAA: Found a loop in " 2076 << TheLoop->getHeader()->getParent()->getName() << ": " 2077 << TheLoop->getHeader()->getName() << '\n'); 2078 2079 // We can only analyze innermost loops. 2080 if (!TheLoop->isInnermost()) { 2081 LLVM_DEBUG(dbgs() << "LAA: loop is not the innermost loop\n"); 2082 recordAnalysis("NotInnerMostLoop") << "loop is not the innermost loop"; 2083 return false; 2084 } 2085 2086 // We must have a single backedge. 2087 if (TheLoop->getNumBackEdges() != 1) { 2088 LLVM_DEBUG( 2089 dbgs() << "LAA: loop control flow is not understood by analyzer\n"); 2090 recordAnalysis("CFGNotUnderstood") 2091 << "loop control flow is not understood by analyzer"; 2092 return false; 2093 } 2094 2095 // ScalarEvolution needs to be able to find the exit count. 2096 const SCEV *ExitCount = PSE->getBackedgeTakenCount(); 2097 if (isa<SCEVCouldNotCompute>(ExitCount)) { 2098 recordAnalysis("CantComputeNumberOfIterations") 2099 << "could not determine number of loop iterations"; 2100 LLVM_DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n"); 2101 return false; 2102 } 2103 2104 return true; 2105 } 2106 2107 void LoopAccessInfo::analyzeLoop(AAResults *AA, LoopInfo *LI, 2108 const TargetLibraryInfo *TLI, 2109 DominatorTree *DT) { 2110 // Holds the Load and Store instructions. 2111 SmallVector<LoadInst *, 16> Loads; 2112 SmallVector<StoreInst *, 16> Stores; 2113 2114 // Holds all the different accesses in the loop. 2115 unsigned NumReads = 0; 2116 unsigned NumReadWrites = 0; 2117 2118 bool HasComplexMemInst = false; 2119 2120 // A runtime check is only legal to insert if there are no convergent calls. 2121 HasConvergentOp = false; 2122 2123 PtrRtChecking->Pointers.clear(); 2124 PtrRtChecking->Need = false; 2125 2126 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 2127 2128 const bool EnableMemAccessVersioningOfLoop = 2129 EnableMemAccessVersioning && 2130 !TheLoop->getHeader()->getParent()->hasOptSize(); 2131 2132 // For each block. 2133 for (BasicBlock *BB : TheLoop->blocks()) { 2134 // Scan the BB and collect legal loads and stores. Also detect any 2135 // convergent instructions. 2136 for (Instruction &I : *BB) { 2137 if (auto *Call = dyn_cast<CallBase>(&I)) { 2138 if (Call->isConvergent()) 2139 HasConvergentOp = true; 2140 } 2141 2142 // With both a non-vectorizable memory instruction and a convergent 2143 // operation, found in this loop, no reason to continue the search. 2144 if (HasComplexMemInst && HasConvergentOp) { 2145 CanVecMem = false; 2146 return; 2147 } 2148 2149 // Avoid hitting recordAnalysis multiple times. 2150 if (HasComplexMemInst) 2151 continue; 2152 2153 // If this is a load, save it. If this instruction can read from memory 2154 // but is not a load, then we quit. Notice that we don't handle function 2155 // calls that read or write. 2156 if (I.mayReadFromMemory()) { 2157 // Many math library functions read the rounding mode. We will only 2158 // vectorize a loop if it contains known function calls that don't set 2159 // the flag. Therefore, it is safe to ignore this read from memory. 2160 auto *Call = dyn_cast<CallInst>(&I); 2161 if (Call && getVectorIntrinsicIDForCall(Call, TLI)) 2162 continue; 2163 2164 // If the function has an explicit vectorized counterpart, we can safely 2165 // assume that it can be vectorized. 2166 if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() && 2167 !VFDatabase::getMappings(*Call).empty()) 2168 continue; 2169 2170 auto *Ld = dyn_cast<LoadInst>(&I); 2171 if (!Ld) { 2172 recordAnalysis("CantVectorizeInstruction", Ld) 2173 << "instruction cannot be vectorized"; 2174 HasComplexMemInst = true; 2175 continue; 2176 } 2177 if (!Ld->isSimple() && !IsAnnotatedParallel) { 2178 recordAnalysis("NonSimpleLoad", Ld) 2179 << "read with atomic ordering or volatile read"; 2180 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple load.\n"); 2181 HasComplexMemInst = true; 2182 continue; 2183 } 2184 NumLoads++; 2185 Loads.push_back(Ld); 2186 DepChecker->addAccess(Ld); 2187 if (EnableMemAccessVersioningOfLoop) 2188 collectStridedAccess(Ld); 2189 continue; 2190 } 2191 2192 // Save 'store' instructions. Abort if other instructions write to memory. 2193 if (I.mayWriteToMemory()) { 2194 auto *St = dyn_cast<StoreInst>(&I); 2195 if (!St) { 2196 recordAnalysis("CantVectorizeInstruction", St) 2197 << "instruction cannot be vectorized"; 2198 HasComplexMemInst = true; 2199 continue; 2200 } 2201 if (!St->isSimple() && !IsAnnotatedParallel) { 2202 recordAnalysis("NonSimpleStore", St) 2203 << "write with atomic ordering or volatile write"; 2204 LLVM_DEBUG(dbgs() << "LAA: Found a non-simple store.\n"); 2205 HasComplexMemInst = true; 2206 continue; 2207 } 2208 NumStores++; 2209 Stores.push_back(St); 2210 DepChecker->addAccess(St); 2211 if (EnableMemAccessVersioningOfLoop) 2212 collectStridedAccess(St); 2213 } 2214 } // Next instr. 2215 } // Next block. 2216 2217 if (HasComplexMemInst) { 2218 CanVecMem = false; 2219 return; 2220 } 2221 2222 // Now we have two lists that hold the loads and the stores. 2223 // Next, we find the pointers that they use. 2224 2225 // Check if we see any stores. If there are no stores, then we don't 2226 // care if the pointers are *restrict*. 2227 if (!Stores.size()) { 2228 LLVM_DEBUG(dbgs() << "LAA: Found a read-only loop!\n"); 2229 CanVecMem = true; 2230 return; 2231 } 2232 2233 MemoryDepChecker::DepCandidates DependentAccesses; 2234 AccessAnalysis Accesses(TheLoop, AA, LI, DependentAccesses, *PSE); 2235 2236 // Holds the analyzed pointers. We don't want to call getUnderlyingObjects 2237 // multiple times on the same object. If the ptr is accessed twice, once 2238 // for read and once for write, it will only appear once (on the write 2239 // list). This is okay, since we are going to check for conflicts between 2240 // writes and between reads and writes, but not between reads and reads. 2241 SmallSet<std::pair<Value *, Type *>, 16> Seen; 2242 2243 // Record uniform store addresses to identify if we have multiple stores 2244 // to the same address. 2245 SmallPtrSet<Value *, 16> UniformStores; 2246 2247 for (StoreInst *ST : Stores) { 2248 Value *Ptr = ST->getPointerOperand(); 2249 2250 if (isUniform(Ptr)) { 2251 // Record store instructions to loop invariant addresses 2252 StoresToInvariantAddresses.push_back(ST); 2253 HasDependenceInvolvingLoopInvariantAddress |= 2254 !UniformStores.insert(Ptr).second; 2255 } 2256 2257 // If we did *not* see this pointer before, insert it to the read-write 2258 // list. At this phase it is only a 'write' list. 2259 Type *AccessTy = getLoadStoreType(ST); 2260 if (Seen.insert({Ptr, AccessTy}).second) { 2261 ++NumReadWrites; 2262 2263 MemoryLocation Loc = MemoryLocation::get(ST); 2264 // The TBAA metadata could have a control dependency on the predication 2265 // condition, so we cannot rely on it when determining whether or not we 2266 // need runtime pointer checks. 2267 if (blockNeedsPredication(ST->getParent(), TheLoop, DT)) 2268 Loc.AATags.TBAA = nullptr; 2269 2270 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop, 2271 [&Accesses, AccessTy, Loc](Value *Ptr) { 2272 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr); 2273 Accesses.addStore(NewLoc, AccessTy); 2274 }); 2275 } 2276 } 2277 2278 if (IsAnnotatedParallel) { 2279 LLVM_DEBUG( 2280 dbgs() << "LAA: A loop annotated parallel, ignore memory dependency " 2281 << "checks.\n"); 2282 CanVecMem = true; 2283 return; 2284 } 2285 2286 for (LoadInst *LD : Loads) { 2287 Value *Ptr = LD->getPointerOperand(); 2288 // If we did *not* see this pointer before, insert it to the 2289 // read list. If we *did* see it before, then it is already in 2290 // the read-write list. This allows us to vectorize expressions 2291 // such as A[i] += x; Because the address of A[i] is a read-write 2292 // pointer. This only works if the index of A[i] is consecutive. 2293 // If the address of i is unknown (for example A[B[i]]) then we may 2294 // read a few words, modify, and write a few words, and some of the 2295 // words may be written to the same address. 2296 bool IsReadOnlyPtr = false; 2297 Type *AccessTy = getLoadStoreType(LD); 2298 if (Seen.insert({Ptr, AccessTy}).second || 2299 !getPtrStride(*PSE, LD->getType(), Ptr, TheLoop, SymbolicStrides)) { 2300 ++NumReads; 2301 IsReadOnlyPtr = true; 2302 } 2303 2304 // See if there is an unsafe dependency between a load to a uniform address and 2305 // store to the same uniform address. 2306 if (UniformStores.count(Ptr)) { 2307 LLVM_DEBUG(dbgs() << "LAA: Found an unsafe dependency between a uniform " 2308 "load and uniform store to the same address!\n"); 2309 HasDependenceInvolvingLoopInvariantAddress = true; 2310 } 2311 2312 MemoryLocation Loc = MemoryLocation::get(LD); 2313 // The TBAA metadata could have a control dependency on the predication 2314 // condition, so we cannot rely on it when determining whether or not we 2315 // need runtime pointer checks. 2316 if (blockNeedsPredication(LD->getParent(), TheLoop, DT)) 2317 Loc.AATags.TBAA = nullptr; 2318 2319 visitPointers(const_cast<Value *>(Loc.Ptr), *TheLoop, 2320 [&Accesses, AccessTy, Loc, IsReadOnlyPtr](Value *Ptr) { 2321 MemoryLocation NewLoc = Loc.getWithNewPtr(Ptr); 2322 Accesses.addLoad(NewLoc, AccessTy, IsReadOnlyPtr); 2323 }); 2324 } 2325 2326 // If we write (or read-write) to a single destination and there are no 2327 // other reads in this loop then is it safe to vectorize. 2328 if (NumReadWrites == 1 && NumReads == 0) { 2329 LLVM_DEBUG(dbgs() << "LAA: Found a write-only loop!\n"); 2330 CanVecMem = true; 2331 return; 2332 } 2333 2334 // Build dependence sets and check whether we need a runtime pointer bounds 2335 // check. 2336 Accesses.buildDependenceSets(); 2337 2338 // Find pointers with computable bounds. We are going to use this information 2339 // to place a runtime bound check. 2340 Value *UncomputablePtr = nullptr; 2341 bool CanDoRTIfNeeded = 2342 Accesses.canCheckPtrAtRT(*PtrRtChecking, PSE->getSE(), TheLoop, 2343 SymbolicStrides, UncomputablePtr, false); 2344 if (!CanDoRTIfNeeded) { 2345 auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr); 2346 recordAnalysis("CantIdentifyArrayBounds", I) 2347 << "cannot identify array bounds"; 2348 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " 2349 << "the array bounds.\n"); 2350 CanVecMem = false; 2351 return; 2352 } 2353 2354 LLVM_DEBUG( 2355 dbgs() << "LAA: May be able to perform a memory runtime check if needed.\n"); 2356 2357 CanVecMem = true; 2358 if (Accesses.isDependencyCheckNeeded()) { 2359 LLVM_DEBUG(dbgs() << "LAA: Checking memory dependencies\n"); 2360 CanVecMem = DepChecker->areDepsSafe( 2361 DependentAccesses, Accesses.getDependenciesToCheck(), SymbolicStrides); 2362 MaxSafeDepDistBytes = DepChecker->getMaxSafeDepDistBytes(); 2363 2364 if (!CanVecMem && DepChecker->shouldRetryWithRuntimeCheck()) { 2365 LLVM_DEBUG(dbgs() << "LAA: Retrying with memory checks\n"); 2366 2367 // Clear the dependency checks. We assume they are not needed. 2368 Accesses.resetDepChecks(*DepChecker); 2369 2370 PtrRtChecking->reset(); 2371 PtrRtChecking->Need = true; 2372 2373 auto *SE = PSE->getSE(); 2374 UncomputablePtr = nullptr; 2375 CanDoRTIfNeeded = Accesses.canCheckPtrAtRT( 2376 *PtrRtChecking, SE, TheLoop, SymbolicStrides, UncomputablePtr, true); 2377 2378 // Check that we found the bounds for the pointer. 2379 if (!CanDoRTIfNeeded) { 2380 auto *I = dyn_cast_or_null<Instruction>(UncomputablePtr); 2381 recordAnalysis("CantCheckMemDepsAtRunTime", I) 2382 << "cannot check memory dependencies at runtime"; 2383 LLVM_DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n"); 2384 CanVecMem = false; 2385 return; 2386 } 2387 2388 CanVecMem = true; 2389 } 2390 } 2391 2392 if (HasConvergentOp) { 2393 recordAnalysis("CantInsertRuntimeCheckWithConvergent") 2394 << "cannot add control dependency to convergent operation"; 2395 LLVM_DEBUG(dbgs() << "LAA: We can't vectorize because a runtime check " 2396 "would be needed with a convergent operation\n"); 2397 CanVecMem = false; 2398 return; 2399 } 2400 2401 if (CanVecMem) 2402 LLVM_DEBUG( 2403 dbgs() << "LAA: No unsafe dependent memory operations in loop. We" 2404 << (PtrRtChecking->Need ? "" : " don't") 2405 << " need runtime memory checks.\n"); 2406 else 2407 emitUnsafeDependenceRemark(); 2408 } 2409 2410 void LoopAccessInfo::emitUnsafeDependenceRemark() { 2411 auto Deps = getDepChecker().getDependences(); 2412 if (!Deps) 2413 return; 2414 auto Found = std::find_if( 2415 Deps->begin(), Deps->end(), [](const MemoryDepChecker::Dependence &D) { 2416 return MemoryDepChecker::Dependence::isSafeForVectorization(D.Type) != 2417 MemoryDepChecker::VectorizationSafetyStatus::Safe; 2418 }); 2419 if (Found == Deps->end()) 2420 return; 2421 MemoryDepChecker::Dependence Dep = *Found; 2422 2423 LLVM_DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n"); 2424 2425 // Emit remark for first unsafe dependence 2426 OptimizationRemarkAnalysis &R = 2427 recordAnalysis("UnsafeDep", Dep.getDestination(*this)) 2428 << "unsafe dependent memory operations in loop. Use " 2429 "#pragma loop distribute(enable) to allow loop distribution " 2430 "to attempt to isolate the offending operations into a separate " 2431 "loop"; 2432 2433 switch (Dep.Type) { 2434 case MemoryDepChecker::Dependence::NoDep: 2435 case MemoryDepChecker::Dependence::Forward: 2436 case MemoryDepChecker::Dependence::BackwardVectorizable: 2437 llvm_unreachable("Unexpected dependence"); 2438 case MemoryDepChecker::Dependence::Backward: 2439 R << "\nBackward loop carried data dependence."; 2440 break; 2441 case MemoryDepChecker::Dependence::ForwardButPreventsForwarding: 2442 R << "\nForward loop carried data dependence that prevents " 2443 "store-to-load forwarding."; 2444 break; 2445 case MemoryDepChecker::Dependence::BackwardVectorizableButPreventsForwarding: 2446 R << "\nBackward loop carried data dependence that prevents " 2447 "store-to-load forwarding."; 2448 break; 2449 case MemoryDepChecker::Dependence::Unknown: 2450 R << "\nUnknown data dependence."; 2451 break; 2452 } 2453 2454 if (Instruction *I = Dep.getSource(*this)) { 2455 DebugLoc SourceLoc = I->getDebugLoc(); 2456 if (auto *DD = dyn_cast_or_null<Instruction>(getPointerOperand(I))) 2457 SourceLoc = DD->getDebugLoc(); 2458 if (SourceLoc) 2459 R << " Memory location is the same as accessed at " 2460 << ore::NV("Location", SourceLoc); 2461 } 2462 } 2463 2464 bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, 2465 DominatorTree *DT) { 2466 assert(TheLoop->contains(BB) && "Unknown block used"); 2467 2468 // Blocks that do not dominate the latch need predication. 2469 BasicBlock* Latch = TheLoop->getLoopLatch(); 2470 return !DT->dominates(BB, Latch); 2471 } 2472 2473 OptimizationRemarkAnalysis &LoopAccessInfo::recordAnalysis(StringRef RemarkName, 2474 Instruction *I) { 2475 assert(!Report && "Multiple reports generated"); 2476 2477 Value *CodeRegion = TheLoop->getHeader(); 2478 DebugLoc DL = TheLoop->getStartLoc(); 2479 2480 if (I) { 2481 CodeRegion = I->getParent(); 2482 // If there is no debug location attached to the instruction, revert back to 2483 // using the loop's. 2484 if (I->getDebugLoc()) 2485 DL = I->getDebugLoc(); 2486 } 2487 2488 Report = std::make_unique<OptimizationRemarkAnalysis>(DEBUG_TYPE, RemarkName, DL, 2489 CodeRegion); 2490 return *Report; 2491 } 2492 2493 bool LoopAccessInfo::isUniform(Value *V) const { 2494 auto *SE = PSE->getSE(); 2495 // Since we rely on SCEV for uniformity, if the type is not SCEVable, it is 2496 // never considered uniform. 2497 // TODO: Is this really what we want? Even without FP SCEV, we may want some 2498 // trivially loop-invariant FP values to be considered uniform. 2499 if (!SE->isSCEVable(V->getType())) 2500 return false; 2501 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop)); 2502 } 2503 2504 void LoopAccessInfo::collectStridedAccess(Value *MemAccess) { 2505 Value *Ptr = getLoadStorePointerOperand(MemAccess); 2506 if (!Ptr) 2507 return; 2508 2509 Value *Stride = getStrideFromPointer(Ptr, PSE->getSE(), TheLoop); 2510 if (!Stride) 2511 return; 2512 2513 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that is a candidate for " 2514 "versioning:"); 2515 LLVM_DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n"); 2516 2517 // Avoid adding the "Stride == 1" predicate when we know that 2518 // Stride >= Trip-Count. Such a predicate will effectively optimize a single 2519 // or zero iteration loop, as Trip-Count <= Stride == 1. 2520 // 2521 // TODO: We are currently not making a very informed decision on when it is 2522 // beneficial to apply stride versioning. It might make more sense that the 2523 // users of this analysis (such as the vectorizer) will trigger it, based on 2524 // their specific cost considerations; For example, in cases where stride 2525 // versioning does not help resolving memory accesses/dependences, the 2526 // vectorizer should evaluate the cost of the runtime test, and the benefit 2527 // of various possible stride specializations, considering the alternatives 2528 // of using gather/scatters (if available). 2529 2530 const SCEV *StrideExpr = PSE->getSCEV(Stride); 2531 const SCEV *BETakenCount = PSE->getBackedgeTakenCount(); 2532 2533 // Match the types so we can compare the stride and the BETakenCount. 2534 // The Stride can be positive/negative, so we sign extend Stride; 2535 // The backedgeTakenCount is non-negative, so we zero extend BETakenCount. 2536 const DataLayout &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 2537 uint64_t StrideTypeSizeBits = DL.getTypeSizeInBits(StrideExpr->getType()); 2538 uint64_t BETypeSizeBits = DL.getTypeSizeInBits(BETakenCount->getType()); 2539 const SCEV *CastedStride = StrideExpr; 2540 const SCEV *CastedBECount = BETakenCount; 2541 ScalarEvolution *SE = PSE->getSE(); 2542 if (BETypeSizeBits >= StrideTypeSizeBits) 2543 CastedStride = SE->getNoopOrSignExtend(StrideExpr, BETakenCount->getType()); 2544 else 2545 CastedBECount = SE->getZeroExtendExpr(BETakenCount, StrideExpr->getType()); 2546 const SCEV *StrideMinusBETaken = SE->getMinusSCEV(CastedStride, CastedBECount); 2547 // Since TripCount == BackEdgeTakenCount + 1, checking: 2548 // "Stride >= TripCount" is equivalent to checking: 2549 // Stride - BETakenCount > 0 2550 if (SE->isKnownPositive(StrideMinusBETaken)) { 2551 LLVM_DEBUG( 2552 dbgs() << "LAA: Stride>=TripCount; No point in versioning as the " 2553 "Stride==1 predicate will imply that the loop executes " 2554 "at most once.\n"); 2555 return; 2556 } 2557 LLVM_DEBUG(dbgs() << "LAA: Found a strided access that we can version.\n"); 2558 2559 SymbolicStrides[Ptr] = Stride; 2560 StrideSet.insert(Stride); 2561 } 2562 2563 LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE, 2564 const TargetLibraryInfo *TLI, AAResults *AA, 2565 DominatorTree *DT, LoopInfo *LI) 2566 : PSE(std::make_unique<PredicatedScalarEvolution>(*SE, *L)), 2567 PtrRtChecking(nullptr), 2568 DepChecker(std::make_unique<MemoryDepChecker>(*PSE, L)), TheLoop(L) { 2569 PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE); 2570 if (canAnalyzeLoop()) { 2571 analyzeLoop(AA, LI, TLI, DT); 2572 } 2573 } 2574 2575 void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const { 2576 if (CanVecMem) { 2577 OS.indent(Depth) << "Memory dependences are safe"; 2578 if (MaxSafeDepDistBytes != -1ULL) 2579 OS << " with a maximum dependence distance of " << MaxSafeDepDistBytes 2580 << " bytes"; 2581 if (PtrRtChecking->Need) 2582 OS << " with run-time checks"; 2583 OS << "\n"; 2584 } 2585 2586 if (HasConvergentOp) 2587 OS.indent(Depth) << "Has convergent operation in loop\n"; 2588 2589 if (Report) 2590 OS.indent(Depth) << "Report: " << Report->getMsg() << "\n"; 2591 2592 if (auto *Dependences = DepChecker->getDependences()) { 2593 OS.indent(Depth) << "Dependences:\n"; 2594 for (const auto &Dep : *Dependences) { 2595 Dep.print(OS, Depth + 2, DepChecker->getMemoryInstructions()); 2596 OS << "\n"; 2597 } 2598 } else 2599 OS.indent(Depth) << "Too many dependences, not recorded\n"; 2600 2601 // List the pair of accesses need run-time checks to prove independence. 2602 PtrRtChecking->print(OS, Depth); 2603 OS << "\n"; 2604 2605 OS.indent(Depth) << "Non vectorizable stores to invariant address were " 2606 << (HasDependenceInvolvingLoopInvariantAddress ? "" : "not ") 2607 << "found in loop.\n"; 2608 2609 OS.indent(Depth) << "SCEV assumptions:\n"; 2610 PSE->getPredicate().print(OS, Depth); 2611 2612 OS << "\n"; 2613 2614 OS.indent(Depth) << "Expressions re-written:\n"; 2615 PSE->print(OS, Depth); 2616 } 2617 2618 LoopAccessLegacyAnalysis::LoopAccessLegacyAnalysis() : FunctionPass(ID) { 2619 initializeLoopAccessLegacyAnalysisPass(*PassRegistry::getPassRegistry()); 2620 } 2621 2622 const LoopAccessInfo &LoopAccessLegacyAnalysis::getInfo(Loop *L) { 2623 auto &LAI = LoopAccessInfoMap[L]; 2624 2625 if (!LAI) 2626 LAI = std::make_unique<LoopAccessInfo>(L, SE, TLI, AA, DT, LI); 2627 2628 return *LAI; 2629 } 2630 2631 void LoopAccessLegacyAnalysis::print(raw_ostream &OS, const Module *M) const { 2632 LoopAccessLegacyAnalysis &LAA = *const_cast<LoopAccessLegacyAnalysis *>(this); 2633 2634 for (Loop *TopLevelLoop : *LI) 2635 for (Loop *L : depth_first(TopLevelLoop)) { 2636 OS.indent(2) << L->getHeader()->getName() << ":\n"; 2637 auto &LAI = LAA.getInfo(L); 2638 LAI.print(OS, 4); 2639 } 2640 } 2641 2642 bool LoopAccessLegacyAnalysis::runOnFunction(Function &F) { 2643 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 2644 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 2645 TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 2646 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 2647 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2648 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2649 2650 return false; 2651 } 2652 2653 void LoopAccessLegacyAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { 2654 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>(); 2655 AU.addRequiredTransitive<AAResultsWrapperPass>(); 2656 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 2657 AU.addRequiredTransitive<LoopInfoWrapperPass>(); 2658 2659 AU.setPreservesAll(); 2660 } 2661 2662 char LoopAccessLegacyAnalysis::ID = 0; 2663 static const char laa_name[] = "Loop Access Analysis"; 2664 #define LAA_NAME "loop-accesses" 2665 2666 INITIALIZE_PASS_BEGIN(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true) 2667 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2668 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 2669 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2670 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 2671 INITIALIZE_PASS_END(LoopAccessLegacyAnalysis, LAA_NAME, laa_name, false, true) 2672 2673 AnalysisKey LoopAccessAnalysis::Key; 2674 2675 LoopAccessInfo LoopAccessAnalysis::run(Loop &L, LoopAnalysisManager &AM, 2676 LoopStandardAnalysisResults &AR) { 2677 return LoopAccessInfo(&L, &AR.SE, &AR.TLI, &AR.AA, &AR.DT, &AR.LI); 2678 } 2679 2680 namespace llvm { 2681 2682 Pass *createLAAPass() { 2683 return new LoopAccessLegacyAnalysis(); 2684 } 2685 2686 } // end namespace llvm 2687