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