LLVM 24.0.0git
DependenceAnalysis.cpp
Go to the documentation of this file.
1//===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// DependenceAnalysis is an LLVM pass that analyses dependences between memory
10// accesses. Currently, it is an (incomplete) implementation of the approach
11// described in
12//
13// Practical Dependence Testing
14// Goff, Kennedy, Tseng
15// PLDI 1991
16//
17// There's a single entry point that analyzes the dependence between a pair
18// of memory references in a function, returning either NULL, for no dependence,
19// or a more-or-less detailed description of the dependence between them.
20//
21// Since Clang linearizes some array subscripts, the dependence
22// analysis is using SCEV->delinearize to recover the representation of multiple
23// subscripts, and thus avoid the more expensive and less precise MIV tests. The
24// delinearization is controlled by the flag -da-delinearize.
25//
26// We should pay some careful attention to the possibility of integer overflow
27// in the implementation of the various tests. This could happen with Add,
28// Subtract, or Multiply, with both APInt's and SCEV's.
29//
30// Some non-linear subscript pairs can be handled by the GCD test
31// (and perhaps other tests).
32// Should explore how often these things occur.
33//
34// Finally, it seems like certain test cases expose weaknesses in the SCEV
35// simplification, especially in the handling of sign and zero extensions.
36// It could be useful to spend time exploring these.
37//
38// Please note that this is work in progress and the interface is subject to
39// change.
40//
41//===----------------------------------------------------------------------===//
42// //
43// In memory of Ken Kennedy, 1945 - 2007 //
44// //
45//===----------------------------------------------------------------------===//
46
48#include "AnalysisOptions.h"
49#include "llvm/ADT/Statistic.h"
58#include "llvm/IR/Module.h"
59#include "llvm/Support/Debug.h"
62
63using namespace llvm;
64
65#define DEBUG_TYPE "da"
66
67//===----------------------------------------------------------------------===//
68// statistics
69
70STATISTIC(TotalArrayPairs, "Array pairs tested");
71STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
72STATISTIC(ZIVapplications, "ZIV applications");
73STATISTIC(ZIVindependence, "ZIV independence");
74STATISTIC(StrongSIVapplications, "Strong SIV applications");
75STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
76STATISTIC(StrongSIVindependence, "Strong SIV independence");
77STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
78STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
79STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
80STATISTIC(ExactSIVapplications, "Exact SIV applications");
81STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
82STATISTIC(ExactSIVindependence, "Exact SIV independence");
83STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
84STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
85STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
86STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
87STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
88STATISTIC(GCDapplications, "GCD applications");
89STATISTIC(GCDsuccesses, "GCD successes");
90STATISTIC(GCDindependence, "GCD independence");
91STATISTIC(BanerjeeApplications, "Banerjee applications");
92STATISTIC(BanerjeeIndependence, "Banerjee independence");
93STATISTIC(BanerjeeSuccesses, "Banerjee successes");
94STATISTIC(SameSDLoopsCount, "Loops with Same iteration Space and Depth");
95
96//===----------------------------------------------------------------------===//
97// basics
98
100 LoopInfo *LI)
101 : Opts(getAnalysisOptions(*F)), AA(AA), SE(SE), LI(LI), F(F) {}
102
105 auto &AA = FAM.getResult<AAManager>(F);
106 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
107 auto &LI = FAM.getResult<LoopAnalysis>(F);
108 return DependenceInfo(&F, &AA, &SE, &LI);
109}
110
111AnalysisKey DependenceAnalysis::Key;
112
113namespace {
114
115/// A wrapper class for std::optional<APInt> that provides arithmetic operators
116/// with overflow checking in a signed sense. This allows us to omit inserting
117/// an overflow check at every arithmetic operation, which simplifies the code
118/// if the operations are chained like `a + b + c + ...`.
119///
120/// If an calculation overflows, the result becomes "invalid" which is
121/// internally represented by std::nullopt. If any operand of an arithmetic
122/// operation is "invalid", the result will also be "invalid".
123struct OverflowSafeSignedAPInt {
124 OverflowSafeSignedAPInt() : Value(std::nullopt) {}
125 OverflowSafeSignedAPInt(const APInt &V) : Value(V) {}
126 OverflowSafeSignedAPInt(const std::optional<APInt> &V) : Value(V) {}
127
128 OverflowSafeSignedAPInt operator+(const OverflowSafeSignedAPInt &RHS) const {
129 if (!Value || !RHS.Value)
130 return OverflowSafeSignedAPInt();
131 bool Overflow;
132 APInt Result = Value->sadd_ov(*RHS.Value, Overflow);
133 if (Overflow)
134 return OverflowSafeSignedAPInt();
135 return OverflowSafeSignedAPInt(Result);
136 }
137
138 OverflowSafeSignedAPInt operator+(int RHS) const {
139 if (!Value)
140 return OverflowSafeSignedAPInt();
141 return *this + fromInt(RHS);
142 }
143
144 OverflowSafeSignedAPInt operator-(const OverflowSafeSignedAPInt &RHS) const {
145 if (!Value || !RHS.Value)
146 return OverflowSafeSignedAPInt();
147 bool Overflow;
148 APInt Result = Value->ssub_ov(*RHS.Value, Overflow);
149 if (Overflow)
150 return OverflowSafeSignedAPInt();
151 return OverflowSafeSignedAPInt(Result);
152 }
153
154 OverflowSafeSignedAPInt operator-(int RHS) const {
155 if (!Value)
156 return OverflowSafeSignedAPInt();
157 return *this - fromInt(RHS);
158 }
159
160 OverflowSafeSignedAPInt operator*(const OverflowSafeSignedAPInt &RHS) const {
161 if (!Value || !RHS.Value)
162 return OverflowSafeSignedAPInt();
163 bool Overflow;
164 APInt Result = Value->smul_ov(*RHS.Value, Overflow);
165 if (Overflow)
166 return OverflowSafeSignedAPInt();
167 return OverflowSafeSignedAPInt(Result);
168 }
169
170 OverflowSafeSignedAPInt operator-() const {
171 if (!Value)
172 return OverflowSafeSignedAPInt();
173 if (Value->isMinSignedValue())
174 return OverflowSafeSignedAPInt();
175 return OverflowSafeSignedAPInt(-*Value);
176 }
177
178 operator bool() const { return Value.has_value(); }
179
180 bool operator!() const { return !Value.has_value(); }
181
182 const APInt &operator*() const {
183 assert(Value && "Value is not available.");
184 return *Value;
185 }
186
187 const APInt *operator->() const {
188 assert(Value && "Value is not available.");
189 return &*Value;
190 }
191
192private:
193 /// Underlying value. std::nullopt means "unknown". An arithmetic operation on
194 /// "unknown" always produces "unknown".
195 std::optional<APInt> Value;
196
197 OverflowSafeSignedAPInt fromInt(uint64_t V) const {
198 assert(Value && "Value is not available.");
199 return OverflowSafeSignedAPInt(
200 APInt(Value->getBitWidth(), V, /*isSigned=*/true));
201 }
202};
203
204} // anonymous namespace
205
206// Used to test the dependence analyzer.
207// Looks through the function, noting instructions that may access memory.
208// Calls depends() on every possible pair and prints out the result.
209// Ignores all other instructions.
211 ScalarEvolution &SE, LoopInfo &LI,
212 bool NormalizeResults) {
213 auto *F = DA->getFunction();
214
215 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); SrcI != SrcE;
216 ++SrcI) {
217 if (SrcI->mayReadOrWriteMemory()) {
218 for (inst_iterator DstI = SrcI, DstE = inst_end(F); DstI != DstE;
219 ++DstI) {
220 if (DstI->mayReadOrWriteMemory()) {
221 OS << "Src:" << *SrcI << " --> Dst:" << *DstI << "\n";
222 OS << " da analyze - ";
223 if (auto D = DA->depends(&*SrcI, &*DstI,
224 /*UnderRuntimeAssumptions=*/true)) {
225
226#ifndef NDEBUG
227 // Verify that the distance being zero is equivalent to the
228 // direction being EQ.
229 for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
230 const SCEV *Distance = D->getDistance(Level);
231 bool IsDistanceZero = Distance && Distance->isZero();
232 bool IsDirectionEQ =
233 D->getDirection(Level) == Dependence::DVEntry::EQ;
234 assert(IsDistanceZero == IsDirectionEQ &&
235 "Inconsistent distance and direction.");
236 }
237#endif
238
239 // Normalize negative direction vectors if required by clients.
240 if (NormalizeResults && D->normalize(&SE))
241 OS << "normalized - ";
242 D->dump(OS);
243 } else
244 OS << "none!\n";
245 }
246 }
247 }
248 }
249}
250
252 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
253 static_cast<PassInfoMixin<DependenceAnalysisPrinterPass> *>(this)
254 ->printPipeline(OS, MapClassName2PassName);
255 if (NormalizeResults)
256 OS << "<normalized-results>";
257}
258
261 OS << "Printing analysis 'Dependence Analysis' for function '" << F.getName()
262 << "':\n";
264 FAM.getResult<ScalarEvolutionAnalysis>(F),
265 FAM.getResult<LoopAnalysis>(F), NormalizeResults);
266 return PreservedAnalyses::all();
267}
268
269//===----------------------------------------------------------------------===//
270// Dependence methods
271
272// Returns true if this is an input dependence.
274 return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
275}
276
277// Returns true if this is an output dependence.
279 return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
280}
281
282// Returns true if this is an flow (aka true) dependence.
283bool Dependence::isFlow() const {
284 return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
285}
286
287// Returns true if this is an anti dependence.
288bool Dependence::isAnti() const {
289 return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
290}
291
292// Returns true if a particular level is scalar; that is,
293// if no subscript in the source or destination mention the induction
294// variable associated with the loop at this level.
295// Leave this out of line, so it will serve as a virtual method anchor
296bool Dependence::isScalar(unsigned level, bool IsSameSD) const { return false; }
297
298//===----------------------------------------------------------------------===//
299// FullDependence methods
300
302 const SCEVUnionPredicate &Assumes,
303 bool PossiblyLoopIndependent,
304 unsigned CommonLevels)
305 : Dependence(Source, Destination, Assumes), Levels(CommonLevels),
306 LoopIndependent(PossiblyLoopIndependent) {
307 SameSDLevels = 0;
308 if (CommonLevels)
309 DV = std::make_unique<DVEntry[]>(CommonLevels);
310}
311
312// FIXME: in some cases the meaning of a negative direction vector
313// may not be straightforward, e.g.,
314// for (int i = 0; i < 32; ++i) {
315// Src: A[i] = ...;
316// Dst: use(A[31 - i]);
317// }
318// The dependency is
319// flow { Src[i] -> Dst[31 - i] : when i >= 16 } and
320// anti { Dst[i] -> Src[31 - i] : when i < 16 },
321// -- hence a [<>].
322// As long as a dependence result contains '>' ('<>', '<=>', "*"), it
323// means that a reversed/normalized dependence needs to be considered
324// as well. Nevertheless, current isDirectionNegative() only returns
325// true with a '>' or '>=' dependency for ease of canonicalizing the
326// dependency vector, since the reverse of '<>', '<=>' and "*" is itself.
328 for (unsigned Level = 1; Level <= Levels; ++Level) {
329 unsigned char Direction = DV[Level - 1].Direction;
330 if (Direction == Dependence::DVEntry::EQ)
331 continue;
332 if (Direction == Dependence::DVEntry::GT ||
333 Direction == Dependence::DVEntry::GE)
334 return true;
335 return false;
336 }
337 return false;
338}
339
341 std::swap(Src, Dst);
342 for (unsigned Level = 1; Level <= Levels; ++Level) {
343 unsigned char Direction = DV[Level - 1].Direction;
344 // Reverse the direction vector, this means LT becomes GT
345 // and GT becomes LT.
346 unsigned char RevDirection = Direction & Dependence::DVEntry::EQ;
347 if (Direction & Dependence::DVEntry::LT)
348 RevDirection |= Dependence::DVEntry::GT;
349 if (Direction & Dependence::DVEntry::GT)
350 RevDirection |= Dependence::DVEntry::LT;
351 DV[Level - 1].Direction = RevDirection;
352 // Reverse the dependence distance as well.
353 if (DV[Level - 1].Distance != nullptr)
354 DV[Level - 1].Distance = SE.getNegativeSCEV(DV[Level - 1].Distance);
355 }
356}
357
359 if (!isDirectionNegative())
360 return false;
361
362 LLVM_DEBUG(dbgs() << "Before normalizing negative direction vectors:\n";
363 dump(dbgs()););
364 negate(*SE);
365 LLVM_DEBUG(dbgs() << "After normalizing negative direction vectors:\n";
366 dump(dbgs()););
367 return true;
368}
369
370// The rest are simple getters that hide the implementation.
371
372// getDirection - Returns the direction associated with a particular common or
373// SameSD level.
374unsigned FullDependence::getDirection(unsigned Level, bool IsSameSD) const {
375 return getDVEntry(Level, IsSameSD).Direction;
376}
377
378// Returns the distance (or NULL) associated with a particular common or
379// SameSD level.
380const SCEV *FullDependence::getDistance(unsigned Level, bool IsSameSD) const {
381 return getDVEntry(Level, IsSameSD).Distance;
382}
383
384// Returns true if a particular regular or SameSD level is scalar; that is,
385// if no subscript in the source or destination mention the induction variable
386// associated with the loop at this level.
387bool FullDependence::isScalar(unsigned Level, bool IsSameSD) const {
388 return getDVEntry(Level, IsSameSD).Scalar;
389}
390
391// inSameSDLoops - Returns true if this level is an SameSD level, i.e.,
392// performed across two separate loop nests that have the Same iteration space
393// and Depth.
394bool FullDependence::inSameSDLoops(unsigned Level) const {
395 assert(0 < Level && Level <= static_cast<unsigned>(Levels) + SameSDLevels &&
396 "Level out of range");
397 return Level > Levels;
398}
399
400//===----------------------------------------------------------------------===//
401// DependenceInfo methods
402
403// For debugging purposes. Dumps a dependence to OS.
405 if (isConfused())
406 OS << "confused";
407 else {
408 if (isFlow())
409 OS << "flow";
410 else if (isOutput())
411 OS << "output";
412 else if (isAnti())
413 OS << "anti";
414 else if (isInput())
415 OS << "input";
416 dumpImp(OS);
417 unsigned SameSDLevels = getSameSDLevels();
418 if (SameSDLevels > 0) {
419 OS << " / assuming " << SameSDLevels << " loop level(s) fused: ";
420 dumpImp(OS, true);
421 }
422 }
423 OS << "!\n";
424
426 if (!Assumptions.isAlwaysTrue()) {
427 OS << " Runtime Assumptions:\n";
428 Assumptions.print(OS, 2);
429 }
430}
431
432// For debugging purposes. Dumps a dependence to OS with or without considering
433// the SameSD levels.
434void Dependence::dumpImp(raw_ostream &OS, bool IsSameSD) const {
435 unsigned Levels = getLevels();
436 unsigned SameSDLevels = getSameSDLevels();
437 bool OnSameSD = false;
438 unsigned LevelNum = Levels;
439 if (IsSameSD)
440 LevelNum += SameSDLevels;
441 OS << " [";
442 for (unsigned II = 1; II <= LevelNum; ++II) {
443 if (!OnSameSD && inSameSDLoops(II))
444 OnSameSD = true;
445 const SCEV *Distance = getDistance(II, OnSameSD);
446 if (Distance)
447 OS << *Distance;
448 else if (isScalar(II, OnSameSD))
449 OS << "S";
450 else {
451 unsigned Direction = getDirection(II, OnSameSD);
452 if (Direction == DVEntry::ALL)
453 OS << "*";
454 else {
455 if (Direction & DVEntry::LT)
456 OS << "<";
457 if (Direction & DVEntry::EQ)
458 OS << "=";
459 if (Direction & DVEntry::GT)
460 OS << ">";
461 }
462 }
463 if (II < LevelNum)
464 OS << " ";
465 }
466 if (isLoopIndependent())
467 OS << "|<";
468 OS << "]";
469}
470
471/// Drop alias scopes that are only valid within a single loop iteration.
472static MDNode *
474 const SmallPtrSetImpl<const MDNode *> &LoopAliasScopes) {
475 if (!ScopeList || LoopAliasScopes.empty())
476 return ScopeList;
477
478 // For the sake of simplicity, drop the whole scope list if any scope is
479 // iteration-local.
480 if (any_of(ScopeList->operands(), [&](Metadata *Scope) {
481 return LoopAliasScopes.contains(cast<MDNode>(Scope));
482 }))
483 return nullptr;
484
485 return ScopeList;
486}
487
488// Location is spanned accross iteration
489// and single iteration alias scope are dropped
490static MemoryLocation
492 const SmallPtrSetImpl<const MDNode *> &LoopAliasScopes) {
494 Adj.AATags.Scope = adjustAliasScopeList(Adj.AATags.Scope, LoopAliasScopes);
495 Adj.AATags.NoAlias =
496 adjustAliasScopeList(Adj.AATags.NoAlias, LoopAliasScopes);
497 return Adj;
498}
499
500// Returns NoAlias/MayAliass/MustAlias for two memory locations based upon their
501// underlaying objects. If LocA and LocB are known to not alias (for any reason:
502// tbaa, non-overlapping regions etc), then it is known there is no dependency.
503// Otherwise the underlying objects are checked to see if they point to
504// different identifiable objects.
505static AliasResult
507 const MemoryLocation &LocA, const MemoryLocation &LocB,
508 const SmallPtrSetImpl<const MDNode *> &LoopAliasScopes) {
509
510 MemoryLocation LocAS = adjustLoc(LocA, LoopAliasScopes);
511 MemoryLocation LocBS = adjustLoc(LocB, LoopAliasScopes);
512
513 BatchAAResults BAA(*AA);
515
516 if (BAA.isNoAlias(LocAS, LocBS))
518
519 // Check the underlying objects are the same
520 const Value *AObj = getUnderlyingObject(LocA.Ptr);
521 const Value *BObj = getUnderlyingObject(LocB.Ptr);
522
523 // If the underlying objects are the same, they must alias
524 if (AObj == BObj)
526
527 // We may have hit the recursion limit for underlying objects, or have
528 // underlying objects where we don't know they will alias.
529 if (!isIdentifiedObject(AObj) || !isIdentifiedObject(BObj))
531
532 // Otherwise we know the objects are different and both identified objects so
533 // must not alias.
535}
536
537// Returns true if the load or store can be analyzed. Atomic and volatile
538// operations have properties which this analysis does not understand.
539static bool isLoadOrStore(const Instruction *I) {
540 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
541 return LI->isUnordered();
542 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
543 return SI->isUnordered();
544 return false;
545}
546
547// Returns true if two loops have the Same iteration Space and Depth. To be
548// more specific, two loops have SameSD if they are in the same nesting
549// depth and have the same backedge count. SameSD stands for Same iteration
550// Space and Depth.
551bool DependenceInfo::haveSameSD(const Loop *SrcLoop,
552 const Loop *DstLoop) const {
553 if (SrcLoop == DstLoop)
554 return true;
555
556 if (SrcLoop->getLoopDepth() != DstLoop->getLoopDepth())
557 return false;
558
559 if (!SrcLoop || !SrcLoop->getLoopLatch() || !DstLoop ||
560 !DstLoop->getLoopLatch())
561 return false;
562
563 const SCEV *SrcUB = SE->getBackedgeTakenCount(SrcLoop);
564 const SCEV *DstUB = SE->getBackedgeTakenCount(DstLoop);
566 return false;
567
568 Type *WiderType = SE->getWiderType(SrcUB->getType(), DstUB->getType());
569 SrcUB = SE->getNoopOrZeroExtend(SrcUB, WiderType);
570 DstUB = SE->getNoopOrZeroExtend(DstUB, WiderType);
571
572 if (SrcUB == DstUB)
573 return true;
574
575 return false;
576}
577
578// Examines the loop nesting of the Src and Dst
579// instructions and establishes their shared loops. Sets the variables
580// CommonLevels, SrcLevels, and MaxLevels.
581// The source and destination instructions needn't be contained in the same
582// loop. The routine establishNestingLevels finds the level of most deeply
583// nested loop that contains them both, CommonLevels. An instruction that's
584// not contained in a loop is at level = 0. MaxLevels is equal to the level
585// of the source plus the level of the destination, minus CommonLevels.
586// This lets us allocate vectors MaxLevels in length, with room for every
587// distinct loop referenced in both the source and destination subscripts.
588// The variable SrcLevels is the nesting depth of the source instruction.
589// It's used to help calculate distinct loops referenced by the destination.
590// Here's the map from loops to levels:
591// 0 - unused
592// 1 - outermost common loop
593// ... - other common loops
594// CommonLevels - innermost common loop
595// ... - loops containing Src but not Dst
596// SrcLevels - innermost loop containing Src but not Dst
597// ... - loops containing Dst but not Src
598// MaxLevels - innermost loops containing Dst but not Src
599// Consider the follow code fragment:
600// for (a = ...) {
601// for (b = ...) {
602// for (c = ...) {
603// for (d = ...) {
604// A[] = ...;
605// }
606// }
607// for (e = ...) {
608// for (f = ...) {
609// for (g = ...) {
610// ... = A[];
611// }
612// }
613// }
614// }
615// }
616// If we're looking at the possibility of a dependence between the store
617// to A (the Src) and the load from A (the Dst), we'll note that they
618// have 2 loops in common, so CommonLevels will equal 2 and the direction
619// vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
620// A map from loop names to loop numbers would look like
621// a - 1
622// b - 2 = CommonLevels
623// c - 3
624// d - 4 = SrcLevels
625// e - 5
626// f - 6
627// g - 7 = MaxLevels
628// SameSDLevels counts the number of levels after common levels that are
629// not common but have the same iteration space and depth. Internally this
630// is checked using haveSameSD. Currently we only need to check for SameSD
631// levels up to one level after the common levels, and therefore SameSDLevels
632// will be either 0 or 1.
633// 1. Assume that in this code fragment, levels c and e have the same iteration
634// space and depth, but levels d and f does not. Then SameSDLevels is set to 1.
635// In that case the level numbers for the previous code look like
636// a - 1
637// b - 2
638// c,e - 3 = CommonLevels
639// d - 4 = SrcLevels
640// f - 5
641// g - 6 = MaxLevels
642void DependenceInfo::establishNestingLevels(const Instruction *Src,
643 const Instruction *Dst) {
644 const BasicBlock *SrcBlock = Src->getParent();
645 const BasicBlock *DstBlock = Dst->getParent();
646 unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
647 unsigned DstLevel = LI->getLoopDepth(DstBlock);
648 const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
649 const Loop *DstLoop = LI->getLoopFor(DstBlock);
650 SrcLevels = SrcLevel;
651 MaxLevels = SrcLevel + DstLevel;
652 SameSDLevels = 0;
653 while (SrcLevel > DstLevel) {
654 SrcLoop = SrcLoop->getParentLoop();
655 SrcLevel--;
656 }
657 while (DstLevel > SrcLevel) {
658 DstLoop = DstLoop->getParentLoop();
659 DstLevel--;
660 }
661
662 const Loop *SrcUncommonFrontier = nullptr, *DstUncommonFrontier = nullptr;
663 // Find the first uncommon level pair and check if the associated levels have
664 // the SameSD.
665 while (SrcLoop != DstLoop) {
666 SrcUncommonFrontier = SrcLoop;
667 DstUncommonFrontier = DstLoop;
668 SrcLoop = SrcLoop->getParentLoop();
669 DstLoop = DstLoop->getParentLoop();
670 SrcLevel--;
671 }
672 if (SrcUncommonFrontier && DstUncommonFrontier &&
673 haveSameSD(SrcUncommonFrontier, DstUncommonFrontier))
674 SameSDLevels = 1;
675 CommonLevels = SrcLevel;
676 MaxLevels -= CommonLevels;
677}
678
679// Given one of the loops containing the source, return
680// its level index in our numbering scheme.
681unsigned DependenceInfo::mapSrcLoop(const Loop *SrcLoop) const {
682 return SrcLoop->getLoopDepth();
683}
684
685// Given one of the loops containing the destination,
686// return its level index in our numbering scheme.
687unsigned DependenceInfo::mapDstLoop(const Loop *DstLoop) const {
688 unsigned D = DstLoop->getLoopDepth();
689 if (D > CommonLevels)
690 // This tries to make sure that we assign unique numbers to src and dst when
691 // the memory accesses reside in different loops that have the same depth.
692 return D - CommonLevels + SrcLevels;
693 else
694 return D;
695}
696
697// Returns true if Expression is loop invariant in LoopNest.
698bool DependenceInfo::isLoopInvariant(const SCEV *Expression,
699 const Loop *LoopNest) const {
700 // Unlike ScalarEvolution::isLoopInvariant() we consider an access outside of
701 // any loop as invariant, because we only consier expression evaluation at a
702 // specific position (where the array access takes place), and not across the
703 // entire function.
704 if (!LoopNest)
705 return true;
706
707 // If the expression is invariant in the outermost loop of the loop nest, it
708 // is invariant anywhere in the loop nest.
709 return SE->isLoopInvariant(Expression, LoopNest->getOutermostLoop());
710}
711
712// Finds the set of loops from the LoopNest that
713// have a level <= CommonLevels and are referred to by the SCEV Expression.
714void DependenceInfo::collectCommonLoops(const SCEV *Expression,
715 const Loop *LoopNest,
716 SmallBitVector &Loops) const {
717 while (LoopNest) {
718 unsigned Level = LoopNest->getLoopDepth();
719 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
720 Loops.set(Level);
721 LoopNest = LoopNest->getParentLoop();
722 }
723}
724
725// Examine the scev and return true iff it's affine.
726// Collect any loops mentioned in the set of "Loops".
727bool DependenceInfo::checkSubscript(const SCEV *Expr, const Loop *LoopNest,
728 SmallBitVector &Loops, bool IsSrc) {
729 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
730 if (!AddRec)
731 return isLoopInvariant(Expr, LoopNest);
732
733 // The AddRec must depend on one of the containing loops. Otherwise,
734 // mapSrcLoop and mapDstLoop return indices outside the intended range. This
735 // can happen when a subscript in one loop references an IV from a sibling
736 // loop that could not be replaced with a concrete exit value by
737 // getSCEVAtScope.
738 const Loop *L = LoopNest;
739 while (L && AddRec->getLoop() != L)
740 L = L->getParentLoop();
741 if (!L)
742 return false;
743
744 if (!AddRec->hasNoSignedWrap())
745 return false;
746
747 const SCEV *Start = AddRec->getStart();
748 const SCEV *Step = AddRec->getStepRecurrence(*SE);
749 if (!isLoopInvariant(Step, LoopNest))
750 return false;
751 if (IsSrc)
752 Loops.set(mapSrcLoop(AddRec->getLoop()));
753 else
754 Loops.set(mapDstLoop(AddRec->getLoop()));
755 return checkSubscript(Start, LoopNest, Loops, IsSrc);
756}
757
758// Examine the scev and return true iff it's linear.
759// Collect any loops mentioned in the set of "Loops".
760bool DependenceInfo::checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
762 return checkSubscript(Src, LoopNest, Loops, true);
763}
764
765// Examine the scev and return true iff it's linear.
766// Collect any loops mentioned in the set of "Loops".
767bool DependenceInfo::checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
769 return checkSubscript(Dst, LoopNest, Loops, false);
770}
771
772// Examines the subscript pair (the Src and Dst SCEVs)
773// and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
774// Collects the associated loops in a set.
775DependenceInfo::Subscript::ClassificationKind
776DependenceInfo::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
777 const SCEV *Dst, const Loop *DstLoopNest,
779 SmallBitVector SrcLoops(MaxLevels + 1);
780 SmallBitVector DstLoops(MaxLevels + 1);
781 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
782 return Subscript::NonLinear;
783 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
784 return Subscript::NonLinear;
785 Loops = SrcLoops;
786 Loops |= DstLoops;
787 unsigned N = Loops.count();
788 if (N == 0)
789 return Subscript::ZIV;
790 if (N == 1)
791 return Subscript::SIV;
792 if (N == 2 && SrcLoops.count() == 1 && DstLoops.count() == 1)
793 return Subscript::RDIV;
794 return Subscript::MIV;
795}
796
797// All subscripts are all the same type.
798// Loop bound may be smaller (e.g., a char).
799// Should zero extend loop bound, since it's always >= 0.
800// This routine collects upper bound and extends or truncates if needed.
801// Truncating is safe when subscripts are known not to wrap. Cases without
802// nowrap flags should have been rejected earlier.
803// Return null if no bound available.
804const SCEV *DependenceInfo::collectUpperBound(const Loop *L, Type *T) const {
805 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
806 const SCEV *UB = SE->getBackedgeTakenCount(L);
807 return SE->getTruncateOrZeroExtend(UB, T);
808 }
809 return nullptr;
810}
811
812// Calls collectUpperBound(), then attempts to cast it to APInt.
813// If the cast fails, returns std::nullopt.
814std::optional<APInt>
815DependenceInfo::collectNonNegativeConstantUpperBound(const Loop *L,
816 Type *T) const {
817 if (const SCEV *UB = collectUpperBound(L, T))
818 if (auto *C = dyn_cast<SCEVConstant>(UB)) {
819 APInt Res = C->getAPInt();
820 if (Res.isNonNegative())
821 return Res;
822 }
823 return std::nullopt;
824}
825
826/// Returns \p A - \p B if it guaranteed not to signed wrap. Otherwise returns
827/// nullptr. \p A and \p B must have the same integer type.
828static const SCEV *minusSCEVNoSignedOverflow(const SCEV *A, const SCEV *B,
829 ScalarEvolution &SE) {
830 if (SE.willNotOverflow(Instruction::Sub, /*Signed=*/true, A, B))
831 return SE.getMinusSCEV(A, B);
832 return nullptr;
833}
834
835/// Returns true iff \p Test is enabled.
836static bool isDependenceTestEnabled(const AnalysisOptions &Opts,
838 if (Opts.da_enable_dependence_test == DependenceTestType::All)
839 return true;
840 // The Banerjee test is disabled by default because of correctness issues,
841 // but can be enabled with -da-enable-dependence-test=banerjee-miv or
842 // -da-enable-dependence-test=all.
843 if (Opts.da_enable_dependence_test == DependenceTestType::Default)
845 return Opts.da_enable_dependence_test == Test;
846}
847
848// testZIV -
849// When we have a pair of subscripts of the form [c1] and [c2],
850// where c1 and c2 are both loop invariant, we attack it using
851// the ZIV test. Basically, we test by comparing the two values,
852// but there are actually three possible results:
853// 1) the values are equal, so there's a dependence
854// 2) the values are different, so there's no dependence
855// 3) the values might be equal, so we have to assume a dependence.
856//
857// Return true if dependence disproved.
858bool DependenceInfo::testZIV(const SCEV *Src, const SCEV *Dst,
859 FullDependence &Result) const {
860 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
861 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
862 ++ZIVapplications;
863 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
864 LLVM_DEBUG(dbgs() << " provably dependent\n");
865 return false; // provably dependent
866 }
867 if (SE->isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
868 LLVM_DEBUG(dbgs() << " provably independent\n");
869 ++ZIVindependence;
870 return true; // provably independent
871 }
872 LLVM_DEBUG(dbgs() << " possibly dependent\n");
873 return false; // possibly dependent
874}
875
876// strongSIVtest -
877// From the paper, Practical Dependence Testing, Section 4.2.1
878//
879// When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
880// where i is an induction variable, c1 and c2 are loop invariant,
881// and a is a constant, we can solve it exactly using the Strong SIV test.
882//
883// Can prove independence. Failing that, can compute distance (and direction).
884// In the presence of symbolic terms, we can sometimes make progress.
885//
886// If there's a dependence,
887//
888// c1 + a*i = c2 + a*i'
889//
890// The dependence distance is
891//
892// d = i' - i = (c1 - c2)/a
893//
894// A dependence only exists if d is an integer and abs(d) <= U, where U is the
895// loop's upper bound. If a dependence exists, the dependence direction is
896// defined as
897//
898// { < if d > 0
899// direction = { = if d = 0
900// { > if d < 0
901//
902// Return true if dependence disproved.
903bool DependenceInfo::strongSIVtest(const SCEVAddRecExpr *Src,
904 const SCEVAddRecExpr *Dst, unsigned Level,
905 FullDependence &Result,
906 bool UnderRuntimeAssumptions) {
908 return false;
909
910 const SCEV *Coeff = Src->getStepRecurrence(*SE);
911 assert(Coeff == Dst->getStepRecurrence(*SE) &&
912 "Expecting same coefficient in Strong SIV test");
913 const SCEV *SrcConst = Src->getStart();
914 const SCEV *DstConst = Dst->getStart();
915 LLVM_DEBUG(dbgs() << "\tStrong SIV test\n");
916 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff);
917 LLVM_DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
918 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
919 LLVM_DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
920 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst);
921 LLVM_DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
922 ++StrongSIVapplications;
923 assert(0 < Level && Level <= CommonLevels && "level out of range");
924 Level--;
925
926 const SCEV *Delta = minusSCEVNoSignedOverflow(SrcConst, DstConst, *SE);
927 if (!Delta)
928 return false;
929 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta);
930 LLVM_DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
931
932 // Can we compute distance?
933 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
934 APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
935 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
936 APInt Distance = ConstDelta; // these need to be initialized
937 APInt Remainder = ConstDelta;
938 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
939 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
940 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
941 // Make sure Coeff divides Delta exactly
942 if (Remainder != 0) {
943 // Coeff doesn't divide Distance, no dependence
944 ++StrongSIVindependence;
945 ++StrongSIVsuccesses;
946 return true;
947 }
948 Result.DV[Level].Distance = SE->getConstant(Distance);
949 if (Distance.sgt(0))
950 Result.DV[Level].Direction &= Dependence::DVEntry::LT;
951 else if (Distance.slt(0))
952 Result.DV[Level].Direction &= Dependence::DVEntry::GT;
953 else
954 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
955 ++StrongSIVsuccesses;
956 } else if (Delta->isZero()) {
957 // Check if coefficient could be zero. If so, 0/0 is undefined and we
958 // cannot conclude that only same-iteration dependencies exist.
959 // When coeff=0, all iterations access the same location.
960 if (SE->isKnownNonZero(Coeff)) {
962 dbgs() << "\t Coefficient proven non-zero by SCEV analysis\n");
963 } else {
964 // Cannot prove at compile time, would need runtime assumption.
965 if (UnderRuntimeAssumptions) {
966 const SCEVPredicate *Pred = SE->getComparePredicate(
967 ICmpInst::ICMP_NE, Coeff, SE->getZero(Coeff->getType()));
968 Result.Assumptions = Result.Assumptions.getUnionWith(Pred, *SE);
969 LLVM_DEBUG(dbgs() << "\t Added runtime assumption: " << *Coeff
970 << " != 0\n");
971 } else {
972 // Cannot add runtime assumptions, this test cannot handle this case.
973 // Let more complex tests try.
974 LLVM_DEBUG(dbgs() << "\t Would need runtime assumption " << *Coeff
975 << " != 0, but not allowed. Failing this test.\n");
976 return false;
977 }
978 }
979 // Since 0/X == 0 (where X is known non-zero or assumed non-zero).
980 Result.DV[Level].Distance = Delta;
981 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
982 ++StrongSIVsuccesses;
983 } else {
984 if (Coeff->isOne()) {
985 LLVM_DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
986 Result.DV[Level].Distance = Delta; // since X/1 == X
987 }
988
989 // maybe we can get a useful direction
990 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
991 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
992 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
993 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
994 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
995 // The double negatives above are confusing.
996 // It helps to read !SE->isKnownNonZero(Delta)
997 // as "Delta might be Zero"
998 unsigned NewDirection = Dependence::DVEntry::NONE;
999 if ((DeltaMaybePositive && CoeffMaybePositive) ||
1000 (DeltaMaybeNegative && CoeffMaybeNegative))
1001 NewDirection = Dependence::DVEntry::LT;
1002 if (DeltaMaybeZero)
1003 NewDirection |= Dependence::DVEntry::EQ;
1004 if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1005 (DeltaMaybePositive && CoeffMaybeNegative))
1006 NewDirection |= Dependence::DVEntry::GT;
1007 if (NewDirection < Result.DV[Level].Direction)
1008 ++StrongSIVsuccesses;
1009 Result.DV[Level].Direction &= NewDirection;
1010 }
1011 return false;
1012}
1013
1014// weakCrossingSIVtest -
1015// From the paper, Practical Dependence Testing, Section 4.2.2
1016//
1017// When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1018// where i is an induction variable, c1 and c2 are loop invariant,
1019// and a is a constant, we can solve it exactly using the
1020// Weak-Crossing SIV test.
1021//
1022// Given c1 + a*i = c2 - a*i', we can look for the intersection of
1023// the two lines, where i = i', yielding
1024//
1025// c1 + a*i = c2 - a*i
1026// 2a*i = c2 - c1
1027// i = (c2 - c1)/2a
1028//
1029// If i < 0, there is no dependence.
1030// If i > upperbound, there is no dependence.
1031// If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1032// If i = upperbound, there's a dependence with distance = 0.
1033// If i is integral, there's a dependence (all directions).
1034// If the non-integer part = 1/2, there's a dependence (<> directions).
1035// Otherwise, there's no dependence.
1036//
1037// Can prove independence. Failing that,
1038// can sometimes refine the directions.
1039// Can determine iteration for splitting.
1040//
1041// Return true if dependence disproved.
1042bool DependenceInfo::weakCrossingSIVtest(const SCEVAddRecExpr *Src,
1043 const SCEVAddRecExpr *Dst,
1044 unsigned Level,
1045 FullDependence &Result) const {
1047 return false;
1048
1049 const SCEV *Coeff = Src->getStepRecurrence(*SE);
1050 const SCEV *SrcConst = Src->getStart();
1051 const SCEV *DstConst = Dst->getStart();
1052
1053 assert(Coeff == SE->getNegativeSCEV(Dst->getStepRecurrence(*SE)) &&
1054 "Unexpected input for weakCrossingSIVtest");
1055
1056 LLVM_DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1057 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
1058 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1059 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1060 ++WeakCrossingSIVapplications;
1061 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1062 Level--;
1063 const SCEV *Delta = minusSCEVNoSignedOverflow(DstConst, SrcConst, *SE);
1064 if (!Delta)
1065 return false;
1066
1067 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1068 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1069 if (!ConstCoeff)
1070 return false;
1071
1072 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1073 if (!ConstDelta)
1074 return false;
1075
1076 ConstantRange SrcRange = SE->getSignedRange(Src);
1077 ConstantRange DstRange = SE->getSignedRange(Dst);
1078 LLVM_DEBUG(dbgs() << "\t SrcRange = " << SrcRange << "\n");
1079 LLVM_DEBUG(dbgs() << "\t DstRange = " << DstRange << "\n");
1080 if (SrcRange.intersectWith(DstRange).isSingleElement()) {
1081 // The ranges touch at exactly one value (i = i' = 0 or i = i' = BTC).
1082 Result.DV[Level].Direction &= ~Dependence::DVEntry::LT;
1083 Result.DV[Level].Direction &= ~Dependence::DVEntry::GT;
1084 ++WeakCrossingSIVsuccesses;
1085 if (!Result.DV[Level].Direction) {
1086 ++WeakCrossingSIVindependence;
1087 return true;
1088 }
1089 Result.DV[Level].Distance = SE->getZero(Delta->getType());
1090 return false;
1091 }
1092
1093 // check that Coeff divides Delta
1094 APInt APDelta = ConstDelta->getAPInt();
1095 APInt APCoeff = ConstCoeff->getAPInt();
1096 APInt Distance = APDelta; // these need to be initialzed
1097 APInt Remainder = APDelta;
1098 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
1099 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1100 if (Remainder != 0) {
1101 // Coeff doesn't divide Delta, no dependence
1102 ++WeakCrossingSIVindependence;
1103 ++WeakCrossingSIVsuccesses;
1104 return true;
1105 }
1106 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1107
1108 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1109 if (Distance[0]) {
1110 // Equal direction isn't possible
1111 Result.DV[Level].Direction &= ~Dependence::DVEntry::EQ;
1112 ++WeakCrossingSIVsuccesses;
1113 }
1114 return false;
1115}
1116
1117// Kirch's algorithm, from
1118//
1119// Optimizing Supercompilers for Supercomputers
1120// Michael Wolfe
1121// MIT Press, 1989
1122//
1123// Program 2.1, page 29.
1124// Computes the GCD of AM and BM.
1125// Also finds a solution to the equation ax - by = gcd(a, b).
1126// Returns true if dependence disproved; i.e., gcd does not divide Delta.
1127//
1128// We don't use OverflowSafeSignedAPInt here because it's known that this
1129// algorithm doesn't overflow.
1130static std::optional<bool> findGCD(unsigned Bits, const APInt &AM,
1131 const APInt &BM, const APInt &Delta,
1132 APInt &G, APInt &X, APInt &Y) {
1133 LLVM_DEBUG(dbgs() << "\t AM = " << AM << "\n");
1134 LLVM_DEBUG(dbgs() << "\t BM = " << BM << "\n");
1135 LLVM_DEBUG(dbgs() << "\t Delta = " << Delta << "\n");
1136 APInt A0(Bits, 1, true), A1(Bits, 0, true);
1137 APInt B0(Bits, 0, true), B1(Bits, 1, true);
1138
1139 // APInt::abs will overflow. In that case, bail out early.
1140 if (AM.isMinSignedValue() || BM.isMinSignedValue())
1141 return std::nullopt;
1142
1143 APInt G0 = AM.abs();
1144 APInt G1 = BM.abs();
1145 APInt Q = G0; // these need to be initialized
1146 APInt R = G0;
1147 APInt::sdivrem(G0, G1, Q, R);
1148 while (R != 0) {
1149 // clang-format off
1150 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1151 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1152 G0 = G1; G1 = R;
1153 // clang-format on
1154 APInt::sdivrem(G0, G1, Q, R);
1155 }
1156 G = G1;
1157 LLVM_DEBUG(dbgs() << "\t GCD = " << G << "\n");
1158 X = AM.slt(0) ? -A1 : A1;
1159 Y = BM.slt(0) ? B1 : -B1;
1160
1161 // make sure gcd divides Delta
1162 R = Delta.srem(G);
1163 if (R != 0)
1164 return true; // gcd doesn't divide Delta, no dependence
1165 Q = Delta.sdiv(G);
1166 return false;
1167}
1168
1169static OverflowSafeSignedAPInt
1170floorOfQuotient(const OverflowSafeSignedAPInt &OA,
1171 const OverflowSafeSignedAPInt &OB) {
1172 if (!OA || !OB)
1173 return OverflowSafeSignedAPInt();
1174
1175 APInt A = *OA;
1176 APInt B = *OB;
1177 APInt Q = A; // these need to be initialized
1178 APInt R = A;
1179 APInt::sdivrem(A, B, Q, R);
1180 if (R == 0)
1181 return Q;
1182 if ((A.sgt(0) && B.sgt(0)) || (A.slt(0) && B.slt(0)))
1183 return Q;
1184 return OverflowSafeSignedAPInt(Q) - 1;
1185}
1186
1187static OverflowSafeSignedAPInt
1188ceilingOfQuotient(const OverflowSafeSignedAPInt &OA,
1189 const OverflowSafeSignedAPInt &OB) {
1190 if (!OA || !OB)
1191 return OverflowSafeSignedAPInt();
1192
1193 APInt A = *OA;
1194 APInt B = *OB;
1195 APInt Q = A; // these need to be initialized
1196 APInt R = A;
1197 APInt::sdivrem(A, B, Q, R);
1198 if (R == 0)
1199 return Q;
1200 if ((A.sgt(0) && B.sgt(0)) || (A.slt(0) && B.slt(0)))
1201 return OverflowSafeSignedAPInt(Q) + 1;
1202 return Q;
1203}
1204
1205/// Given an affine expression of the form A*k + B, where k is an arbitrary
1206/// integer, infer the possible range of k based on the known range of the
1207/// affine expression. If we know A*k + B is non-negative, i.e.,
1208///
1209/// A*k + B >=s 0
1210///
1211/// we can derive the following inequalities for k when A is positive:
1212///
1213/// k >=s -B / A
1214///
1215/// Since k is an integer, it means k is greater than or equal to the
1216/// ceil(-B / A).
1217///
1218/// If the upper bound of the affine expression \p UB is passed, the following
1219/// inequality can be derived as well:
1220///
1221/// A*k + B <=s UB
1222///
1223/// which leads to:
1224///
1225/// k <=s (UB - B) / A
1226///
1227/// Again, as k is an integer, it means k is less than or equal to the
1228/// floor((UB - B) / A).
1229///
1230/// The similar logic applies when A is negative, but the inequalities sign flip
1231/// while working with them.
1232///
1233/// Preconditions: \p A is non-zero, and we know A*k + B and \p UB are
1234/// non-negative.
1235static std::pair<OverflowSafeSignedAPInt, OverflowSafeSignedAPInt>
1236inferDomainOfAffine(OverflowSafeSignedAPInt A, OverflowSafeSignedAPInt B,
1237 OverflowSafeSignedAPInt UB) {
1238 assert(A && B && "A and B must be available");
1239 assert(*A != 0 && "A must be non-zero");
1240 assert((!UB || UB->isNonNegative()) && "UB must be non-negative");
1241 OverflowSafeSignedAPInt TL, TU;
1242 if (A->sgt(0)) {
1243 TL = ceilingOfQuotient(-B, A);
1244 LLVM_DEBUG(if (TL) dbgs() << "\t Possible TL = " << *TL << "\n");
1245
1246 // New bound check - modification to Banerjee's e3 check
1247 TU = floorOfQuotient(UB - B, A);
1248 LLVM_DEBUG(if (TU) dbgs() << "\t Possible TU = " << *TU << "\n");
1249 } else {
1250 TU = floorOfQuotient(-B, A);
1251 LLVM_DEBUG(if (TU) dbgs() << "\t Possible TU = " << *TU << "\n");
1252
1253 // New bound check - modification to Banerjee's e3 check
1254 TL = ceilingOfQuotient(UB - B, A);
1255 LLVM_DEBUG(if (TL) dbgs() << "\t Possible TL = " << *TL << "\n");
1256 }
1257 return std::make_pair(TL, TU);
1258}
1259
1260// exactSIVtest -
1261// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1262// where i is an induction variable, c1 and c2 are loop invariant, and a1
1263// and a2 are constant, we can solve it exactly using an algorithm developed
1264// by Banerjee and Wolfe. See Algorithm 6.2.1 (case 2.5) in:
1265//
1266// Dependence Analysis for Supercomputing
1267// Utpal Banerjee
1268// Kluwer Academic Publishers, 1988
1269//
1270// It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1271// so use them if possible. They're also a bit better with symbolics and,
1272// in the case of the strong SIV test, can compute Distances.
1273//
1274// Return true if dependence disproved.
1275//
1276// This is a modified version of the original Banerjee algorithm. The original
1277// only tested whether Dst depends on Src. This algorithm extends that and
1278// returns all the dependencies that exist between Dst and Src.
1279bool DependenceInfo::exactSIVtest(const SCEVAddRecExpr *Src,
1280 const SCEVAddRecExpr *Dst, unsigned Level,
1281 FullDependence &Result) const {
1283 return false;
1284
1285 LLVM_DEBUG(dbgs() << "\tExact SIV test\n");
1286 ++ExactSIVapplications;
1287 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1288 Level--;
1289 bool Res = exactTestImpl(Src, Dst, Result, Level);
1290 if (Res) {
1291 ++ExactSIVsuccesses;
1292 ++ExactSIVindependence;
1293 }
1294 return Res;
1295}
1296
1297// Return true if the divisor evenly divides the dividend.
1298static bool isRemainderZero(const SCEVConstant *Dividend,
1299 const SCEVConstant *Divisor) {
1300 const APInt &ConstDividend = Dividend->getAPInt();
1301 const APInt &ConstDivisor = Divisor->getAPInt();
1302 return ConstDividend.srem(ConstDivisor) == 0;
1303}
1304
1305bool DependenceInfo::weakZeroSIVtestImpl(const SCEVAddRecExpr *AR,
1306 const SCEV *Const, unsigned Level,
1307 FullDependence &Result) const {
1308 const SCEV *ARCoeff = AR->getStepRecurrence(*SE);
1309 const SCEV *ARConst = AR->getStart();
1310
1311 if (Const == ARConst && SE->isKnownNonZero(ARCoeff)) {
1312 if (Level < CommonLevels) {
1313 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1314 ++WeakZeroSIVsuccesses;
1315 }
1316 return false; // dependences caused by first iteration
1317 }
1318
1319 const SCEV *Delta = minusSCEVNoSignedOverflow(Const, ARConst, *SE);
1320 if (!Delta)
1321 return false;
1322 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(ARCoeff);
1323 if (!ConstCoeff)
1324 return false;
1325
1326 if (const SCEV *UpperBound =
1327 collectUpperBound(AR->getLoop(), Delta->getType())) {
1328 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1329 bool OverlapAtLast = [&] {
1330 if (!SE->isKnownNonZero(ConstCoeff))
1331 return false;
1332 const SCEV *Last = AR->evaluateAtIteration(UpperBound, *SE);
1333 return Last == Const;
1334 }();
1335 if (OverlapAtLast) {
1336 // dependences caused by last iteration
1337 if (Level < CommonLevels) {
1338 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1339 ++WeakZeroSIVsuccesses;
1340 }
1341 return false;
1342 }
1343 }
1344
1345 // if ARCoeff doesn't divide Delta, then no dependence
1346 if (isa<SCEVConstant>(Delta) &&
1347 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1348 ++WeakZeroSIVindependence;
1349 ++WeakZeroSIVsuccesses;
1350 return true;
1351 }
1352 return false;
1353}
1354
1355// weakZeroSrcSIVtest -
1356// From the paper, Practical Dependence Testing, Section 4.2.2
1357//
1358// When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1359// where i is an induction variable, c1 and c2 are loop invariant,
1360// and a is a constant, we can solve it exactly using the
1361// Weak-Zero SIV test.
1362//
1363// Given
1364//
1365// c1 = c2 + a*i
1366//
1367// we get
1368//
1369// (c1 - c2)/a = i
1370//
1371// If i is not an integer, there's no dependence.
1372// If i < 0 or > UB, there's no dependence.
1373// If i = 0, the direction is >=.
1374// If i = UB, the direction is <=.
1375// Otherwise, the direction is *.
1376//
1377// Can prove independence. Failing that, we can sometimes refine
1378// the directions. Can sometimes show that first or last
1379// iteration carries all the dependences (so worth peeling).
1380//
1381// (see also weakZeroDstSIVtest)
1382//
1383// Return true if dependence disproved.
1384bool DependenceInfo::weakZeroSrcSIVtest(const SCEV *SrcConst,
1385 const SCEVAddRecExpr *Dst,
1386 unsigned Level,
1387 FullDependence &Result) const {
1389 return false;
1390
1391 // For the WeakSIV test, it's possible the loop isn't common to
1392 // the Src and Dst loops. If it isn't, then there's no need to
1393 // record a direction.
1394 [[maybe_unused]] const SCEV *DstCoeff = Dst->getStepRecurrence(*SE);
1395 [[maybe_unused]] const SCEV *DstConst = Dst->getStart();
1396 LLVM_DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1397 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1398 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1399 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1400 ++WeakZeroSIVapplications;
1401 assert(0 < Level && Level <= MaxLevels && "Level out of range");
1402 Level--;
1403
1404 // We have analyzed a dependence from Src to Dst, so \c Result may represent a
1405 // dependence in that direction. However, \c weakZeroSIVtestImpl will analyze
1406 // a dependence from \c Dst to \c SrcConst. To keep the consistency, we need
1407 // to negate the current result before passing it to \c weakZeroSIVtestImpl,
1408 // and negate it back after that.
1409 Result.negate(*SE);
1410 bool Res = weakZeroSIVtestImpl(Dst, SrcConst, Level, Result);
1411 Result.negate(*SE);
1412 return Res;
1413}
1414
1415// weakZeroDstSIVtest -
1416// From the paper, Practical Dependence Testing, Section 4.2.2
1417//
1418// When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1419// where i is an induction variable, c1 and c2 are loop invariant,
1420// and a is a constant, we can solve it exactly using the
1421// Weak-Zero SIV test.
1422//
1423// Given
1424//
1425// c1 + a*i = c2
1426//
1427// we get
1428//
1429// i = (c2 - c1)/a
1430//
1431// If i is not an integer, there's no dependence.
1432// If i < 0 or > UB, there's no dependence.
1433// If i = 0, the direction is <=.
1434// If i = UB, the direction is >=.
1435// Otherwise, the direction is *.
1436//
1437// Can prove independence. Failing that, we can sometimes refine
1438// the directions. Can sometimes show that first or last
1439// iteration carries all the dependences (so worth peeling).
1440//
1441// (see also weakZeroSrcSIVtest)
1442//
1443// Return true if dependence disproved.
1444bool DependenceInfo::weakZeroDstSIVtest(const SCEVAddRecExpr *Src,
1445 const SCEV *DstConst, unsigned Level,
1446 FullDependence &Result) const {
1448 return false;
1449
1450 // For the WeakSIV test, it's possible the loop isn't common to the
1451 // Src and Dst loops. If it isn't, then there's no need to record a direction.
1452 [[maybe_unused]] const SCEV *SrcCoeff = Src->getStepRecurrence(*SE);
1453 [[maybe_unused]] const SCEV *SrcConst = Src->getStart();
1454 LLVM_DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1455 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1456 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1457 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1458 ++WeakZeroSIVapplications;
1459 assert(0 < Level && Level <= SrcLevels && "Level out of range");
1460 Level--;
1461
1462 return weakZeroSIVtestImpl(Src, DstConst, Level, Result);
1463}
1464
1465// exactRDIVtest - Tests the RDIV subscript pair for dependence.
1466// Things of the form [c1 + a*i] and [c2 + b*j],
1467// where i and j are induction variable, c1 and c2 are loop invariant,
1468// and a and b are constants.
1469// Returns true if any possible dependence is disproved.
1470// Works in some cases that symbolicRDIVtest doesn't, and vice versa.
1471bool DependenceInfo::exactRDIVtest(const SCEVAddRecExpr *Src,
1472 const SCEVAddRecExpr *Dst,
1473 FullDependence &Result) const {
1475 return false;
1476
1477 LLVM_DEBUG(dbgs() << "\tExact RDIV test\n");
1478 ++ExactRDIVapplications;
1479 bool Res = exactTestImpl(Src, Dst, Result, std::nullopt);
1480 if (Res)
1481 ++ExactRDIVindependence;
1482 return Res;
1483}
1484
1485bool DependenceInfo::exactTestImpl(const SCEVAddRecExpr *Src,
1486 const SCEVAddRecExpr *Dst,
1487 FullDependence &Result,
1488 std::optional<unsigned> Level) const {
1489 const SCEV *SrcCoeff = Src->getStepRecurrence(*SE);
1490 const SCEV *SrcConst = Src->getStart();
1491 const SCEV *DstCoeff = Dst->getStepRecurrence(*SE);
1492 const SCEV *DstConst = Dst->getStart();
1493 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1494 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1495 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1496 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1497
1498 const SCEV *Delta = minusSCEVNoSignedOverflow(DstConst, SrcConst, *SE);
1499 if (!Delta)
1500 return false;
1501 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1502 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1503 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1504 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1505 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1506 return false;
1507
1508 // find gcd
1509 APInt G, X, Y;
1510 APInt AM = ConstSrcCoeff->getAPInt();
1511 APInt BM = ConstDstCoeff->getAPInt();
1512 APInt CM = ConstDelta->getAPInt();
1513 unsigned Bits = AM.getBitWidth();
1514 std::optional<bool> GCDRes = findGCD(Bits, AM, BM, CM, G, X, Y);
1515
1516 // GCD calculation failed so we cannot proceed with this test.
1517 if (!GCDRes)
1518 return false;
1519 if (*GCDRes) {
1520 // gcd doesn't divide Delta, no dependence
1521 return true;
1522 }
1523
1524 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1525
1526 // since SCEV construction seems to normalize, LM = 0
1527 std::optional<APInt> SrcUM =
1528 collectNonNegativeConstantUpperBound(Src->getLoop(), Delta->getType());
1529 if (SrcUM)
1530 LLVM_DEBUG(dbgs() << "\t SrcUM = " << *SrcUM << "\n");
1531
1532 std::optional<APInt> DstUM =
1533 collectNonNegativeConstantUpperBound(Dst->getLoop(), Delta->getType());
1534 if (DstUM)
1535 LLVM_DEBUG(dbgs() << "\t DstUM = " << *DstUM << "\n");
1536
1537 OverflowSafeSignedAPInt TC = CM.sdiv(G);
1538 OverflowSafeSignedAPInt TX = OverflowSafeSignedAPInt(X) * TC;
1539 OverflowSafeSignedAPInt TY = OverflowSafeSignedAPInt(Y) * TC;
1540 if (!TC || !TX || !TY)
1541 return false;
1542 LLVM_DEBUG(dbgs() << "\t TC = " << *TC << "\n");
1543 LLVM_DEBUG(dbgs() << "\t TX = " << *TX << "\n");
1544 LLVM_DEBUG(dbgs() << "\t TY = " << *TY << "\n");
1545
1546 APInt TB = BM.sdiv(G);
1547 APInt TA = AM.sdiv(G);
1548
1549 // At this point, we have the following equations:
1550 //
1551 // TA*i - TB*j = TC
1552 //
1553 // Also, we know that the all pairs of (i, j) can be expressed as:
1554 //
1555 // (TX + k*TB, TY + k*TA)
1556 //
1557 // where k is an arbitrary integer.
1558 auto [TL0, TU0] = inferDomainOfAffine(TB, TX, SrcUM);
1559 auto [TL1, TU1] = inferDomainOfAffine(TA, TY, DstUM);
1560
1561 LLVM_DEBUG(dbgs() << "\t TA = " << TA << "\n");
1562 LLVM_DEBUG(dbgs() << "\t TB = " << TB << "\n");
1563
1564 auto GetMaxOrMin = [](const OverflowSafeSignedAPInt &V0,
1565 const OverflowSafeSignedAPInt &V1,
1566 bool IsMin) -> std::optional<APInt> {
1567 if (V0 && V1)
1568 return IsMin ? APIntOps::smin(*V0, *V1) : APIntOps::smax(*V0, *V1);
1569 if (V0)
1570 return *V0;
1571 if (V1)
1572 return *V1;
1573 return std::nullopt;
1574 };
1575
1576 std::optional<APInt> OptTL = GetMaxOrMin(TL0, TL1, false);
1577 std::optional<APInt> OptTU = GetMaxOrMin(TU0, TU1, true);
1578 if (!OptTL || !OptTU)
1579 return false;
1580
1581 APInt TL = std::move(*OptTL);
1582 APInt TU = std::move(*OptTU);
1583 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
1584 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
1585
1586 if (TL.sgt(TU))
1587 return true;
1588
1589 if (!Level)
1590 return false;
1591 assert(SrcUM == DstUM && "Expecting same upper bound for Src and Dst");
1592
1593 // explore directions
1594 unsigned NewDirection = Dependence::DVEntry::NONE;
1595 OverflowSafeSignedAPInt LowerDistance, UpperDistance;
1596 OverflowSafeSignedAPInt OTY(TY), OTX(TX), OTA(TA), OTB(TB), OTL(TL), OTU(TU);
1597 // NOTE: It's unclear whether these calculations can overflow. At the moment,
1598 // we conservatively assume they can.
1599 if (TA.sgt(TB)) {
1600 LowerDistance = (OTY - OTX) + (OTA - OTB) * OTL;
1601 UpperDistance = (OTY - OTX) + (OTA - OTB) * OTU;
1602 } else {
1603 LowerDistance = (OTY - OTX) + (OTA - OTB) * OTU;
1604 UpperDistance = (OTY - OTX) + (OTA - OTB) * OTL;
1605 }
1606
1607 if (!LowerDistance || !UpperDistance)
1608 return false;
1609
1610 LLVM_DEBUG(dbgs() << "\t LowerDistance = " << *LowerDistance << "\n");
1611 LLVM_DEBUG(dbgs() << "\t UpperDistance = " << *UpperDistance << "\n");
1612
1613 if (LowerDistance->sle(0) && UpperDistance->sge(0))
1614 NewDirection |= Dependence::DVEntry::EQ;
1615 if (LowerDistance->slt(0))
1616 NewDirection |= Dependence::DVEntry::GT;
1617 if (UpperDistance->sgt(0))
1618 NewDirection |= Dependence::DVEntry::LT;
1619
1620 // finished
1621 Result.DV[*Level].Direction &= NewDirection;
1622 LLVM_DEBUG(dbgs() << "\t Result = ");
1623 LLVM_DEBUG(Result.dump(dbgs()));
1624 return Result.DV[*Level].Direction == Dependence::DVEntry::NONE;
1625}
1626
1627// testSIV -
1628// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
1629// where i is an induction variable, c1 and c2 are loop invariant, and a1 and
1630// a2 are constant, we attack it with an SIV test. While they can all be
1631// solved with the Exact SIV test, it's worthwhile to use simpler tests when
1632// they apply; they're cheaper and sometimes more precise.
1633//
1634// Return true if dependence disproved.
1635bool DependenceInfo::testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
1636 FullDependence &Result,
1637 bool UnderRuntimeAssumptions) {
1638 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
1639 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
1640 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
1641 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
1642 if (SrcAddRec && DstAddRec) {
1643 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
1644 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
1645 const Loop *CurSrcLoop = SrcAddRec->getLoop();
1646 [[maybe_unused]] const Loop *CurDstLoop = DstAddRec->getLoop();
1647 assert(haveSameSD(CurSrcLoop, CurDstLoop) &&
1648 "Loops in the SIV test should have the same iteration space and "
1649 "depth");
1650 Level = mapSrcLoop(CurSrcLoop);
1651 bool disproven = false;
1652 if (SrcCoeff == DstCoeff)
1653 disproven = strongSIVtest(SrcAddRec, DstAddRec, Level, Result,
1654 UnderRuntimeAssumptions);
1655 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
1656 disproven = weakCrossingSIVtest(SrcAddRec, DstAddRec, Level, Result);
1657 return disproven || exactSIVtest(SrcAddRec, DstAddRec, Level, Result);
1658 }
1659 if (SrcAddRec) {
1660 const Loop *CurSrcLoop = SrcAddRec->getLoop();
1661 Level = mapSrcLoop(CurSrcLoop);
1662 return weakZeroDstSIVtest(SrcAddRec, Dst, Level, Result);
1663 }
1664 if (DstAddRec) {
1665 const Loop *CurDstLoop = DstAddRec->getLoop();
1666 Level = mapDstLoop(CurDstLoop);
1667 return weakZeroSrcSIVtest(Src, DstAddRec, Level, Result);
1668 }
1669 llvm_unreachable("SIV test expected at least one AddRec");
1670 return false;
1671}
1672
1673// testRDIV -
1674// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
1675// where i and j are induction variables, c1 and c2 are loop invariant,
1676// and a1 and a2 are constant, we can solve it exactly with an easy adaptation
1677// of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
1678// It doesn't make sense to talk about distance or direction in this case,
1679// so there's no point in making special versions of the Strong SIV test or
1680// the Weak-crossing SIV test.
1681//
1682// Return true if dependence disproved.
1683bool DependenceInfo::testRDIV(const SCEV *Src, const SCEV *Dst,
1684 FullDependence &Result) const {
1685 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
1686 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
1687 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
1688 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
1689 assert(SrcAddRec && DstAddRec && "Unexpected non-addrec input");
1690 return exactRDIVtest(SrcAddRec, DstAddRec, Result) ||
1691 gcdMIVtest(Src, Dst, Result);
1692}
1693
1694// Tests the single-subscript MIV pair (Src and Dst) for dependence.
1695// Return true if dependence disproved.
1696// Can sometimes refine direction vectors.
1697bool DependenceInfo::testMIV(const SCEV *Src, const SCEV *Dst,
1698 const SmallBitVector &Loops,
1699 FullDependence &Result) const {
1700 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
1701 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
1702 return gcdMIVtest(Src, Dst, Result) ||
1703 banerjeeMIVtest(Src, Dst, Loops, Result);
1704}
1705
1706/// Given a SCEVMulExpr, returns its first operand if its first operand is a
1707/// constant and the product doesn't overflow in a signed sense. Otherwise,
1708/// returns std::nullopt. For example, given (10 * X * Y)<nsw>, it returns 10.
1709/// Notably, if it doesn't have nsw, the multiplication may overflow, and if
1710/// so, it may not a multiple of 10.
1711static std::optional<APInt> getConstantCoefficient(const SCEV *Expr) {
1712 if (const auto *Constant = dyn_cast<SCEVConstant>(Expr))
1713 return Constant->getAPInt();
1714 if (const auto *Product = dyn_cast<SCEVMulExpr>(Expr))
1715 if (const auto *Constant = dyn_cast<SCEVConstant>(Product->getOperand(0)))
1716 if (Product->hasNoSignedWrap())
1717 return Constant->getAPInt();
1718 return std::nullopt;
1719}
1720
1721const SCEV *DependenceInfo::accumulateCoefficientsGCD(const SCEV *Expr,
1722 const Loop *CurLoop,
1723 const SCEV *&CurLoopCoeff,
1724 APInt &RunningGCD) const {
1725 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
1726 if (!AddRec) {
1727 assert(isLoopInvariant(Expr, CurLoop) &&
1728 "Expected loop invariant expression");
1729 return Expr;
1730 }
1731
1732 assert(AddRec->isAffine() && "Unexpected Expr");
1733 const SCEV *Start = AddRec->getStart();
1734 const SCEV *Step = AddRec->getStepRecurrence(*SE);
1735 if (AddRec->getLoop() == CurLoop) {
1736 CurLoopCoeff = Step;
1737 } else {
1738 std::optional<APInt> ConstCoeff = getConstantCoefficient(Step);
1739
1740 // If the coefficient is the product of a constant and other stuff, we can
1741 // use the constant in the GCD computation.
1742 if (!ConstCoeff)
1743 return nullptr;
1744
1745 // TODO: What happens if ConstCoeff is the "most negative" signed number
1746 // (e.g. -128 for 8 bit wide APInt)?
1747 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
1748 }
1749
1750 return accumulateCoefficientsGCD(Start, CurLoop, CurLoopCoeff, RunningGCD);
1751}
1752
1753//===----------------------------------------------------------------------===//
1754// gcdMIVtest -
1755// Tests an MIV subscript pair for dependence.
1756// Returns true if any possible dependence is disproved.
1757// Can sometimes disprove the equal direction for 1 or more loops,
1758// as discussed in Michael Wolfe's book,
1759// High Performance Compilers for Parallel Computing, page 235.
1760//
1761// We spend some effort (code!) to handle cases like
1762// [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
1763// but M and N are just loop-invariant variables.
1764// This should help us handle linearized subscripts;
1765// also makes this test a useful backup to the various SIV tests.
1766//
1767// It occurs to me that the presence of loop-invariant variables
1768// changes the nature of the test from "greatest common divisor"
1769// to "a common divisor".
1770bool DependenceInfo::gcdMIVtest(const SCEV *Src, const SCEV *Dst,
1771 FullDependence &Result) const {
1773 return false;
1774
1775 LLVM_DEBUG(dbgs() << "starting gcd\n");
1776 ++GCDapplications;
1777 unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
1778 APInt RunningGCD = APInt::getZero(BitWidth);
1779
1780 const SCEV *Dummy = nullptr;
1781 const SCEV *SrcConst =
1782 accumulateCoefficientsGCD(Src, nullptr, Dummy, RunningGCD);
1783 if (!SrcConst)
1784 return false;
1785 const SCEV *DstConst =
1786 accumulateCoefficientsGCD(Dst, nullptr, Dummy, RunningGCD);
1787 if (!DstConst)
1788 return false;
1789
1790 const SCEV *Delta = minusSCEVNoSignedOverflow(DstConst, SrcConst, *SE);
1791 if (!Delta)
1792 return false;
1793 LLVM_DEBUG(dbgs() << " Delta = " << *Delta << "\n");
1794 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
1795 if (!Constant)
1796 return false;
1797 APInt ConstDelta = Constant->getAPInt();
1798 LLVM_DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
1799 if (ConstDelta == 0)
1800 return false;
1801 LLVM_DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
1802 APInt Remainder = ConstDelta.srem(RunningGCD);
1803 if (Remainder != 0) {
1804 ++GCDindependence;
1805 return true;
1806 }
1807
1808 // Try to disprove equal directions.
1809 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
1810 // the code above can't disprove the dependence because the GCD = 1.
1811 // So we consider what happen if i = i' and what happens if j = j'.
1812 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
1813 // which is infeasible, so we can disallow the = direction for the i level.
1814 // Setting j = j' doesn't help matters, so we end up with a direction vector
1815 // of [<>, *]
1816
1817 bool Improved = false;
1818 const SCEV *Coefficients = Src;
1819 while (const SCEVAddRecExpr *AddRec =
1820 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
1821 Coefficients = AddRec->getStart();
1822 const Loop *CurLoop = AddRec->getLoop();
1823 RunningGCD = 0;
1824 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
1825 const SCEV *DstCoeff = SE->getZero(SrcCoeff->getType());
1826
1827 if (!accumulateCoefficientsGCD(Src, CurLoop, SrcCoeff, RunningGCD) ||
1828 !accumulateCoefficientsGCD(Dst, CurLoop, DstCoeff, RunningGCD))
1829 return false;
1830
1831 Delta = minusSCEVNoSignedOverflow(DstCoeff, SrcCoeff, *SE);
1832 if (!Delta)
1833 continue;
1834 // If the coefficient is the product of a constant and other stuff,
1835 // we can use the constant in the GCD computation.
1836 std::optional<APInt> ConstCoeff = getConstantCoefficient(Delta);
1837 if (!ConstCoeff)
1838 // The difference of the two coefficients might not be a product
1839 // or constant, in which case we give up on this direction.
1840 continue;
1841 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
1842 LLVM_DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
1843 if (RunningGCD != 0) {
1844 Remainder = ConstDelta.srem(RunningGCD);
1845 LLVM_DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
1846 if (Remainder != 0) {
1847 unsigned Level = mapSrcLoop(CurLoop);
1848 Result.DV[Level - 1].Direction &= ~Dependence::DVEntry::EQ;
1849 Improved = true;
1850 }
1851 }
1852 }
1853 if (Improved)
1854 ++GCDsuccesses;
1855 LLVM_DEBUG(dbgs() << "all done\n");
1856 return false;
1857}
1858
1859//===----------------------------------------------------------------------===//
1860
1861namespace {
1862/// A closed signed interval containing the possible values of part of the
1863/// Banerjee subscript-difference expression.
1864/// A null Lower denotes -infinity, and a null Upper denotes +infinity. If
1865/// both finite endpoints are in reverse signed order (Lower >s Upper), the
1866/// interval is empty.
1867struct BanerjeeInterval {
1868 const SCEV *Lower;
1869 const SCEV *Upper;
1870
1871 BanerjeeInterval(const SCEV *Lower, const SCEV *Upper)
1872 : Lower(Lower), Upper(Upper) {}
1873
1874 bool isEmpty(ScalarEvolution &SE) const {
1875 return Lower && Upper &&
1877 }
1878};
1879} // namespace
1880
1881/// Add two intervals. A missing endpoint propagates the corresponding
1882/// infinity.
1883static BanerjeeInterval addIntervals(const BanerjeeInterval &A,
1884 const BanerjeeInterval &B,
1885 ScalarEvolution &SE) {
1886 const SCEV *Lower = nullptr;
1887 const SCEV *Upper = nullptr;
1888 if (A.Lower && B.Lower)
1889 Lower = SE.getAddExpr(A.Lower, B.Lower);
1890 if (A.Upper && B.Upper)
1891 Upper = SE.getAddExpr(A.Upper, B.Upper);
1892 return BanerjeeInterval(Lower, Upper);
1893}
1894
1895/// Intersect two intervals. Both inputs conservatively contain the feasible
1896/// values, so their intersection does too and may provide tighter one-sided
1897/// bounds.
1898static BanerjeeInterval intersectIntervals(const BanerjeeInterval &A,
1899 const BanerjeeInterval &B,
1900 ScalarEvolution &SE) {
1901 const SCEV *Lower = A.Lower;
1902 const SCEV *Upper = A.Upper;
1903 if (B.Lower)
1904 Lower = Lower ? SE.getSMaxExpr(Lower, B.Lower) : B.Lower;
1905 if (B.Upper)
1906 Upper = Upper ? SE.getSMinExpr(Upper, B.Upper) : B.Upper;
1907 return BanerjeeInterval(Lower, Upper);
1908}
1909
1910/// Return the singleton interval containing \p C.
1911static BanerjeeInterval constantInterval(const SCEV *C) {
1912 return BanerjeeInterval(C, C);
1913}
1914
1915/// Return the canonical empty interval [1, 0].
1916static BanerjeeInterval emptyInterval(Type *Ty, ScalarEvolution &SE) {
1917 return BanerjeeInterval(SE.getOne(Ty), SE.getZero(Ty));
1918}
1919
1920/// Compute the range of \p Coeff * X for \p Lower <=s X <=s \p Upper.
1921static BanerjeeInterval signedRangeInterval(const SCEV *Coeff,
1922 const SCEV *Lower,
1923 const SCEV *Upper,
1924 ScalarEvolution &SE) {
1925 // Coeff and the endpoints have already been extended to WideType. The
1926 // width proof in banerjeeMIVtest guarantees that these multiplications do
1927 // not wrap, so their SCEV values match mathematical signed integers.
1928 const SCEV *LowerValue = SE.getMulExpr(Coeff, Lower);
1929 const SCEV *UpperValue = SE.getMulExpr(Coeff, Upper);
1930 return BanerjeeInterval(SE.getSMinExpr(LowerValue, UpperValue),
1931 SE.getSMaxExpr(LowerValue, UpperValue));
1932}
1933
1934/// Compute the range of Coeff * X for 0 <= X <= Upper. A null Upper denotes
1935/// an unbounded nonnegative X.
1936static BanerjeeInterval variableInterval(const SCEV *Coeff, const SCEV *Upper,
1937 ScalarEvolution &SE) {
1938 const SCEV *Zero = SE.getZero(Coeff->getType());
1939 if (Coeff->isZero())
1940 return constantInterval(Zero);
1941 if (!Upper) {
1942 if (SE.isKnownNegative(Coeff))
1943 return BanerjeeInterval(nullptr, Zero);
1944 if (SE.isKnownNonNegative(Coeff))
1945 return BanerjeeInterval(Zero, nullptr);
1946 return BanerjeeInterval(nullptr, nullptr);
1947 }
1948 return signedRangeInterval(Coeff, Zero, Upper, SE);
1949}
1950
1951/// Compute any finite one-sided bound on
1952///
1953/// A * SrcIndex - B * DstIndex
1954///
1955/// for a strict direction when no upper bound is known for the nonnegative
1956/// normalized indices.
1957///
1958/// For SrcIndex < DstIndex, write DstIndex = SrcIndex + D, where D >= 1:
1959///
1960/// A * SrcIndex - B * DstIndex
1961/// = (A - B) * SrcIndex + (-B) * D.
1962///
1963/// If A - B >= 0 and B <= 0, both terms increase with their nonnegative
1964/// variables (SrcIndex and D), so the expression is bounded below by -B.
1965/// If A - B <= 0 and B >= 0, it is bounded above by -B.
1966///
1967/// For SrcIndex > DstIndex, write SrcIndex = DstIndex + D:
1968///
1969/// A * SrcIndex - B * DstIndex
1970/// = (A - B) * DstIndex + A * D.
1971///
1972/// If A - B >= 0 and A >= 0, the expression is bounded below by A.
1973/// If A - B <= 0 and A <= 0, it is bounded above by A.
1975 const SCEV *ACoeff, const SCEV *BCoeff, unsigned char Direction,
1976 ScalarEvolution &SE) {
1977 const SCEV *DeltaCoeff = SE.getMinusSCEV(ACoeff, BCoeff);
1978
1979 switch (Direction) {
1981 const SCEV *Boundary = SE.getNegativeSCEV(BCoeff);
1982 const SCEV *Lower = nullptr;
1983 const SCEV *Upper = nullptr;
1984 if (SE.isKnownNonNegative(DeltaCoeff) && SE.isKnownNonPositive(BCoeff))
1985 Lower = Boundary;
1986 if (SE.isKnownNonPositive(DeltaCoeff) && SE.isKnownNonNegative(BCoeff))
1987 Upper = Boundary;
1988 return BanerjeeInterval(Lower, Upper);
1989 }
1991 const SCEV *Lower = nullptr;
1992 const SCEV *Upper = nullptr;
1993 if (SE.isKnownNonNegative(ACoeff) && SE.isKnownNonNegative(DeltaCoeff))
1994 Lower = ACoeff;
1995 if (SE.isKnownNonPositive(ACoeff) && SE.isKnownNonPositive(DeltaCoeff))
1996 Upper = ACoeff;
1997 return BanerjeeInterval(Lower, Upper);
1998 }
1999 default:
2000 llvm_unreachable("unexpected direction");
2001 }
2002}
2003
2004/// Return the smallest closed interval containing Values.
2006 ScalarEvolution &SE) {
2007 assert(!Values.empty() && "expected at least one value");
2008 const SCEV *Lower = Values.front();
2009 const SCEV *Upper = Values.front();
2010 for (const SCEV *Value : Values.drop_front()) {
2013 }
2014 return BanerjeeInterval(Lower, Upper);
2015}
2016
2017/// Evaluate one loop level's contribution A * SrcIndex - B * DstIndex to the
2018/// complete source-minus-destination subscript difference.
2019static const SCEV *
2020evaluateSubscriptDifference(const SCEV *A, const SCEV *SrcIndex, const SCEV *B,
2021 const SCEV *DstIndex, ScalarEvolution &SE) {
2022 return SE.getMinusSCEV(SE.getMulExpr(A, SrcIndex),
2023 SE.getMulExpr(B, DstIndex));
2024}
2025
2026/// Return the widest type used by a subscript or by an exact backedge-taken
2027/// count of one of its recurrences.
2028static Type *getBanerjeeBaseType(const SCEV *Src, const SCEV *Dst,
2029 ScalarEvolution &SE) {
2030 Type *BaseType = SE.getWiderType(Src->getType(), Dst->getType());
2031 for (const SCEV *Subscript : {Src, Dst}) {
2032 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2033 const SCEV *MaxIterIndex = SE.getBackedgeTakenCount(AddRec->getLoop());
2034 if (!isa<SCEVCouldNotCompute>(MaxIterIndex))
2035 BaseType = SE.getWiderType(BaseType, MaxIterIndex->getType());
2036 Subscript = AddRec->getStart();
2037 }
2038 }
2039 return BaseType;
2040}
2041
2042/// banerjeeMIVtest -
2043/// Use Banerjee's Inequalities to test an MIV subscript pair.
2044/// (Wolfe calls this the Extreme Value Test; see Section 2.5.2 of
2045/// Optimizing Supercompilers for Supercomputers, Michael Wolfe.)
2046///
2047/// The original Wolfe formulae are algebraically simplified for normalized
2048/// loops (L_k=0, N_k=1); we now evaluate the subscript difference directly
2049/// at the vertices of the constraint polytope for each direction (e.g., (0,1),
2050/// (0,U), (U-1,U) for <). All operands are extended to a sufficiently wide
2051/// SCEV integer type before the arithmetic, so symbolic expressions remain
2052/// available to ScalarEvolution without wrapping intermediate results.
2053///
2054/// Loop bounds are backedge-taken counts (maximum normalized iteration
2055/// index). A single-iteration loop has bound 0, making < and > impossible.
2056/// Unknown interval endpoints are treated conservatively as infinities.
2057///
2058/// Return true if dependence disproved.
2059bool DependenceInfo::banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
2060 const SmallBitVector &Loops,
2061 FullDependence &Result) const {
2063 return false;
2064
2065 LLVM_DEBUG(dbgs() << "starting Banerjee\n");
2066 ++BanerjeeApplications;
2067
2068 Type *BaseType = getBanerjeeBaseType(Src, Dst, *SE);
2069 unsigned BaseBits = SE->getTypeSizeInBits(BaseType);
2070 // Let B be the maximum bit width among the source and destination
2071 // subscripts and the exact backedge-taken counts of the loops appearing
2072 // in their recurrences. Let L = MaxLevels. A coefficient C is a signed
2073 // B-bit value, so |C| <= 2^(B-1). A normalized iteration index I is a
2074 // nonnegative B-bit value, so I < 2^B. Therefore |C*I| < 2^(2B-1), and one
2075 // level's contribution |A*I-B*J| < 2^(2B). The accumulated
2076 // subscript-difference bound across L levels is less than
2077 // L*2^(2B) <= 2^(2B+L). One additional bit holds the sign, so 2B+L+1 bits
2078 // are sufficient for every intermediate Banerjee computation.
2079 unsigned WideBits = 2 * BaseBits + MaxLevels + 1;
2080 Type *WideType = IntegerType::get(F->getContext(), WideBits);
2081 const SCEV *Zero = SE->getZero(WideType);
2082
2083 CoefficientInfo EmptyCoeff{Zero, Zero, nullptr};
2084 SmallVector<CoefficientInfo, 4> CI(MaxLevels + 1, EmptyCoeff);
2085 assert(Loops.size() > MaxLevels && "loop bit vector is too small");
2086 assert(Result.Levels >= CommonLevels &&
2087 "direction vector is too small for common levels");
2088
2089 const SCEV *A0 = collectCoeffInfo(Src, true, WideType, CI);
2090 const SCEV *B0 = collectCoeffInfo(Dst, false, WideType, CI);
2091 const SCEV *Delta = SE->getMinusSCEV(B0, A0);
2092 LLVM_DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
2093
2094 SmallVector<BoundInfo, 4> Bound(MaxLevels + 1);
2095 for (unsigned K = 0; K <= MaxLevels; ++K) {
2096 Bound[K].Direction = Dependence::DVEntry::ALL;
2097 Bound[K].DirSet = Dependence::DVEntry::NONE;
2098 }
2099 for (unsigned K = 1; K <= MaxLevels; ++K) {
2100 findBoundsALL(CI, Bound, K);
2101 findBoundsLT(CI, Bound, K);
2102 findBoundsEQ(CI, Bound, K);
2103 findBoundsGT(CI, Bound, K);
2104 }
2105
2106 if (!testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2107 ++BanerjeeIndependence;
2108 return true;
2109 }
2110
2111 unsigned NewDeps = exploreDirections(1, Bound, Loops, Delta, Result);
2112 if (NewDeps == 0) {
2113 ++BanerjeeIndependence;
2114 return true;
2115 }
2116
2117 bool Improved = false;
2118 for (unsigned K = 1; K <= CommonLevels; ++K) {
2119 if (!Loops[K])
2120 continue;
2121 unsigned Old = Result.DV[K - 1].Direction;
2122 Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2123 Improved |= Old != Result.DV[K - 1].Direction;
2124 if (!Result.DV[K - 1].Direction) {
2125 ++BanerjeeIndependence;
2126 return true;
2127 }
2128 }
2129
2130 if (Improved)
2131 ++BanerjeeSuccesses;
2132 return false;
2133}
2134
2135/// Walks through the subscript and collects its coefficient at each loop
2136/// level. Each level has one maximum iteration index shared by the source and
2137/// destination coefficients. All collected values and the returned constant
2138/// term are extended to the widened analysis type before Banerjee arithmetic.
2139const SCEV *
2140DependenceInfo::collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
2141 Type *WideType,
2143 SmallBitVector SeenLevels(MaxLevels + 1);
2144 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2145 unsigned K =
2146 SrcFlag ? mapSrcLoop(AddRec->getLoop()) : mapDstLoop(AddRec->getLoop());
2147 assert(K > 0 && K <= MaxLevels && "invalid mapped loop level");
2148 assert(!SeenLevels[K] && "duplicate recurrence for loop level");
2149 SeenLevels.set(K);
2150
2151 const SCEV *Step = AddRec->getStepRecurrence(*SE);
2152 const SCEV *&Coeff = SrcFlag ? CI[K].SrcCoeff : CI[K].DstCoeff;
2153 Coeff = SE->getNoopOrSignExtend(Step, WideType);
2154
2155 const SCEV *MaxIterIndex = SE->getBackedgeTakenCount(AddRec->getLoop());
2156 if (!isa<SCEVCouldNotCompute>(MaxIterIndex)) {
2157 // A backedge-taken count is semantically an unsigned, nonnegative
2158 // iteration index. When its signed nonnegativity is also known, sign
2159 // extension preserves more symbolic relationships. Otherwise use zero
2160 // extension; this fallback does not assume that the value is negative.
2161 CI[K].MaxIterIndex =
2162 SE->isKnownNonNegative(MaxIterIndex)
2163 ? SE->getNoopOrSignExtend(MaxIterIndex, WideType)
2164 : SE->getNoopOrZeroExtend(MaxIterIndex, WideType);
2165 }
2166
2167 Subscript = AddRec->getStart();
2168 }
2169 return SE->getNoopOrSignExtend(Subscript, WideType);
2170}
2171
2172/// Looks through all the bounds info and computes the selected lower bound.
2173const SCEV *DependenceInfo::getLowerBound(ArrayRef<BoundInfo> Bound) const {
2174 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2175 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2176 if (!Bound[K].Lower[Bound[K].Direction])
2177 return nullptr;
2178 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2179 }
2180 return Sum;
2181}
2182
2183/// Looks through all the bounds info and computes the selected upper bound.
2184const SCEV *DependenceInfo::getUpperBound(ArrayRef<BoundInfo> Bound) const {
2185 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2186 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2187 if (!Bound[K].Upper[Bound[K].Direction])
2188 return nullptr;
2189 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2190 }
2191 return Sum;
2192}
2193
2194/// Returns false when the selected bounds are proven infeasible. Returns true
2195/// when they may be feasible or ScalarEvolution cannot decide.
2196bool DependenceInfo::testBounds(unsigned char DirKind, unsigned Level,
2198 const SCEV *Delta) const {
2199 Bound[Level].Direction = DirKind;
2200 for (unsigned K = 1; K <= MaxLevels; ++K) {
2201 unsigned char Direction = Bound[K].Direction;
2202 BanerjeeInterval Interval(Bound[K].Lower[Direction],
2203 Bound[K].Upper[Direction]);
2204 if (Interval.isEmpty(*SE))
2205 return false;
2206 }
2207 if (const SCEV *Lower = getLowerBound(Bound))
2208 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, Lower, Delta))
2209 return false;
2210 if (const SCEV *Upper = getUpperBound(Bound))
2211 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, Delta, Upper))
2212 return false;
2213 return true;
2214}
2215
2216/// Hierarchically expands the direction-vector search space.
2217unsigned DependenceInfo::exploreDirections(unsigned Level,
2219 const SmallBitVector &Loops,
2220 const SCEV *Delta,
2221 const FullDependence &Result) const {
2222 if (CommonLevels > Opts.da_miv_max_level_threshold) {
2223 LLVM_DEBUG(dbgs() << "Number of common levels exceeded the threshold. MIV "
2224 "direction exploration is terminated.\n");
2225 for (unsigned K = 1; K <= CommonLevels; ++K)
2226 if (Loops[K])
2227 Bound[K].DirSet = Dependence::DVEntry::ALL;
2228 return 1;
2229 }
2230
2231 if (Level > CommonLevels) {
2232 for (unsigned K = 1; K <= CommonLevels; ++K)
2233 if (Loops[K])
2234 Bound[K].DirSet |= Bound[K].Direction;
2235 return 1;
2236 }
2237
2238 if (!Loops[Level])
2239 return exploreDirections(Level + 1, Bound, Loops, Delta, Result);
2240
2241 unsigned NewDeps = 0;
2242 unsigned OldDirections = Result.DV[Level - 1].Direction;
2243 for (unsigned char Dir : {Dependence::DVEntry::LT, Dependence::DVEntry::EQ,
2245 if (!(OldDirections & Dir))
2246 continue;
2247 if (testBounds(Dir, Level, Bound, Delta))
2248 NewDeps += exploreDirections(Level + 1, Bound, Loops, Delta, Result);
2249 }
2250 Bound[Level].Direction = Dependence::DVEntry::ALL;
2251 return NewDeps;
2252}
2253
2254/// Computes the lower and upper bounds for level K using the * direction.
2255///
2256/// At this level the contribution to the subscript difference is
2257///
2258/// F_k(i, j) = A_k i - B_k j.
2259///
2260/// The * direction imposes no relation between i and j, so the feasible domain
2261/// is the rectangle [0, U_A] x [0, U_B]. The extrema of this affine expression
2262/// occur at its corners. Equivalently, when U_A = U_B = U, Wolfe's normalized
2263/// bounds are
2264///
2265/// LB^*_k = (A^-_k - B^+_k) U
2266/// UB^*_k = (A^+_k - B^-_k) U,
2267///
2268/// where X^+ = max(X, 0) and X^- = min(X, 0).
2269void DependenceInfo::findBoundsALL(ArrayRef<CoefficientInfo> CI,
2271 unsigned K) const {
2272 BanerjeeInterval SrcInterval =
2273 variableInterval(CI[K].SrcCoeff, CI[K].MaxIterIndex, *SE);
2274 BanerjeeInterval DstInterval = variableInterval(
2275 SE->getNegativeSCEV(CI[K].DstCoeff), CI[K].MaxIterIndex, *SE);
2276 BanerjeeInterval Interval = addIntervals(SrcInterval, DstInterval, *SE);
2277 Bound[K].Lower[Dependence::DVEntry::ALL] = Interval.Lower;
2278 Bound[K].Upper[Dependence::DVEntry::ALL] = Interval.Upper;
2279}
2280
2281/// Computes the lower and upper bounds for level K using the = direction.
2282///
2283/// Here i = j, so F_k(i, i) = (A_k - B_k)i over the common range
2284/// [0, min(U_A, U_B)]. The extrema therefore occur at the two endpoints.
2285/// When the common upper bound is U, Wolfe's normalized bounds are
2286///
2287/// LB^=_k = (A_k - B_k)^- U
2288/// UB^=_k = (A_k - B_k)^+ U.
2289void DependenceInfo::findBoundsEQ(ArrayRef<CoefficientInfo> CI,
2291 unsigned K) const {
2292 BanerjeeInterval Interval =
2293 variableInterval(SE->getMinusSCEV(CI[K].SrcCoeff, CI[K].DstCoeff),
2294 CI[K].MaxIterIndex, *SE);
2295 Bound[K].Lower[Dependence::DVEntry::EQ] = Interval.Lower;
2296 Bound[K].Upper[Dependence::DVEntry::EQ] = Interval.Upper;
2297}
2298
2299/// Computes the lower and upper bounds for level K using the < direction.
2300///
2301/// For a known common upper bound U, the feasible domain is
2302/// 0 <= i < j <= U. Its vertices are (0, 1), (0, U), and (U - 1, U), so
2303/// evaluating F_k at those points gives the exact extrema. Equivalently,
2304/// Wolfe's normalized bounds are
2305///
2306/// LB^<_k = (A^-_k - B_k)^- (U - 1) - B_k
2307/// UB^<_k = (A^+_k - B_k)^+ (U - 1) - B_k.
2308///
2309/// If U is zero the domain is empty. If no common upper bound is known, the
2310/// implementation computes any finite one-sided bound it can prove and leaves
2311/// the other side unbounded.
2312void DependenceInfo::findBoundsLT(ArrayRef<CoefficientInfo> CI,
2314 unsigned K) const {
2315 const SCEV *ACoeff = CI[K].SrcCoeff;
2316 const SCEV *BCoeff = CI[K].DstCoeff;
2317 const SCEV *MaxIterIndex = CI[K].MaxIterIndex;
2318
2320 ACoeff, BCoeff, Dependence::DVEntry::LT, *SE);
2321 if (MaxIterIndex && MaxIterIndex->isZero()) {
2322 Interval = emptyInterval(ACoeff->getType(), *SE);
2323 } else if (MaxIterIndex) {
2324 const SCEV *Zero = SE->getZero(ACoeff->getType());
2325 const SCEV *One = SE->getOne(ACoeff->getType());
2326 const SCEV *MaxMinusOne = SE->getMinusSCEV(MaxIterIndex, One);
2328 Values.push_back(
2329 evaluateSubscriptDifference(ACoeff, Zero, BCoeff, One, *SE));
2330 Values.push_back(
2331 evaluateSubscriptDifference(ACoeff, Zero, BCoeff, MaxIterIndex, *SE));
2332 Values.push_back(evaluateSubscriptDifference(ACoeff, MaxMinusOne, BCoeff,
2333 MaxIterIndex, *SE));
2334 Interval =
2336 }
2337 Bound[K].Lower[Dependence::DVEntry::LT] = Interval.Lower;
2338 Bound[K].Upper[Dependence::DVEntry::LT] = Interval.Upper;
2339}
2340
2341/// Computes the lower and upper bounds for level K using the > direction.
2342///
2343/// For a known common upper bound U, the feasible domain is
2344/// 0 <= j < i <= U. Its vertices are (1, 0), (U, 0), and (U, U - 1), so
2345/// evaluating F_k at those points gives the exact extrema. Equivalently,
2346/// Wolfe's normalized bounds are
2347///
2348/// LB^>_k = (A_k - B^+_k)^- (U - 1) + A_k
2349/// UB^>_k = (A_k - B^-_k)^+ (U - 1) + A_k.
2350///
2351/// If U is zero the domain is empty. If no common upper bound is known, the
2352/// implementation computes any finite one-sided bound it can prove and leaves
2353/// the other side unbounded.
2354void DependenceInfo::findBoundsGT(ArrayRef<CoefficientInfo> CI,
2356 unsigned K) const {
2357 const SCEV *ACoeff = CI[K].SrcCoeff;
2358 const SCEV *BCoeff = CI[K].DstCoeff;
2359 const SCEV *MaxIterIndex = CI[K].MaxIterIndex;
2360
2362 ACoeff, BCoeff, Dependence::DVEntry::GT, *SE);
2363 if (MaxIterIndex && MaxIterIndex->isZero()) {
2364 Interval = emptyInterval(ACoeff->getType(), *SE);
2365 } else if (MaxIterIndex) {
2366 const SCEV *Zero = SE->getZero(ACoeff->getType());
2367 const SCEV *One = SE->getOne(ACoeff->getType());
2368 const SCEV *MaxMinusOne = SE->getMinusSCEV(MaxIterIndex, One);
2370 Values.push_back(
2371 evaluateSubscriptDifference(ACoeff, One, BCoeff, Zero, *SE));
2372 Values.push_back(
2373 evaluateSubscriptDifference(ACoeff, MaxIterIndex, BCoeff, Zero, *SE));
2374 Values.push_back(evaluateSubscriptDifference(ACoeff, MaxIterIndex, BCoeff,
2375 MaxMinusOne, *SE));
2376 Interval =
2378 }
2379 Bound[K].Lower[Dependence::DVEntry::GT] = Interval.Lower;
2380 Bound[K].Upper[Dependence::DVEntry::GT] = Interval.Upper;
2381}
2382
2383/// Check if we can delinearize the subscripts. If the SCEVs representing the
2384/// source and destination array references are recurrences on a nested loop,
2385/// this function flattens the nested recurrences into separate recurrences
2386/// for each loop level.
2387bool DependenceInfo::tryDelinearize(Instruction *Src, Instruction *Dst,
2389 assert(isLoadOrStore(Src) && "instruction is not load or store");
2390 assert(isLoadOrStore(Dst) && "instruction is not load or store");
2391 Value *SrcPtr = getLoadStorePointerOperand(Src);
2392 Value *DstPtr = getLoadStorePointerOperand(Dst);
2393 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
2394 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
2395 const SCEV *SrcAccessFn = SE->getSCEVAtScope(SrcPtr, SrcLoop);
2396 const SCEV *DstAccessFn = SE->getSCEVAtScope(DstPtr, DstLoop);
2397 const SCEVUnknown *SrcBase =
2398 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
2399 const SCEVUnknown *DstBase =
2400 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
2401
2402 if (!SrcBase || !DstBase || SrcBase != DstBase)
2403 return false;
2404
2405 SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
2406
2407 if (!tryDelinearizeFixedSize(Src, Dst, SrcAccessFn, DstAccessFn,
2408 SrcSubscripts, DstSubscripts) &&
2409 !tryDelinearizeParametricSize(Src, Dst, SrcAccessFn, DstAccessFn,
2410 SrcSubscripts, DstSubscripts))
2411 return false;
2412
2413 assert(isLoopInvariant(SrcBase, SrcLoop) &&
2414 isLoopInvariant(DstBase, DstLoop) &&
2415 "Expected SrcBase and DstBase to be loop invariant");
2416
2417 int Size = SrcSubscripts.size();
2418 LLVM_DEBUG({
2419 dbgs() << "\nSrcSubscripts: ";
2420 for (int I = 0; I < Size; I++)
2421 dbgs() << *SrcSubscripts[I];
2422 dbgs() << "\nDstSubscripts: ";
2423 for (int I = 0; I < Size; I++)
2424 dbgs() << *DstSubscripts[I];
2425 dbgs() << "\n";
2426 });
2427
2428 // The delinearization transforms a single-subscript MIV dependence test into
2429 // a multi-subscript SIV dependence test that is easier to compute. So we
2430 // resize Pair to contain as many pairs of subscripts as the delinearization
2431 // has found, and then initialize the pairs following the delinearization.
2432 Pair.resize(Size);
2433 for (int I = 0; I < Size; ++I) {
2434 Pair[I].Src = SrcSubscripts[I];
2435 Pair[I].Dst = DstSubscripts[I];
2436
2437 assert(Pair[I].Src->getType() == Pair[I].Dst->getType() &&
2438 "Unexpected different types for the subscripts");
2439 }
2440
2441 return true;
2442}
2443
2444/// Try to delinearize \p SrcAccessFn and \p DstAccessFn if the underlying
2445/// arrays accessed are fixed-size arrays. Return true if delinearization was
2446/// successful.
2447bool DependenceInfo::tryDelinearizeFixedSize(
2448 Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
2449 const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
2450 SmallVectorImpl<const SCEV *> &DstSubscripts) {
2451 LLVM_DEBUG({
2452 const SCEVUnknown *SrcBase =
2453 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
2454 const SCEVUnknown *DstBase =
2455 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
2456 assert(SrcBase && DstBase && SrcBase == DstBase &&
2457 "expected src and dst scev unknowns to be equal");
2458 });
2459
2460 const SCEV *ElemSize = SE->getElementSize(Src);
2461 assert(ElemSize == SE->getElementSize(Dst) && "Different element sizes");
2462 SmallVector<const SCEV *, 4> SrcSizes, DstSizes;
2463 if (!delinearizeFixedSizeArray(*SE, SE->removePointerBase(SrcAccessFn),
2464 SrcSubscripts, SrcSizes, ElemSize) ||
2465 !delinearizeFixedSizeArray(*SE, SE->removePointerBase(DstAccessFn),
2466 DstSubscripts, DstSizes, ElemSize))
2467 return false;
2468
2469 // Check that the two size arrays are non-empty and equal in length and
2470 // value. SCEV expressions are uniqued, so we can compare pointers.
2471 if (SrcSizes.size() != DstSizes.size() ||
2472 !std::equal(SrcSizes.begin(), SrcSizes.end(), DstSizes.begin())) {
2473 SrcSubscripts.clear();
2474 DstSubscripts.clear();
2475 return false;
2476 }
2477
2478 assert(SrcSubscripts.size() == DstSubscripts.size() &&
2479 "Expected equal number of entries in the list of SrcSubscripts and "
2480 "DstSubscripts.");
2481
2482 // In general we cannot safely assume that the subscripts recovered from GEPs
2483 // are in the range of values defined for their corresponding array
2484 // dimensions. For example some C language usage/interpretation make it
2485 // impossible to verify this at compile-time. As such we can only delinearize
2486 // iff the subscripts are positive and are less than the range of the
2487 // dimension.
2488 if (Opts.da_delinearization_checks) {
2489 if (!validateDelinearizationResult(*SE, SrcSizes, SrcSubscripts) ||
2490 !validateDelinearizationResult(*SE, DstSizes, DstSubscripts)) {
2491 SrcSubscripts.clear();
2492 DstSubscripts.clear();
2493 return false;
2494 }
2495 }
2496 LLVM_DEBUG({
2497 dbgs() << "Delinearized subscripts of fixed-size array\n"
2498 << "SrcGEP:" << *getLoadStorePointerOperand(Src) << "\n"
2499 << "DstGEP:" << *getLoadStorePointerOperand(Dst) << "\n";
2500 });
2501 return true;
2502}
2503
2504bool DependenceInfo::tryDelinearizeParametricSize(
2505 Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
2506 const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
2507 SmallVectorImpl<const SCEV *> &DstSubscripts) {
2508
2509 const SCEVUnknown *SrcBase =
2510 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
2511 const SCEVUnknown *DstBase =
2512 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
2513 assert(SrcBase && DstBase && SrcBase == DstBase &&
2514 "expected src and dst scev unknowns to be equal");
2515
2516 const SCEV *ElementSize = SE->getElementSize(Src);
2517 if (ElementSize != SE->getElementSize(Dst))
2518 return false;
2519
2520 const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
2521 const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
2522
2523 const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
2524 const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
2525 if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
2526 return false;
2527
2528 // First step: collect parametric terms in both array references.
2530 collectParametricTerms(*SE, SrcAR, Terms);
2531 collectParametricTerms(*SE, DstAR, Terms);
2532
2533 // Second step: find subscript sizes.
2535 findArrayDimensions(*SE, Terms, Sizes, ElementSize);
2536
2537 // Third step: compute the access functions for each subscript.
2538 computeAccessFunctions(*SE, SrcAR, SrcSubscripts, Sizes);
2539 computeAccessFunctions(*SE, DstAR, DstSubscripts, Sizes);
2540
2541 // Fail when there is only a subscript: that's a linearized access function.
2542 if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
2543 SrcSubscripts.size() != DstSubscripts.size())
2544 return false;
2545
2546 // Statically check that the array bounds are in-range. The first subscript we
2547 // don't have a size for and it cannot overflow into another subscript, so is
2548 // always safe. The others need to be 0 <= subscript[i] < bound, for both src
2549 // and dst.
2550 // FIXME: It may be better to record these sizes and add them as constraints
2551 // to the dependency checks.
2552 if (Opts.da_delinearization_checks)
2553 if (!validateDelinearizationResult(*SE, Sizes, SrcSubscripts) ||
2554 !validateDelinearizationResult(*SE, Sizes, DstSubscripts))
2555 return false;
2556
2557 return true;
2558}
2559
2560//===----------------------------------------------------------------------===//
2561
2562#ifndef NDEBUG
2563// For debugging purposes, dump a small bit vector to dbgs().
2565 dbgs() << "{";
2566 for (unsigned VI : BV.set_bits()) {
2567 dbgs() << VI;
2568 if (BV.find_next(VI) >= 0)
2569 dbgs() << ' ';
2570 }
2571 dbgs() << "}\n";
2572}
2573#endif
2574
2576 FunctionAnalysisManager::Invalidator &Inv) {
2577 // Check if the analysis itself has been invalidated.
2578 auto PAC = PA.getChecker<DependenceAnalysis>();
2579 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
2580 return true;
2581
2582 // Check transitive dependencies.
2583 return Inv.invalidate<AAManager>(F, PA) ||
2584 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
2585 Inv.invalidate<LoopAnalysis>(F, PA);
2586}
2587
2588void DependenceInfo::updateLoopAliasScopes(const Loop *L) {
2589 if (!L || !AlreadyCheckedLoops.insert(L).second)
2590 return;
2591
2592 Function *DeclFn = F->getParent()
2593 ? F->getParent()->getFunction(Intrinsic::getName(
2594 Intrinsic::experimental_noalias_scope_decl))
2595 : nullptr;
2596 // No decls in this module. Parent loops cannot add any either.
2597 if (!DeclFn || DeclFn->use_empty())
2598 return;
2599
2600 for (BasicBlock *BB : L->blocks()) {
2601 // Subloop blocks belong to the inner loop. Scan them when that loop
2602 // is updated. The parent walk below picks up a decl between two loops.
2603 if (LI->getLoopFor(BB) != L)
2604 continue;
2605 for (const Instruction &I : *BB) {
2606 if (const auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I)) {
2607 for (Metadata *Op : Decl->getScopeList()->operands())
2608 LoopAliasScopes.insert(cast<MDNode>(Op));
2609 }
2610 }
2611 }
2612 updateLoopAliasScopes(L->getParentLoop());
2613}
2614
2615// depends -
2616// Returns NULL if there is no dependence.
2617// Otherwise, return a Dependence with as many details as possible.
2618// Corresponds to Section 3.1 in the paper
2619//
2620// Practical Dependence Testing
2621// Goff, Kennedy, Tseng
2622// PLDI 1991
2623//
2624std::unique_ptr<Dependence>
2626 bool UnderRuntimeAssumptions) {
2628 bool PossiblyLoopIndependent = true;
2629 if (Src == Dst)
2630 PossiblyLoopIndependent = false;
2631
2632 if (!(Src->mayReadOrWriteMemory() && Dst->mayReadOrWriteMemory()))
2633 // if both instructions don't reference memory, there's no dependence
2634 return nullptr;
2635
2636 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
2637 // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
2638 LLVM_DEBUG(dbgs() << "can only handle simple loads and stores\n");
2639 return std::make_unique<Dependence>(Src, Dst,
2640 SCEVUnionPredicate(Assume, *SE));
2641 }
2642
2643 const MemoryLocation &DstLoc = MemoryLocation::get(Dst);
2644 const MemoryLocation &SrcLoc = MemoryLocation::get(Src);
2645
2646 updateLoopAliasScopes(LI->getLoopFor(Src->getParent()));
2647 updateLoopAliasScopes(LI->getLoopFor(Dst->getParent()));
2648
2649 switch (underlyingObjectsAlias(AA, F->getDataLayout(), DstLoc, SrcLoc,
2650 LoopAliasScopes)) {
2653 // cannot analyse objects if we don't understand their aliasing.
2654 LLVM_DEBUG(dbgs() << "can't analyze may or partial alias\n");
2655 return std::make_unique<Dependence>(Src, Dst,
2656 SCEVUnionPredicate(Assume, *SE));
2658 // If the objects noalias, they are distinct, accesses are independent.
2659 LLVM_DEBUG(dbgs() << "no alias\n");
2660 return nullptr;
2662 break; // The underlying objects alias; test accesses for dependence.
2663 }
2664
2665 if (DstLoc.Size != SrcLoc.Size || !DstLoc.Size.isPrecise() ||
2666 !SrcLoc.Size.isPrecise()) {
2667 // The dependence test gets confused if the size of the memory accesses
2668 // differ.
2669 LLVM_DEBUG(dbgs() << "can't analyze must alias with different sizes\n");
2670 return std::make_unique<Dependence>(Src, Dst,
2671 SCEVUnionPredicate(Assume, *SE));
2672 }
2673
2674 Value *SrcPtr = getLoadStorePointerOperand(Src);
2675 Value *DstPtr = getLoadStorePointerOperand(Dst);
2676 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
2677 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
2678 LLVM_DEBUG(dbgs() << " SrcSCEV = " << *SrcSCEV << "\n");
2679 LLVM_DEBUG(dbgs() << " DstSCEV = " << *DstSCEV << "\n");
2680 const SCEV *SrcBase = SE->getPointerBase(SrcSCEV);
2681 const SCEV *DstBase = SE->getPointerBase(DstSCEV);
2682 if (SrcBase != DstBase) {
2683 // If two pointers have different bases, trying to analyze indexes won't
2684 // work; we can't compare them to each other. This can happen, for example,
2685 // if one is produced by an LCSSA PHI node.
2686 //
2687 // We check this upfront so we don't crash in cases where getMinusSCEV()
2688 // returns a SCEVCouldNotCompute.
2689 LLVM_DEBUG(dbgs() << "can't analyze SCEV with different pointer base\n");
2690 return std::make_unique<Dependence>(Src, Dst,
2691 SCEVUnionPredicate(Assume, *SE));
2692 }
2693
2694 // Even if the base pointers are the same, they may not be loop-invariant. It
2695 // could lead to incorrect results, as we're analyzing loop-carried
2696 // dependencies. Src and Dst can be in different loops, so we need to check
2697 // the base pointer is invariant in both loops.
2698 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
2699 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
2700 if (!isLoopInvariant(SrcBase, SrcLoop) ||
2701 !isLoopInvariant(DstBase, DstLoop)) {
2702 LLVM_DEBUG(dbgs() << "The base pointer is not loop invariant.\n");
2703 return std::make_unique<Dependence>(Src, Dst,
2704 SCEVUnionPredicate(Assume, *SE));
2705 }
2706
2707 uint64_t EltSize = SrcLoc.Size.toRaw();
2708 const SCEV *SrcEv = SE->getMinusSCEV(SrcSCEV, SrcBase);
2709 const SCEV *DstEv = SE->getMinusSCEV(DstSCEV, DstBase);
2710
2711 // Check that memory access offsets are multiples of element sizes.
2712 // Add to Assume if only runtime assumptions are allowed.
2713 if (!SE->isKnownMultipleOf(SrcEv, EltSize,
2714 UnderRuntimeAssumptions ? &Assume : nullptr) ||
2715 !SE->isKnownMultipleOf(DstEv, EltSize,
2716 UnderRuntimeAssumptions ? &Assume : nullptr)) {
2717 LLVM_DEBUG(dbgs() << "can't analyze SCEV with different offsets\n");
2718 return std::make_unique<Dependence>(Src, Dst,
2719 SCEVUnionPredicate(Assume, *SE));
2720 }
2721
2722 unsigned Pairs = 1;
2723 SmallVector<Subscript, 2> Pair(Pairs);
2724 Pair[0].Src = SrcEv;
2725 Pair[0].Dst = DstEv;
2726 if (Opts.da_delinearize) {
2727 if (tryDelinearize(Src, Dst, Pair)) {
2728 LLVM_DEBUG(dbgs() << " delinearized\n");
2729 Pairs = Pair.size();
2730 }
2731 }
2732
2733 // Establish loop nesting levels considering SameSD loops as common
2734 establishNestingLevels(Src, Dst);
2735
2736 LLVM_DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n");
2737 LLVM_DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n");
2738 LLVM_DEBUG(dbgs() << " SameSD nesting levels = " << SameSDLevels << "\n");
2739
2740 // Modify common levels to consider the SameSD levels in the tests
2741 CommonLevels += SameSDLevels;
2742 MaxLevels -= SameSDLevels;
2743 if (SameSDLevels > 0) {
2744 // Not all tests are handled yet over SameSD loops
2745 // Revoke if there are any tests other than ZIV, SIV or RDIV
2746 for (unsigned P = 0; P < Pairs; ++P) {
2748 Subscript::ClassificationKind TestClass =
2749 classifyPair(Pair[P].Src, SrcLoop, Pair[P].Dst, DstLoop, Loops);
2750
2751 if (TestClass != Subscript::ZIV && TestClass != Subscript::SIV &&
2752 TestClass != Subscript::RDIV) {
2753 // Revert the levels to not consider the SameSD levels
2754 CommonLevels -= SameSDLevels;
2755 MaxLevels += SameSDLevels;
2756 SameSDLevels = 0;
2757 break;
2758 }
2759 }
2760 }
2761
2762 if (SameSDLevels > 0)
2763 SameSDLoopsCount++;
2764
2765 FullDependence Result(Src, Dst, SCEVUnionPredicate(Assume, *SE),
2766 PossiblyLoopIndependent, CommonLevels);
2767 ++TotalArrayPairs;
2768
2769 for (unsigned P = 0; P < Pairs; ++P) {
2770 assert(Pair[P].Src->getType()->isIntegerTy() && "Src must be an integer");
2771 assert(Pair[P].Dst->getType()->isIntegerTy() && "Dst must be an integer");
2772 Pair[P].Loops.resize(MaxLevels + 1);
2773 Pair[P].Classification =
2774 classifyPair(Pair[P].Src, SrcLoop, Pair[P].Dst, DstLoop, Pair[P].Loops);
2775 LLVM_DEBUG(dbgs() << " subscript " << P << "\n");
2776 LLVM_DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
2777 LLVM_DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
2778 LLVM_DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
2779 LLVM_DEBUG(dbgs() << "\tloops = ");
2781 }
2782
2783 // Test each subscript individually
2784 for (unsigned SI = 0; SI < Pairs; ++SI) {
2785 LLVM_DEBUG(dbgs() << "testing subscript " << SI);
2786
2787 // Attempt signed range test first.
2788 ConstantRange SrcRange = SE->getSignedRange(Pair[SI].Src);
2789 ConstantRange DstRange = SE->getSignedRange(Pair[SI].Dst);
2790 if (SrcRange.intersectWith(DstRange).isEmptySet())
2791 return nullptr;
2792
2793 switch (Pair[SI].Classification) {
2794 case Subscript::NonLinear:
2795 // ignore these, but collect loops for later
2796 ++NonlinearSubscriptPairs;
2797 collectCommonLoops(Pair[SI].Src, SrcLoop, Pair[SI].Loops);
2798 collectCommonLoops(Pair[SI].Dst, DstLoop, Pair[SI].Loops);
2799 break;
2800 case Subscript::ZIV:
2801 LLVM_DEBUG(dbgs() << ", ZIV\n");
2802 if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
2803 return nullptr;
2804 break;
2805 case Subscript::SIV: {
2806 LLVM_DEBUG(dbgs() << ", SIV\n");
2807 unsigned Level;
2808 if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result,
2809 UnderRuntimeAssumptions))
2810 return nullptr;
2811 break;
2812 }
2813 case Subscript::RDIV:
2814 LLVM_DEBUG(dbgs() << ", RDIV\n");
2815 if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
2816 return nullptr;
2817 break;
2818 case Subscript::MIV:
2819 LLVM_DEBUG(dbgs() << ", MIV\n");
2820 if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
2821 return nullptr;
2822 break;
2823 }
2824 }
2825
2826 // Make sure the Scalar flags are set correctly.
2827 SmallBitVector CompleteLoops(MaxLevels + 1);
2828 for (unsigned SI = 0; SI < Pairs; ++SI)
2829 CompleteLoops |= Pair[SI].Loops;
2830 for (unsigned II = 1; II <= CommonLevels; ++II)
2831 if (CompleteLoops[II])
2832 Result.DV[II - 1].Scalar = false;
2833
2834 // Set the distance to zero if the direction is EQ.
2835 // TODO: Ideally, the distance should be set to 0 immediately simultaneously
2836 // with the corresponding direction being set to EQ.
2837 for (unsigned II = 1; II <= Result.getLevels(); ++II) {
2838 if (Result.getDirection(II) == Dependence::DVEntry::EQ) {
2839 if (Result.DV[II - 1].Distance == nullptr)
2840 Result.DV[II - 1].Distance = SE->getZero(SrcSCEV->getType());
2841 else
2842 assert(Result.DV[II - 1].Distance->isZero() &&
2843 "Inconsistency between distance and direction");
2844 }
2845
2846#ifndef NDEBUG
2847 // Check that the converse (i.e., if the distance is zero, then the
2848 // direction is EQ) holds.
2849 const SCEV *Distance = Result.getDistance(II);
2850 if (Distance && Distance->isZero())
2851 assert(Result.getDirection(II) == Dependence::DVEntry::EQ &&
2852 "Distance is zero, but direction is not EQ");
2853#endif
2854 }
2855
2856 if (SameSDLevels > 0) {
2857 // Extracting SameSD levels from the common levels
2858 // Reverting CommonLevels and MaxLevels to their original values
2859 assert(CommonLevels >= SameSDLevels);
2860 CommonLevels -= SameSDLevels;
2861 MaxLevels += SameSDLevels;
2862 std::unique_ptr<FullDependence::DVEntry[]> DV, DVSameSD;
2863 DV = std::make_unique<FullDependence::DVEntry[]>(CommonLevels);
2864 DVSameSD = std::make_unique<FullDependence::DVEntry[]>(SameSDLevels);
2865 for (unsigned Level = 0; Level < CommonLevels; ++Level)
2866 DV[Level] = Result.DV[Level];
2867 for (unsigned Level = 0; Level < SameSDLevels; ++Level)
2868 DVSameSD[Level] = Result.DV[CommonLevels + Level];
2869 Result.DV = std::move(DV);
2870 Result.DVSameSD = std::move(DVSameSD);
2871 Result.Levels = CommonLevels;
2872 Result.SameSDLevels = SameSDLevels;
2873 }
2874
2875 if (PossiblyLoopIndependent) {
2876 // Make sure the LoopIndependent flag is set correctly.
2877 // All directions must include equal, otherwise no
2878 // loop-independent dependence is possible.
2879 for (unsigned II = 1; II <= CommonLevels; ++II) {
2880 if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
2881 Result.LoopIndependent = false;
2882 break;
2883 }
2884 }
2885 } else {
2886 // On the other hand, if all directions are equal and there's no
2887 // loop-independent dependence possible, then no dependence exists.
2888 // However, if there are runtime assumptions, we must return the result.
2889 bool AllEqual = true;
2890 for (unsigned II = 1; II <= CommonLevels; ++II) {
2891 if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
2892 AllEqual = false;
2893 break;
2894 }
2895 }
2896 if (AllEqual && Result.Assumptions.getPredicates().empty())
2897 return nullptr;
2898 }
2899
2900 return std::make_unique<FullDependence>(std::move(Result));
2901}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
bpf unwind BPF Unwind Lower
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool isLoadOrStore(const Instruction *I)
static std::optional< bool > findGCD(unsigned Bits, const APInt &AM, const APInt &BM, const APInt &Delta, APInt &G, APInt &X, APInt &Y)
static OverflowSafeSignedAPInt floorOfQuotient(const OverflowSafeSignedAPInt &OA, const OverflowSafeSignedAPInt &OB)
static void dumpExampleDependence(raw_ostream &OS, DependenceInfo *DA, ScalarEvolution &SE, LoopInfo &LI, bool NormalizeResults)
static OverflowSafeSignedAPInt ceilingOfQuotient(const OverflowSafeSignedAPInt &OA, const OverflowSafeSignedAPInt &OB)
static void dumpSmallBitVector(SmallBitVector &BV)
static BanerjeeInterval emptyInterval(Type *Ty, ScalarEvolution &SE)
Return the canonical empty interval [1, 0].
static std::pair< OverflowSafeSignedAPInt, OverflowSafeSignedAPInt > inferDomainOfAffine(OverflowSafeSignedAPInt A, OverflowSafeSignedAPInt B, OverflowSafeSignedAPInt UB)
Given an affine expression of the form A*k + B, where k is an arbitrary integer, infer the possible r...
static MDNode * adjustAliasScopeList(MDNode *ScopeList, const SmallPtrSetImpl< const MDNode * > &LoopAliasScopes)
Drop alias scopes that are only valid within a single loop iteration.
static const SCEV * minusSCEVNoSignedOverflow(const SCEV *A, const SCEV *B, ScalarEvolution &SE)
Returns A - B if it guaranteed not to signed wrap.
static AliasResult underlyingObjectsAlias(AAResults *AA, const DataLayout &DL, const MemoryLocation &LocA, const MemoryLocation &LocB, const SmallPtrSetImpl< const MDNode * > &LoopAliasScopes)
static BanerjeeInterval constantInterval(const SCEV *C)
Return the singleton interval containing C.
static Type * getBanerjeeBaseType(const SCEV *Src, const SCEV *Dst, ScalarEvolution &SE)
Return the widest type used by a subscript or by an exact backedge-taken count of one of its recurren...
static BanerjeeInterval variableInterval(const SCEV *Coeff, const SCEV *Upper, ScalarEvolution &SE)
Compute the range of Coeff * X for 0 <= X <= Upper.
static std::optional< APInt > getConstantCoefficient(const SCEV *Expr)
Given a SCEVMulExpr, returns its first operand if its first operand is a constant and the product doe...
static BanerjeeInterval strictDirectionIntervalWithUnknownUpperBound(const SCEV *ACoeff, const SCEV *BCoeff, unsigned char Direction, ScalarEvolution &SE)
Compute any finite one-sided bound on.
static const SCEV * evaluateSubscriptDifference(const SCEV *A, const SCEV *SrcIndex, const SCEV *B, const SCEV *DstIndex, ScalarEvolution &SE)
Evaluate one loop level's contribution A * SrcIndex - B * DstIndex to the complete source-minus-desti...
static bool isRemainderZero(const SCEVConstant *Dividend, const SCEVConstant *Divisor)
static BanerjeeInterval signedRangeInterval(const SCEV *Coeff, const SCEV *Lower, const SCEV *Upper, ScalarEvolution &SE)
Compute the range of Coeff * X for Lower <=s X <=s Upper.
static BanerjeeInterval intervalFromValues(ArrayRef< const SCEV * > Values, ScalarEvolution &SE)
Return the smallest closed interval containing Values.
static bool isDependenceTestEnabled(const AnalysisOptions &Opts, DependenceTestType Test)
Returns true iff Test is enabled.
static BanerjeeInterval addIntervals(const BanerjeeInterval &A, const BanerjeeInterval &B, ScalarEvolution &SE)
Add two intervals.
static BanerjeeInterval intersectIntervals(const BanerjeeInterval &A, const BanerjeeInterval &B, ScalarEvolution &SE)
Intersect two intervals.
static MemoryLocation adjustLoc(MemoryLocation Loc, const SmallPtrSetImpl< const MDNode * > &LoopAliasScopes)
Hexagon Hardware Loops
Module.h This file contains the declarations for the Module class.
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:249
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
std::pair< uint64_t, uint64_t > Interval
#define T
uint64_t IntrinsicInst * II
#define P(N)
FunctionAnalysisManager FAM
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
A manager for alias analyses.
Class for arbitrary precision integers.
Definition APInt.h:78
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1928
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1774
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
The possible results of an alias query.
@ MayAlias
The two locations may or may not alias.
@ NoAlias
The two locations do not alias at all.
@ PartialAlias
The two locations alias, but only due to a partial overlap.
@ MustAlias
The two locations precisely alias each other.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:61
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
void enableCrossIterationMode()
Assume that values may come from different cycle iterations.
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_NE
not equal
Definition InstrTypes.h:762
This class represents a range of values.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
AnalysisPass to compute dependence information in a function.
LLVM_ABI Result run(Function &F, FunctionAnalysisManager &FAM)
DependenceInfo - This class is the main dependence-analysis driver.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle transitive invalidation when the cached analysis results go away.
LLVM_ABI DependenceInfo(Function *F, AAResults *AA, ScalarEvolution *SE, LoopInfo *LI)
LLVM_ABI std::unique_ptr< Dependence > depends(Instruction *Src, Instruction *Dst, bool UnderRuntimeAssumptions=false)
depends - Tests for a dependence between the Src and Dst instructions.
void dumpImp(raw_ostream &OS, bool IsSameSD=false) const
dumpImp - For debugging purposes.
Dependence(Dependence &&)=default
SCEVUnionPredicate getRuntimeAssumptions() const
getRuntimeAssumptions - Returns the runtime assumptions under which this Dependence relation is valid...
virtual bool isConfused() const
isConfused - Returns true if this dependence is confused (the compiler understands nothing and makes ...
virtual unsigned getSameSDLevels() const
getSameSDLevels - Returns the number of separate SameSD loops surrounding the source and destination ...
virtual const SCEV * getDistance(unsigned Level, bool SameSD=false) const
getDistance - Returns the distance (or NULL) associated with a particular common or SameSD level.
virtual unsigned getLevels() const
getLevels - Returns the number of common loops surrounding the source and destination of the dependen...
virtual unsigned getDirection(unsigned Level, bool SameSD=false) const
getDirection - Returns the direction associated with a particular common or SameSD level.
virtual bool isScalar(unsigned Level, bool SameSD=false) const
isScalar - Returns true if a particular regular or SameSD level is scalar; that is,...
bool isFlow() const
isFlow - Returns true if this is a flow (aka true) dependence.
bool isInput() const
isInput - Returns true if this is an input dependence.
bool isAnti() const
isAnti - Returns true if this is an anti dependence.
virtual bool isLoopIndependent() const
isLoopIndependent - Returns true if this is a loop-independent dependence.
bool isOutput() const
isOutput - Returns true if this is an output dependence.
void dump(raw_ostream &OS) const
dump - For debugging purposes, dumps a dependence to OS.
virtual bool inSameSDLoops(unsigned Level) const
inSameSDLoops - Returns true if this level is an SameSD level, i.e., performed across two separate lo...
Class representing an expression and its matching format.
FullDependence - This class represents a dependence between two memory references in a function.
FullDependence(Instruction *Source, Instruction *Destination, const SCEVUnionPredicate &Assumes, bool PossiblyLoopIndependent, unsigned Levels)
unsigned getDirection(unsigned Level, bool SameSD=false) const override
getDirection - Returns the direction associated with a particular common or SameSD level.
bool isScalar(unsigned Level, bool SameSD=false) const override
isScalar - Returns true if a particular regular or SameSD level is scalar; that is,...
bool isDirectionNegative() const override
Check if the direction vector is negative.
void negate(ScalarEvolution &SE) override
Negate the dependence by swapping the source and destination, and reversing the direction and distanc...
const SCEV * getDistance(unsigned Level, bool SameSD=false) const override
getDistance - Returns the distance (or NULL) associated with a particular common or SameSD level.
DVEntry getDVEntry(unsigned Level, bool IsSameSD) const
getDVEntry - Returns the DV entry associated with a regular or a SameSD level.
bool inSameSDLoops(unsigned Level) const override
inSameSDLoops - Returns true if this level is an SameSD level, i.e., performed across two separate lo...
bool normalize(ScalarEvolution *SE) override
If the direction vector is negative, normalize the direction vector to make it non-negative.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
An instruction for reading from memory.
bool isPrecise() const
uint64_t toRaw() const
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This class represents a loop nest and can be used to query its properties.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1087
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1441
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
LocationSize Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known.
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
const Value * Ptr
The address of the start of the location.
Root of the metadata hierarchy.
Definition Metadata.h:65
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEV * evaluateAtIteration(const SCEV *It, ScalarEvolution &SE) const
Return the value of this chain of recurrences at the specified iteration number.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class represents a constant integer value.
const APInt & getAPInt() const
This class represents a composition of other SCEV predicates, and is the class that most clients will...
This class represents an analyzed expression in the program.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEVFlags Flags=SCEV::FlagNone, unsigned Depth=0)
Return LHS-RHS.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEVFlags Flags=SCEV::FlagNone)
Return the SCEV object corresponding to -V.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, unsigned Depth=0)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
iterator_range< const_set_bits_iterator > set_bits() const
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize(size_type N)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:49
bool use_empty() const
Definition Value.h:348
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B, bool IsSigned=false)
Compute GCD of two APInt values.
Definition APInt.cpp:826
constexpr bool operator!(E Val)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
@ TB
TB - TwoByte - Set if this instruction has a two byte opcode, which starts with a 0x0F byte before th...
This is an optimization pass for GlobalISel generic memory operations.
InstIterator< SymbolTableList< BasicBlock >, Function::iterator, BasicBlock::iterator, Instruction > inst_iterator
LLVM_ABI void collectParametricTerms(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Terms)
Collect parametric terms occurring in step expressions (first step of delinearization).
LLVM_ABI void findArrayDimensions(ScalarEvolution &SE, SmallVectorImpl< const SCEV * > &Terms, SmallVectorImpl< const SCEV * > &Sizes, const SCEV *ElementSize)
Compute the array dimensions Sizes from the set of Terms extracted from the memory access function of...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2261
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
inst_iterator inst_begin(Function *F)
LLVM_ABI bool validateDelinearizationResult(ScalarEvolution &SE, ArrayRef< const SCEV * > Sizes, ArrayRef< const SCEV * > Subscripts)
Check that each subscript in Subscripts is within the corresponding size in Sizes.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI void computeAccessFunctions(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Subscripts, SmallVectorImpl< const SCEV * > &Sizes)
Return in Subscripts the access functions for each dimension in Sizes (third step of delinearization)...
LLVM_ABI bool delinearizeFixedSizeArray(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Subscripts, SmallVectorImpl< const SCEV * > &Sizes, const SCEV *ElementSize)
Split this SCEVAddRecExpr into two vectors of SCEVs representing the subscripts and sizes of an acces...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
inst_iterator inst_end(Function *F)
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
APInt operator-(APInt)
Definition APInt.h:2214
APInt operator+(APInt a, const APInt &b)
Definition APInt.h:2219
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:798
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:801
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
Dependence::DVEntry - Each level in the distance/direction vector has a direction (or perhaps a union...