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" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/ValueTracking.h" |
| 20 | #include "llvm/IR/DiagnosticInfo.h" |
| 21 | #include "llvm/IR/Dominators.h" |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 22 | #include "llvm/IR/IRBuilder.h" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 23 | #include "llvm/Support/Debug.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 24 | #include "llvm/Support/raw_ostream.h" |
David Blaikie | b447ac6 | 2015-06-26 18:02:52 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/VectorUtils.h" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 26 | using namespace llvm; |
| 27 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 28 | #define DEBUG_TYPE "loop-accesses" |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 29 | |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 30 | static cl::opt<unsigned, true> |
| 31 | VectorizationFactor("force-vector-width", cl::Hidden, |
| 32 | cl::desc("Sets the SIMD width. Zero is autoselect."), |
| 33 | cl::location(VectorizerParams::VectorizationFactor)); |
Adam Nemet | 1d862af | 2015-02-26 04:39:09 +0000 | [diff] [blame] | 34 | unsigned VectorizerParams::VectorizationFactor; |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 35 | |
| 36 | static cl::opt<unsigned, true> |
| 37 | VectorizationInterleave("force-vector-interleave", cl::Hidden, |
| 38 | cl::desc("Sets the vectorization interleave count. " |
| 39 | "Zero is autoselect."), |
| 40 | cl::location( |
| 41 | VectorizerParams::VectorizationInterleave)); |
Adam Nemet | 1d862af | 2015-02-26 04:39:09 +0000 | [diff] [blame] | 42 | unsigned VectorizerParams::VectorizationInterleave; |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 43 | |
Adam Nemet | 1d862af | 2015-02-26 04:39:09 +0000 | [diff] [blame] | 44 | static cl::opt<unsigned, true> RuntimeMemoryCheckThreshold( |
| 45 | "runtime-memory-check-threshold", cl::Hidden, |
| 46 | cl::desc("When performing memory disambiguation checks at runtime do not " |
| 47 | "generate more than this number of comparisons (default = 8)."), |
| 48 | cl::location(VectorizerParams::RuntimeMemoryCheckThreshold), cl::init(8)); |
| 49 | unsigned VectorizerParams::RuntimeMemoryCheckThreshold; |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 50 | |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 51 | /// \brief The maximum iterations used to merge memory checks |
| 52 | static cl::opt<unsigned> MemoryCheckMergeThreshold( |
| 53 | "memory-check-merge-threshold", cl::Hidden, |
| 54 | cl::desc("Maximum number of comparisons done when trying to merge " |
| 55 | "runtime memory checks. (default = 100)"), |
| 56 | cl::init(100)); |
| 57 | |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 58 | /// Maximum SIMD width. |
| 59 | const unsigned VectorizerParams::MaxVectorWidth = 64; |
| 60 | |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 61 | /// \brief We collect interesting dependences up to this threshold. |
| 62 | static cl::opt<unsigned> MaxInterestingDependence( |
| 63 | "max-interesting-dependences", cl::Hidden, |
| 64 | cl::desc("Maximum number of interesting dependences collected by " |
| 65 | "loop-access analysis (default = 100)"), |
| 66 | cl::init(100)); |
| 67 | |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 68 | bool VectorizerParams::isInterleaveForced() { |
| 69 | return ::VectorizationInterleave.getNumOccurrences() > 0; |
| 70 | } |
| 71 | |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 72 | void LoopAccessReport::emitAnalysis(const LoopAccessReport &Message, |
| 73 | const Function *TheFunction, |
| 74 | const Loop *TheLoop, |
| 75 | const char *PassName) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 76 | DebugLoc DL = TheLoop->getStartLoc(); |
Adam Nemet | 3e87634 | 2015-02-19 19:15:13 +0000 | [diff] [blame] | 77 | if (const Instruction *I = Message.getInstr()) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 78 | DL = I->getDebugLoc(); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 79 | emitOptimizationRemarkAnalysis(TheFunction->getContext(), PassName, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 80 | *TheFunction, DL, Message.str()); |
| 81 | } |
| 82 | |
| 83 | Value *llvm::stripIntegerCast(Value *V) { |
| 84 | if (CastInst *CI = dyn_cast<CastInst>(V)) |
| 85 | if (CI->getOperand(0)->getType()->isIntegerTy()) |
| 86 | return CI->getOperand(0); |
| 87 | return V; |
| 88 | } |
| 89 | |
| 90 | const SCEV *llvm::replaceSymbolicStrideSCEV(ScalarEvolution *SE, |
Adam Nemet | 8bc61df | 2015-02-24 00:41:59 +0000 | [diff] [blame] | 91 | const ValueToValueMap &PtrToStride, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 92 | Value *Ptr, Value *OrigPtr) { |
| 93 | |
| 94 | const SCEV *OrigSCEV = SE->getSCEV(Ptr); |
| 95 | |
| 96 | // If there is an entry in the map return the SCEV of the pointer with the |
| 97 | // symbolic stride replaced by one. |
Adam Nemet | 8bc61df | 2015-02-24 00:41:59 +0000 | [diff] [blame] | 98 | ValueToValueMap::const_iterator SI = |
| 99 | PtrToStride.find(OrigPtr ? OrigPtr : Ptr); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 100 | if (SI != PtrToStride.end()) { |
| 101 | Value *StrideVal = SI->second; |
| 102 | |
| 103 | // Strip casts. |
| 104 | StrideVal = stripIntegerCast(StrideVal); |
| 105 | |
| 106 | // Replace symbolic stride by one. |
| 107 | Value *One = ConstantInt::get(StrideVal->getType(), 1); |
| 108 | ValueToValueMap RewriteMap; |
| 109 | RewriteMap[StrideVal] = One; |
| 110 | |
| 111 | const SCEV *ByOne = |
| 112 | SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 113 | DEBUG(dbgs() << "LAA: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 114 | << "\n"); |
| 115 | return ByOne; |
| 116 | } |
| 117 | |
| 118 | // Otherwise, just return the SCEV of the original pointer. |
| 119 | return SE->getSCEV(Ptr); |
| 120 | } |
| 121 | |
Adam Nemet | 8bc61df | 2015-02-24 00:41:59 +0000 | [diff] [blame] | 122 | void LoopAccessInfo::RuntimePointerCheck::insert( |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 123 | Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId, unsigned ASId, |
| 124 | const ValueToValueMap &Strides) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 125 | // Get the stride replaced scev. |
| 126 | const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr); |
| 127 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc); |
| 128 | assert(AR && "Invalid addrec expression"); |
| 129 | const SCEV *Ex = SE->getBackedgeTakenCount(Lp); |
| 130 | const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE); |
| 131 | Pointers.push_back(Ptr); |
| 132 | Starts.push_back(AR->getStart()); |
| 133 | Ends.push_back(ScEnd); |
| 134 | IsWritePtr.push_back(WritePtr); |
| 135 | DependencySetId.push_back(DepSetId); |
| 136 | AliasSetId.push_back(ASId); |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 137 | Exprs.push_back(Sc); |
| 138 | } |
| 139 | |
| 140 | bool LoopAccessInfo::RuntimePointerCheck::needsChecking( |
| 141 | const CheckingPtrGroup &M, const CheckingPtrGroup &N, |
| 142 | const SmallVectorImpl<int> *PtrPartition) const { |
| 143 | for (unsigned I = 0, EI = M.Members.size(); EI != I; ++I) |
| 144 | for (unsigned J = 0, EJ = N.Members.size(); EJ != J; ++J) |
| 145 | if (needsChecking(M.Members[I], N.Members[J], PtrPartition)) |
| 146 | return true; |
| 147 | return false; |
| 148 | } |
| 149 | |
| 150 | /// Compare \p I and \p J and return the minimum. |
| 151 | /// Return nullptr in case we couldn't find an answer. |
| 152 | static const SCEV *getMinFromExprs(const SCEV *I, const SCEV *J, |
| 153 | ScalarEvolution *SE) { |
| 154 | const SCEV *Diff = SE->getMinusSCEV(J, I); |
| 155 | const SCEVConstant *C = dyn_cast<const SCEVConstant>(Diff); |
| 156 | |
| 157 | if (!C) |
| 158 | return nullptr; |
| 159 | if (C->getValue()->isNegative()) |
| 160 | return J; |
| 161 | return I; |
| 162 | } |
| 163 | |
| 164 | bool LoopAccessInfo::RuntimePointerCheck::CheckingPtrGroup::addPointer( |
| 165 | unsigned Index) { |
| 166 | // Compare the starts and ends with the known minimum and maximum |
| 167 | // of this set. We need to know how we compare against the min/max |
| 168 | // of the set in order to be able to emit memchecks. |
| 169 | const SCEV *Min0 = getMinFromExprs(RtCheck.Starts[Index], Low, RtCheck.SE); |
| 170 | if (!Min0) |
| 171 | return false; |
| 172 | |
| 173 | const SCEV *Min1 = getMinFromExprs(RtCheck.Ends[Index], High, RtCheck.SE); |
| 174 | if (!Min1) |
| 175 | return false; |
| 176 | |
| 177 | // Update the low bound expression if we've found a new min value. |
| 178 | if (Min0 == RtCheck.Starts[Index]) |
| 179 | Low = RtCheck.Starts[Index]; |
| 180 | |
| 181 | // Update the high bound expression if we've found a new max value. |
| 182 | if (Min1 != RtCheck.Ends[Index]) |
| 183 | High = RtCheck.Ends[Index]; |
| 184 | |
| 185 | Members.push_back(Index); |
| 186 | return true; |
| 187 | } |
| 188 | |
| 189 | void LoopAccessInfo::RuntimePointerCheck::groupChecks( |
| 190 | MemoryDepChecker::DepCandidates &DepCands, |
| 191 | bool UseDependencies) { |
| 192 | // We build the groups from dependency candidates equivalence classes |
| 193 | // because: |
| 194 | // - We know that pointers in the same equivalence class share |
| 195 | // the same underlying object and therefore there is a chance |
| 196 | // that we can compare pointers |
| 197 | // - We wouldn't be able to merge two pointers for which we need |
| 198 | // to emit a memcheck. The classes in DepCands are already |
| 199 | // conveniently built such that no two pointers in the same |
| 200 | // class need checking against each other. |
| 201 | |
| 202 | // We use the following (greedy) algorithm to construct the groups |
| 203 | // For every pointer in the equivalence class: |
| 204 | // For each existing group: |
| 205 | // - if the difference between this pointer and the min/max bounds |
| 206 | // of the group is a constant, then make the pointer part of the |
| 207 | // group and update the min/max bounds of that group as required. |
| 208 | |
| 209 | CheckingGroups.clear(); |
| 210 | |
| 211 | // If we don't have the dependency partitions, construct a new |
| 212 | // checking pointer group for each pointer. |
| 213 | if (!UseDependencies) { |
| 214 | for (unsigned I = 0; I < Pointers.size(); ++I) |
| 215 | CheckingGroups.push_back(CheckingPtrGroup(I, *this)); |
| 216 | return; |
| 217 | } |
| 218 | |
| 219 | unsigned TotalComparisons = 0; |
| 220 | |
| 221 | DenseMap<Value *, unsigned> PositionMap; |
| 222 | for (unsigned Pointer = 0; Pointer < Pointers.size(); ++Pointer) |
| 223 | PositionMap[Pointers[Pointer]] = Pointer; |
| 224 | |
Silviu Baranga | ce3877f | 2015-07-09 15:18:25 +0000 | [diff] [blame] | 225 | // We need to keep track of what pointers we've already seen so we |
| 226 | // don't process them twice. |
| 227 | SmallSet<unsigned, 2> Seen; |
| 228 | |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 229 | // Go through all equivalence classes, get the the "pointer check groups" |
Silviu Baranga | ce3877f | 2015-07-09 15:18:25 +0000 | [diff] [blame] | 230 | // and add them to the overall solution. We use the order in which accesses |
| 231 | // appear in 'Pointers' to enforce determinism. |
| 232 | for (unsigned I = 0; I < Pointers.size(); ++I) { |
| 233 | // We've seen this pointer before, and therefore already processed |
| 234 | // its equivalence class. |
| 235 | if (Seen.count(I)) |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 236 | continue; |
| 237 | |
Silviu Baranga | ce3877f | 2015-07-09 15:18:25 +0000 | [diff] [blame] | 238 | MemoryDepChecker::MemAccessInfo Access(Pointers[I], IsWritePtr[I]); |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 239 | |
Silviu Baranga | ce3877f | 2015-07-09 15:18:25 +0000 | [diff] [blame] | 240 | SmallVector<CheckingPtrGroup, 2> Groups; |
| 241 | auto LeaderI = DepCands.findValue(DepCands.getLeaderValue(Access)); |
| 242 | |
| 243 | SmallVector<unsigned, 2> MemberIndices; |
| 244 | |
| 245 | // Get all indeces of the members of this equivalence class and sort them. |
| 246 | // This will allow us to process all accesses in the order in which they |
| 247 | // were added to the RuntimePointerCheck. |
| 248 | for (auto MI = DepCands.member_begin(LeaderI), ME = DepCands.member_end(); |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 249 | MI != ME; ++MI) { |
| 250 | unsigned Pointer = PositionMap[MI->getPointer()]; |
Silviu Baranga | ce3877f | 2015-07-09 15:18:25 +0000 | [diff] [blame] | 251 | MemberIndices.push_back(Pointer); |
| 252 | } |
| 253 | std::sort(MemberIndices.begin(), MemberIndices.end()); |
| 254 | |
| 255 | for (unsigned Pointer : MemberIndices) { |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 256 | bool Merged = false; |
Silviu Baranga | ce3877f | 2015-07-09 15:18:25 +0000 | [diff] [blame] | 257 | // Mark this pointer as seen. |
| 258 | Seen.insert(Pointer); |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 259 | |
| 260 | // Go through all the existing sets and see if we can find one |
| 261 | // which can include this pointer. |
| 262 | for (CheckingPtrGroup &Group : Groups) { |
| 263 | // Don't perform more than a certain amount of comparisons. |
| 264 | // This should limit the cost of grouping the pointers to something |
| 265 | // reasonable. If we do end up hitting this threshold, the algorithm |
| 266 | // will create separate groups for all remaining pointers. |
| 267 | if (TotalComparisons > MemoryCheckMergeThreshold) |
| 268 | break; |
| 269 | |
| 270 | TotalComparisons++; |
| 271 | |
| 272 | if (Group.addPointer(Pointer)) { |
| 273 | Merged = true; |
| 274 | break; |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | if (!Merged) |
| 279 | // We couldn't add this pointer to any existing set or the threshold |
| 280 | // for the number of comparisons has been reached. Create a new group |
| 281 | // to hold the current pointer. |
| 282 | Groups.push_back(CheckingPtrGroup(Pointer, *this)); |
| 283 | } |
| 284 | |
| 285 | // We've computed the grouped checks for this partition. |
| 286 | // Save the results and continue with the next one. |
| 287 | std::copy(Groups.begin(), Groups.end(), std::back_inserter(CheckingGroups)); |
| 288 | } |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 289 | } |
| 290 | |
Adam Nemet | ec1e2bb | 2015-03-10 18:54:26 +0000 | [diff] [blame] | 291 | bool LoopAccessInfo::RuntimePointerCheck::needsChecking( |
| 292 | unsigned I, unsigned J, const SmallVectorImpl<int> *PtrPartition) const { |
Adam Nemet | a8945b7 | 2015-02-18 03:43:58 +0000 | [diff] [blame] | 293 | // No need to check if two readonly pointers intersect. |
| 294 | if (!IsWritePtr[I] && !IsWritePtr[J]) |
| 295 | return false; |
| 296 | |
| 297 | // Only need to check pointers between two different dependency sets. |
| 298 | if (DependencySetId[I] == DependencySetId[J]) |
| 299 | return false; |
| 300 | |
| 301 | // Only need to check pointers in the same alias set. |
| 302 | if (AliasSetId[I] != AliasSetId[J]) |
| 303 | return false; |
| 304 | |
Adam Nemet | ec1e2bb | 2015-03-10 18:54:26 +0000 | [diff] [blame] | 305 | // If PtrPartition is set omit checks between pointers of the same partition. |
| 306 | // Partition number -1 means that the pointer is used in multiple partitions. |
| 307 | // In this case we can't omit the check. |
| 308 | if (PtrPartition && (*PtrPartition)[I] != -1 && |
| 309 | (*PtrPartition)[I] == (*PtrPartition)[J]) |
| 310 | return false; |
| 311 | |
Adam Nemet | a8945b7 | 2015-02-18 03:43:58 +0000 | [diff] [blame] | 312 | return true; |
| 313 | } |
| 314 | |
Adam Nemet | ec1e2bb | 2015-03-10 18:54:26 +0000 | [diff] [blame] | 315 | void LoopAccessInfo::RuntimePointerCheck::print( |
| 316 | raw_ostream &OS, unsigned Depth, |
| 317 | const SmallVectorImpl<int> *PtrPartition) const { |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 318 | |
| 319 | OS.indent(Depth) << "Run-time memory checks:\n"; |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 320 | |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 321 | unsigned N = 0; |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 322 | for (unsigned I = 0; I < CheckingGroups.size(); ++I) |
| 323 | for (unsigned J = I + 1; J < CheckingGroups.size(); ++J) |
| 324 | if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition)) { |
| 325 | OS.indent(Depth) << "Check " << N++ << ":\n"; |
| 326 | OS.indent(Depth + 2) << "Comparing group " << I << ":\n"; |
| 327 | |
| 328 | for (unsigned K = 0; K < CheckingGroups[I].Members.size(); ++K) { |
| 329 | OS.indent(Depth + 2) << *Pointers[CheckingGroups[I].Members[K]] |
| 330 | << "\n"; |
| 331 | if (PtrPartition) |
| 332 | OS << " (Partition: " |
| 333 | << (*PtrPartition)[CheckingGroups[I].Members[K]] << ")" |
| 334 | << "\n"; |
| 335 | } |
| 336 | |
| 337 | OS.indent(Depth + 2) << "Against group " << J << ":\n"; |
| 338 | |
| 339 | for (unsigned K = 0; K < CheckingGroups[J].Members.size(); ++K) { |
| 340 | OS.indent(Depth + 2) << *Pointers[CheckingGroups[J].Members[K]] |
| 341 | << "\n"; |
| 342 | if (PtrPartition) |
| 343 | OS << " (Partition: " |
| 344 | << (*PtrPartition)[CheckingGroups[J].Members[K]] << ")" |
| 345 | << "\n"; |
| 346 | } |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 347 | } |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 348 | |
| 349 | OS.indent(Depth) << "Grouped accesses:\n"; |
| 350 | for (unsigned I = 0; I < CheckingGroups.size(); ++I) { |
| 351 | OS.indent(Depth + 2) << "Group " << I << ":\n"; |
| 352 | OS.indent(Depth + 4) << "(Low: " << *CheckingGroups[I].Low |
| 353 | << " High: " << *CheckingGroups[I].High << ")\n"; |
| 354 | for (unsigned J = 0; J < CheckingGroups[I].Members.size(); ++J) { |
| 355 | OS.indent(Depth + 6) << "Member: " << *Exprs[CheckingGroups[I].Members[J]] |
| 356 | << "\n"; |
| 357 | } |
| 358 | } |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 359 | } |
| 360 | |
Silviu Baranga | 98a1371 | 2015-06-08 10:27:06 +0000 | [diff] [blame] | 361 | unsigned LoopAccessInfo::RuntimePointerCheck::getNumberOfChecks( |
Adam Nemet | 51870d1 | 2015-04-07 03:35:26 +0000 | [diff] [blame] | 362 | const SmallVectorImpl<int> *PtrPartition) const { |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 363 | |
| 364 | unsigned NumPartitions = CheckingGroups.size(); |
Silviu Baranga | 98a1371 | 2015-06-08 10:27:06 +0000 | [diff] [blame] | 365 | unsigned CheckCount = 0; |
Adam Nemet | 51870d1 | 2015-04-07 03:35:26 +0000 | [diff] [blame] | 366 | |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 367 | for (unsigned I = 0; I < NumPartitions; ++I) |
| 368 | for (unsigned J = I + 1; J < NumPartitions; ++J) |
| 369 | if (needsChecking(CheckingGroups[I], CheckingGroups[J], PtrPartition)) |
Silviu Baranga | 98a1371 | 2015-06-08 10:27:06 +0000 | [diff] [blame] | 370 | CheckCount++; |
| 371 | return CheckCount; |
| 372 | } |
| 373 | |
| 374 | bool LoopAccessInfo::RuntimePointerCheck::needsAnyChecking( |
| 375 | const SmallVectorImpl<int> *PtrPartition) const { |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 376 | unsigned NumPointers = Pointers.size(); |
| 377 | |
| 378 | for (unsigned I = 0; I < NumPointers; ++I) |
| 379 | for (unsigned J = I + 1; J < NumPointers; ++J) |
| 380 | if (needsChecking(I, J, PtrPartition)) |
| 381 | return true; |
| 382 | return false; |
Adam Nemet | 51870d1 | 2015-04-07 03:35:26 +0000 | [diff] [blame] | 383 | } |
| 384 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 385 | namespace { |
| 386 | /// \brief Analyses memory accesses in a loop. |
| 387 | /// |
| 388 | /// Checks whether run time pointer checks are needed and builds sets for data |
| 389 | /// dependence checking. |
| 390 | class AccessAnalysis { |
| 391 | public: |
| 392 | /// \brief Read or write access location. |
| 393 | typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; |
| 394 | typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet; |
| 395 | |
Adam Nemet | e2b885c | 2015-04-23 20:09:20 +0000 | [diff] [blame] | 396 | AccessAnalysis(const DataLayout &Dl, AliasAnalysis *AA, LoopInfo *LI, |
Adam Nemet | dee666b | 2015-03-10 17:40:34 +0000 | [diff] [blame] | 397 | MemoryDepChecker::DepCandidates &DA) |
Adam Nemet | 5dc3b2c | 2015-07-09 06:47:18 +0000 | [diff] [blame] | 398 | : DL(Dl), AST(*AA), LI(LI), DepCands(DA), |
| 399 | IsRTCheckAnalysisNeeded(false) {} |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 400 | |
| 401 | /// \brief Register a load and whether it is only read from. |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 402 | void addLoad(MemoryLocation &Loc, bool IsReadOnly) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 403 | Value *Ptr = const_cast<Value*>(Loc.Ptr); |
Chandler Carruth | ecbd168 | 2015-06-17 07:21:38 +0000 | [diff] [blame] | 404 | AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 405 | Accesses.insert(MemAccessInfo(Ptr, false)); |
| 406 | if (IsReadOnly) |
| 407 | ReadOnlyPtr.insert(Ptr); |
| 408 | } |
| 409 | |
| 410 | /// \brief Register a store. |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 411 | void addStore(MemoryLocation &Loc) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 412 | Value *Ptr = const_cast<Value*>(Loc.Ptr); |
Chandler Carruth | ecbd168 | 2015-06-17 07:21:38 +0000 | [diff] [blame] | 413 | AST.add(Ptr, MemoryLocation::UnknownSize, Loc.AATags); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 414 | Accesses.insert(MemAccessInfo(Ptr, true)); |
| 415 | } |
| 416 | |
| 417 | /// \brief Check whether we can check the pointers at runtime for |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 418 | /// non-intersection. |
| 419 | /// |
| 420 | /// Returns true if we need no check or if we do and we can generate them |
| 421 | /// (i.e. the pointers have computable bounds). |
Adam Nemet | 30f16e1 | 2015-02-18 03:42:35 +0000 | [diff] [blame] | 422 | bool canCheckPtrAtRT(LoopAccessInfo::RuntimePointerCheck &RtCheck, |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 423 | ScalarEvolution *SE, Loop *TheLoop, |
Silviu Baranga | 98a1371 | 2015-06-08 10:27:06 +0000 | [diff] [blame] | 424 | const ValueToValueMap &Strides, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 425 | bool ShouldCheckStride = false); |
| 426 | |
| 427 | /// \brief Goes over all memory accesses, checks whether a RT check is needed |
| 428 | /// and builds sets of dependent accesses. |
| 429 | void buildDependenceSets() { |
| 430 | processMemAccesses(); |
| 431 | } |
| 432 | |
Adam Nemet | 5dc3b2c | 2015-07-09 06:47:18 +0000 | [diff] [blame] | 433 | /// \brief Initial processing of memory accesses determined that we need to |
| 434 | /// perform dependency checking. |
| 435 | /// |
| 436 | /// Note that this can later be cleared if we retry memcheck analysis without |
| 437 | /// dependency checking (i.e. ShouldRetryWithRuntimeCheck). |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 438 | bool isDependencyCheckNeeded() { return !CheckDeps.empty(); } |
Adam Nemet | df3dc5b | 2015-05-18 15:37:03 +0000 | [diff] [blame] | 439 | |
| 440 | /// We decided that no dependence analysis would be used. Reset the state. |
| 441 | void resetDepChecks(MemoryDepChecker &DepChecker) { |
| 442 | CheckDeps.clear(); |
| 443 | DepChecker.clearInterestingDependences(); |
| 444 | } |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 445 | |
| 446 | MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; } |
| 447 | |
| 448 | private: |
| 449 | typedef SetVector<MemAccessInfo> PtrAccessSet; |
| 450 | |
| 451 | /// \brief Go over all memory access and check whether runtime pointer checks |
Adam Nemet | b41d2d3 | 2015-07-09 06:47:21 +0000 | [diff] [blame] | 452 | /// are needed and build sets of dependency check candidates. |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 453 | void processMemAccesses(); |
| 454 | |
| 455 | /// Set of all accesses. |
| 456 | PtrAccessSet Accesses; |
| 457 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 458 | const DataLayout &DL; |
| 459 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 460 | /// Set of accesses that need a further dependence check. |
| 461 | MemAccessInfoSet CheckDeps; |
| 462 | |
| 463 | /// Set of pointers that are read only. |
| 464 | SmallPtrSet<Value*, 16> ReadOnlyPtr; |
| 465 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 466 | /// An alias set tracker to partition the access set by underlying object and |
| 467 | //intrinsic property (such as TBAA metadata). |
| 468 | AliasSetTracker AST; |
| 469 | |
Adam Nemet | e2b885c | 2015-04-23 20:09:20 +0000 | [diff] [blame] | 470 | LoopInfo *LI; |
| 471 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 472 | /// Sets of potentially dependent accesses - members of one set share an |
| 473 | /// underlying pointer. The set "CheckDeps" identfies which sets really need a |
| 474 | /// dependence check. |
Adam Nemet | dee666b | 2015-03-10 17:40:34 +0000 | [diff] [blame] | 475 | MemoryDepChecker::DepCandidates &DepCands; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 476 | |
Adam Nemet | 5dc3b2c | 2015-07-09 06:47:18 +0000 | [diff] [blame] | 477 | /// \brief Initial processing of memory accesses determined that we may need |
| 478 | /// to add memchecks. Perform the analysis to determine the necessary checks. |
| 479 | /// |
| 480 | /// Note that, this is different from isDependencyCheckNeeded. When we retry |
| 481 | /// memcheck analysis without dependency checking |
| 482 | /// (i.e. ShouldRetryWithRuntimeCheck), isDependencyCheckNeeded is cleared |
| 483 | /// while this remains set if we have potentially dependent accesses. |
| 484 | bool IsRTCheckAnalysisNeeded; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 485 | }; |
| 486 | |
| 487 | } // end anonymous namespace |
| 488 | |
| 489 | /// \brief Check whether a pointer can participate in a runtime bounds check. |
Adam Nemet | 8bc61df | 2015-02-24 00:41:59 +0000 | [diff] [blame] | 490 | static bool hasComputableBounds(ScalarEvolution *SE, |
| 491 | const ValueToValueMap &Strides, Value *Ptr) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 492 | const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr); |
| 493 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); |
| 494 | if (!AR) |
| 495 | return false; |
| 496 | |
| 497 | return AR->isAffine(); |
| 498 | } |
| 499 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 500 | bool AccessAnalysis::canCheckPtrAtRT( |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 501 | LoopAccessInfo::RuntimePointerCheck &RtCheck, ScalarEvolution *SE, |
| 502 | Loop *TheLoop, const ValueToValueMap &StridesMap, bool ShouldCheckStride) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 503 | // Find pointers with computable bounds. We are going to use this information |
| 504 | // to place a runtime bound check. |
| 505 | bool CanDoRT = true; |
| 506 | |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 507 | bool NeedRTCheck = false; |
Adam Nemet | 5dc3b2c | 2015-07-09 06:47:18 +0000 | [diff] [blame] | 508 | if (!IsRTCheckAnalysisNeeded) return true; |
Silviu Baranga | 98a1371 | 2015-06-08 10:27:06 +0000 | [diff] [blame] | 509 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 510 | bool IsDepCheckNeeded = isDependencyCheckNeeded(); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 511 | |
| 512 | // We assign a consecutive id to access from different alias sets. |
| 513 | // Accesses between different groups doesn't need to be checked. |
| 514 | unsigned ASId = 1; |
| 515 | for (auto &AS : AST) { |
Adam Nemet | 424edc6 | 2015-07-08 22:58:48 +0000 | [diff] [blame] | 516 | int NumReadPtrChecks = 0; |
| 517 | int NumWritePtrChecks = 0; |
| 518 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 519 | // We assign consecutive id to access from different dependence sets. |
| 520 | // Accesses within the same set don't need a runtime check. |
| 521 | unsigned RunningDepId = 1; |
| 522 | DenseMap<Value *, unsigned> DepSetId; |
| 523 | |
| 524 | for (auto A : AS) { |
| 525 | Value *Ptr = A.getValue(); |
| 526 | bool IsWrite = Accesses.count(MemAccessInfo(Ptr, true)); |
| 527 | MemAccessInfo Access(Ptr, IsWrite); |
| 528 | |
Adam Nemet | 424edc6 | 2015-07-08 22:58:48 +0000 | [diff] [blame] | 529 | if (IsWrite) |
| 530 | ++NumWritePtrChecks; |
| 531 | else |
| 532 | ++NumReadPtrChecks; |
| 533 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 534 | if (hasComputableBounds(SE, StridesMap, Ptr) && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 535 | // When we run after a failing dependency check we have to make sure |
| 536 | // we don't have wrapping pointers. |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 537 | (!ShouldCheckStride || |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 538 | isStridedPtr(SE, Ptr, TheLoop, StridesMap) == 1)) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 539 | // The id of the dependence set. |
| 540 | unsigned DepId; |
| 541 | |
| 542 | if (IsDepCheckNeeded) { |
| 543 | Value *Leader = DepCands.getLeaderValue(Access).getPointer(); |
| 544 | unsigned &LeaderId = DepSetId[Leader]; |
| 545 | if (!LeaderId) |
| 546 | LeaderId = RunningDepId++; |
| 547 | DepId = LeaderId; |
| 548 | } else |
| 549 | // Each access has its own dependence set. |
| 550 | DepId = RunningDepId++; |
| 551 | |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 552 | RtCheck.insert(TheLoop, Ptr, IsWrite, DepId, ASId, StridesMap); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 553 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 554 | DEBUG(dbgs() << "LAA: Found a runtime check ptr:" << *Ptr << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 555 | } else { |
Adam Nemet | f10ca27 | 2015-05-18 15:36:52 +0000 | [diff] [blame] | 556 | DEBUG(dbgs() << "LAA: Can't find bounds for ptr:" << *Ptr << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 557 | CanDoRT = false; |
| 558 | } |
| 559 | } |
| 560 | |
Adam Nemet | 424edc6 | 2015-07-08 22:58:48 +0000 | [diff] [blame] | 561 | // If we have at least two writes or one write and a read then we need to |
| 562 | // check them. But there is no need to checks if there is only one |
| 563 | // dependence set for this alias set. |
| 564 | // |
| 565 | // Note that this function computes CanDoRT and NeedRTCheck independently. |
| 566 | // For example CanDoRT=false, NeedRTCheck=false means that we have a pointer |
| 567 | // for which we couldn't find the bounds but we don't actually need to emit |
| 568 | // any checks so it does not matter. |
| 569 | if (!(IsDepCheckNeeded && CanDoRT && RunningDepId == 2)) |
| 570 | NeedRTCheck |= (NumWritePtrChecks >= 2 || (NumReadPtrChecks >= 1 && |
| 571 | NumWritePtrChecks >= 1)); |
| 572 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 573 | ++ASId; |
| 574 | } |
| 575 | |
| 576 | // If the pointers that we would use for the bounds comparison have different |
| 577 | // address spaces, assume the values aren't directly comparable, so we can't |
| 578 | // use them for the runtime check. We also have to assume they could |
| 579 | // overlap. In the future there should be metadata for whether address spaces |
| 580 | // are disjoint. |
| 581 | unsigned NumPointers = RtCheck.Pointers.size(); |
| 582 | for (unsigned i = 0; i < NumPointers; ++i) { |
| 583 | for (unsigned j = i + 1; j < NumPointers; ++j) { |
| 584 | // Only need to check pointers between two different dependency sets. |
| 585 | if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j]) |
| 586 | continue; |
| 587 | // Only need to check pointers in the same alias set. |
| 588 | if (RtCheck.AliasSetId[i] != RtCheck.AliasSetId[j]) |
| 589 | continue; |
| 590 | |
| 591 | Value *PtrI = RtCheck.Pointers[i]; |
| 592 | Value *PtrJ = RtCheck.Pointers[j]; |
| 593 | |
| 594 | unsigned ASi = PtrI->getType()->getPointerAddressSpace(); |
| 595 | unsigned ASj = PtrJ->getType()->getPointerAddressSpace(); |
| 596 | if (ASi != ASj) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 597 | DEBUG(dbgs() << "LAA: Runtime check would require comparison between" |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 598 | " different address spaces\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 599 | return false; |
| 600 | } |
| 601 | } |
| 602 | } |
| 603 | |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 604 | if (NeedRTCheck && CanDoRT) |
| 605 | RtCheck.groupChecks(DepCands, IsDepCheckNeeded); |
| 606 | |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 607 | DEBUG(dbgs() << "LAA: We need to do " << RtCheck.getNumberOfChecks(nullptr) |
| 608 | << " pointer comparisons.\n"); |
| 609 | |
| 610 | RtCheck.Need = NeedRTCheck; |
| 611 | |
| 612 | bool CanDoRTIfNeeded = !NeedRTCheck || CanDoRT; |
| 613 | if (!CanDoRTIfNeeded) |
| 614 | RtCheck.reset(); |
| 615 | return CanDoRTIfNeeded; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 616 | } |
| 617 | |
| 618 | void AccessAnalysis::processMemAccesses() { |
| 619 | // We process the set twice: first we process read-write pointers, last we |
| 620 | // process read-only pointers. This allows us to skip dependence tests for |
| 621 | // read-only pointers. |
| 622 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 623 | DEBUG(dbgs() << "LAA: Processing memory accesses...\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 624 | DEBUG(dbgs() << " AST: "; AST.dump()); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 625 | DEBUG(dbgs() << "LAA: Accesses(" << Accesses.size() << "):\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 626 | DEBUG({ |
| 627 | for (auto A : Accesses) |
| 628 | dbgs() << "\t" << *A.getPointer() << " (" << |
| 629 | (A.getInt() ? "write" : (ReadOnlyPtr.count(A.getPointer()) ? |
| 630 | "read-only" : "read")) << ")\n"; |
| 631 | }); |
| 632 | |
| 633 | // The AliasSetTracker has nicely partitioned our pointers by metadata |
| 634 | // compatibility and potential for underlying-object overlap. As a result, we |
| 635 | // only need to check for potential pointer dependencies within each alias |
| 636 | // set. |
| 637 | for (auto &AS : AST) { |
| 638 | // Note that both the alias-set tracker and the alias sets themselves used |
| 639 | // linked lists internally and so the iteration order here is deterministic |
| 640 | // (matching the original instruction order within each set). |
| 641 | |
| 642 | bool SetHasWrite = false; |
| 643 | |
| 644 | // Map of pointers to last access encountered. |
| 645 | typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap; |
| 646 | UnderlyingObjToAccessMap ObjToLastAccess; |
| 647 | |
| 648 | // Set of access to check after all writes have been processed. |
| 649 | PtrAccessSet DeferredAccesses; |
| 650 | |
| 651 | // Iterate over each alias set twice, once to process read/write pointers, |
| 652 | // and then to process read-only pointers. |
| 653 | for (int SetIteration = 0; SetIteration < 2; ++SetIteration) { |
| 654 | bool UseDeferred = SetIteration > 0; |
| 655 | PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses; |
| 656 | |
| 657 | for (auto AV : AS) { |
| 658 | Value *Ptr = AV.getValue(); |
| 659 | |
| 660 | // For a single memory access in AliasSetTracker, Accesses may contain |
| 661 | // both read and write, and they both need to be handled for CheckDeps. |
| 662 | for (auto AC : S) { |
| 663 | if (AC.getPointer() != Ptr) |
| 664 | continue; |
| 665 | |
| 666 | bool IsWrite = AC.getInt(); |
| 667 | |
| 668 | // If we're using the deferred access set, then it contains only |
| 669 | // reads. |
| 670 | bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite; |
| 671 | if (UseDeferred && !IsReadOnlyPtr) |
| 672 | continue; |
| 673 | // Otherwise, the pointer must be in the PtrAccessSet, either as a |
| 674 | // read or a write. |
| 675 | assert(((IsReadOnlyPtr && UseDeferred) || IsWrite || |
| 676 | S.count(MemAccessInfo(Ptr, false))) && |
| 677 | "Alias-set pointer not in the access set?"); |
| 678 | |
| 679 | MemAccessInfo Access(Ptr, IsWrite); |
| 680 | DepCands.insert(Access); |
| 681 | |
| 682 | // Memorize read-only pointers for later processing and skip them in |
| 683 | // the first round (they need to be checked after we have seen all |
| 684 | // write pointers). Note: we also mark pointer that are not |
| 685 | // consecutive as "read-only" pointers (so that we check |
| 686 | // "a[b[i]] +="). Hence, we need the second check for "!IsWrite". |
| 687 | if (!UseDeferred && IsReadOnlyPtr) { |
| 688 | DeferredAccesses.insert(Access); |
| 689 | continue; |
| 690 | } |
| 691 | |
| 692 | // If this is a write - check other reads and writes for conflicts. If |
| 693 | // this is a read only check other writes for conflicts (but only if |
| 694 | // there is no other write to the ptr - this is an optimization to |
| 695 | // catch "a[i] = a[i] + " without having to do a dependence check). |
| 696 | if ((IsWrite || IsReadOnlyPtr) && SetHasWrite) { |
| 697 | CheckDeps.insert(Access); |
Adam Nemet | 5dc3b2c | 2015-07-09 06:47:18 +0000 | [diff] [blame] | 698 | IsRTCheckAnalysisNeeded = true; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 699 | } |
| 700 | |
| 701 | if (IsWrite) |
| 702 | SetHasWrite = true; |
| 703 | |
| 704 | // Create sets of pointers connected by a shared alias set and |
| 705 | // underlying object. |
| 706 | typedef SmallVector<Value *, 16> ValueVector; |
| 707 | ValueVector TempObjects; |
Adam Nemet | e2b885c | 2015-04-23 20:09:20 +0000 | [diff] [blame] | 708 | |
| 709 | GetUnderlyingObjects(Ptr, TempObjects, DL, LI); |
| 710 | DEBUG(dbgs() << "Underlying objects for pointer " << *Ptr << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 711 | for (Value *UnderlyingObj : TempObjects) { |
| 712 | UnderlyingObjToAccessMap::iterator Prev = |
| 713 | ObjToLastAccess.find(UnderlyingObj); |
| 714 | if (Prev != ObjToLastAccess.end()) |
| 715 | DepCands.unionSets(Access, Prev->second); |
| 716 | |
| 717 | ObjToLastAccess[UnderlyingObj] = Access; |
Adam Nemet | e2b885c | 2015-04-23 20:09:20 +0000 | [diff] [blame] | 718 | DEBUG(dbgs() << " " << *UnderlyingObj << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 719 | } |
| 720 | } |
| 721 | } |
| 722 | } |
| 723 | } |
| 724 | } |
| 725 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 726 | static bool isInBoundsGep(Value *Ptr) { |
| 727 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) |
| 728 | return GEP->isInBounds(); |
| 729 | return false; |
| 730 | } |
| 731 | |
Adam Nemet | c4866d2 | 2015-06-26 17:25:43 +0000 | [diff] [blame] | 732 | /// \brief Return true if an AddRec pointer \p Ptr is unsigned non-wrapping, |
| 733 | /// i.e. monotonically increasing/decreasing. |
| 734 | static bool isNoWrapAddRec(Value *Ptr, const SCEVAddRecExpr *AR, |
| 735 | ScalarEvolution *SE, const Loop *L) { |
| 736 | // FIXME: This should probably only return true for NUW. |
| 737 | if (AR->getNoWrapFlags(SCEV::NoWrapMask)) |
| 738 | return true; |
| 739 | |
| 740 | // Scalar evolution does not propagate the non-wrapping flags to values that |
| 741 | // are derived from a non-wrapping induction variable because non-wrapping |
| 742 | // could be flow-sensitive. |
| 743 | // |
| 744 | // Look through the potentially overflowing instruction to try to prove |
| 745 | // non-wrapping for the *specific* value of Ptr. |
| 746 | |
| 747 | // The arithmetic implied by an inbounds GEP can't overflow. |
| 748 | auto *GEP = dyn_cast<GetElementPtrInst>(Ptr); |
| 749 | if (!GEP || !GEP->isInBounds()) |
| 750 | return false; |
| 751 | |
| 752 | // Make sure there is only one non-const index and analyze that. |
| 753 | Value *NonConstIndex = nullptr; |
| 754 | for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index) |
| 755 | if (!isa<ConstantInt>(*Index)) { |
| 756 | if (NonConstIndex) |
| 757 | return false; |
| 758 | NonConstIndex = *Index; |
| 759 | } |
| 760 | if (!NonConstIndex) |
| 761 | // The recurrence is on the pointer, ignore for now. |
| 762 | return false; |
| 763 | |
| 764 | // The index in GEP is signed. It is non-wrapping if it's derived from a NSW |
| 765 | // AddRec using a NSW operation. |
| 766 | if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(NonConstIndex)) |
| 767 | if (OBO->hasNoSignedWrap() && |
| 768 | // Assume constant for other the operand so that the AddRec can be |
| 769 | // easily found. |
| 770 | isa<ConstantInt>(OBO->getOperand(1))) { |
| 771 | auto *OpScev = SE->getSCEV(OBO->getOperand(0)); |
| 772 | |
| 773 | if (auto *OpAR = dyn_cast<SCEVAddRecExpr>(OpScev)) |
| 774 | return OpAR->getLoop() == L && OpAR->getNoWrapFlags(SCEV::FlagNSW); |
| 775 | } |
| 776 | |
| 777 | return false; |
| 778 | } |
| 779 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 780 | /// \brief Check whether the access through \p Ptr has a constant stride. |
Hao Liu | 32c0539 | 2015-06-08 06:39:56 +0000 | [diff] [blame] | 781 | int llvm::isStridedPtr(ScalarEvolution *SE, Value *Ptr, const Loop *Lp, |
| 782 | const ValueToValueMap &StridesMap) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 783 | const Type *Ty = Ptr->getType(); |
| 784 | assert(Ty->isPointerTy() && "Unexpected non-ptr"); |
| 785 | |
| 786 | // Make sure that the pointer does not point to aggregate types. |
| 787 | const PointerType *PtrTy = cast<PointerType>(Ty); |
| 788 | if (PtrTy->getElementType()->isAggregateType()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 789 | DEBUG(dbgs() << "LAA: Bad stride - Not a pointer to a scalar type" |
| 790 | << *Ptr << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 791 | return 0; |
| 792 | } |
| 793 | |
| 794 | const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr); |
| 795 | |
| 796 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); |
| 797 | if (!AR) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 798 | DEBUG(dbgs() << "LAA: Bad stride - Not an AddRecExpr pointer " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 799 | << *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 800 | return 0; |
| 801 | } |
| 802 | |
| 803 | // The accesss function must stride over the innermost loop. |
| 804 | if (Lp != AR->getLoop()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 805 | DEBUG(dbgs() << "LAA: Bad stride - Not striding over innermost loop " << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 806 | *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 807 | } |
| 808 | |
| 809 | // The address calculation must not wrap. Otherwise, a dependence could be |
| 810 | // inverted. |
| 811 | // An inbounds getelementptr that is a AddRec with a unit stride |
| 812 | // cannot wrap per definition. The unit stride requirement is checked later. |
| 813 | // An getelementptr without an inbounds attribute and unit stride would have |
| 814 | // to access the pointer value "0" which is undefined behavior in address |
| 815 | // space 0, therefore we can also vectorize this case. |
| 816 | bool IsInBoundsGEP = isInBoundsGep(Ptr); |
Adam Nemet | c4866d2 | 2015-06-26 17:25:43 +0000 | [diff] [blame] | 817 | bool IsNoWrapAddRec = isNoWrapAddRec(Ptr, AR, SE, Lp); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 818 | bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0; |
| 819 | if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 820 | DEBUG(dbgs() << "LAA: Bad stride - Pointer may wrap in the address space " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 821 | << *Ptr << " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 822 | return 0; |
| 823 | } |
| 824 | |
| 825 | // Check the step is constant. |
| 826 | const SCEV *Step = AR->getStepRecurrence(*SE); |
| 827 | |
Adam Nemet | 943befe | 2015-07-09 00:03:22 +0000 | [diff] [blame] | 828 | // Calculate the pointer stride and check if it is constant. |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 829 | const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); |
| 830 | if (!C) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 831 | DEBUG(dbgs() << "LAA: Bad stride - Not a constant strided " << *Ptr << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 832 | " SCEV: " << *PtrScev << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 833 | return 0; |
| 834 | } |
| 835 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 836 | auto &DL = Lp->getHeader()->getModule()->getDataLayout(); |
| 837 | int64_t Size = DL.getTypeAllocSize(PtrTy->getElementType()); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 838 | const APInt &APStepVal = C->getValue()->getValue(); |
| 839 | |
| 840 | // Huge step value - give up. |
| 841 | if (APStepVal.getBitWidth() > 64) |
| 842 | return 0; |
| 843 | |
| 844 | int64_t StepVal = APStepVal.getSExtValue(); |
| 845 | |
| 846 | // Strided access. |
| 847 | int64_t Stride = StepVal / Size; |
| 848 | int64_t Rem = StepVal % Size; |
| 849 | if (Rem) |
| 850 | return 0; |
| 851 | |
| 852 | // If the SCEV could wrap but we have an inbounds gep with a unit stride we |
| 853 | // know we can't "wrap around the address space". In case of address space |
| 854 | // zero we know that this won't happen without triggering undefined behavior. |
| 855 | if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) && |
| 856 | Stride != 1 && Stride != -1) |
| 857 | return 0; |
| 858 | |
| 859 | return Stride; |
| 860 | } |
| 861 | |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 862 | bool MemoryDepChecker::Dependence::isSafeForVectorization(DepType Type) { |
| 863 | switch (Type) { |
| 864 | case NoDep: |
| 865 | case Forward: |
| 866 | case BackwardVectorizable: |
| 867 | return true; |
| 868 | |
| 869 | case Unknown: |
| 870 | case ForwardButPreventsForwarding: |
| 871 | case Backward: |
| 872 | case BackwardVectorizableButPreventsForwarding: |
| 873 | return false; |
| 874 | } |
David Majnemer | d388e93 | 2015-03-10 20:23:29 +0000 | [diff] [blame] | 875 | llvm_unreachable("unexpected DepType!"); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 876 | } |
| 877 | |
| 878 | bool MemoryDepChecker::Dependence::isInterestingDependence(DepType Type) { |
| 879 | switch (Type) { |
| 880 | case NoDep: |
| 881 | case Forward: |
| 882 | return false; |
| 883 | |
| 884 | case BackwardVectorizable: |
| 885 | case Unknown: |
| 886 | case ForwardButPreventsForwarding: |
| 887 | case Backward: |
| 888 | case BackwardVectorizableButPreventsForwarding: |
| 889 | return true; |
| 890 | } |
David Majnemer | d388e93 | 2015-03-10 20:23:29 +0000 | [diff] [blame] | 891 | llvm_unreachable("unexpected DepType!"); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 892 | } |
| 893 | |
| 894 | bool MemoryDepChecker::Dependence::isPossiblyBackward() const { |
| 895 | switch (Type) { |
| 896 | case NoDep: |
| 897 | case Forward: |
| 898 | case ForwardButPreventsForwarding: |
| 899 | return false; |
| 900 | |
| 901 | case Unknown: |
| 902 | case BackwardVectorizable: |
| 903 | case Backward: |
| 904 | case BackwardVectorizableButPreventsForwarding: |
| 905 | return true; |
| 906 | } |
David Majnemer | d388e93 | 2015-03-10 20:23:29 +0000 | [diff] [blame] | 907 | llvm_unreachable("unexpected DepType!"); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 908 | } |
| 909 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 910 | bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance, |
| 911 | unsigned TypeByteSize) { |
| 912 | // If loads occur at a distance that is not a multiple of a feasible vector |
| 913 | // factor store-load forwarding does not take place. |
| 914 | // Positive dependences might cause troubles because vectorizing them might |
| 915 | // prevent store-load forwarding making vectorized code run a lot slower. |
| 916 | // a[i] = a[i-3] ^ a[i-8]; |
| 917 | // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and |
| 918 | // hence on your typical architecture store-load forwarding does not take |
| 919 | // place. Vectorizing in such cases does not make sense. |
| 920 | // Store-load forwarding distance. |
| 921 | const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize; |
| 922 | // Maximum vector factor. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 923 | unsigned MaxVFWithoutSLForwardIssues = |
| 924 | VectorizerParams::MaxVectorWidth * TypeByteSize; |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 925 | if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 926 | MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes; |
| 927 | |
| 928 | for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues; |
| 929 | vf *= 2) { |
| 930 | if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) { |
| 931 | MaxVFWithoutSLForwardIssues = (vf >>=1); |
| 932 | break; |
| 933 | } |
| 934 | } |
| 935 | |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 936 | if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 937 | DEBUG(dbgs() << "LAA: Distance " << Distance << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 938 | " that could cause a store-load forwarding conflict\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 939 | return true; |
| 940 | } |
| 941 | |
| 942 | if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes && |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 943 | MaxVFWithoutSLForwardIssues != |
| 944 | VectorizerParams::MaxVectorWidth * TypeByteSize) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 945 | MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues; |
| 946 | return false; |
| 947 | } |
| 948 | |
Hao Liu | 751004a | 2015-06-08 04:48:37 +0000 | [diff] [blame] | 949 | /// \brief Check the dependence for two accesses with the same stride \p Stride. |
| 950 | /// \p Distance is the positive distance and \p TypeByteSize is type size in |
| 951 | /// bytes. |
| 952 | /// |
| 953 | /// \returns true if they are independent. |
| 954 | static bool areStridedAccessesIndependent(unsigned Distance, unsigned Stride, |
| 955 | unsigned TypeByteSize) { |
| 956 | assert(Stride > 1 && "The stride must be greater than 1"); |
| 957 | assert(TypeByteSize > 0 && "The type size in byte must be non-zero"); |
| 958 | assert(Distance > 0 && "The distance must be non-zero"); |
| 959 | |
| 960 | // Skip if the distance is not multiple of type byte size. |
| 961 | if (Distance % TypeByteSize) |
| 962 | return false; |
| 963 | |
| 964 | unsigned ScaledDist = Distance / TypeByteSize; |
| 965 | |
| 966 | // No dependence if the scaled distance is not multiple of the stride. |
| 967 | // E.g. |
| 968 | // for (i = 0; i < 1024 ; i += 4) |
| 969 | // A[i+2] = A[i] + 1; |
| 970 | // |
| 971 | // Two accesses in memory (scaled distance is 2, stride is 4): |
| 972 | // | A[0] | | | | A[4] | | | | |
| 973 | // | | | A[2] | | | | A[6] | | |
| 974 | // |
| 975 | // E.g. |
| 976 | // for (i = 0; i < 1024 ; i += 3) |
| 977 | // A[i+4] = A[i] + 1; |
| 978 | // |
| 979 | // Two accesses in memory (scaled distance is 4, stride is 3): |
| 980 | // | A[0] | | | A[3] | | | A[6] | | | |
| 981 | // | | | | | A[4] | | | A[7] | | |
| 982 | return ScaledDist % Stride; |
| 983 | } |
| 984 | |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 985 | MemoryDepChecker::Dependence::DepType |
| 986 | MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx, |
| 987 | const MemAccessInfo &B, unsigned BIdx, |
| 988 | const ValueToValueMap &Strides) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 989 | assert (AIdx < BIdx && "Must pass arguments in program order"); |
| 990 | |
| 991 | Value *APtr = A.getPointer(); |
| 992 | Value *BPtr = B.getPointer(); |
| 993 | bool AIsWrite = A.getInt(); |
| 994 | bool BIsWrite = B.getInt(); |
| 995 | |
| 996 | // Two reads are independent. |
| 997 | if (!AIsWrite && !BIsWrite) |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 998 | return Dependence::NoDep; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 999 | |
| 1000 | // We cannot check pointers in different address spaces. |
| 1001 | if (APtr->getType()->getPointerAddressSpace() != |
| 1002 | BPtr->getType()->getPointerAddressSpace()) |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1003 | return Dependence::Unknown; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1004 | |
| 1005 | const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr); |
| 1006 | const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr); |
| 1007 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1008 | int StrideAPtr = isStridedPtr(SE, APtr, InnermostLoop, Strides); |
| 1009 | int StrideBPtr = isStridedPtr(SE, BPtr, InnermostLoop, Strides); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1010 | |
| 1011 | const SCEV *Src = AScev; |
| 1012 | const SCEV *Sink = BScev; |
| 1013 | |
| 1014 | // If the induction step is negative we have to invert source and sink of the |
| 1015 | // dependence. |
| 1016 | if (StrideAPtr < 0) { |
| 1017 | //Src = BScev; |
| 1018 | //Sink = AScev; |
| 1019 | std::swap(APtr, BPtr); |
| 1020 | std::swap(Src, Sink); |
| 1021 | std::swap(AIsWrite, BIsWrite); |
| 1022 | std::swap(AIdx, BIdx); |
| 1023 | std::swap(StrideAPtr, StrideBPtr); |
| 1024 | } |
| 1025 | |
| 1026 | const SCEV *Dist = SE->getMinusSCEV(Sink, Src); |
| 1027 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1028 | DEBUG(dbgs() << "LAA: Src Scev: " << *Src << "Sink Scev: " << *Sink |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1029 | << "(Induction step: " << StrideAPtr << ")\n"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1030 | DEBUG(dbgs() << "LAA: Distance for " << *InstMap[AIdx] << " to " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1031 | << *InstMap[BIdx] << ": " << *Dist << "\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1032 | |
Adam Nemet | 943befe | 2015-07-09 00:03:22 +0000 | [diff] [blame] | 1033 | // Need accesses with constant stride. We don't want to vectorize |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1034 | // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in |
| 1035 | // the address space. |
| 1036 | if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){ |
Adam Nemet | 943befe | 2015-07-09 00:03:22 +0000 | [diff] [blame] | 1037 | DEBUG(dbgs() << "Pointer access with non-constant stride\n"); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1038 | return Dependence::Unknown; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1039 | } |
| 1040 | |
| 1041 | const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist); |
| 1042 | if (!C) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1043 | DEBUG(dbgs() << "LAA: Dependence because of non-constant distance\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1044 | ShouldRetryWithRuntimeCheck = true; |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1045 | return Dependence::Unknown; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1046 | } |
| 1047 | |
| 1048 | Type *ATy = APtr->getType()->getPointerElementType(); |
| 1049 | Type *BTy = BPtr->getType()->getPointerElementType(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1050 | auto &DL = InnermostLoop->getHeader()->getModule()->getDataLayout(); |
| 1051 | unsigned TypeByteSize = DL.getTypeAllocSize(ATy); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1052 | |
| 1053 | // Negative distances are not plausible dependencies. |
| 1054 | const APInt &Val = C->getValue()->getValue(); |
| 1055 | if (Val.isNegative()) { |
| 1056 | bool IsTrueDataDependence = (AIsWrite && !BIsWrite); |
| 1057 | if (IsTrueDataDependence && |
| 1058 | (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) || |
| 1059 | ATy != BTy)) |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1060 | return Dependence::ForwardButPreventsForwarding; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1061 | |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1062 | DEBUG(dbgs() << "LAA: Dependence is negative: NoDep\n"); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1063 | return Dependence::Forward; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1064 | } |
| 1065 | |
| 1066 | // Write to the same location with the same size. |
| 1067 | // Could be improved to assert type sizes are the same (i32 == float, etc). |
| 1068 | if (Val == 0) { |
| 1069 | if (ATy == BTy) |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1070 | return Dependence::NoDep; |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1071 | DEBUG(dbgs() << "LAA: Zero dependence difference but different types\n"); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1072 | return Dependence::Unknown; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1073 | } |
| 1074 | |
| 1075 | assert(Val.isStrictlyPositive() && "Expect a positive value"); |
| 1076 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1077 | if (ATy != BTy) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1078 | DEBUG(dbgs() << |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1079 | "LAA: ReadWrite-Write positive dependency with different types\n"); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1080 | return Dependence::Unknown; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1081 | } |
| 1082 | |
| 1083 | unsigned Distance = (unsigned) Val.getZExtValue(); |
| 1084 | |
Hao Liu | 751004a | 2015-06-08 04:48:37 +0000 | [diff] [blame] | 1085 | unsigned Stride = std::abs(StrideAPtr); |
| 1086 | if (Stride > 1 && |
Adam Nemet | 0131a56 | 2015-07-08 18:47:38 +0000 | [diff] [blame] | 1087 | areStridedAccessesIndependent(Distance, Stride, TypeByteSize)) { |
| 1088 | DEBUG(dbgs() << "LAA: Strided accesses are independent\n"); |
Hao Liu | 751004a | 2015-06-08 04:48:37 +0000 | [diff] [blame] | 1089 | return Dependence::NoDep; |
Adam Nemet | 0131a56 | 2015-07-08 18:47:38 +0000 | [diff] [blame] | 1090 | } |
Hao Liu | 751004a | 2015-06-08 04:48:37 +0000 | [diff] [blame] | 1091 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1092 | // Bail out early if passed-in parameters make vectorization not feasible. |
Adam Nemet | f219c64 | 2015-02-19 19:14:52 +0000 | [diff] [blame] | 1093 | unsigned ForcedFactor = (VectorizerParams::VectorizationFactor ? |
| 1094 | VectorizerParams::VectorizationFactor : 1); |
| 1095 | unsigned ForcedUnroll = (VectorizerParams::VectorizationInterleave ? |
| 1096 | VectorizerParams::VectorizationInterleave : 1); |
Hao Liu | 751004a | 2015-06-08 04:48:37 +0000 | [diff] [blame] | 1097 | // The minimum number of iterations for a vectorized/unrolled version. |
| 1098 | unsigned MinNumIter = std::max(ForcedFactor * ForcedUnroll, 2U); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1099 | |
Hao Liu | 751004a | 2015-06-08 04:48:37 +0000 | [diff] [blame] | 1100 | // It's not vectorizable if the distance is smaller than the minimum distance |
| 1101 | // needed for a vectroized/unrolled version. Vectorizing one iteration in |
| 1102 | // front needs TypeByteSize * Stride. Vectorizing the last iteration needs |
| 1103 | // TypeByteSize (No need to plus the last gap distance). |
| 1104 | // |
| 1105 | // E.g. Assume one char is 1 byte in memory and one int is 4 bytes. |
| 1106 | // foo(int *A) { |
| 1107 | // int *B = (int *)((char *)A + 14); |
| 1108 | // for (i = 0 ; i < 1024 ; i += 2) |
| 1109 | // B[i] = A[i] + 1; |
| 1110 | // } |
| 1111 | // |
| 1112 | // Two accesses in memory (stride is 2): |
| 1113 | // | A[0] | | A[2] | | A[4] | | A[6] | | |
| 1114 | // | B[0] | | B[2] | | B[4] | |
| 1115 | // |
| 1116 | // Distance needs for vectorizing iterations except the last iteration: |
| 1117 | // 4 * 2 * (MinNumIter - 1). Distance needs for the last iteration: 4. |
| 1118 | // So the minimum distance needed is: 4 * 2 * (MinNumIter - 1) + 4. |
| 1119 | // |
| 1120 | // If MinNumIter is 2, it is vectorizable as the minimum distance needed is |
| 1121 | // 12, which is less than distance. |
| 1122 | // |
| 1123 | // If MinNumIter is 4 (Say if a user forces the vectorization factor to be 4), |
| 1124 | // the minimum distance needed is 28, which is greater than distance. It is |
| 1125 | // not safe to do vectorization. |
| 1126 | unsigned MinDistanceNeeded = |
| 1127 | TypeByteSize * Stride * (MinNumIter - 1) + TypeByteSize; |
| 1128 | if (MinDistanceNeeded > Distance) { |
| 1129 | DEBUG(dbgs() << "LAA: Failure because of positive distance " << Distance |
| 1130 | << '\n'); |
| 1131 | return Dependence::Backward; |
| 1132 | } |
| 1133 | |
| 1134 | // Unsafe if the minimum distance needed is greater than max safe distance. |
| 1135 | if (MinDistanceNeeded > MaxSafeDepDistBytes) { |
| 1136 | DEBUG(dbgs() << "LAA: Failure because it needs at least " |
| 1137 | << MinDistanceNeeded << " size in bytes"); |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1138 | return Dependence::Backward; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1139 | } |
| 1140 | |
Adam Nemet | 9cc0c39 | 2015-02-26 17:58:48 +0000 | [diff] [blame] | 1141 | // Positive distance bigger than max vectorization factor. |
Hao Liu | 751004a | 2015-06-08 04:48:37 +0000 | [diff] [blame] | 1142 | // FIXME: Should use max factor instead of max distance in bytes, which could |
| 1143 | // not handle different types. |
| 1144 | // E.g. Assume one char is 1 byte in memory and one int is 4 bytes. |
| 1145 | // void foo (int *A, char *B) { |
| 1146 | // for (unsigned i = 0; i < 1024; i++) { |
| 1147 | // A[i+2] = A[i] + 1; |
| 1148 | // B[i+2] = B[i] + 1; |
| 1149 | // } |
| 1150 | // } |
| 1151 | // |
| 1152 | // This case is currently unsafe according to the max safe distance. If we |
| 1153 | // analyze the two accesses on array B, the max safe dependence distance |
| 1154 | // is 2. Then we analyze the accesses on array A, the minimum distance needed |
| 1155 | // is 8, which is less than 2 and forbidden vectorization, But actually |
| 1156 | // both A and B could be vectorized by 2 iterations. |
| 1157 | MaxSafeDepDistBytes = |
| 1158 | Distance < MaxSafeDepDistBytes ? Distance : MaxSafeDepDistBytes; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1159 | |
| 1160 | bool IsTrueDataDependence = (!AIsWrite && BIsWrite); |
| 1161 | if (IsTrueDataDependence && |
| 1162 | couldPreventStoreLoadForward(Distance, TypeByteSize)) |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1163 | return Dependence::BackwardVectorizableButPreventsForwarding; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1164 | |
Hao Liu | 751004a | 2015-06-08 04:48:37 +0000 | [diff] [blame] | 1165 | DEBUG(dbgs() << "LAA: Positive distance " << Val.getSExtValue() |
| 1166 | << " with max VF = " |
| 1167 | << MaxSafeDepDistBytes / (TypeByteSize * Stride) << '\n'); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1168 | |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1169 | return Dependence::BackwardVectorizable; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1170 | } |
| 1171 | |
Adam Nemet | dee666b | 2015-03-10 17:40:34 +0000 | [diff] [blame] | 1172 | bool MemoryDepChecker::areDepsSafe(DepCandidates &AccessSets, |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1173 | MemAccessInfoSet &CheckDeps, |
Adam Nemet | 8bc61df | 2015-02-24 00:41:59 +0000 | [diff] [blame] | 1174 | const ValueToValueMap &Strides) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1175 | |
| 1176 | MaxSafeDepDistBytes = -1U; |
| 1177 | while (!CheckDeps.empty()) { |
| 1178 | MemAccessInfo CurAccess = *CheckDeps.begin(); |
| 1179 | |
| 1180 | // Get the relevant memory access set. |
| 1181 | EquivalenceClasses<MemAccessInfo>::iterator I = |
| 1182 | AccessSets.findValue(AccessSets.getLeaderValue(CurAccess)); |
| 1183 | |
| 1184 | // Check accesses within this set. |
| 1185 | EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE; |
| 1186 | AI = AccessSets.member_begin(I), AE = AccessSets.member_end(); |
| 1187 | |
| 1188 | // Check every access pair. |
| 1189 | while (AI != AE) { |
| 1190 | CheckDeps.erase(*AI); |
| 1191 | EquivalenceClasses<MemAccessInfo>::member_iterator OI = std::next(AI); |
| 1192 | while (OI != AE) { |
| 1193 | // Check every accessing instruction pair in program order. |
| 1194 | for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(), |
| 1195 | I1E = Accesses[*AI].end(); I1 != I1E; ++I1) |
| 1196 | for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(), |
| 1197 | I2E = Accesses[*OI].end(); I2 != I2E; ++I2) { |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1198 | auto A = std::make_pair(&*AI, *I1); |
| 1199 | auto B = std::make_pair(&*OI, *I2); |
| 1200 | |
| 1201 | assert(*I1 != *I2); |
| 1202 | if (*I1 > *I2) |
| 1203 | std::swap(A, B); |
| 1204 | |
| 1205 | Dependence::DepType Type = |
| 1206 | isDependent(*A.first, A.second, *B.first, B.second, Strides); |
| 1207 | SafeForVectorization &= Dependence::isSafeForVectorization(Type); |
| 1208 | |
| 1209 | // Gather dependences unless we accumulated MaxInterestingDependence |
| 1210 | // dependences. In that case return as soon as we find the first |
| 1211 | // unsafe dependence. This puts a limit on this quadratic |
| 1212 | // algorithm. |
| 1213 | if (RecordInterestingDependences) { |
| 1214 | if (Dependence::isInterestingDependence(Type)) |
| 1215 | InterestingDependences.push_back( |
| 1216 | Dependence(A.second, B.second, Type)); |
| 1217 | |
| 1218 | if (InterestingDependences.size() >= MaxInterestingDependence) { |
| 1219 | RecordInterestingDependences = false; |
| 1220 | InterestingDependences.clear(); |
| 1221 | DEBUG(dbgs() << "Too many dependences, stopped recording\n"); |
| 1222 | } |
| 1223 | } |
| 1224 | if (!RecordInterestingDependences && !SafeForVectorization) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1225 | return false; |
| 1226 | } |
| 1227 | ++OI; |
| 1228 | } |
| 1229 | AI++; |
| 1230 | } |
| 1231 | } |
Adam Nemet | 9c92657 | 2015-03-10 17:40:37 +0000 | [diff] [blame] | 1232 | |
| 1233 | DEBUG(dbgs() << "Total Interesting Dependences: " |
| 1234 | << InterestingDependences.size() << "\n"); |
| 1235 | return SafeForVectorization; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1236 | } |
| 1237 | |
Adam Nemet | ec1e2bb | 2015-03-10 18:54:26 +0000 | [diff] [blame] | 1238 | SmallVector<Instruction *, 4> |
| 1239 | MemoryDepChecker::getInstructionsForAccess(Value *Ptr, bool isWrite) const { |
| 1240 | MemAccessInfo Access(Ptr, isWrite); |
| 1241 | auto &IndexVector = Accesses.find(Access)->second; |
| 1242 | |
| 1243 | SmallVector<Instruction *, 4> Insts; |
| 1244 | std::transform(IndexVector.begin(), IndexVector.end(), |
| 1245 | std::back_inserter(Insts), |
| 1246 | [&](unsigned Idx) { return this->InstMap[Idx]; }); |
| 1247 | return Insts; |
| 1248 | } |
| 1249 | |
Adam Nemet | 58913d6 | 2015-03-10 17:40:43 +0000 | [diff] [blame] | 1250 | const char *MemoryDepChecker::Dependence::DepName[] = { |
| 1251 | "NoDep", "Unknown", "Forward", "ForwardButPreventsForwarding", "Backward", |
| 1252 | "BackwardVectorizable", "BackwardVectorizableButPreventsForwarding"}; |
| 1253 | |
| 1254 | void MemoryDepChecker::Dependence::print( |
| 1255 | raw_ostream &OS, unsigned Depth, |
| 1256 | const SmallVectorImpl<Instruction *> &Instrs) const { |
| 1257 | OS.indent(Depth) << DepName[Type] << ":\n"; |
| 1258 | OS.indent(Depth + 2) << *Instrs[Source] << " -> \n"; |
| 1259 | OS.indent(Depth + 2) << *Instrs[Destination] << "\n"; |
| 1260 | } |
| 1261 | |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1262 | bool LoopAccessInfo::canAnalyzeLoop() { |
Adam Nemet | 8dcb3b6 | 2015-04-17 22:43:10 +0000 | [diff] [blame] | 1263 | // We need to have a loop header. |
| 1264 | DEBUG(dbgs() << "LAA: Found a loop: " << |
| 1265 | TheLoop->getHeader()->getName() << '\n'); |
| 1266 | |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1267 | // We can only analyze innermost loops. |
| 1268 | if (!TheLoop->empty()) { |
Adam Nemet | 8dcb3b6 | 2015-04-17 22:43:10 +0000 | [diff] [blame] | 1269 | DEBUG(dbgs() << "LAA: loop is not the innermost loop\n"); |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1270 | emitAnalysis(LoopAccessReport() << "loop is not the innermost loop"); |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1271 | return false; |
| 1272 | } |
| 1273 | |
| 1274 | // We must have a single backedge. |
| 1275 | if (TheLoop->getNumBackEdges() != 1) { |
Adam Nemet | 8dcb3b6 | 2015-04-17 22:43:10 +0000 | [diff] [blame] | 1276 | DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n"); |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1277 | emitAnalysis( |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1278 | LoopAccessReport() << |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1279 | "loop control flow is not understood by analyzer"); |
| 1280 | return false; |
| 1281 | } |
| 1282 | |
| 1283 | // We must have a single exiting block. |
| 1284 | if (!TheLoop->getExitingBlock()) { |
Adam Nemet | 8dcb3b6 | 2015-04-17 22:43:10 +0000 | [diff] [blame] | 1285 | DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n"); |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1286 | emitAnalysis( |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1287 | LoopAccessReport() << |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1288 | "loop control flow is not understood by analyzer"); |
| 1289 | return false; |
| 1290 | } |
| 1291 | |
| 1292 | // We only handle bottom-tested loops, i.e. loop in which the condition is |
| 1293 | // checked at the end of each iteration. With that we can assume that all |
| 1294 | // instructions in the loop are executed the same number of times. |
| 1295 | if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) { |
Adam Nemet | 8dcb3b6 | 2015-04-17 22:43:10 +0000 | [diff] [blame] | 1296 | DEBUG(dbgs() << "LAA: loop control flow is not understood by analyzer\n"); |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1297 | emitAnalysis( |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1298 | LoopAccessReport() << |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1299 | "loop control flow is not understood by analyzer"); |
| 1300 | return false; |
| 1301 | } |
| 1302 | |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1303 | // ScalarEvolution needs to be able to find the exit count. |
| 1304 | const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop); |
| 1305 | if (ExitCount == SE->getCouldNotCompute()) { |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1306 | emitAnalysis(LoopAccessReport() << |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1307 | "could not determine number of loop iterations"); |
| 1308 | DEBUG(dbgs() << "LAA: SCEV could not compute the loop exit count.\n"); |
| 1309 | return false; |
| 1310 | } |
| 1311 | |
| 1312 | return true; |
| 1313 | } |
| 1314 | |
Adam Nemet | 8bc61df | 2015-02-24 00:41:59 +0000 | [diff] [blame] | 1315 | void LoopAccessInfo::analyzeLoop(const ValueToValueMap &Strides) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1316 | |
| 1317 | typedef SmallVector<Value*, 16> ValueVector; |
| 1318 | typedef SmallPtrSet<Value*, 16> ValueSet; |
| 1319 | |
| 1320 | // Holds the Load and Store *instructions*. |
| 1321 | ValueVector Loads; |
| 1322 | ValueVector Stores; |
| 1323 | |
| 1324 | // Holds all the different accesses in the loop. |
| 1325 | unsigned NumReads = 0; |
| 1326 | unsigned NumReadWrites = 0; |
| 1327 | |
| 1328 | PtrRtCheck.Pointers.clear(); |
| 1329 | PtrRtCheck.Need = false; |
| 1330 | |
| 1331 | const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1332 | |
| 1333 | // For each block. |
| 1334 | for (Loop::block_iterator bb = TheLoop->block_begin(), |
| 1335 | be = TheLoop->block_end(); bb != be; ++bb) { |
| 1336 | |
| 1337 | // Scan the BB and collect legal loads and stores. |
| 1338 | for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; |
| 1339 | ++it) { |
| 1340 | |
| 1341 | // If this is a load, save it. If this instruction can read from memory |
| 1342 | // but is not a load, then we quit. Notice that we don't handle function |
| 1343 | // calls that read or write. |
| 1344 | if (it->mayReadFromMemory()) { |
| 1345 | // Many math library functions read the rounding mode. We will only |
| 1346 | // vectorize a loop if it contains known function calls that don't set |
| 1347 | // the flag. Therefore, it is safe to ignore this read from memory. |
| 1348 | CallInst *Call = dyn_cast<CallInst>(it); |
| 1349 | if (Call && getIntrinsicIDForCall(Call, TLI)) |
| 1350 | continue; |
| 1351 | |
Michael Zolotukhin | 9b3cf60 | 2015-03-17 19:46:50 +0000 | [diff] [blame] | 1352 | // If the function has an explicit vectorized counterpart, we can safely |
| 1353 | // assume that it can be vectorized. |
| 1354 | if (Call && !Call->isNoBuiltin() && Call->getCalledFunction() && |
| 1355 | TLI->isFunctionVectorizable(Call->getCalledFunction()->getName())) |
| 1356 | continue; |
| 1357 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1358 | LoadInst *Ld = dyn_cast<LoadInst>(it); |
| 1359 | if (!Ld || (!Ld->isSimple() && !IsAnnotatedParallel)) { |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1360 | emitAnalysis(LoopAccessReport(Ld) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1361 | << "read with atomic ordering or volatile read"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1362 | DEBUG(dbgs() << "LAA: Found a non-simple load.\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1363 | CanVecMem = false; |
| 1364 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1365 | } |
| 1366 | NumLoads++; |
| 1367 | Loads.push_back(Ld); |
| 1368 | DepChecker.addAccess(Ld); |
| 1369 | continue; |
| 1370 | } |
| 1371 | |
| 1372 | // Save 'store' instructions. Abort if other instructions write to memory. |
| 1373 | if (it->mayWriteToMemory()) { |
| 1374 | StoreInst *St = dyn_cast<StoreInst>(it); |
| 1375 | if (!St) { |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1376 | emitAnalysis(LoopAccessReport(it) << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1377 | "instruction cannot be vectorized"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1378 | CanVecMem = false; |
| 1379 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1380 | } |
| 1381 | if (!St->isSimple() && !IsAnnotatedParallel) { |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1382 | emitAnalysis(LoopAccessReport(St) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1383 | << "write with atomic ordering or volatile write"); |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1384 | DEBUG(dbgs() << "LAA: Found a non-simple store.\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1385 | CanVecMem = false; |
| 1386 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1387 | } |
| 1388 | NumStores++; |
| 1389 | Stores.push_back(St); |
| 1390 | DepChecker.addAccess(St); |
| 1391 | } |
| 1392 | } // Next instr. |
| 1393 | } // Next block. |
| 1394 | |
| 1395 | // Now we have two lists that hold the loads and the stores. |
| 1396 | // Next, we find the pointers that they use. |
| 1397 | |
| 1398 | // Check if we see any stores. If there are no stores, then we don't |
| 1399 | // care if the pointers are *restrict*. |
| 1400 | if (!Stores.size()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1401 | DEBUG(dbgs() << "LAA: Found a read-only loop!\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1402 | CanVecMem = true; |
| 1403 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1404 | } |
| 1405 | |
Adam Nemet | dee666b | 2015-03-10 17:40:34 +0000 | [diff] [blame] | 1406 | MemoryDepChecker::DepCandidates DependentAccesses; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1407 | AccessAnalysis Accesses(TheLoop->getHeader()->getModule()->getDataLayout(), |
Adam Nemet | e2b885c | 2015-04-23 20:09:20 +0000 | [diff] [blame] | 1408 | AA, LI, DependentAccesses); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1409 | |
| 1410 | // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects |
| 1411 | // multiple times on the same object. If the ptr is accessed twice, once |
| 1412 | // for read and once for write, it will only appear once (on the write |
| 1413 | // list). This is okay, since we are going to check for conflicts between |
| 1414 | // writes and between reads and writes, but not between reads and reads. |
| 1415 | ValueSet Seen; |
| 1416 | |
| 1417 | ValueVector::iterator I, IE; |
| 1418 | for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) { |
| 1419 | StoreInst *ST = cast<StoreInst>(*I); |
| 1420 | Value* Ptr = ST->getPointerOperand(); |
Adam Nemet | ce48250 | 2015-04-08 17:48:40 +0000 | [diff] [blame] | 1421 | // Check for store to loop invariant address. |
| 1422 | StoreToLoopInvariantAddress |= isUniform(Ptr); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1423 | // If we did *not* see this pointer before, insert it to the read-write |
| 1424 | // list. At this phase it is only a 'write' list. |
| 1425 | if (Seen.insert(Ptr).second) { |
| 1426 | ++NumReadWrites; |
| 1427 | |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 1428 | MemoryLocation Loc = MemoryLocation::get(ST); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1429 | // The TBAA metadata could have a control dependency on the predication |
| 1430 | // condition, so we cannot rely on it when determining whether or not we |
| 1431 | // need runtime pointer checks. |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 1432 | if (blockNeedsPredication(ST->getParent(), TheLoop, DT)) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1433 | Loc.AATags.TBAA = nullptr; |
| 1434 | |
| 1435 | Accesses.addStore(Loc); |
| 1436 | } |
| 1437 | } |
| 1438 | |
| 1439 | if (IsAnnotatedParallel) { |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1440 | DEBUG(dbgs() |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1441 | << "LAA: A loop annotated parallel, ignore memory dependency " |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1442 | << "checks.\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1443 | CanVecMem = true; |
| 1444 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1445 | } |
| 1446 | |
| 1447 | for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) { |
| 1448 | LoadInst *LD = cast<LoadInst>(*I); |
| 1449 | Value* Ptr = LD->getPointerOperand(); |
| 1450 | // If we did *not* see this pointer before, insert it to the |
| 1451 | // read list. If we *did* see it before, then it is already in |
| 1452 | // the read-write list. This allows us to vectorize expressions |
| 1453 | // such as A[i] += x; Because the address of A[i] is a read-write |
| 1454 | // pointer. This only works if the index of A[i] is consecutive. |
| 1455 | // If the address of i is unknown (for example A[B[i]]) then we may |
| 1456 | // read a few words, modify, and write a few words, and some of the |
| 1457 | // words may be written to the same address. |
| 1458 | bool IsReadOnlyPtr = false; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1459 | if (Seen.insert(Ptr).second || !isStridedPtr(SE, Ptr, TheLoop, Strides)) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1460 | ++NumReads; |
| 1461 | IsReadOnlyPtr = true; |
| 1462 | } |
| 1463 | |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 1464 | MemoryLocation Loc = MemoryLocation::get(LD); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1465 | // The TBAA metadata could have a control dependency on the predication |
| 1466 | // condition, so we cannot rely on it when determining whether or not we |
| 1467 | // need runtime pointer checks. |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 1468 | if (blockNeedsPredication(LD->getParent(), TheLoop, DT)) |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1469 | Loc.AATags.TBAA = nullptr; |
| 1470 | |
| 1471 | Accesses.addLoad(Loc, IsReadOnlyPtr); |
| 1472 | } |
| 1473 | |
| 1474 | // If we write (or read-write) to a single destination and there are no |
| 1475 | // other reads in this loop then is it safe to vectorize. |
| 1476 | if (NumReadWrites == 1 && NumReads == 0) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1477 | DEBUG(dbgs() << "LAA: Found a write-only loop!\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1478 | CanVecMem = true; |
| 1479 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1480 | } |
| 1481 | |
| 1482 | // Build dependence sets and check whether we need a runtime pointer bounds |
| 1483 | // check. |
| 1484 | Accesses.buildDependenceSets(); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1485 | |
| 1486 | // Find pointers with computable bounds. We are going to use this information |
| 1487 | // to place a runtime bound check. |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 1488 | bool CanDoRTIfNeeded = |
| 1489 | Accesses.canCheckPtrAtRT(PtrRtCheck, SE, TheLoop, Strides); |
| 1490 | if (!CanDoRTIfNeeded) { |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1491 | emitAnalysis(LoopAccessReport() << "cannot identify array bounds"); |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 1492 | DEBUG(dbgs() << "LAA: We can't vectorize because we can't find " |
| 1493 | << "the array bounds.\n"); |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1494 | CanVecMem = false; |
| 1495 | return; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1496 | } |
| 1497 | |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 1498 | DEBUG(dbgs() << "LAA: We can perform a memory runtime check if needed.\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1499 | |
Adam Nemet | 436018c | 2015-02-19 19:15:00 +0000 | [diff] [blame] | 1500 | CanVecMem = true; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1501 | if (Accesses.isDependencyCheckNeeded()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1502 | DEBUG(dbgs() << "LAA: Checking memory dependencies\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1503 | CanVecMem = DepChecker.areDepsSafe( |
| 1504 | DependentAccesses, Accesses.getDependenciesToCheck(), Strides); |
| 1505 | MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes(); |
| 1506 | |
| 1507 | if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) { |
Adam Nemet | 339f42b | 2015-02-19 19:15:07 +0000 | [diff] [blame] | 1508 | DEBUG(dbgs() << "LAA: Retrying with memory checks\n"); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1509 | |
| 1510 | // Clear the dependency checks. We assume they are not needed. |
Adam Nemet | df3dc5b | 2015-05-18 15:37:03 +0000 | [diff] [blame] | 1511 | Accesses.resetDepChecks(DepChecker); |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1512 | |
| 1513 | PtrRtCheck.reset(); |
| 1514 | PtrRtCheck.Need = true; |
| 1515 | |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 1516 | CanDoRTIfNeeded = |
| 1517 | Accesses.canCheckPtrAtRT(PtrRtCheck, SE, TheLoop, Strides, true); |
Silviu Baranga | 98a1371 | 2015-06-08 10:27:06 +0000 | [diff] [blame] | 1518 | |
Adam Nemet | 949e91a | 2015-03-10 19:12:41 +0000 | [diff] [blame] | 1519 | // Check that we found the bounds for the pointer. |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 1520 | if (!CanDoRTIfNeeded) { |
Adam Nemet | b6dc76f | 2015-03-10 18:54:19 +0000 | [diff] [blame] | 1521 | emitAnalysis(LoopAccessReport() |
| 1522 | << "cannot check memory dependencies at runtime"); |
| 1523 | DEBUG(dbgs() << "LAA: Can't vectorize with memory checks\n"); |
Adam Nemet | b6dc76f | 2015-03-10 18:54:19 +0000 | [diff] [blame] | 1524 | CanVecMem = false; |
| 1525 | return; |
| 1526 | } |
| 1527 | |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1528 | CanVecMem = true; |
| 1529 | } |
| 1530 | } |
| 1531 | |
Adam Nemet | 4bb90a7 | 2015-03-10 21:47:39 +0000 | [diff] [blame] | 1532 | if (CanVecMem) |
| 1533 | DEBUG(dbgs() << "LAA: No unsafe dependent memory operations in loop. We" |
Adam Nemet | ee61474 | 2015-07-09 22:17:38 +0000 | [diff] [blame^] | 1534 | << (PtrRtCheck.Need ? "" : " don't") |
Adam Nemet | 4bb90a7 | 2015-03-10 21:47:39 +0000 | [diff] [blame] | 1535 | << " need a runtime memory check.\n"); |
| 1536 | else { |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1537 | emitAnalysis(LoopAccessReport() << |
Adam Nemet | 04d4163 | 2015-02-19 19:14:34 +0000 | [diff] [blame] | 1538 | "unsafe dependent memory operations in loop"); |
Adam Nemet | 4bb90a7 | 2015-03-10 21:47:39 +0000 | [diff] [blame] | 1539 | DEBUG(dbgs() << "LAA: unsafe dependent memory operations in loop\n"); |
| 1540 | } |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1541 | } |
| 1542 | |
Adam Nemet | 01abb2c | 2015-02-18 03:43:19 +0000 | [diff] [blame] | 1543 | bool LoopAccessInfo::blockNeedsPredication(BasicBlock *BB, Loop *TheLoop, |
| 1544 | DominatorTree *DT) { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1545 | assert(TheLoop->contains(BB) && "Unknown block used"); |
| 1546 | |
| 1547 | // Blocks that do not dominate the latch need predication. |
| 1548 | BasicBlock* Latch = TheLoop->getLoopLatch(); |
| 1549 | return !DT->dominates(BB, Latch); |
| 1550 | } |
| 1551 | |
Adam Nemet | 2bd6e98 | 2015-02-19 19:15:15 +0000 | [diff] [blame] | 1552 | void LoopAccessInfo::emitAnalysis(LoopAccessReport &Message) { |
Adam Nemet | c922853 | 2015-02-19 19:14:56 +0000 | [diff] [blame] | 1553 | assert(!Report && "Multiple reports generated"); |
| 1554 | Report = Message; |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1555 | } |
| 1556 | |
Adam Nemet | 57ac766 | 2015-02-19 19:15:21 +0000 | [diff] [blame] | 1557 | bool LoopAccessInfo::isUniform(Value *V) const { |
Adam Nemet | 0456327 | 2015-02-01 16:56:15 +0000 | [diff] [blame] | 1558 | return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop)); |
| 1559 | } |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1560 | |
| 1561 | // FIXME: this function is currently a duplicate of the one in |
| 1562 | // LoopVectorize.cpp. |
| 1563 | static Instruction *getFirstInst(Instruction *FirstInst, Value *V, |
| 1564 | Instruction *Loc) { |
| 1565 | if (FirstInst) |
| 1566 | return FirstInst; |
| 1567 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 1568 | return I->getParent() == Loc->getParent() ? I : nullptr; |
| 1569 | return nullptr; |
| 1570 | } |
| 1571 | |
Adam Nemet | ec1e2bb | 2015-03-10 18:54:26 +0000 | [diff] [blame] | 1572 | std::pair<Instruction *, Instruction *> LoopAccessInfo::addRuntimeCheck( |
| 1573 | Instruction *Loc, const SmallVectorImpl<int> *PtrPartition) const { |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1574 | if (!PtrRtCheck.Need) |
Adam Nemet | 90fec84 | 2015-04-02 17:51:57 +0000 | [diff] [blame] | 1575 | return std::make_pair(nullptr, nullptr); |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1576 | |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 1577 | SmallVector<TrackingVH<Value>, 2> Starts; |
| 1578 | SmallVector<TrackingVH<Value>, 2> Ends; |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1579 | |
| 1580 | LLVMContext &Ctx = Loc->getContext(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1581 | SCEVExpander Exp(*SE, DL, "induction"); |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1582 | Instruction *FirstInst = nullptr; |
| 1583 | |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 1584 | for (unsigned i = 0; i < PtrRtCheck.CheckingGroups.size(); ++i) { |
| 1585 | const RuntimePointerCheck::CheckingPtrGroup &CG = |
| 1586 | PtrRtCheck.CheckingGroups[i]; |
| 1587 | Value *Ptr = PtrRtCheck.Pointers[CG.Members[0]]; |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1588 | const SCEV *Sc = SE->getSCEV(Ptr); |
| 1589 | |
| 1590 | if (SE->isLoopInvariant(Sc, TheLoop)) { |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 1591 | DEBUG(dbgs() << "LAA: Adding RT check for a loop invariant ptr:" << *Ptr |
| 1592 | << "\n"); |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1593 | Starts.push_back(Ptr); |
| 1594 | Ends.push_back(Ptr); |
| 1595 | } else { |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1596 | unsigned AS = Ptr->getType()->getPointerAddressSpace(); |
| 1597 | |
| 1598 | // Use this type for pointer arithmetic. |
| 1599 | Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS); |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 1600 | Value *Start = nullptr, *End = nullptr; |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1601 | |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 1602 | DEBUG(dbgs() << "LAA: Adding RT check for range:\n"); |
| 1603 | Start = Exp.expandCodeFor(CG.Low, PtrArithTy, Loc); |
| 1604 | End = Exp.expandCodeFor(CG.High, PtrArithTy, Loc); |
| 1605 | DEBUG(dbgs() << "Start: " << *CG.Low << " End: " << *CG.High << "\n"); |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1606 | Starts.push_back(Start); |
| 1607 | Ends.push_back(End); |
| 1608 | } |
| 1609 | } |
| 1610 | |
| 1611 | IRBuilder<> ChkBuilder(Loc); |
| 1612 | // Our instructions might fold to a constant. |
| 1613 | Value *MemoryRuntimeCheck = nullptr; |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 1614 | for (unsigned i = 0; i < PtrRtCheck.CheckingGroups.size(); ++i) { |
| 1615 | for (unsigned j = i + 1; j < PtrRtCheck.CheckingGroups.size(); ++j) { |
| 1616 | const RuntimePointerCheck::CheckingPtrGroup &CGI = |
| 1617 | PtrRtCheck.CheckingGroups[i]; |
| 1618 | const RuntimePointerCheck::CheckingPtrGroup &CGJ = |
| 1619 | PtrRtCheck.CheckingGroups[j]; |
| 1620 | |
| 1621 | if (!PtrRtCheck.needsChecking(CGI, CGJ, PtrPartition)) |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1622 | continue; |
| 1623 | |
| 1624 | unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace(); |
| 1625 | unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace(); |
| 1626 | |
| 1627 | assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) && |
| 1628 | (AS1 == Ends[i]->getType()->getPointerAddressSpace()) && |
| 1629 | "Trying to bounds check pointers with different address spaces"); |
| 1630 | |
| 1631 | Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0); |
| 1632 | Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1); |
| 1633 | |
| 1634 | Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc"); |
| 1635 | Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc"); |
| 1636 | Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc"); |
| 1637 | Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc"); |
| 1638 | |
| 1639 | Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0"); |
| 1640 | FirstInst = getFirstInst(FirstInst, Cmp0, Loc); |
| 1641 | Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1"); |
| 1642 | FirstInst = getFirstInst(FirstInst, Cmp1, Loc); |
| 1643 | Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); |
| 1644 | FirstInst = getFirstInst(FirstInst, IsConflict, Loc); |
| 1645 | if (MemoryRuntimeCheck) { |
| 1646 | IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, |
| 1647 | "conflict.rdx"); |
| 1648 | FirstInst = getFirstInst(FirstInst, IsConflict, Loc); |
| 1649 | } |
| 1650 | MemoryRuntimeCheck = IsConflict; |
| 1651 | } |
| 1652 | } |
| 1653 | |
Adam Nemet | 90fec84 | 2015-04-02 17:51:57 +0000 | [diff] [blame] | 1654 | if (!MemoryRuntimeCheck) |
| 1655 | return std::make_pair(nullptr, nullptr); |
| 1656 | |
Adam Nemet | 7206d7a | 2015-02-06 18:31:04 +0000 | [diff] [blame] | 1657 | // We have to do this trickery because the IRBuilder might fold the check to a |
| 1658 | // constant expression in which case there is no Instruction anchored in a |
| 1659 | // the block. |
| 1660 | Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck, |
| 1661 | ConstantInt::getTrue(Ctx)); |
| 1662 | ChkBuilder.Insert(Check, "memcheck.conflict"); |
| 1663 | FirstInst = getFirstInst(FirstInst, Check, Loc); |
| 1664 | return std::make_pair(FirstInst, Check); |
| 1665 | } |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1666 | |
| 1667 | LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1668 | const DataLayout &DL, |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1669 | const TargetLibraryInfo *TLI, AliasAnalysis *AA, |
Adam Nemet | e2b885c | 2015-04-23 20:09:20 +0000 | [diff] [blame] | 1670 | DominatorTree *DT, LoopInfo *LI, |
Adam Nemet | 8bc61df | 2015-02-24 00:41:59 +0000 | [diff] [blame] | 1671 | const ValueToValueMap &Strides) |
Silviu Baranga | 1b6b50a | 2015-07-08 09:16:33 +0000 | [diff] [blame] | 1672 | : PtrRtCheck(SE), DepChecker(SE, L), TheLoop(L), SE(SE), DL(DL), TLI(TLI), |
| 1673 | AA(AA), DT(DT), LI(LI), NumLoads(0), NumStores(0), |
Adam Nemet | ce48250 | 2015-04-08 17:48:40 +0000 | [diff] [blame] | 1674 | MaxSafeDepDistBytes(-1U), CanVecMem(false), |
| 1675 | StoreToLoopInvariantAddress(false) { |
Adam Nemet | 929c38e | 2015-02-19 19:15:10 +0000 | [diff] [blame] | 1676 | if (canAnalyzeLoop()) |
| 1677 | analyzeLoop(Strides); |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1678 | } |
| 1679 | |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1680 | void LoopAccessInfo::print(raw_ostream &OS, unsigned Depth) const { |
| 1681 | if (CanVecMem) { |
Adam Nemet | 26da8e9 | 2015-04-14 01:12:55 +0000 | [diff] [blame] | 1682 | if (PtrRtCheck.Need) |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1683 | OS.indent(Depth) << "Memory dependences are safe with run-time checks\n"; |
Adam Nemet | 26da8e9 | 2015-04-14 01:12:55 +0000 | [diff] [blame] | 1684 | else |
| 1685 | OS.indent(Depth) << "Memory dependences are safe\n"; |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1686 | } |
| 1687 | |
| 1688 | if (Report) |
| 1689 | OS.indent(Depth) << "Report: " << Report->str() << "\n"; |
| 1690 | |
Adam Nemet | 58913d6 | 2015-03-10 17:40:43 +0000 | [diff] [blame] | 1691 | if (auto *InterestingDependences = DepChecker.getInterestingDependences()) { |
| 1692 | OS.indent(Depth) << "Interesting Dependences:\n"; |
| 1693 | for (auto &Dep : *InterestingDependences) { |
| 1694 | Dep.print(OS, Depth + 2, DepChecker.getMemoryInstructions()); |
| 1695 | OS << "\n"; |
| 1696 | } |
| 1697 | } else |
| 1698 | OS.indent(Depth) << "Too many interesting dependences, not recorded\n"; |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1699 | |
| 1700 | // List the pair of accesses need run-time checks to prove independence. |
| 1701 | PtrRtCheck.print(OS, Depth); |
| 1702 | OS << "\n"; |
Adam Nemet | c338432 | 2015-05-18 15:36:57 +0000 | [diff] [blame] | 1703 | |
| 1704 | OS.indent(Depth) << "Store to invariant address was " |
| 1705 | << (StoreToLoopInvariantAddress ? "" : "not ") |
| 1706 | << "found in loop.\n"; |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1707 | } |
| 1708 | |
Adam Nemet | 8bc61df | 2015-02-24 00:41:59 +0000 | [diff] [blame] | 1709 | const LoopAccessInfo & |
| 1710 | LoopAccessAnalysis::getInfo(Loop *L, const ValueToValueMap &Strides) { |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1711 | auto &LAI = LoopAccessInfoMap[L]; |
| 1712 | |
| 1713 | #ifndef NDEBUG |
| 1714 | assert((!LAI || LAI->NumSymbolicStrides == Strides.size()) && |
| 1715 | "Symbolic strides changed for loop"); |
| 1716 | #endif |
| 1717 | |
| 1718 | if (!LAI) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1719 | const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); |
Adam Nemet | e2b885c | 2015-04-23 20:09:20 +0000 | [diff] [blame] | 1720 | LAI = llvm::make_unique<LoopAccessInfo>(L, SE, DL, TLI, AA, DT, LI, |
| 1721 | Strides); |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1722 | #ifndef NDEBUG |
| 1723 | LAI->NumSymbolicStrides = Strides.size(); |
| 1724 | #endif |
| 1725 | } |
| 1726 | return *LAI.get(); |
| 1727 | } |
| 1728 | |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1729 | void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const { |
| 1730 | LoopAccessAnalysis &LAA = *const_cast<LoopAccessAnalysis *>(this); |
| 1731 | |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1732 | ValueToValueMap NoSymbolicStrides; |
| 1733 | |
| 1734 | for (Loop *TopLevelLoop : *LI) |
| 1735 | for (Loop *L : depth_first(TopLevelLoop)) { |
| 1736 | OS.indent(2) << L->getHeader()->getName() << ":\n"; |
| 1737 | auto &LAI = LAA.getInfo(L, NoSymbolicStrides); |
| 1738 | LAI.print(OS, 4); |
| 1739 | } |
| 1740 | } |
| 1741 | |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1742 | bool LoopAccessAnalysis::runOnFunction(Function &F) { |
| 1743 | SE = &getAnalysis<ScalarEvolution>(); |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1744 | auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); |
| 1745 | TLI = TLIP ? &TLIP->getTLI() : nullptr; |
| 1746 | AA = &getAnalysis<AliasAnalysis>(); |
| 1747 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Adam Nemet | e2b885c | 2015-04-23 20:09:20 +0000 | [diff] [blame] | 1748 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1749 | |
| 1750 | return false; |
| 1751 | } |
| 1752 | |
| 1753 | void LoopAccessAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { |
| 1754 | AU.addRequired<ScalarEvolution>(); |
| 1755 | AU.addRequired<AliasAnalysis>(); |
| 1756 | AU.addRequired<DominatorTreeWrapperPass>(); |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1757 | AU.addRequired<LoopInfoWrapperPass>(); |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1758 | |
| 1759 | AU.setPreservesAll(); |
| 1760 | } |
| 1761 | |
| 1762 | char LoopAccessAnalysis::ID = 0; |
| 1763 | static const char laa_name[] = "Loop Access Analysis"; |
| 1764 | #define LAA_NAME "loop-accesses" |
| 1765 | |
| 1766 | INITIALIZE_PASS_BEGIN(LoopAccessAnalysis, LAA_NAME, laa_name, false, true) |
| 1767 | INITIALIZE_AG_DEPENDENCY(AliasAnalysis) |
| 1768 | INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) |
| 1769 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Adam Nemet | e91cc6e | 2015-02-19 19:15:19 +0000 | [diff] [blame] | 1770 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
Adam Nemet | 3bfd93d | 2015-02-19 19:15:04 +0000 | [diff] [blame] | 1771 | INITIALIZE_PASS_END(LoopAccessAnalysis, LAA_NAME, laa_name, false, true) |
| 1772 | |
| 1773 | namespace llvm { |
| 1774 | Pass *createLAAPass() { |
| 1775 | return new LoopAccessAnalysis(); |
| 1776 | } |
| 1777 | } |