LoopAccessAnalysis.cpp 66 KB

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