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