Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1 | //===- LoopAccessAnalysis.cpp - Loop Access Analysis Implementation --------==// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // The implementation for the loop memory dependence that was originally |
| 11 | // developed for the loop vectorizer. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "llvm/Analysis/LoopAccessAnalysis.h" |
| 16 | #include "llvm/Analysis/LoopInfo.h" |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 17 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/ValueTracking.h" |
| 19 | #include "llvm/IR/DiagnosticInfo.h" |
| 20 | #include "llvm/IR/Dominators.h" |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 21 | #include "llvm/IR/IRBuilder.h" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 22 | #include "llvm/Support/Debug.h" |
| 23 | #include "llvm/Transforms/Utils/VectorUtils.h" |
| 24 | using namespace llvm; |
| 25 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 26 | #define DEBUG_TYPE "loop-vectorize" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 27 | |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 28 | static cl::opt<unsigned, true> |
| 29 | VectorizationFactor("force-vector-width", cl::Hidden, |
| 30 | cl::desc("Sets the SIMD width. Zero is autoselect."), |
| 31 | cl::location(VectorizerParams::VectorizationFactor)); |
| 32 | unsigned VectorizerParams::VectorizationFactor = 0; |
| 33 | |
| 34 | static cl::opt<unsigned, true> |
| 35 | VectorizationInterleave("force-vector-interleave", cl::Hidden, |
| 36 | cl::desc("Sets the vectorization interleave count. " |
| 37 | "Zero is autoselect."), |
| 38 | cl::location( |
| 39 | VectorizerParams::VectorizationInterleave)); |
| 40 | unsigned VectorizerParams::VectorizationInterleave = 0; |
| 41 | |
| 42 | /// When performing memory disambiguation checks at runtime do not make more |
| 43 | /// than this number of comparisons. |
| 44 | const unsigned VectorizerParams::RuntimeMemoryCheckThreshold = 8; |
| 45 | |
| 46 | /// Maximum SIMD width. |
| 47 | const unsigned VectorizerParams::MaxVectorWidth = 64; |
| 48 | |
| 49 | bool VectorizerParams::isInterleaveForced() { |
| 50 | return ::VectorizationInterleave.getNumOccurrences() > 0; |
| 51 | } |
| 52 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 53 | void VectorizationReport::emitAnalysis(VectorizationReport &Message, |
| 54 | const Function *TheFunction, |
| 55 | const Loop *TheLoop) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 56 | DebugLoc DL = TheLoop->getStartLoc(); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 57 | if (Instruction *I = Message.getInstr()) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 58 | DL = I->getDebugLoc(); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 59 | emitOptimizationRemarkAnalysis(TheFunction->getContext(), DEBUG_TYPE, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 60 | *TheFunction, DL, Message.str()); |
| 61 | } |
| 62 | |
| 63 | Value *llvm::stripIntegerCast(Value *V) { |
| 64 | if (CastInst *CI = dyn_cast<CastInst>(V)) |
| 65 | if (CI->getOperand(0)->getType()->isIntegerTy()) |
| 66 | return CI->getOperand(0); |
| 67 | return V; |
| 68 | } |
| 69 | |
| 70 | const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE, |
| 71 | ValueToValueMap &PtrToStride, |
| 72 | Value *Ptr, Value *OrigPtr) { |
| 73 | |
| 74 | const SCEV *OrigSCEV = SE->getSCEV(Ptr); |
| 75 | |
| 76 | // If there is an entry in the map return the SCEV of the pointer with the |
| 77 | // symbolic stride replaced by one. |
| 78 | ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr); |
| 79 | if (SI != PtrToStride.end()) { |
| 80 | Value *StrideVal = SI->second; |
| 81 | |
| 82 | // Strip casts. |
| 83 | StrideVal = stripIntegerCast(StrideVal); |
| 84 | |
| 85 | // Replace symbolic stride by one. |
| 86 | Value *One = ConstantInt::get(StrideVal->getType(), 1); |
| 87 | ValueToValueMap RewriteMap; |
| 88 | RewriteMap[StrideVal] = One; |
| 89 | |
| 90 | const SCEV *ByOne = |
| 91 | SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 92 | DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 93 | << "\n"); |
| 94 | return ByOne; |
| 95 | } |
| 96 | |
| 97 | // Otherwise, just return the SCEV of the original pointer. |
| 98 | return SE->getSCEV(Ptr); |
| 99 | } |
| 100 | |
Adam Nemet | 30f16e1 | 2015-02-18 03:42:35 +0000 | [diff] [blame] | 101 | void LoopAccessInfo::RuntimePointerCheck::insert(ScalarEvolution *SE, Loop *Lp, |
| 102 | Value *Ptr, bool WritePtr, |
| 103 | unsigned DepSetId, |
| 104 | unsigned ASId, |
| 105 | ValueToValueMap &Strides) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 106 | // Get the stride replaced scev. |
| 107 | const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr); |
| 108 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc); |
| 109 | assert(AR && "Invalid addrec expression"); |
| 110 | const SCEV *Ex = SE->getBackedgeTakenCount(Lp); |
| 111 | const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE); |
| 112 | Pointers.push_back(Ptr); |
| 113 | Starts.push_back(AR->getStart()); |
| 114 | Ends.push_back(ScEnd); |
| 115 | IsWritePtr.push_back(WritePtr); |
| 116 | DependencySetId.push_back(DepSetId); |
| 117 | AliasSetId.push_back(ASId); |
| 118 | } |
| 119 | |
Adam Nemet | a8945b7 | 2015-02-18 03:43:58 +0000 | [diff] [blame] | 120 | bool LoopAccessInfo::RuntimePointerCheck::needsChecking(unsigned I, |
| 121 | unsigned J) const { |
| 122 | // No need to check if two readonly pointers intersect. |
| 123 | if (!IsWritePtr[I] && !IsWritePtr[J]) |
| 124 | return false; |
| 125 | |
| 126 | // Only need to check pointers between two different dependency sets. |
| 127 | if (DependencySetId[I] == DependencySetId[J]) |
| 128 | return false; |
| 129 | |
| 130 | // Only need to check pointers in the same alias set. |
| 131 | if (AliasSetId[I] != AliasSetId[J]) |
| 132 | return false; |
| 133 | |
| 134 | return true; |
| 135 | } |
| 136 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 137 | namespace { |
| 138 | /// \brief Analyses memory accesses in a loop. |
| 139 | /// |
| 140 | /// Checks whether run time pointer checks are needed and builds sets for data |
| 141 | /// dependence checking. |
| 142 | class AccessAnalysis { |
| 143 | public: |
| 144 | /// \brief Read or write access location. |
| 145 | typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; |
| 146 | typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet; |
| 147 | |
| 148 | /// \brief Set of potential dependent memory accesses. |
| 149 | typedef EquivalenceClasses<MemAccessInfo> DepCandidates; |
| 150 | |
| 151 | AccessAnalysis(const DataLayout *Dl, AliasAnalysis *AA, DepCandidates &DA) : |
| 152 | DL(Dl), AST(*AA), DepCands(DA), IsRTCheckNeeded(false) {} |
| 153 | |
| 154 | /// \brief Register a load and whether it is only read from. |
| 155 | void addLoad(AliasAnalysis::Location &Loc, bool IsReadOnly) { |
| 156 | Value *Ptr = const_cast<Value*>(Loc.Ptr); |
| 157 | AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags); |
| 158 | Accesses.insert(MemAccessInfo(Ptr, false)); |
| 159 | if (IsReadOnly) |
| 160 | ReadOnlyPtr.insert(Ptr); |
| 161 | } |
| 162 | |
| 163 | /// \brief Register a store. |
| 164 | void addStore(AliasAnalysis::Location &Loc) { |
| 165 | Value *Ptr = const_cast<Value*>(Loc.Ptr); |
| 166 | AST.add(Ptr, AliasAnalysis::UnknownSize, Loc.AATags); |
| 167 | Accesses.insert(MemAccessInfo(Ptr, true)); |
| 168 | } |
| 169 | |
| 170 | /// \brief Check whether we can check the pointers at runtime for |
| 171 | /// non-intersection. |
Adam Nemet | 30f16e1 | 2015-02-18 03:42:35 +0000 | [diff] [blame] | 172 | bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 173 | unsigned &NumComparisons, |
| 174 | ScalarEvolution *SE, Loop *TheLoop, |
| 175 | ValueToValueMap &Strides, |
| 176 | bool ShouldCheckStride = false); |
| 177 | |
| 178 | /// \brief Goes over all memory accesses, checks whether a RT check is needed |
| 179 | /// and builds sets of dependent accesses. |
| 180 | void buildDependenceSets() { |
| 181 | processMemAccesses(); |
| 182 | } |
| 183 | |
| 184 | bool isRTCheckNeeded() { return IsRTCheckNeeded; } |
| 185 | |
| 186 | bool isDependencyCheckNeeded() { return !CheckDeps.empty(); } |
| 187 | void resetDepChecks() { CheckDeps.clear(); } |
| 188 | |
| 189 | MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; } |
| 190 | |
| 191 | private: |
| 192 | typedef SetVector<MemAccessInfo> PtrAccessSet; |
| 193 | |
| 194 | /// \brief Go over all memory access and check whether runtime pointer checks |
| 195 | /// are needed /// and build sets of dependency check candidates. |
| 196 | void processMemAccesses(); |
| 197 | |
| 198 | /// Set of all accesses. |
| 199 | PtrAccessSet Accesses; |
| 200 | |
| 201 | /// Set of accesses that need a further dependence check. |
| 202 | MemAccessInfoSet CheckDeps; |
| 203 | |
| 204 | /// Set of pointers that are read only. |
| 205 | SmallPtrSet<Value*, 16> ReadOnlyPtr; |
| 206 | |
| 207 | const DataLayout *DL; |
| 208 | |
| 209 | /// An alias set tracker to partition the access set by underlying object and |
| 210 | //intrinsic property (such as TBAA metadata). |
| 211 | AliasSetTracker AST; |
| 212 | |
| 213 | /// Sets of potentially dependent accesses - members of one set share an |
| 214 | /// underlying pointer. The set "CheckDeps" identfies which sets really need a |
| 215 | /// dependence check. |
| 216 | DepCandidates &DepCands; |
| 217 | |
| 218 | bool IsRTCheckNeeded; |
| 219 | }; |
| 220 | |
| 221 | } // end anonymous namespace |
| 222 | |
| 223 | /// \brief Check whether a pointer can participate in a runtime bounds check. |
| 224 | static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides, |
| 225 | Value *Ptr) { |
| 226 | const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr); |
| 227 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); |
| 228 | if (!AR) |
| 229 | return false; |
| 230 | |
| 231 | return AR->isAffine(); |
| 232 | } |
| 233 | |
| 234 | /// \brief Check the stride of the pointer and ensure that it does not wrap in |
| 235 | /// the address space. |
| 236 | static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr, |
| 237 | const Loop *Lp, ValueToValueMap &StridesMap); |
| 238 | |
| 239 | bool AccessAnalysis::canCheckPtrAtRT( |
Adam Nemet | 30f16e1 | 2015-02-18 03:42:35 +0000 | [diff] [blame] | 240 | LoopAccessInfo::RuntimePointerCheck &RtCheck, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 241 | unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop, |
| 242 | ValueToValueMap &StridesMap, bool ShouldCheckStride) { |
| 243 | // Find pointers with computable bounds. We are going to use this information |
| 244 | // to place a runtime bound check. |
| 245 | bool CanDoRT = true; |
| 246 | |
| 247 | bool IsDepCheckNeeded = isDependencyCheckNeeded(); |
| 248 | NumComparisons = 0; |
| 249 | |
| 250 | // We assign a consecutive id to access from different alias sets. |
| 251 | // Accesses between different groups doesn't need to be checked. |
| 252 | unsigned ASId = 1; |
| 253 | for (auto &AS : AST) { |
| 254 | unsigned NumReadPtrChecks = 0; |
| 255 | unsigned NumWritePtrChecks = 0; |
| 256 | |
| 257 | // We assign consecutive id to access from different dependence sets. |
| 258 | // Accesses within the same set don't need a runtime check. |
| 259 | unsigned RunningDepId = 1; |
| 260 | DenseMap<Value *, unsigned> DepSetId; |
| 261 | |
| 262 | for (auto A : AS) { |
| 263 | Value *Ptr = A.getValue(); |
| 264 | bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true)); |
| 265 | MemAccessInfo Access(Ptr, IsWrite); |
| 266 | |
| 267 | if (IsWrite) |
| 268 | ++NumWritePtrChecks; |
| 269 | else |
| 270 | ++NumReadPtrChecks; |
| 271 | |
| 272 | if (hasComputableBounds(SE, StridesMap, Ptr) && |
| 273 | // When we run after a failing dependency check we have to make sure we |
| 274 | // don't have wrapping pointers. |
| 275 | (!ShouldCheckStride || |
| 276 | isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) { |
| 277 | // The id of the dependence set. |
| 278 | unsigned DepId; |
| 279 | |
| 280 | if (IsDepCheckNeeded) { |
| 281 | Value *Leader = DepCands.getLeaderValue(Access).getPointer(); |
| 282 | unsigned &LeaderId = DepSetId[Leader]; |
| 283 | if (!LeaderId) |
| 284 | LeaderId = RunningDepId++; |
| 285 | DepId = LeaderId; |
| 286 | } else |
| 287 | // Each access has its own dependence set. |
| 288 | DepId = RunningDepId++; |
| 289 | |
| 290 | RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap); |
| 291 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 292 | DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 293 | } else { |
| 294 | CanDoRT = false; |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2) |
| 299 | NumComparisons += 0; // Only one dependence set. |
| 300 | else { |
| 301 | NumComparisons += (NumWritePtrChecks * (NumReadPtrChecks + |
| 302 | NumWritePtrChecks - 1)); |
| 303 | } |
| 304 | |
| 305 | ++ASId; |
| 306 | } |
| 307 | |
| 308 | // If the pointers that we would use for the bounds comparison have different |
| 309 | // address spaces, assume the values aren't directly comparable, so we can't |
| 310 | // use them for the runtime check. We also have to assume they could |
| 311 | // overlap. In the future there should be metadata for whether address spaces |
| 312 | // are disjoint. |
| 313 | unsigned NumPointers = RtCheck.Pointers.size(); |
| 314 | for (unsigned i = 0; i < NumPointers; ++i) { |
| 315 | for (unsigned j = i + 1; j < NumPointers; ++j) { |
| 316 | // Only need to check pointers between two different dependency sets. |
| 317 | if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j]) |
| 318 | continue; |
| 319 | // Only need to check pointers in the same alias set. |
| 320 | if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j]) |
| 321 | continue; |
| 322 | |
| 323 | Value *PtrI = RtCheck.Pointers[i]; |
| 324 | Value *PtrJ = RtCheck.Pointers[j]; |
| 325 | |
| 326 | unsigned ASi = PtrI->getType()->getPointerAddressSpace(); |
| 327 | unsigned ASj = PtrJ->getType()->getPointerAddressSpace(); |
| 328 | if (ASi != ASj) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 329 | DEBUG(dbgs() << "LV: Runtime check would require comparison between" |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 330 | " different address spaces\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 331 | return false; |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | return CanDoRT; |
| 337 | } |
| 338 | |
| 339 | void AccessAnalysis::processMemAccesses() { |
| 340 | // We process the set twice: first we process read-write pointers, last we |
| 341 | // process read-only pointers. This allows us to skip dependence tests for |
| 342 | // read-only pointers. |
| 343 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 344 | DEBUG(dbgs() << "LV: Processing memory accesses...\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 345 | DEBUG(dbgs() << " AST: "; AST.dump()); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 346 | DEBUG(dbgs() << "LV: Accesses:\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 347 | DEBUG({ |
| 348 | for (auto A : Accesses) |
| 349 | dbgs() << "\t" << *A.getPointer() << " (" << |
| 350 | (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ? |
| 351 | "read-only" : "read")) << ")\n"; |
| 352 | }); |
| 353 | |
| 354 | // The AliasSetTracker has nicely partitioned our pointers by metadata |
| 355 | // compatibility and potential for underlying-object overlap. As a result, we |
| 356 | // only need to check for potential pointer dependencies within each alias |
| 357 | // set. |
| 358 | for (auto &AS : AST) { |
| 359 | // Note that both the alias-set tracker and the alias sets themselves used |
| 360 | // linked lists internally and so the iteration order here is deterministic |
| 361 | // (matching the original instruction order within each set). |
| 362 | |
| 363 | bool SetHasWrite = false; |
| 364 | |
| 365 | // Map of pointers to last access encountered. |
| 366 | typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap; |
| 367 | UnderlyingObjToAccessMap ObjToLastAccess; |
| 368 | |
| 369 | // Set of access to check after all writes have been processed. |
| 370 | PtrAccessSet DeferredAccesses; |
| 371 | |
| 372 | // Iterate over each alias set twice, once to process read/write pointers, |
| 373 | // and then to process read-only pointers. |
| 374 | for (int SetIteration = 0; SetIteration < 2; ++SetIteration) { |
| 375 | bool UseDeferred = SetIteration > 0; |
| 376 | PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses; |
| 377 | |
| 378 | for (auto AV : AS) { |
| 379 | Value *Ptr = AV.getValue(); |
| 380 | |
| 381 | // For a single memory access in AliasSetTracker, Accesses may contain |
| 382 | // both read and write, and they both need to be handled for CheckDeps. |
| 383 | for (auto AC : S) { |
| 384 | if (AC.getPointer() != Ptr) |
| 385 | continue; |
| 386 | |
| 387 | bool IsWrite = AC.getInt(); |
| 388 | |
| 389 | // If we're using the deferred access set, then it contains only |
| 390 | // reads. |
| 391 | bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite; |
| 392 | if (UseDeferred && !IsReadOnlyPtr) |
| 393 | continue; |
| 394 | // Otherwise, the pointer must be in the PtrAccessSet, either as a |
| 395 | // read or a write. |
| 396 | assert(((IsReadOnlyPtr && UseDeferred) || IsWrite || |
| 397 | S.count(MemAccessInfo(Ptr, false))) && |
| 398 | "Alias-set pointer not in the access set?"); |
| 399 | |
| 400 | MemAccessInfo Access(Ptr, IsWrite); |
| 401 | DepCands.insert(Access); |
| 402 | |
| 403 | // Memorize read-only pointers for later processing and skip them in |
| 404 | // the first round (they need to be checked after we have seen all |
| 405 | // write pointers). Note: we also mark pointer that are not |
| 406 | // consecutive as "read-only" pointers (so that we check |
| 407 | // "a[b[i]] +="). Hence, we need the second check for "!IsWrite". |
| 408 | if (!UseDeferred && IsReadOnlyPtr) { |
| 409 | DeferredAccesses.insert(Access); |
| 410 | continue; |
| 411 | } |
| 412 | |
| 413 | // If this is a write - check other reads and writes for conflicts. If |
| 414 | // this is a read only check other writes for conflicts (but only if |
| 415 | // there is no other write to the ptr - this is an optimization to |
| 416 | // catch "a[i] = a[i] + " without having to do a dependence check). |
| 417 | if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) { |
| 418 | CheckDeps.insert(Access); |
| 419 | IsRTCheckNeeded = true; |
| 420 | } |
| 421 | |
| 422 | if (IsWrite) |
| 423 | SetHasWrite = true; |
| 424 | |
| 425 | // Create sets of pointers connected by a shared alias set and |
| 426 | // underlying object. |
| 427 | typedef SmallVector<Value *, 16> ValueVector; |
| 428 | ValueVector TempObjects; |
| 429 | GetUnderlyingObjects(Ptr, TempObjects, DL); |
| 430 | for (Value *UnderlyingObj : TempObjects) { |
| 431 | UnderlyingObjToAccessMap::iterator Prev = |
| 432 | ObjToLastAccess.find(UnderlyingObj); |
| 433 | if (Prev != ObjToLastAccess.end()) |
| 434 | DepCands.unionSets(Access, Prev->second); |
| 435 | |
| 436 | ObjToLastAccess[UnderlyingObj] = Access; |
| 437 | } |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | namespace { |
| 445 | /// \brief Checks memory dependences among accesses to the same underlying |
| 446 | /// object to determine whether there vectorization is legal or not (and at |
| 447 | /// which vectorization factor). |
| 448 | /// |
| 449 | /// This class works under the assumption that we already checked that memory |
| 450 | /// locations with different underlying pointers are "must-not alias". |
| 451 | /// We use the ScalarEvolution framework to symbolically evalutate access |
| 452 | /// functions pairs. Since we currently don't restructure the loop we can rely |
| 453 | /// on the program order of memory accesses to determine their safety. |
| 454 | /// At the moment we will only deem accesses as safe for: |
| 455 | /// * A negative constant distance assuming program order. |
| 456 | /// |
| 457 | /// Safe: tmp = a[i + 1]; OR a[i + 1] = x; |
| 458 | /// a[i] = tmp; y = a[i]; |
| 459 | /// |
| 460 | /// The latter case is safe because later checks guarantuee that there can't |
| 461 | /// be a cycle through a phi node (that is, we check that "x" and "y" is not |
| 462 | /// the same variable: a header phi can only be an induction or a reduction, a |
| 463 | /// reduction can't have a memory sink, an induction can't have a memory |
| 464 | /// source). This is important and must not be violated (or we have to |
| 465 | /// resort to checking for cycles through memory). |
| 466 | /// |
| 467 | /// * A positive constant distance assuming program order that is bigger |
| 468 | /// than the biggest memory access. |
| 469 | /// |
| 470 | /// tmp = a[i] OR b[i] = x |
| 471 | /// a[i+2] = tmp y = b[i+2]; |
| 472 | /// |
| 473 | /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively. |
| 474 | /// |
| 475 | /// * Zero distances and all accesses have the same size. |
| 476 | /// |
| 477 | class MemoryDepChecker { |
| 478 | public: |
| 479 | typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; |
| 480 | typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet; |
| 481 | |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 482 | MemoryDepChecker(ScalarEvolution *Se, const DataLayout *Dl, const Loop *L) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 483 | : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0), |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 484 | ShouldRetryWithRuntimeCheck(false) {} |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 485 | |
| 486 | /// \brief Register the location (instructions are given increasing numbers) |
| 487 | /// of a write access. |
| 488 | void addAccess(StoreInst *SI) { |
| 489 | Value *Ptr = SI->getPointerOperand(); |
| 490 | Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx); |
| 491 | InstMap.push_back(SI); |
| 492 | ++AccessIdx; |
| 493 | } |
| 494 | |
| 495 | /// \brief Register the location (instructions are given increasing numbers) |
| 496 | /// of a write access. |
| 497 | void addAccess(LoadInst *LI) { |
| 498 | Value *Ptr = LI->getPointerOperand(); |
| 499 | Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx); |
| 500 | InstMap.push_back(LI); |
| 501 | ++AccessIdx; |
| 502 | } |
| 503 | |
| 504 | /// \brief Check whether the dependencies between the accesses are safe. |
| 505 | /// |
| 506 | /// Only checks sets with elements in \p CheckDeps. |
| 507 | bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets, |
| 508 | MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides); |
| 509 | |
| 510 | /// \brief The maximum number of bytes of a vector register we can vectorize |
| 511 | /// the accesses safely with. |
| 512 | unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; } |
| 513 | |
| 514 | /// \brief In same cases when the dependency check fails we can still |
| 515 | /// vectorize the loop with a dynamic array access check. |
| 516 | bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; } |
| 517 | |
| 518 | private: |
| 519 | ScalarEvolution *SE; |
| 520 | const DataLayout *DL; |
| 521 | const Loop *InnermostLoop; |
| 522 | |
| 523 | /// \brief Maps access locations (ptr, read/write) to program order. |
| 524 | DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses; |
| 525 | |
| 526 | /// \brief Memory access instructions in program order. |
| 527 | SmallVector<Instruction *, 16> InstMap; |
| 528 | |
| 529 | /// \brief The program order index to be used for the next instruction. |
| 530 | unsigned AccessIdx; |
| 531 | |
| 532 | // We can access this many bytes in parallel safely. |
| 533 | unsigned MaxSafeDepDistBytes; |
| 534 | |
| 535 | /// \brief If we see a non-constant dependence distance we can still try to |
| 536 | /// vectorize this loop with runtime checks. |
| 537 | bool ShouldRetryWithRuntimeCheck; |
| 538 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 539 | /// \brief Check whether there is a plausible dependence between the two |
| 540 | /// accesses. |
| 541 | /// |
| 542 | /// Access \p A must happen before \p B in program order. The two indices |
| 543 | /// identify the index into the program order map. |
| 544 | /// |
| 545 | /// This function checks whether there is a plausible dependence (or the |
| 546 | /// absence of such can't be proved) between the two accesses. If there is a |
| 547 | /// plausible dependence but the dependence distance is bigger than one |
| 548 | /// element access it records this distance in \p MaxSafeDepDistBytes (if this |
| 549 | /// distance is smaller than any other distance encountered so far). |
| 550 | /// Otherwise, this function returns true signaling a possible dependence. |
| 551 | bool isDependent(const MemAccessInfo &A, unsigned AIdx, |
| 552 | const MemAccessInfo &B, unsigned BIdx, |
| 553 | ValueToValueMap &Strides); |
| 554 | |
| 555 | /// \brief Check whether the data dependence could prevent store-load |
| 556 | /// forwarding. |
| 557 | bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize); |
| 558 | }; |
| 559 | |
| 560 | } // end anonymous namespace |
| 561 | |
| 562 | static bool isInBoundsGep(Value *Ptr) { |
| 563 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) |
| 564 | return GEP->isInBounds(); |
| 565 | return false; |
| 566 | } |
| 567 | |
| 568 | /// \brief Check whether the access through \p Ptr has a constant stride. |
| 569 | static int isStridedPtr(ScalarEvolution *SE, const DataLayout *DL, Value *Ptr, |
| 570 | const Loop *Lp, ValueToValueMap &StridesMap) { |
| 571 | const Type *Ty = Ptr->getType(); |
| 572 | assert(Ty->isPointerTy() && "Unexpected non-ptr"); |
| 573 | |
| 574 | // Make sure that the pointer does not point to aggregate types. |
| 575 | const PointerType *PtrTy = cast<PointerType>(Ty); |
| 576 | if (PtrTy->getElementType()->isAggregateType()) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 577 | DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr << |
| 578 | "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 579 | return 0; |
| 580 | } |
| 581 | |
| 582 | const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr); |
| 583 | |
| 584 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); |
| 585 | if (!AR) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 586 | DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer " |
| 587 | << *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 588 | return 0; |
| 589 | } |
| 590 | |
| 591 | // The accesss function must stride over the innermost loop. |
| 592 | if (Lp != AR->getLoop()) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 593 | DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " << |
| 594 | *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 595 | } |
| 596 | |
| 597 | // The address calculation must not wrap. Otherwise, a dependence could be |
| 598 | // inverted. |
| 599 | // An inbounds getelementptr that is a AddRec with a unit stride |
| 600 | // cannot wrap per definition. The unit stride requirement is checked later. |
| 601 | // An getelementptr without an inbounds attribute and unit stride would have |
| 602 | // to access the pointer value "0" which is undefined behavior in address |
| 603 | // space 0, therefore we can also vectorize this case. |
| 604 | bool IsInBoundsGEP = isInBoundsGep(Ptr); |
| 605 | bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask); |
| 606 | bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0; |
| 607 | if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 608 | DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 609 | << *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 610 | return 0; |
| 611 | } |
| 612 | |
| 613 | // Check the step is constant. |
| 614 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 615 | |
| 616 | // Calculate the pointer stride and check if it is consecutive. |
| 617 | const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); |
| 618 | if (!C) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 619 | DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr << |
| 620 | " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 621 | return 0; |
| 622 | } |
| 623 | |
| 624 | int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType()); |
| 625 | const APInt &APStepVal = C->getValue()->getValue(); |
| 626 | |
| 627 | // Huge step value - give up. |
| 628 | if (APStepVal.getBitWidth() > 64) |
| 629 | return 0; |
| 630 | |
| 631 | int64_t StepVal = APStepVal.getSExtValue(); |
| 632 | |
| 633 | // Strided access. |
| 634 | int64_t Stride = StepVal / Size; |
| 635 | int64_t Rem = StepVal % Size; |
| 636 | if (Rem) |
| 637 | return 0; |
| 638 | |
| 639 | // If the SCEV could wrap but we have an inbounds gep with a unit stride we |
| 640 | // know we can't "wrap around the address space". In case of address space |
| 641 | // zero we know that this won't happen without triggering undefined behavior. |
| 642 | if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) && |
| 643 | Stride != 1 && Stride != -1) |
| 644 | return 0; |
| 645 | |
| 646 | return Stride; |
| 647 | } |
| 648 | |
| 649 | bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance, |
| 650 | unsigned TypeByteSize) { |
| 651 | // If loads occur at a distance that is not a multiple of a feasible vector |
| 652 | // factor store-load forwarding does not take place. |
| 653 | // Positive dependences might cause troubles because vectorizing them might |
| 654 | // prevent store-load forwarding making vectorized code run a lot slower. |
| 655 | // a[i] = a[i-3] ^ a[i-8]; |
| 656 | // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and |
| 657 | // hence on your typical architecture store-load forwarding does not take |
| 658 | // place. Vectorizing in such cases does not make sense. |
| 659 | // Store-load forwarding distance. |
| 660 | const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize; |
| 661 | // Maximum vector factor. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 662 | unsigned MaxVFWithoutSLForwardIssues = |
| 663 | VectorizerParams::MaxVectorWidth * TypeByteSize; |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 664 | if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 665 | MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes; |
| 666 | |
| 667 | for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues; |
| 668 | vf *= 2) { |
| 669 | if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) { |
| 670 | MaxVFWithoutSLForwardIssues = (vf >>=1); |
| 671 | break; |
| 672 | } |
| 673 | } |
| 674 | |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 675 | if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) { |
| 676 | DEBUG(dbgs() << "LV: Distance " << Distance << |
| 677 | " that could cause a store-load forwarding conflict\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 678 | return true; |
| 679 | } |
| 680 | |
| 681 | if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes && |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 682 | MaxVFWithoutSLForwardIssues != |
| 683 | VectorizerParams::MaxVectorWidth * TypeByteSize) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 684 | MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues; |
| 685 | return false; |
| 686 | } |
| 687 | |
| 688 | bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx, |
| 689 | const MemAccessInfo &B, unsigned BIdx, |
| 690 | ValueToValueMap &Strides) { |
| 691 | assert (AIdx < BIdx && "Must pass arguments in program order"); |
| 692 | |
| 693 | Value *APtr = A.getPointer(); |
| 694 | Value *BPtr = B.getPointer(); |
| 695 | bool AIsWrite = A.getInt(); |
| 696 | bool BIsWrite = B.getInt(); |
| 697 | |
| 698 | // Two reads are independent. |
| 699 | if (!AIsWrite && !BIsWrite) |
| 700 | return false; |
| 701 | |
| 702 | // We cannot check pointers in different address spaces. |
| 703 | if (APtr->getType()->getPointerAddressSpace() != |
| 704 | BPtr->getType()->getPointerAddressSpace()) |
| 705 | return true; |
| 706 | |
| 707 | const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr); |
| 708 | const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr); |
| 709 | |
| 710 | int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides); |
| 711 | int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides); |
| 712 | |
| 713 | const SCEV *Src = AScev; |
| 714 | const SCEV *Sink = BScev; |
| 715 | |
| 716 | // If the induction step is negative we have to invert source and sink of the |
| 717 | // dependence. |
| 718 | if (StrideAPtr < 0) { |
| 719 | //Src = BScev; |
| 720 | //Sink = AScev; |
| 721 | std::swap(APtr, BPtr); |
| 722 | std::swap(Src, Sink); |
| 723 | std::swap(AIsWrite, BIsWrite); |
| 724 | std::swap(AIdx, BIdx); |
| 725 | std::swap(StrideAPtr, StrideBPtr); |
| 726 | } |
| 727 | |
| 728 | const SCEV *Dist = SE->getMinusSCEV(Sink, Src); |
| 729 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 730 | DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 731 | << "(Induction step: " << StrideAPtr << ")\n"); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 732 | DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 733 | << *InstMap[BIdx] << ": " << *Dist << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 734 | |
| 735 | // Need consecutive accesses. We don't want to vectorize |
| 736 | // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in |
| 737 | // the address space. |
| 738 | if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){ |
| 739 | DEBUG(dbgs() << "Non-consecutive pointer access\n"); |
| 740 | return true; |
| 741 | } |
| 742 | |
| 743 | const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist); |
| 744 | if (!C) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 745 | DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 746 | ShouldRetryWithRuntimeCheck = true; |
| 747 | return true; |
| 748 | } |
| 749 | |
| 750 | Type *ATy = APtr->getType()->getPointerElementType(); |
| 751 | Type *BTy = BPtr->getType()->getPointerElementType(); |
| 752 | unsigned TypeByteSize = DL->getTypeAllocSize(ATy); |
| 753 | |
| 754 | // Negative distances are not plausible dependencies. |
| 755 | const APInt &Val = C->getValue()->getValue(); |
| 756 | if (Val.isNegative()) { |
| 757 | bool IsTrueDataDependence = (AIsWrite && !BIsWrite); |
| 758 | if (IsTrueDataDependence && |
| 759 | (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) || |
| 760 | ATy != BTy)) |
| 761 | return true; |
| 762 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 763 | DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 764 | return false; |
| 765 | } |
| 766 | |
| 767 | // Write to the same location with the same size. |
| 768 | // Could be improved to assert type sizes are the same (i32 == float, etc). |
| 769 | if (Val == 0) { |
| 770 | if (ATy == BTy) |
| 771 | return false; |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 772 | DEBUG(dbgs() << "LV: Zero dependence difference but different types\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 773 | return true; |
| 774 | } |
| 775 | |
| 776 | assert(Val.isStrictlyPositive() && "Expect a positive value"); |
| 777 | |
| 778 | // Positive distance bigger than max vectorization factor. |
| 779 | if (ATy != BTy) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 780 | DEBUG(dbgs() << |
| 781 | "LV: ReadWrite-Write positive dependency with different types\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 782 | return false; |
| 783 | } |
| 784 | |
| 785 | unsigned Distance = (unsigned) Val.getZExtValue(); |
| 786 | |
| 787 | // Bail out early if passed-in parameters make vectorization not feasible. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 788 | unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ? |
| 789 | VectorizerParams::VectorizationFactor : 1); |
| 790 | unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ? |
| 791 | VectorizerParams::VectorizationInterleave : 1); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 792 | |
| 793 | // The distance must be bigger than the size needed for a vectorized version |
| 794 | // of the operation and the size of the vectorized operation must not be |
| 795 | // bigger than the currrent maximum size. |
| 796 | if (Distance < 2*TypeByteSize || |
| 797 | 2*TypeByteSize > MaxSafeDepDistBytes || |
| 798 | Distance < TypeByteSize * ForcedUnroll * ForcedFactor) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 799 | DEBUG(dbgs() << "LV: Failure because of Positive distance " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 800 | << Val.getSExtValue() << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 801 | return true; |
| 802 | } |
| 803 | |
| 804 | MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ? |
| 805 | Distance : MaxSafeDepDistBytes; |
| 806 | |
| 807 | bool IsTrueDataDependence = (!AIsWrite && BIsWrite); |
| 808 | if (IsTrueDataDependence && |
| 809 | couldPreventStoreLoadForward(Distance, TypeByteSize)) |
| 810 | return true; |
| 811 | |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 812 | DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() << |
| 813 | " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 814 | |
| 815 | return false; |
| 816 | } |
| 817 | |
| 818 | bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets, |
| 819 | MemAccessInfoSet &CheckDeps, |
| 820 | ValueToValueMap &Strides) { |
| 821 | |
| 822 | MaxSafeDepDistBytes = -1U; |
| 823 | while (!CheckDeps.empty()) { |
| 824 | MemAccessInfo CurAccess = *CheckDeps.begin(); |
| 825 | |
| 826 | // Get the relevant memory access set. |
| 827 | EquivalenceClasses<MemAccessInfo>::iterator I = |
| 828 | AccessSets.findValue(AccessSets.getLeaderValue(CurAccess)); |
| 829 | |
| 830 | // Check accesses within this set. |
| 831 | EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE; |
| 832 | AI = AccessSets.member_begin(I), AE = AccessSets.member_end(); |
| 833 | |
| 834 | // Check every access pair. |
| 835 | while (AI != AE) { |
| 836 | CheckDeps.erase(*AI); |
| 837 | EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI); |
| 838 | while (OI != AE) { |
| 839 | // Check every accessing instruction pair in program order. |
| 840 | for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(), |
| 841 | I1E = Accesses[*AI].end(); I1 != I1E; ++I1) |
| 842 | for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(), |
| 843 | I2E = Accesses[*OI].end(); I2 != I2E; ++I2) { |
| 844 | if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides)) |
| 845 | return false; |
| 846 | if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides)) |
| 847 | return false; |
| 848 | } |
| 849 | ++OI; |
| 850 | } |
| 851 | AI++; |
| 852 | } |
| 853 | } |
| 854 | return true; |
| 855 | } |
| 856 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 857 | bool LoopAccessInfo::canVectorizeMemory(ValueToValueMap &Strides) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 858 | |
| 859 | typedef SmallVector<Value*, 16> ValueVector; |
| 860 | typedef SmallPtrSet<Value*, 16> ValueSet; |
| 861 | |
| 862 | // Holds the Load and Store *instructions*. |
| 863 | ValueVector Loads; |
| 864 | ValueVector Stores; |
| 865 | |
| 866 | // Holds all the different accesses in the loop. |
| 867 | unsigned NumReads = 0; |
| 868 | unsigned NumReadWrites = 0; |
| 869 | |
| 870 | PtrRtCheck.Pointers.clear(); |
| 871 | PtrRtCheck.Need = false; |
| 872 | |
| 873 | const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 874 | MemoryDepChecker DepChecker(SE, DL, TheLoop); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 875 | |
| 876 | // For each block. |
| 877 | for (Loop::block_iterator bb = TheLoop->block_begin(), |
| 878 | be = TheLoop->block_end(); bb != be; ++bb) { |
| 879 | |
| 880 | // Scan the BB and collect legal loads and stores. |
| 881 | for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; |
| 882 | ++it) { |
| 883 | |
| 884 | // If this is a load, save it. If this instruction can read from memory |
| 885 | // but is not a load, then we quit. Notice that we don't handle function |
| 886 | // calls that read or write. |
| 887 | if (it->mayReadFromMemory()) { |
| 888 | // Many math library functions read the rounding mode. We will only |
| 889 | // vectorize a loop if it contains known function calls that don't set |
| 890 | // the flag. Therefore, it is safe to ignore this read from memory. |
| 891 | CallInst *Call = dyn_cast<CallInst>(it); |
| 892 | if (Call && getIntrinsicIDForCall(Call, TLI)) |
| 893 | continue; |
| 894 | |
| 895 | LoadInst *Ld = dyn_cast<LoadInst>(it); |
| 896 | if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 897 | emitAnalysis(VectorizationReport(Ld) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 898 | << "read with atomic ordering or volatile read"); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 899 | DEBUG(dbgs() << "LV: Found a non-simple load.\n"); |
| 900 | return false; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 901 | } |
| 902 | NumLoads++; |
| 903 | Loads.push_back(Ld); |
| 904 | DepChecker.addAccess(Ld); |
| 905 | continue; |
| 906 | } |
| 907 | |
| 908 | // Save 'store' instructions. Abort if other instructions write to memory. |
| 909 | if (it->mayWriteToMemory()) { |
| 910 | StoreInst *St = dyn_cast<StoreInst>(it); |
| 911 | if (!St) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 912 | emitAnalysis(VectorizationReport(it) << |
| 913 | "instruction cannot be vectorized"); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 914 | return false; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 915 | } |
| 916 | if (!St->isSimple() && !IsAnnotatedParallel) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 917 | emitAnalysis(VectorizationReport(St) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 918 | << "write with atomic ordering or volatile write"); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 919 | DEBUG(dbgs() << "LV: Found a non-simple store.\n"); |
| 920 | return false; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 921 | } |
| 922 | NumStores++; |
| 923 | Stores.push_back(St); |
| 924 | DepChecker.addAccess(St); |
| 925 | } |
| 926 | } // Next instr. |
| 927 | } // Next block. |
| 928 | |
| 929 | // Now we have two lists that hold the loads and the stores. |
| 930 | // Next, we find the pointers that they use. |
| 931 | |
| 932 | // Check if we see any stores. If there are no stores, then we don't |
| 933 | // care if the pointers are *restrict*. |
| 934 | if (!Stores.size()) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 935 | DEBUG(dbgs() << "LV: Found a read-only loop!\n"); |
| 936 | return true; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 937 | } |
| 938 | |
| 939 | AccessAnalysis::DepCandidates DependentAccesses; |
| 940 | AccessAnalysis Accesses(DL, AA, DependentAccesses); |
| 941 | |
| 942 | // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects |
| 943 | // multiple times on the same object. If the ptr is accessed twice, once |
| 944 | // for read and once for write, it will only appear once (on the write |
| 945 | // list). This is okay, since we are going to check for conflicts between |
| 946 | // writes and between reads and writes, but not between reads and reads. |
| 947 | ValueSet Seen; |
| 948 | |
| 949 | ValueVector::iterator I, IE; |
| 950 | for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) { |
| 951 | StoreInst *ST = cast<StoreInst>(*I); |
| 952 | Value* Ptr = ST->getPointerOperand(); |
| 953 | |
| 954 | if (isUniform(Ptr)) { |
| 955 | emitAnalysis( |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 956 | VectorizationReport(ST) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 957 | << "write to a loop invariant address could not be vectorized"); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 958 | DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n"); |
| 959 | return false; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 960 | } |
| 961 | |
| 962 | // If we did *not* see this pointer before, insert it to the read-write |
| 963 | // list. At this phase it is only a 'write' list. |
| 964 | if (Seen.insert(Ptr).second) { |
| 965 | ++NumReadWrites; |
| 966 | |
| 967 | AliasAnalysis::Location Loc = AA->getLocation(ST); |
| 968 | // The TBAA metadata could have a control dependency on the predication |
| 969 | // condition, so we cannot rely on it when determining whether or not we |
| 970 | // need runtime pointer checks. |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 971 | if (blockNeedsPredication(ST->getParent(), TheLoop, DT)) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 972 | Loc.AATags.TBAA = nullptr; |
| 973 | |
| 974 | Accesses.addStore(Loc); |
| 975 | } |
| 976 | } |
| 977 | |
| 978 | if (IsAnnotatedParallel) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 979 | DEBUG(dbgs() |
| 980 | << "LV: A loop annotated parallel, ignore memory dependency " |
| 981 | << "checks.\n"); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 982 | return true; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 983 | } |
| 984 | |
| 985 | for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) { |
| 986 | LoadInst *LD = cast<LoadInst>(*I); |
| 987 | Value* Ptr = LD->getPointerOperand(); |
| 988 | // If we did *not* see this pointer before, insert it to the |
| 989 | // read list. If we *did* see it before, then it is already in |
| 990 | // the read-write list. This allows us to vectorize expressions |
| 991 | // such as A[i] += x; Because the address of A[i] is a read-write |
| 992 | // pointer. This only works if the index of A[i] is consecutive. |
| 993 | // If the address of i is unknown (for example A[B[i]]) then we may |
| 994 | // read a few words, modify, and write a few words, and some of the |
| 995 | // words may be written to the same address. |
| 996 | bool IsReadOnlyPtr = false; |
| 997 | if (Seen.insert(Ptr).second || |
| 998 | !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) { |
| 999 | ++NumReads; |
| 1000 | IsReadOnlyPtr = true; |
| 1001 | } |
| 1002 | |
| 1003 | AliasAnalysis::Location Loc = AA->getLocation(LD); |
| 1004 | // The TBAA metadata could have a control dependency on the predication |
| 1005 | // condition, so we cannot rely on it when determining whether or not we |
| 1006 | // need runtime pointer checks. |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 1007 | if (blockNeedsPredication(LD->getParent(), TheLoop, DT)) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1008 | Loc.AATags.TBAA = nullptr; |
| 1009 | |
| 1010 | Accesses.addLoad(Loc, IsReadOnlyPtr); |
| 1011 | } |
| 1012 | |
| 1013 | // If we write (or read-write) to a single destination and there are no |
| 1014 | // other reads in this loop then is it safe to vectorize. |
| 1015 | if (NumReadWrites == 1 && NumReads == 0) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1016 | DEBUG(dbgs() << "LV: Found a write-only loop!\n"); |
| 1017 | return true; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1018 | } |
| 1019 | |
| 1020 | // Build dependence sets and check whether we need a runtime pointer bounds |
| 1021 | // check. |
| 1022 | Accesses.buildDependenceSets(); |
| 1023 | bool NeedRTCheck = Accesses.isRTCheckNeeded(); |
| 1024 | |
| 1025 | // Find pointers with computable bounds. We are going to use this information |
| 1026 | // to place a runtime bound check. |
| 1027 | unsigned NumComparisons = 0; |
| 1028 | bool CanDoRT = false; |
| 1029 | if (NeedRTCheck) |
| 1030 | CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop, |
| 1031 | Strides); |
| 1032 | |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1033 | DEBUG(dbgs() << "LV: We need to do " << NumComparisons << |
| 1034 | " pointer comparisons.\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1035 | |
| 1036 | // If we only have one set of dependences to check pointers among we don't |
| 1037 | // need a runtime check. |
| 1038 | if (NumComparisons == 0 && NeedRTCheck) |
| 1039 | NeedRTCheck = false; |
| 1040 | |
| 1041 | // Check that we did not collect too many pointers or found an unsizeable |
| 1042 | // pointer. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 1043 | if (!CanDoRT || |
| 1044 | NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1045 | PtrRtCheck.reset(); |
| 1046 | CanDoRT = false; |
| 1047 | } |
| 1048 | |
| 1049 | if (CanDoRT) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1050 | DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1051 | } |
| 1052 | |
| 1053 | if (NeedRTCheck && !CanDoRT) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1054 | emitAnalysis(VectorizationReport() << "cannot identify array bounds"); |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1055 | DEBUG(dbgs() << "LV: We can't vectorize because we can't find " << |
| 1056 | "the array bounds.\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1057 | PtrRtCheck.reset(); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1058 | return false; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1059 | } |
| 1060 | |
| 1061 | PtrRtCheck.Need = NeedRTCheck; |
| 1062 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1063 | bool CanVecMem = true; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1064 | if (Accesses.isDependencyCheckNeeded()) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1065 | DEBUG(dbgs() << "LV: Checking memory dependencies\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1066 | CanVecMem = DepChecker.areDepsSafe( |
| 1067 | DependentAccesses, Accesses.getDependenciesToCheck(), Strides); |
| 1068 | MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes(); |
| 1069 | |
| 1070 | if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1071 | DEBUG(dbgs() << "LV: Retrying with memory checks\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1072 | NeedRTCheck = true; |
| 1073 | |
| 1074 | // Clear the dependency checks. We assume they are not needed. |
| 1075 | Accesses.resetDepChecks(); |
| 1076 | |
| 1077 | PtrRtCheck.reset(); |
| 1078 | PtrRtCheck.Need = true; |
| 1079 | |
| 1080 | CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, |
| 1081 | TheLoop, Strides, true); |
| 1082 | // Check that we did not collect too many pointers or found an unsizeable |
| 1083 | // pointer. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 1084 | if (!CanDoRT || |
| 1085 | NumComparisons > VectorizerParams::RuntimeMemoryCheckThreshold) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1086 | if (!CanDoRT && NumComparisons > 0) |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1087 | emitAnalysis(VectorizationReport() |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1088 | << "cannot check memory dependencies at runtime"); |
| 1089 | else |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1090 | emitAnalysis(VectorizationReport() |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1091 | << NumComparisons << " exceeds limit of " |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 1092 | << VectorizerParams::RuntimeMemoryCheckThreshold |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1093 | << " dependent memory operations checked at runtime"); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1094 | DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1095 | PtrRtCheck.reset(); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1096 | return false; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1097 | } |
| 1098 | |
| 1099 | CanVecMem = true; |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | if (!CanVecMem) |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1104 | emitAnalysis(VectorizationReport() << |
| 1105 | "unsafe dependent memory operations in loop"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1106 | |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1107 | DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") << |
| 1108 | " need a runtime memory check.\n"); |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1109 | |
| 1110 | return CanVecMem; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1111 | } |
| 1112 | |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 1113 | bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, |
| 1114 | DominatorTree *DT) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1115 | assert(TheLoop->contains(BB) && "Unknown block used"); |
| 1116 | |
| 1117 | // Blocks that do not dominate the latch need predication. |
| 1118 | BasicBlock* Latch = TheLoop->getLoopLatch(); |
| 1119 | return !DT->dominates(BB, Latch); |
| 1120 | } |
| 1121 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1122 | void LoopAccessInfo::emitAnalysis(VectorizationReport &Message) { |
Adam Nemet | c922853 | 2015-02-19 19:14:56 +0000 | [diff] [blame^] | 1123 | assert(!Report && "Multiple reports generated"); |
| 1124 | Report = Message; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1125 | } |
| 1126 | |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1127 | bool LoopAccessInfo::isUniform(Value *V) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1128 | return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop)); |
| 1129 | } |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1130 | |
| 1131 | // FIXME: this function is currently a duplicate of the one in |
| 1132 | // LoopVectorize.cpp. |
| 1133 | static Instruction *getFirstInst(Instruction *FirstInst, Value *V, |
| 1134 | Instruction *Loc) { |
| 1135 | if (FirstInst) |
| 1136 | return FirstInst; |
| 1137 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 1138 | return I->getParent() == Loc->getParent() ? I : nullptr; |
| 1139 | return nullptr; |
| 1140 | } |
| 1141 | |
| 1142 | std::pair<Instruction *, Instruction *> |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1143 | LoopAccessInfo::addRuntimeCheck(Instruction *Loc) { |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1144 | Instruction *tnullptr = nullptr; |
| 1145 | if (!PtrRtCheck.Need) |
| 1146 | return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr); |
| 1147 | |
| 1148 | unsigned NumPointers = PtrRtCheck.Pointers.size(); |
| 1149 | SmallVector<TrackingVH<Value> , 2> Starts; |
| 1150 | SmallVector<TrackingVH<Value> , 2> Ends; |
| 1151 | |
| 1152 | LLVMContext &Ctx = Loc->getContext(); |
| 1153 | SCEVExpander Exp(*SE, "induction"); |
| 1154 | Instruction *FirstInst = nullptr; |
| 1155 | |
| 1156 | for (unsigned i = 0; i < NumPointers; ++i) { |
| 1157 | Value *Ptr = PtrRtCheck.Pointers[i]; |
| 1158 | const SCEV *Sc = SE->getSCEV(Ptr); |
| 1159 | |
| 1160 | if (SE->isLoopInvariant(Sc, TheLoop)) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1161 | DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" << |
| 1162 | *Ptr <<"\n"); |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1163 | Starts.push_back(Ptr); |
| 1164 | Ends.push_back(Ptr); |
| 1165 | } else { |
NAKAMURA Takumi | fa520c5 | 2015-02-18 08:34:47 +0000 | [diff] [blame] | 1166 | DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n'); |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1167 | unsigned AS = Ptr->getType()->getPointerAddressSpace(); |
| 1168 | |
| 1169 | // Use this type for pointer arithmetic. |
| 1170 | Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS); |
| 1171 | |
| 1172 | Value *Start = Exp.expandCodeFor(PtrRtCheck.Starts[i], PtrArithTy, Loc); |
| 1173 | Value *End = Exp.expandCodeFor(PtrRtCheck.Ends[i], PtrArithTy, Loc); |
| 1174 | Starts.push_back(Start); |
| 1175 | Ends.push_back(End); |
| 1176 | } |
| 1177 | } |
| 1178 | |
| 1179 | IRBuilder<> ChkBuilder(Loc); |
| 1180 | // Our instructions might fold to a constant. |
| 1181 | Value *MemoryRuntimeCheck = nullptr; |
| 1182 | for (unsigned i = 0; i < NumPointers; ++i) { |
| 1183 | for (unsigned j = i+1; j < NumPointers; ++j) { |
Adam Nemet | a8945b7 | 2015-02-18 03:43:58 +0000 | [diff] [blame] | 1184 | if (!PtrRtCheck.needsChecking(i, j)) |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1185 | continue; |
| 1186 | |
| 1187 | unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace(); |
| 1188 | unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace(); |
| 1189 | |
| 1190 | assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) && |
| 1191 | (AS1 == Ends[i]->getType()->getPointerAddressSpace()) && |
| 1192 | "Trying to bounds check pointers with different address spaces"); |
| 1193 | |
| 1194 | Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0); |
| 1195 | Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1); |
| 1196 | |
| 1197 | Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc"); |
| 1198 | Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc"); |
| 1199 | Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc"); |
| 1200 | Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc"); |
| 1201 | |
| 1202 | Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0"); |
| 1203 | FirstInst = getFirstInst(FirstInst, Cmp0, Loc); |
| 1204 | Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1"); |
| 1205 | FirstInst = getFirstInst(FirstInst, Cmp1, Loc); |
| 1206 | Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); |
| 1207 | FirstInst = getFirstInst(FirstInst, IsConflict, Loc); |
| 1208 | if (MemoryRuntimeCheck) { |
| 1209 | IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, |
| 1210 | "conflict.rdx"); |
| 1211 | FirstInst = getFirstInst(FirstInst, IsConflict, Loc); |
| 1212 | } |
| 1213 | MemoryRuntimeCheck = IsConflict; |
| 1214 | } |
| 1215 | } |
| 1216 | |
| 1217 | // We have to do this trickery because the IRBuilder might fold the check to a |
| 1218 | // constant expression in which case there is no Instruction anchored in a |
| 1219 | // the block. |
| 1220 | Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck, |
| 1221 | ConstantInt::getTrue(Ctx)); |
| 1222 | ChkBuilder.Insert(Check, "memcheck.conflict"); |
| 1223 | FirstInst = getFirstInst(FirstInst, Check, Loc); |
| 1224 | return std::make_pair(FirstInst, Check); |
| 1225 | } |