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