LLVM 23.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 "llvm/ADT/Statistic.h"
56#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(SymbolicRDIVapplications, "Symbolic RDIV applications");
89STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
90STATISTIC(GCDapplications, "GCD applications");
91STATISTIC(GCDsuccesses, "GCD successes");
92STATISTIC(GCDindependence, "GCD independence");
93STATISTIC(BanerjeeApplications, "Banerjee applications");
94STATISTIC(BanerjeeIndependence, "Banerjee independence");
95STATISTIC(BanerjeeSuccesses, "Banerjee successes");
96STATISTIC(SameSDLoopsCount, "Loops with Same iteration Space and Depth");
97
98static cl::opt<bool>
99 Delinearize("da-delinearize", cl::init(true), cl::Hidden,
100 cl::desc("Try to delinearize array references."));
102 "da-disable-delinearization-checks", cl::Hidden,
103 cl::desc(
104 "Disable checks that try to statically verify validity of "
105 "delinearized subscripts. Enabling this option may result in incorrect "
106 "dependence vectors for languages that allow the subscript of one "
107 "dimension to underflow or overflow into another dimension."));
108
110 "da-miv-max-level-threshold", cl::init(7), cl::Hidden,
111 cl::desc("Maximum depth allowed for the recursive algorithm used to "
112 "explore MIV direction vectors."));
113
114namespace {
115
116/// Types of dependence test routines.
117enum class DependenceTestType {
118 All,
119 StrongSIV,
120 WeakCrossingSIV,
121 ExactSIV,
122 WeakZeroSIV,
123 ExactRDIV,
124 SymbolicRDIV,
125 GCDMIV,
126 BanerjeeMIV,
127};
128
129} // anonymous namespace
130
132 "da-enable-dependence-test", cl::init(DependenceTestType::All),
134 cl::desc("Run only specified dependence test routine and disable others. "
135 "The purpose is mainly to exclude the influence of other "
136 "dependence test routines in regression tests. If set to All, all "
137 "dependence test routines are enabled."),
138 cl::values(clEnumValN(DependenceTestType::All, "all",
139 "Enable all dependence test routines."),
140 clEnumValN(DependenceTestType::StrongSIV, "strong-siv",
141 "Enable only Strong SIV test."),
142 clEnumValN(DependenceTestType::WeakCrossingSIV,
143 "weak-crossing-siv",
144 "Enable only Weak-Crossing SIV test."),
145 clEnumValN(DependenceTestType::ExactSIV, "exact-siv",
146 "Enable only Exact SIV test."),
147 clEnumValN(DependenceTestType::WeakZeroSIV, "weak-zero-siv",
148 "Enable only Weak-Zero SIV test."),
149 clEnumValN(DependenceTestType::ExactRDIV, "exact-rdiv",
150 "Enable only Exact RDIV test."),
151 clEnumValN(DependenceTestType::SymbolicRDIV, "symbolic-rdiv",
152 "Enable only Symbolic RDIV test."),
153 clEnumValN(DependenceTestType::GCDMIV, "gcd-miv",
154 "Enable only GCD MIV test."),
155 clEnumValN(DependenceTestType::BanerjeeMIV, "banerjee-miv",
156 "Enable only Banerjee MIV test.")));
157
158// TODO: This flag is disabled by default because it is still under development.
159// Enable it or delete this flag when the feature is ready.
161 "da-enable-monotonicity-check", cl::init(false), cl::Hidden,
162 cl::desc("Check if the subscripts are monotonic. If it's not, dependence "
163 "is reported as unknown."));
164
166 "da-dump-monotonicity-report", cl::init(false), cl::Hidden,
167 cl::desc(
168 "When printing analysis, dump the results of monotonicity checks."));
169
170//===----------------------------------------------------------------------===//
171// basics
172
175 auto &AA = FAM.getResult<AAManager>(F);
176 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
177 auto &LI = FAM.getResult<LoopAnalysis>(F);
178 return DependenceInfo(&F, &AA, &SE, &LI);
179}
180
181AnalysisKey DependenceAnalysis::Key;
182
184 "Dependence Analysis", true, true)
190
192
195
199
201 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
202 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
203 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
204 info.reset(new DependenceInfo(&F, &AA, &SE, &LI));
205 return false;
206}
207
209
211
218
219namespace {
220
221/// The property of monotonicity of a SCEV. To define the monotonicity, assume
222/// a SCEV defined within N-nested loops. Let i_k denote the iteration number
223/// of the k-th loop. Then we can regard the SCEV as an N-ary function:
224///
225/// F(i_1, i_2, ..., i_N)
226///
227/// The domain of i_k is the closed range [0, BTC_k], where BTC_k is the
228/// backedge-taken count of the k-th loop.
229///
230/// A function F is said to be "monotonically increasing with respect to the
231/// k-th loop" if x <= y implies the following condition:
232///
233/// F(i_1, ..., i_{k-1}, x, i_{k+1}, ..., i_N) <=
234/// F(i_1, ..., i_{k-1}, y, i_{k+1}, ..., i_N)
235///
236/// where i_1, ..., i_{k-1}, i_{k+1}, ..., i_N, x, and y are elements of their
237/// respective domains.
238///
239/// Likewise F is "monotonically decreasing with respect to the k-th loop"
240/// if x <= y implies
241///
242/// F(i_1, ..., i_{k-1}, x, i_{k+1}, ..., i_N) >=
243/// F(i_1, ..., i_{k-1}, y, i_{k+1}, ..., i_N)
244///
245/// A function F that is monotonically increasing or decreasing with respect to
246/// the k-th loop is simply called "monotonic with respect to k-th loop".
247///
248/// A function F is said to be "multivariate monotonic" when it is monotonic
249/// with respect to all of the N loops.
250///
251/// Since integer comparison can be either signed or unsigned, we need to
252/// distinguish monotonicity in the signed sense from that in the unsigned
253/// sense. Note that the inequality "x <= y" merely indicates loop progression
254/// and is not affected by the difference between signed and unsigned order.
255///
256/// Currently we only consider monotonicity in a signed sense.
257enum class SCEVMonotonicityType {
258 /// We don't know anything about the monotonicity of the SCEV.
259 Unknown,
260
261 /// The SCEV is loop-invariant with respect to the outermost loop. In other
262 /// words, the function F corresponding to the SCEV is a constant function.
263 Invariant,
264
265 /// The function F corresponding to the SCEV is multivariate monotonic in a
266 /// signed sense. Note that the multivariate monotonic function may also be a
267 /// constant function. The order employed in the definition of monotonicity
268 /// is not strict order.
269 MultivariateSignedMonotonic,
270};
271
272struct SCEVMonotonicity {
273 SCEVMonotonicity(SCEVMonotonicityType Type,
274 const SCEV *FailurePoint = nullptr);
275
276 SCEVMonotonicityType getType() const { return Type; }
277
278 const SCEV *getFailurePoint() const { return FailurePoint; }
279
280 bool isUnknown() const { return Type == SCEVMonotonicityType::Unknown; }
281
282 void print(raw_ostream &OS, unsigned Depth) const;
283
284private:
285 SCEVMonotonicityType Type;
286
287 /// The subexpression that caused Unknown. Mainly for debugging purpose.
288 const SCEV *FailurePoint;
289};
290
291/// Check the monotonicity of a SCEV. Since dependence tests (SIV, MIV, etc.)
292/// assume that subscript expressions are (multivariate) monotonic, we need to
293/// verify this property before applying those tests. Violating this assumption
294/// may cause them to produce incorrect results.
295struct SCEVMonotonicityChecker
296 : public SCEVVisitor<SCEVMonotonicityChecker, SCEVMonotonicity> {
297
298 SCEVMonotonicityChecker(ScalarEvolution *SE) : SE(SE) {}
299
300 /// Check the monotonicity of \p Expr. \p Expr must be integer type. If \p
301 /// OutermostLoop is not null, \p Expr must be defined in \p OutermostLoop or
302 /// one of its nested loops.
303 SCEVMonotonicity checkMonotonicity(const SCEV *Expr,
304 const Loop *OutermostLoop);
305
306private:
307 ScalarEvolution *SE;
308
309 /// The outermost loop that DA is analyzing.
310 const Loop *OutermostLoop;
311
312 /// A helper to classify \p Expr as either Invariant or Unknown.
313 SCEVMonotonicity invariantOrUnknown(const SCEV *Expr);
314
315 /// Return true if \p Expr is loop-invariant with respect to the outermost
316 /// loop.
317 bool isLoopInvariant(const SCEV *Expr) const;
318
319 /// A helper to create an Unknown SCEVMonotonicity.
320 SCEVMonotonicity createUnknown(const SCEV *FailurePoint) {
321 return SCEVMonotonicity(SCEVMonotonicityType::Unknown, FailurePoint);
322 }
323
324 SCEVMonotonicity visitAddRecExpr(const SCEVAddRecExpr *Expr);
325
326 SCEVMonotonicity visitConstant(const SCEVConstant *) {
327 return SCEVMonotonicity(SCEVMonotonicityType::Invariant);
328 }
329 SCEVMonotonicity visitVScale(const SCEVVScale *) {
330 return SCEVMonotonicity(SCEVMonotonicityType::Invariant);
331 }
332
333 // TODO: Handle more cases.
334 SCEVMonotonicity visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
335 return invariantOrUnknown(Expr);
336 }
337 SCEVMonotonicity visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
338 return invariantOrUnknown(Expr);
339 }
340 SCEVMonotonicity visitAddExpr(const SCEVAddExpr *Expr) {
341 return invariantOrUnknown(Expr);
342 }
343 SCEVMonotonicity visitMulExpr(const SCEVMulExpr *Expr) {
344 return invariantOrUnknown(Expr);
345 }
346 SCEVMonotonicity visitPtrToAddrExpr(const SCEVPtrToAddrExpr *Expr) {
347 return invariantOrUnknown(Expr);
348 }
349 SCEVMonotonicity visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) {
350 return invariantOrUnknown(Expr);
351 }
352 SCEVMonotonicity visitTruncateExpr(const SCEVTruncateExpr *Expr) {
353 return invariantOrUnknown(Expr);
354 }
355 SCEVMonotonicity visitUDivExpr(const SCEVUDivExpr *Expr) {
356 return invariantOrUnknown(Expr);
357 }
358 SCEVMonotonicity visitSMaxExpr(const SCEVSMaxExpr *Expr) {
359 return invariantOrUnknown(Expr);
360 }
361 SCEVMonotonicity visitUMaxExpr(const SCEVUMaxExpr *Expr) {
362 return invariantOrUnknown(Expr);
363 }
364 SCEVMonotonicity visitSMinExpr(const SCEVSMinExpr *Expr) {
365 return invariantOrUnknown(Expr);
366 }
367 SCEVMonotonicity visitUMinExpr(const SCEVUMinExpr *Expr) {
368 return invariantOrUnknown(Expr);
369 }
370 SCEVMonotonicity visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
371 return invariantOrUnknown(Expr);
372 }
373 SCEVMonotonicity visitUnknown(const SCEVUnknown *Expr) {
374 return invariantOrUnknown(Expr);
375 }
376 SCEVMonotonicity visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
377 return invariantOrUnknown(Expr);
378 }
379
380 friend struct SCEVVisitor<SCEVMonotonicityChecker, SCEVMonotonicity>;
381};
382
383/// A wrapper class for std::optional<APInt> that provides arithmetic operators
384/// with overflow checking in a signed sense. This allows us to omit inserting
385/// an overflow check at every arithmetic operation, which simplifies the code
386/// if the operations are chained like `a + b + c + ...`.
387///
388/// If an calculation overflows, the result becomes "invalid" which is
389/// internally represented by std::nullopt. If any operand of an arithmetic
390/// operation is "invalid", the result will also be "invalid".
391struct OverflowSafeSignedAPInt {
392 OverflowSafeSignedAPInt() : Value(std::nullopt) {}
393 OverflowSafeSignedAPInt(const APInt &V) : Value(V) {}
394 OverflowSafeSignedAPInt(const std::optional<APInt> &V) : Value(V) {}
395
396 OverflowSafeSignedAPInt operator+(const OverflowSafeSignedAPInt &RHS) const {
397 if (!Value || !RHS.Value)
398 return OverflowSafeSignedAPInt();
399 bool Overflow;
400 APInt Result = Value->sadd_ov(*RHS.Value, Overflow);
401 if (Overflow)
402 return OverflowSafeSignedAPInt();
403 return OverflowSafeSignedAPInt(Result);
404 }
405
406 OverflowSafeSignedAPInt operator+(int RHS) const {
407 if (!Value)
408 return OverflowSafeSignedAPInt();
409 return *this + fromInt(RHS);
410 }
411
412 OverflowSafeSignedAPInt operator-(const OverflowSafeSignedAPInt &RHS) const {
413 if (!Value || !RHS.Value)
414 return OverflowSafeSignedAPInt();
415 bool Overflow;
416 APInt Result = Value->ssub_ov(*RHS.Value, Overflow);
417 if (Overflow)
418 return OverflowSafeSignedAPInt();
419 return OverflowSafeSignedAPInt(Result);
420 }
421
422 OverflowSafeSignedAPInt operator-(int RHS) const {
423 if (!Value)
424 return OverflowSafeSignedAPInt();
425 return *this - fromInt(RHS);
426 }
427
428 OverflowSafeSignedAPInt operator*(const OverflowSafeSignedAPInt &RHS) const {
429 if (!Value || !RHS.Value)
430 return OverflowSafeSignedAPInt();
431 bool Overflow;
432 APInt Result = Value->smul_ov(*RHS.Value, Overflow);
433 if (Overflow)
434 return OverflowSafeSignedAPInt();
435 return OverflowSafeSignedAPInt(Result);
436 }
437
438 OverflowSafeSignedAPInt operator-() const {
439 if (!Value)
440 return OverflowSafeSignedAPInt();
441 if (Value->isMinSignedValue())
442 return OverflowSafeSignedAPInt();
443 return OverflowSafeSignedAPInt(-*Value);
444 }
445
446 operator bool() const { return Value.has_value(); }
447
448 bool operator!() const { return !Value.has_value(); }
449
450 const APInt &operator*() const {
451 assert(Value && "Value is not available.");
452 return *Value;
453 }
454
455 const APInt *operator->() const {
456 assert(Value && "Value is not available.");
457 return &*Value;
458 }
459
460private:
461 /// Underlying value. std::nullopt means "unknown". An arithmetic operation on
462 /// "unknown" always produces "unknown".
463 std::optional<APInt> Value;
464
465 OverflowSafeSignedAPInt fromInt(uint64_t V) const {
466 assert(Value && "Value is not available.");
467 return OverflowSafeSignedAPInt(
468 APInt(Value->getBitWidth(), V, /*isSigned=*/true));
469 }
470};
471
472} // anonymous namespace
473
474// Used to test the dependence analyzer.
475// Looks through the function, noting instructions that may access memory.
476// Calls depends() on every possible pair and prints out the result.
477// Ignores all other instructions.
479 ScalarEvolution &SE, LoopInfo &LI,
480 bool NormalizeResults) {
481 auto *F = DA->getFunction();
482
484 SCEVMonotonicityChecker Checker(&SE);
485 OS << "Monotonicity check:\n";
486 for (Instruction &Inst : instructions(F)) {
487 if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst))
488 continue;
489 Value *Ptr = getLoadStorePointerOperand(&Inst);
490 const Loop *L = LI.getLoopFor(Inst.getParent());
491 const Loop *OutermostLoop = L ? L->getOutermostLoop() : nullptr;
492 const SCEV *PtrSCEV = SE.getSCEVAtScope(Ptr, L);
493 const SCEV *AccessFn = SE.removePointerBase(PtrSCEV);
494 SCEVMonotonicity Mon = Checker.checkMonotonicity(AccessFn, OutermostLoop);
495 OS.indent(2) << "Inst: " << Inst << "\n";
496 OS.indent(4) << "Expr: " << *AccessFn << "\n";
497 Mon.print(OS, 4);
498 }
499 OS << "\n";
500 }
501
502 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); SrcI != SrcE;
503 ++SrcI) {
504 if (SrcI->mayReadOrWriteMemory()) {
505 for (inst_iterator DstI = SrcI, DstE = inst_end(F); DstI != DstE;
506 ++DstI) {
507 if (DstI->mayReadOrWriteMemory()) {
508 OS << "Src:" << *SrcI << " --> Dst:" << *DstI << "\n";
509 OS << " da analyze - ";
510 if (auto D = DA->depends(&*SrcI, &*DstI,
511 /*UnderRuntimeAssumptions=*/true)) {
512
513#ifndef NDEBUG
514 // Verify that the distance being zero is equivalent to the
515 // direction being EQ.
516 for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
517 const SCEV *Distance = D->getDistance(Level);
518 bool IsDistanceZero = Distance && Distance->isZero();
519 bool IsDirectionEQ =
520 D->getDirection(Level) == Dependence::DVEntry::EQ;
521 assert(IsDistanceZero == IsDirectionEQ &&
522 "Inconsistent distance and direction.");
523 }
524#endif
525
526 // Normalize negative direction vectors if required by clients.
527 if (NormalizeResults && D->normalize(&SE))
528 OS << "normalized - ";
529 D->dump(OS);
530 } else
531 OS << "none!\n";
532 }
533 }
534 }
535 }
536}
537
539 const Module *) const {
541 OS, info.get(), getAnalysis<ScalarEvolutionWrapperPass>().getSE(),
542 getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), false);
543}
544
547 OS << "Printing analysis 'Dependence Analysis' for function '" << F.getName()
548 << "':\n";
550 FAM.getResult<ScalarEvolutionAnalysis>(F),
551 FAM.getResult<LoopAnalysis>(F), NormalizeResults);
552 return PreservedAnalyses::all();
553}
554
555//===----------------------------------------------------------------------===//
556// Dependence methods
557
558// Returns true if this is an input dependence.
560 return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
561}
562
563// Returns true if this is an output dependence.
565 return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
566}
567
568// Returns true if this is an flow (aka true) dependence.
569bool Dependence::isFlow() const {
570 return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
571}
572
573// Returns true if this is an anti dependence.
574bool Dependence::isAnti() const {
575 return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
576}
577
578// Returns true if a particular level is scalar; that is,
579// if no subscript in the source or destination mention the induction
580// variable associated with the loop at this level.
581// Leave this out of line, so it will serve as a virtual method anchor
582bool Dependence::isScalar(unsigned level, bool IsSameSD) const { return false; }
583
584//===----------------------------------------------------------------------===//
585// FullDependence methods
586
588 const SCEVUnionPredicate &Assumes,
589 bool PossiblyLoopIndependent,
590 unsigned CommonLevels)
591 : Dependence(Source, Destination, Assumes), Levels(CommonLevels),
592 LoopIndependent(PossiblyLoopIndependent) {
593 SameSDLevels = 0;
594 if (CommonLevels)
595 DV = std::make_unique<DVEntry[]>(CommonLevels);
596}
597
598// FIXME: in some cases the meaning of a negative direction vector
599// may not be straightforward, e.g.,
600// for (int i = 0; i < 32; ++i) {
601// Src: A[i] = ...;
602// Dst: use(A[31 - i]);
603// }
604// The dependency is
605// flow { Src[i] -> Dst[31 - i] : when i >= 16 } and
606// anti { Dst[i] -> Src[31 - i] : when i < 16 },
607// -- hence a [<>].
608// As long as a dependence result contains '>' ('<>', '<=>', "*"), it
609// means that a reversed/normalized dependence needs to be considered
610// as well. Nevertheless, current isDirectionNegative() only returns
611// true with a '>' or '>=' dependency for ease of canonicalizing the
612// dependency vector, since the reverse of '<>', '<=>' and "*" is itself.
614 for (unsigned Level = 1; Level <= Levels; ++Level) {
615 unsigned char Direction = DV[Level - 1].Direction;
616 if (Direction == Dependence::DVEntry::EQ)
617 continue;
618 if (Direction == Dependence::DVEntry::GT ||
619 Direction == Dependence::DVEntry::GE)
620 return true;
621 return false;
622 }
623 return false;
624}
625
627 if (!isDirectionNegative())
628 return false;
629
630 LLVM_DEBUG(dbgs() << "Before normalizing negative direction vectors:\n";
631 dump(dbgs()););
632 std::swap(Src, Dst);
633 for (unsigned Level = 1; Level <= Levels; ++Level) {
634 unsigned char Direction = DV[Level - 1].Direction;
635 // Reverse the direction vector, this means LT becomes GT
636 // and GT becomes LT.
637 unsigned char RevDirection = Direction & Dependence::DVEntry::EQ;
638 if (Direction & Dependence::DVEntry::LT)
639 RevDirection |= Dependence::DVEntry::GT;
640 if (Direction & Dependence::DVEntry::GT)
641 RevDirection |= Dependence::DVEntry::LT;
642 DV[Level - 1].Direction = RevDirection;
643 // Reverse the dependence distance as well.
644 if (DV[Level - 1].Distance != nullptr)
645 DV[Level - 1].Distance = SE->getNegativeSCEV(DV[Level - 1].Distance);
646 }
647
648 LLVM_DEBUG(dbgs() << "After normalizing negative direction vectors:\n";
649 dump(dbgs()););
650 return true;
651}
652
653// The rest are simple getters that hide the implementation.
654
655// getDirection - Returns the direction associated with a particular common or
656// SameSD level.
657unsigned FullDependence::getDirection(unsigned Level, bool IsSameSD) const {
658 return getDVEntry(Level, IsSameSD).Direction;
659}
660
661// Returns the distance (or NULL) associated with a particular common or
662// SameSD level.
663const SCEV *FullDependence::getDistance(unsigned Level, bool IsSameSD) const {
664 return getDVEntry(Level, IsSameSD).Distance;
665}
666
667// Returns true if a particular regular or SameSD level is scalar; that is,
668// if no subscript in the source or destination mention the induction variable
669// associated with the loop at this level.
670bool FullDependence::isScalar(unsigned Level, bool IsSameSD) const {
671 return getDVEntry(Level, IsSameSD).Scalar;
672}
673
674// inSameSDLoops - Returns true if this level is an SameSD level, i.e.,
675// performed across two separate loop nests that have the Same iteration space
676// and Depth.
677bool FullDependence::inSameSDLoops(unsigned Level) const {
678 assert(0 < Level && Level <= static_cast<unsigned>(Levels) + SameSDLevels &&
679 "Level out of range");
680 return Level > Levels;
681}
682
683//===----------------------------------------------------------------------===//
684// SCEVMonotonicity
685
686SCEVMonotonicity::SCEVMonotonicity(SCEVMonotonicityType Type,
687 const SCEV *FailurePoint)
688 : Type(Type), FailurePoint(FailurePoint) {
689 assert(
690 ((Type == SCEVMonotonicityType::Unknown) == (FailurePoint != nullptr)) &&
691 "FailurePoint must be provided iff Type is Unknown");
692}
693
694void SCEVMonotonicity::print(raw_ostream &OS, unsigned Depth) const {
695 OS.indent(Depth) << "Monotonicity: ";
696 switch (Type) {
697 case SCEVMonotonicityType::Unknown:
698 assert(FailurePoint && "FailurePoint must be provided for Unknown");
699 OS << "Unknown\n";
700 OS.indent(Depth) << "Reason: " << *FailurePoint << "\n";
701 break;
702 case SCEVMonotonicityType::Invariant:
703 OS << "Invariant\n";
704 break;
705 case SCEVMonotonicityType::MultivariateSignedMonotonic:
706 OS << "MultivariateSignedMonotonic\n";
707 break;
708 }
709}
710
711bool SCEVMonotonicityChecker::isLoopInvariant(const SCEV *Expr) const {
712 return !OutermostLoop || SE->isLoopInvariant(Expr, OutermostLoop);
713}
714
715SCEVMonotonicity SCEVMonotonicityChecker::invariantOrUnknown(const SCEV *Expr) {
716 if (isLoopInvariant(Expr))
717 return SCEVMonotonicity(SCEVMonotonicityType::Invariant);
718 return createUnknown(Expr);
719}
720
721SCEVMonotonicity
722SCEVMonotonicityChecker::checkMonotonicity(const SCEV *Expr,
723 const Loop *OutermostLoop) {
724 assert((!OutermostLoop || OutermostLoop->isOutermost()) &&
725 "OutermostLoop must be outermost");
726 assert(Expr->getType()->isIntegerTy() && "Expr must be integer type");
727 this->OutermostLoop = OutermostLoop;
728 return visit(Expr);
729}
730
731/// We only care about an affine AddRec at the moment. For an affine AddRec,
732/// the monotonicity can be inferred from its nowrap property. For example, let
733/// X and Y be loop-invariant, and assume Y is non-negative. An AddRec
734/// {X,+.Y}<nsw> implies:
735///
736/// X <=s (X + Y) <=s ((X + Y) + Y) <=s ...
737///
738/// Thus, we can conclude that the AddRec is monotonically increasing with
739/// respect to the associated loop in a signed sense. The similar reasoning
740/// applies when Y is non-positive, leading to a monotonically decreasing
741/// AddRec.
742SCEVMonotonicity
743SCEVMonotonicityChecker::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
744 if (!Expr->isAffine() || !Expr->hasNoSignedWrap())
745 return createUnknown(Expr);
746
747 const SCEV *Start = Expr->getStart();
748 const SCEV *Step = Expr->getStepRecurrence(*SE);
749
750 SCEVMonotonicity StartMon = visit(Start);
751 if (StartMon.isUnknown())
752 return StartMon;
753
754 if (!isLoopInvariant(Step))
755 return createUnknown(Expr);
756
757 return SCEVMonotonicity(SCEVMonotonicityType::MultivariateSignedMonotonic);
758}
759
760//===----------------------------------------------------------------------===//
761// DependenceInfo methods
762
763// For debugging purposes. Dumps a dependence to OS.
765 if (isConfused())
766 OS << "confused";
767 else {
768 if (isFlow())
769 OS << "flow";
770 else if (isOutput())
771 OS << "output";
772 else if (isAnti())
773 OS << "anti";
774 else if (isInput())
775 OS << "input";
776 dumpImp(OS);
777 unsigned SameSDLevels = getSameSDLevels();
778 if (SameSDLevels > 0) {
779 OS << " / assuming " << SameSDLevels << " loop level(s) fused: ";
780 dumpImp(OS, true);
781 }
782 }
783 OS << "!\n";
784
786 if (!Assumptions.isAlwaysTrue()) {
787 OS << " Runtime Assumptions:\n";
788 Assumptions.print(OS, 2);
789 }
790}
791
792// For debugging purposes. Dumps a dependence to OS with or without considering
793// the SameSD levels.
794void Dependence::dumpImp(raw_ostream &OS, bool IsSameSD) const {
795 unsigned Levels = getLevels();
796 unsigned SameSDLevels = getSameSDLevels();
797 bool OnSameSD = false;
798 unsigned LevelNum = Levels;
799 if (IsSameSD)
800 LevelNum += SameSDLevels;
801 OS << " [";
802 for (unsigned II = 1; II <= LevelNum; ++II) {
803 if (!OnSameSD && inSameSDLoops(II))
804 OnSameSD = true;
805 const SCEV *Distance = getDistance(II, OnSameSD);
806 if (Distance)
807 OS << *Distance;
808 else if (isScalar(II, OnSameSD))
809 OS << "S";
810 else {
811 unsigned Direction = getDirection(II, OnSameSD);
812 if (Direction == DVEntry::ALL)
813 OS << "*";
814 else {
815 if (Direction & DVEntry::LT)
816 OS << "<";
817 if (Direction & DVEntry::EQ)
818 OS << "=";
819 if (Direction & DVEntry::GT)
820 OS << ">";
821 }
822 }
823 if (II < LevelNum)
824 OS << " ";
825 }
826 if (isLoopIndependent())
827 OS << "|<";
828 OS << "]";
829}
830
831// Returns NoAlias/MayAliass/MustAlias for two memory locations based upon their
832// underlaying objects. If LocA and LocB are known to not alias (for any reason:
833// tbaa, non-overlapping regions etc), then it is known there is no dependecy.
834// Otherwise the underlying objects are checked to see if they point to
835// different identifiable objects.
837 const MemoryLocation &LocA,
838 const MemoryLocation &LocB) {
839 // Check the original locations (minus size) for noalias, which can happen for
840 // tbaa, incompatible underlying object locations, etc.
841 MemoryLocation LocAS =
843 MemoryLocation LocBS =
845 BatchAAResults BAA(*AA);
847
848 if (BAA.isNoAlias(LocAS, LocBS))
850
851 // Check the underlying objects are the same
852 const Value *AObj = getUnderlyingObject(LocA.Ptr);
853 const Value *BObj = getUnderlyingObject(LocB.Ptr);
854
855 // If the underlying objects are the same, they must alias
856 if (AObj == BObj)
858
859 // We may have hit the recursion limit for underlying objects, or have
860 // underlying objects where we don't know they will alias.
861 if (!isIdentifiedObject(AObj) || !isIdentifiedObject(BObj))
863
864 // Otherwise we know the objects are different and both identified objects so
865 // must not alias.
867}
868
869// Returns true if the load or store can be analyzed. Atomic and volatile
870// operations have properties which this analysis does not understand.
871static bool isLoadOrStore(const Instruction *I) {
872 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
873 return LI->isUnordered();
874 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
875 return SI->isUnordered();
876 return false;
877}
878
879// Returns true if two loops have the Same iteration Space and Depth. To be
880// more specific, two loops have SameSD if they are in the same nesting
881// depth and have the same backedge count. SameSD stands for Same iteration
882// Space and Depth.
883bool DependenceInfo::haveSameSD(const Loop *SrcLoop,
884 const Loop *DstLoop) const {
885 if (SrcLoop == DstLoop)
886 return true;
887
888 if (SrcLoop->getLoopDepth() != DstLoop->getLoopDepth())
889 return false;
890
891 if (!SrcLoop || !SrcLoop->getLoopLatch() || !DstLoop ||
892 !DstLoop->getLoopLatch())
893 return false;
894
895 const SCEV *SrcUB = nullptr, *DstUP = nullptr;
896 if (SE->hasLoopInvariantBackedgeTakenCount(SrcLoop))
897 SrcUB = SE->getBackedgeTakenCount(SrcLoop);
898 if (SE->hasLoopInvariantBackedgeTakenCount(DstLoop))
899 DstUP = SE->getBackedgeTakenCount(DstLoop);
900
901 if (SrcUB != nullptr && DstUP != nullptr) {
902 Type *WiderType = SE->getWiderType(SrcUB->getType(), DstUP->getType());
903 SrcUB = SE->getNoopOrZeroExtend(SrcUB, WiderType);
904 DstUP = SE->getNoopOrZeroExtend(DstUP, WiderType);
905
906 if (SE->isKnownPredicate(ICmpInst::ICMP_EQ, SrcUB, DstUP))
907 return true;
908 }
909
910 return false;
911}
912
913// Examines the loop nesting of the Src and Dst
914// instructions and establishes their shared loops. Sets the variables
915// CommonLevels, SrcLevels, and MaxLevels.
916// The source and destination instructions needn't be contained in the same
917// loop. The routine establishNestingLevels finds the level of most deeply
918// nested loop that contains them both, CommonLevels. An instruction that's
919// not contained in a loop is at level = 0. MaxLevels is equal to the level
920// of the source plus the level of the destination, minus CommonLevels.
921// This lets us allocate vectors MaxLevels in length, with room for every
922// distinct loop referenced in both the source and destination subscripts.
923// The variable SrcLevels is the nesting depth of the source instruction.
924// It's used to help calculate distinct loops referenced by the destination.
925// Here's the map from loops to levels:
926// 0 - unused
927// 1 - outermost common loop
928// ... - other common loops
929// CommonLevels - innermost common loop
930// ... - loops containing Src but not Dst
931// SrcLevels - innermost loop containing Src but not Dst
932// ... - loops containing Dst but not Src
933// MaxLevels - innermost loops containing Dst but not Src
934// Consider the follow code fragment:
935// for (a = ...) {
936// for (b = ...) {
937// for (c = ...) {
938// for (d = ...) {
939// A[] = ...;
940// }
941// }
942// for (e = ...) {
943// for (f = ...) {
944// for (g = ...) {
945// ... = A[];
946// }
947// }
948// }
949// }
950// }
951// If we're looking at the possibility of a dependence between the store
952// to A (the Src) and the load from A (the Dst), we'll note that they
953// have 2 loops in common, so CommonLevels will equal 2 and the direction
954// vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
955// A map from loop names to loop numbers would look like
956// a - 1
957// b - 2 = CommonLevels
958// c - 3
959// d - 4 = SrcLevels
960// e - 5
961// f - 6
962// g - 7 = MaxLevels
963// SameSDLevels counts the number of levels after common levels that are
964// not common but have the same iteration space and depth. Internally this
965// is checked using haveSameSD. Assume that in this code fragment, levels c and
966// e have the same iteration space and depth, but levels d and f does not. Then
967// SameSDLevels is set to 1. In that case the level numbers for the previous
968// code look like
969// a - 1
970// b - 2
971// c,e - 3 = CommonLevels
972// d - 4 = SrcLevels
973// f - 5
974// g - 6 = MaxLevels
975void DependenceInfo::establishNestingLevels(const Instruction *Src,
976 const Instruction *Dst) {
977 const BasicBlock *SrcBlock = Src->getParent();
978 const BasicBlock *DstBlock = Dst->getParent();
979 unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
980 unsigned DstLevel = LI->getLoopDepth(DstBlock);
981 const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
982 const Loop *DstLoop = LI->getLoopFor(DstBlock);
983 SrcLevels = SrcLevel;
984 MaxLevels = SrcLevel + DstLevel;
985 SameSDLevels = 0;
986 while (SrcLevel > DstLevel) {
987 SrcLoop = SrcLoop->getParentLoop();
988 SrcLevel--;
989 }
990 while (DstLevel > SrcLevel) {
991 DstLoop = DstLoop->getParentLoop();
992 DstLevel--;
993 }
994
995 // find the first common level and count the SameSD levels leading to it
996 while (SrcLoop != DstLoop) {
997 SameSDLevels++;
998 if (!haveSameSD(SrcLoop, DstLoop))
999 SameSDLevels = 0;
1000 SrcLoop = SrcLoop->getParentLoop();
1001 DstLoop = DstLoop->getParentLoop();
1002 SrcLevel--;
1003 }
1004 CommonLevels = SrcLevel;
1005 MaxLevels -= CommonLevels;
1006}
1007
1008// Given one of the loops containing the source, return
1009// its level index in our numbering scheme.
1010unsigned DependenceInfo::mapSrcLoop(const Loop *SrcLoop) const {
1011 return SrcLoop->getLoopDepth();
1012}
1013
1014// Given one of the loops containing the destination,
1015// return its level index in our numbering scheme.
1016unsigned DependenceInfo::mapDstLoop(const Loop *DstLoop) const {
1017 unsigned D = DstLoop->getLoopDepth();
1018 if (D > CommonLevels)
1019 // This tries to make sure that we assign unique numbers to src and dst when
1020 // the memory accesses reside in different loops that have the same depth.
1021 return D - CommonLevels + SrcLevels;
1022 else
1023 return D;
1024}
1025
1026// Returns true if Expression is loop invariant in LoopNest.
1027bool DependenceInfo::isLoopInvariant(const SCEV *Expression,
1028 const Loop *LoopNest) const {
1029 // Unlike ScalarEvolution::isLoopInvariant() we consider an access outside of
1030 // any loop as invariant, because we only consier expression evaluation at a
1031 // specific position (where the array access takes place), and not across the
1032 // entire function.
1033 if (!LoopNest)
1034 return true;
1035
1036 // If the expression is invariant in the outermost loop of the loop nest, it
1037 // is invariant anywhere in the loop nest.
1038 return SE->isLoopInvariant(Expression, LoopNest->getOutermostLoop());
1039}
1040
1041// Finds the set of loops from the LoopNest that
1042// have a level <= CommonLevels and are referred to by the SCEV Expression.
1043void DependenceInfo::collectCommonLoops(const SCEV *Expression,
1044 const Loop *LoopNest,
1045 SmallBitVector &Loops) const {
1046 while (LoopNest) {
1047 unsigned Level = LoopNest->getLoopDepth();
1048 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
1049 Loops.set(Level);
1050 LoopNest = LoopNest->getParentLoop();
1051 }
1052}
1053
1054// Examine the scev and return true iff it's affine.
1055// Collect any loops mentioned in the set of "Loops".
1056bool DependenceInfo::checkSubscript(const SCEV *Expr, const Loop *LoopNest,
1057 SmallBitVector &Loops, bool IsSrc) {
1058 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
1059 if (!AddRec)
1060 return isLoopInvariant(Expr, LoopNest);
1061
1062 // The AddRec must depend on one of the containing loops. Otherwise,
1063 // mapSrcLoop and mapDstLoop return indices outside the intended range. This
1064 // can happen when a subscript in one loop references an IV from a sibling
1065 // loop that could not be replaced with a concrete exit value by
1066 // getSCEVAtScope.
1067 const Loop *L = LoopNest;
1068 while (L && AddRec->getLoop() != L)
1069 L = L->getParentLoop();
1070 if (!L)
1071 return false;
1072
1073 const SCEV *Start = AddRec->getStart();
1074 const SCEV *Step = AddRec->getStepRecurrence(*SE);
1075 if (!isLoopInvariant(Step, LoopNest))
1076 return false;
1077 if (IsSrc)
1078 Loops.set(mapSrcLoop(AddRec->getLoop()));
1079 else
1080 Loops.set(mapDstLoop(AddRec->getLoop()));
1081 return checkSubscript(Start, LoopNest, Loops, IsSrc);
1082}
1083
1084// Examine the scev and return true iff it's linear.
1085// Collect any loops mentioned in the set of "Loops".
1086bool DependenceInfo::checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
1088 return checkSubscript(Src, LoopNest, Loops, true);
1089}
1090
1091// Examine the scev and return true iff it's linear.
1092// Collect any loops mentioned in the set of "Loops".
1093bool DependenceInfo::checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
1095 return checkSubscript(Dst, LoopNest, Loops, false);
1096}
1097
1098// Examines the subscript pair (the Src and Dst SCEVs)
1099// and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
1100// Collects the associated loops in a set.
1101DependenceInfo::Subscript::ClassificationKind
1102DependenceInfo::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
1103 const SCEV *Dst, const Loop *DstLoopNest,
1105 SmallBitVector SrcLoops(MaxLevels + 1);
1106 SmallBitVector DstLoops(MaxLevels + 1);
1107 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
1108 return Subscript::NonLinear;
1109 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
1110 return Subscript::NonLinear;
1111 Loops = SrcLoops;
1112 Loops |= DstLoops;
1113 unsigned N = Loops.count();
1114 if (N == 0)
1115 return Subscript::ZIV;
1116 if (N == 1)
1117 return Subscript::SIV;
1118 if (N == 2 && SrcLoops.count() == 1 && DstLoops.count() == 1)
1119 return Subscript::RDIV;
1120 return Subscript::MIV;
1121}
1122
1123// All subscripts are all the same type.
1124// Loop bound may be smaller (e.g., a char).
1125// Should zero extend loop bound, since it's always >= 0.
1126// This routine collects upper bound and extends or truncates if needed.
1127// Truncating is safe when subscripts are known not to wrap. Cases without
1128// nowrap flags should have been rejected earlier.
1129// Return null if no bound available.
1130const SCEV *DependenceInfo::collectUpperBound(const Loop *L, Type *T) const {
1131 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
1132 const SCEV *UB = SE->getBackedgeTakenCount(L);
1133 return SE->getTruncateOrZeroExtend(UB, T);
1134 }
1135 return nullptr;
1136}
1137
1138// Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
1139// If the cast fails, returns NULL.
1140const SCEVConstant *DependenceInfo::collectConstantUpperBound(const Loop *L,
1141 Type *T) const {
1142 if (const SCEV *UB = collectUpperBound(L, T))
1143 return dyn_cast<SCEVConstant>(UB);
1144 return nullptr;
1145}
1146
1147/// Returns \p A - \p B if it guaranteed not to signed wrap. Otherwise returns
1148/// nullptr. \p A and \p B must have the same integer type.
1149static const SCEV *minusSCEVNoSignedOverflow(const SCEV *A, const SCEV *B,
1150 ScalarEvolution &SE) {
1151 if (SE.willNotOverflow(Instruction::Sub, /*Signed=*/true, A, B))
1152 return SE.getMinusSCEV(A, B);
1153 return nullptr;
1154}
1155
1156/// Returns true iff \p Test is enabled.
1157static bool isDependenceTestEnabled(DependenceTestType Test) {
1158 if (EnableDependenceTest == DependenceTestType::All)
1159 return true;
1160 return EnableDependenceTest == Test;
1161}
1162
1163// testZIV -
1164// When we have a pair of subscripts of the form [c1] and [c2],
1165// where c1 and c2 are both loop invariant, we attack it using
1166// the ZIV test. Basically, we test by comparing the two values,
1167// but there are actually three possible results:
1168// 1) the values are equal, so there's a dependence
1169// 2) the values are different, so there's no dependence
1170// 3) the values might be equal, so we have to assume a dependence.
1171//
1172// Return true if dependence disproved.
1173bool DependenceInfo::testZIV(const SCEV *Src, const SCEV *Dst,
1174 FullDependence &Result) const {
1175 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
1176 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
1177 ++ZIVapplications;
1178 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
1179 LLVM_DEBUG(dbgs() << " provably dependent\n");
1180 return false; // provably dependent
1181 }
1182 if (SE->isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
1183 LLVM_DEBUG(dbgs() << " provably independent\n");
1184 ++ZIVindependence;
1185 return true; // provably independent
1186 }
1187 LLVM_DEBUG(dbgs() << " possibly dependent\n");
1188 return false; // possibly dependent
1189}
1190
1191// strongSIVtest -
1192// From the paper, Practical Dependence Testing, Section 4.2.1
1193//
1194// When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
1195// where i is an induction variable, c1 and c2 are loop invariant,
1196// and a is a constant, we can solve it exactly using the Strong SIV test.
1197//
1198// Can prove independence. Failing that, can compute distance (and direction).
1199// In the presence of symbolic terms, we can sometimes make progress.
1200//
1201// If there's a dependence,
1202//
1203// c1 + a*i = c2 + a*i'
1204//
1205// The dependence distance is
1206//
1207// d = i' - i = (c1 - c2)/a
1208//
1209// A dependence only exists if d is an integer and abs(d) <= U, where U is the
1210// loop's upper bound. If a dependence exists, the dependence direction is
1211// defined as
1212//
1213// { < if d > 0
1214// direction = { = if d = 0
1215// { > if d < 0
1216//
1217// Return true if dependence disproved.
1218bool DependenceInfo::strongSIVtest(const SCEVAddRecExpr *Src,
1219 const SCEVAddRecExpr *Dst, unsigned Level,
1220 FullDependence &Result,
1221 bool UnderRuntimeAssumptions) {
1222 if (!isDependenceTestEnabled(DependenceTestType::StrongSIV))
1223 return false;
1224
1225 const SCEV *Coeff = Src->getStepRecurrence(*SE);
1226 assert(Coeff == Dst->getStepRecurrence(*SE) &&
1227 "Expecting same coefficient in Strong SIV test");
1228 const SCEV *SrcConst = Src->getStart();
1229 const SCEV *DstConst = Dst->getStart();
1230 LLVM_DEBUG(dbgs() << "\tStrong SIV test\n");
1231 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff);
1232 LLVM_DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1233 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
1234 LLVM_DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1235 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst);
1236 LLVM_DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
1237 ++StrongSIVapplications;
1238 assert(0 < Level && Level <= CommonLevels && "level out of range");
1239 Level--;
1240
1241 // First try to prove independence based on the ranges of the two subscripts.
1242 ConstantRange SrcRange = SE->getSignedRange(Src);
1243 ConstantRange DstRange = SE->getSignedRange(Dst);
1244 if (SrcRange.intersectWith(DstRange).isEmptySet()) {
1245 ++StrongSIVindependence;
1246 ++StrongSIVsuccesses;
1247 return true;
1248 }
1249
1250 const SCEV *Delta = minusSCEVNoSignedOverflow(SrcConst, DstConst, *SE);
1251 if (!Delta)
1252 return false;
1253 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta);
1254 LLVM_DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
1255
1256 // Can we compute distance?
1257 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
1258 APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
1259 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
1260 APInt Distance = ConstDelta; // these need to be initialized
1261 APInt Remainder = ConstDelta;
1262 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
1263 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1264 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1265 // Make sure Coeff divides Delta exactly
1266 if (Remainder != 0) {
1267 // Coeff doesn't divide Distance, no dependence
1268 ++StrongSIVindependence;
1269 ++StrongSIVsuccesses;
1270 return true;
1271 }
1272 Result.DV[Level].Distance = SE->getConstant(Distance);
1273 if (Distance.sgt(0))
1274 Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1275 else if (Distance.slt(0))
1276 Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1277 else
1278 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1279 ++StrongSIVsuccesses;
1280 } else if (Delta->isZero()) {
1281 // Check if coefficient could be zero. If so, 0/0 is undefined and we
1282 // cannot conclude that only same-iteration dependencies exist.
1283 // When coeff=0, all iterations access the same location.
1284 if (SE->isKnownNonZero(Coeff)) {
1285 LLVM_DEBUG(
1286 dbgs() << "\t Coefficient proven non-zero by SCEV analysis\n");
1287 } else {
1288 // Cannot prove at compile time, would need runtime assumption.
1289 if (UnderRuntimeAssumptions) {
1290 const SCEVPredicate *Pred = SE->getComparePredicate(
1291 ICmpInst::ICMP_NE, Coeff, SE->getZero(Coeff->getType()));
1292 Result.Assumptions = Result.Assumptions.getUnionWith(Pred, *SE);
1293 LLVM_DEBUG(dbgs() << "\t Added runtime assumption: " << *Coeff
1294 << " != 0\n");
1295 } else {
1296 // Cannot add runtime assumptions, this test cannot handle this case.
1297 // Let more complex tests try.
1298 LLVM_DEBUG(dbgs() << "\t Would need runtime assumption " << *Coeff
1299 << " != 0, but not allowed. Failing this test.\n");
1300 return false;
1301 }
1302 }
1303 // Since 0/X == 0 (where X is known non-zero or assumed non-zero).
1304 Result.DV[Level].Distance = Delta;
1305 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1306 ++StrongSIVsuccesses;
1307 } else {
1308 if (Coeff->isOne()) {
1309 LLVM_DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
1310 Result.DV[Level].Distance = Delta; // since X/1 == X
1311 }
1312
1313 // maybe we can get a useful direction
1314 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
1315 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1316 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1317 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1318 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1319 // The double negatives above are confusing.
1320 // It helps to read !SE->isKnownNonZero(Delta)
1321 // as "Delta might be Zero"
1322 unsigned NewDirection = Dependence::DVEntry::NONE;
1323 if ((DeltaMaybePositive && CoeffMaybePositive) ||
1324 (DeltaMaybeNegative && CoeffMaybeNegative))
1325 NewDirection = Dependence::DVEntry::LT;
1326 if (DeltaMaybeZero)
1327 NewDirection |= Dependence::DVEntry::EQ;
1328 if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1329 (DeltaMaybePositive && CoeffMaybeNegative))
1330 NewDirection |= Dependence::DVEntry::GT;
1331 if (NewDirection < Result.DV[Level].Direction)
1332 ++StrongSIVsuccesses;
1333 Result.DV[Level].Direction &= NewDirection;
1334 }
1335 return false;
1336}
1337
1338// weakCrossingSIVtest -
1339// From the paper, Practical Dependence Testing, Section 4.2.2
1340//
1341// When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1342// where i is an induction variable, c1 and c2 are loop invariant,
1343// and a is a constant, we can solve it exactly using the
1344// Weak-Crossing SIV test.
1345//
1346// Given c1 + a*i = c2 - a*i', we can look for the intersection of
1347// the two lines, where i = i', yielding
1348//
1349// c1 + a*i = c2 - a*i
1350// 2a*i = c2 - c1
1351// i = (c2 - c1)/2a
1352//
1353// If i < 0, there is no dependence.
1354// If i > upperbound, there is no dependence.
1355// If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1356// If i = upperbound, there's a dependence with distance = 0.
1357// If i is integral, there's a dependence (all directions).
1358// If the non-integer part = 1/2, there's a dependence (<> directions).
1359// Otherwise, there's no dependence.
1360//
1361// Can prove independence. Failing that,
1362// can sometimes refine the directions.
1363// Can determine iteration for splitting.
1364//
1365// Return true if dependence disproved.
1366bool DependenceInfo::weakCrossingSIVtest(const SCEV *Coeff,
1367 const SCEV *SrcConst,
1368 const SCEV *DstConst,
1369 const Loop *CurSrcLoop,
1370 const Loop *CurDstLoop, unsigned Level,
1371 FullDependence &Result) const {
1372 if (!isDependenceTestEnabled(DependenceTestType::WeakCrossingSIV))
1373 return false;
1374
1375 LLVM_DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1376 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
1377 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1378 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1379 ++WeakCrossingSIVapplications;
1380 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1381 Level--;
1382 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1383 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1384 if (Delta->isZero()) {
1385 Result.DV[Level].Direction &= ~Dependence::DVEntry::LT;
1386 Result.DV[Level].Direction &= ~Dependence::DVEntry::GT;
1387 ++WeakCrossingSIVsuccesses;
1388 if (!Result.DV[Level].Direction) {
1389 ++WeakCrossingSIVindependence;
1390 return true;
1391 }
1392 Result.DV[Level].Distance = Delta; // = 0
1393 return false;
1394 }
1395 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1396 if (!ConstCoeff)
1397 return false;
1398
1399 if (SE->isKnownNegative(ConstCoeff)) {
1400 ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1401 assert(ConstCoeff &&
1402 "dynamic cast of negative of ConstCoeff should yield constant");
1403 Delta = SE->getNegativeSCEV(Delta);
1404 }
1405 assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1406
1407 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1408 if (!ConstDelta)
1409 return false;
1410
1411 // We're certain that ConstCoeff > 0; therefore,
1412 // if Delta < 0, then no dependence.
1413 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1414 LLVM_DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n");
1415 if (SE->isKnownNegative(Delta)) {
1416 // No dependence, Delta < 0
1417 ++WeakCrossingSIVindependence;
1418 ++WeakCrossingSIVsuccesses;
1419 return true;
1420 }
1421
1422 // We're certain that Delta > 0 and ConstCoeff > 0.
1423 // Check Delta/(2*ConstCoeff) against upper loop bound
1424 if (const SCEV *UpperBound =
1425 collectUpperBound(CurSrcLoop, Delta->getType())) {
1426 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1427 const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1428 const SCEV *ML =
1429 SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound), ConstantTwo);
1430 LLVM_DEBUG(dbgs() << "\t ML = " << *ML << "\n");
1431 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1432 // Delta too big, no dependence
1433 ++WeakCrossingSIVindependence;
1434 ++WeakCrossingSIVsuccesses;
1435 return true;
1436 }
1437 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1438 // i = i' = UB
1439 Result.DV[Level].Direction &= ~Dependence::DVEntry::LT;
1440 Result.DV[Level].Direction &= ~Dependence::DVEntry::GT;
1441 ++WeakCrossingSIVsuccesses;
1442 if (!Result.DV[Level].Direction) {
1443 ++WeakCrossingSIVindependence;
1444 return true;
1445 }
1446 Result.DV[Level].Distance = SE->getZero(Delta->getType());
1447 return false;
1448 }
1449 }
1450
1451 // check that Coeff divides Delta
1452 APInt APDelta = ConstDelta->getAPInt();
1453 APInt APCoeff = ConstCoeff->getAPInt();
1454 APInt Distance = APDelta; // these need to be initialzed
1455 APInt Remainder = APDelta;
1456 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
1457 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1458 if (Remainder != 0) {
1459 // Coeff doesn't divide Delta, no dependence
1460 ++WeakCrossingSIVindependence;
1461 ++WeakCrossingSIVsuccesses;
1462 return true;
1463 }
1464 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1465
1466 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1467 APInt Two = APInt(Distance.getBitWidth(), 2, true);
1468 Remainder = Distance.srem(Two);
1469 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
1470 if (Remainder != 0) {
1471 // Equal direction isn't possible
1472 Result.DV[Level].Direction &= ~Dependence::DVEntry::EQ;
1473 ++WeakCrossingSIVsuccesses;
1474 }
1475 return false;
1476}
1477
1478// Kirch's algorithm, from
1479//
1480// Optimizing Supercompilers for Supercomputers
1481// Michael Wolfe
1482// MIT Press, 1989
1483//
1484// Program 2.1, page 29.
1485// Computes the GCD of AM and BM.
1486// Also finds a solution to the equation ax - by = gcd(a, b).
1487// Returns true if dependence disproved; i.e., gcd does not divide Delta.
1488//
1489// We don't use OverflowSafeSignedAPInt here because it's known that this
1490// algorithm doesn't overflow.
1491static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM,
1492 const APInt &Delta, APInt &G, APInt &X, APInt &Y) {
1493 APInt A0(Bits, 1, true), A1(Bits, 0, true);
1494 APInt B0(Bits, 0, true), B1(Bits, 1, true);
1495 APInt G0 = AM.abs();
1496 APInt G1 = BM.abs();
1497 APInt Q = G0; // these need to be initialized
1498 APInt R = G0;
1499 APInt::sdivrem(G0, G1, Q, R);
1500 while (R != 0) {
1501 // clang-format off
1502 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1503 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1504 G0 = G1; G1 = R;
1505 // clang-format on
1506 APInt::sdivrem(G0, G1, Q, R);
1507 }
1508 G = G1;
1509 LLVM_DEBUG(dbgs() << "\t GCD = " << G << "\n");
1510 X = AM.slt(0) ? -A1 : A1;
1511 Y = BM.slt(0) ? B1 : -B1;
1512
1513 // make sure gcd divides Delta
1514 R = Delta.srem(G);
1515 if (R != 0)
1516 return true; // gcd doesn't divide Delta, no dependence
1517 Q = Delta.sdiv(G);
1518 return false;
1519}
1520
1521static OverflowSafeSignedAPInt
1522floorOfQuotient(const OverflowSafeSignedAPInt &OA,
1523 const OverflowSafeSignedAPInt &OB) {
1524 if (!OA || !OB)
1525 return OverflowSafeSignedAPInt();
1526
1527 APInt A = *OA;
1528 APInt B = *OB;
1529 APInt Q = A; // these need to be initialized
1530 APInt R = A;
1531 APInt::sdivrem(A, B, Q, R);
1532 if (R == 0)
1533 return Q;
1534 if ((A.sgt(0) && B.sgt(0)) || (A.slt(0) && B.slt(0)))
1535 return Q;
1536 return OverflowSafeSignedAPInt(Q) - 1;
1537}
1538
1539static OverflowSafeSignedAPInt
1540ceilingOfQuotient(const OverflowSafeSignedAPInt &OA,
1541 const OverflowSafeSignedAPInt &OB) {
1542 if (!OA || !OB)
1543 return OverflowSafeSignedAPInt();
1544
1545 APInt A = *OA;
1546 APInt B = *OB;
1547 APInt Q = A; // these need to be initialized
1548 APInt R = A;
1549 APInt::sdivrem(A, B, Q, R);
1550 if (R == 0)
1551 return Q;
1552 if ((A.sgt(0) && B.sgt(0)) || (A.slt(0) && B.slt(0)))
1553 return OverflowSafeSignedAPInt(Q) + 1;
1554 return Q;
1555}
1556
1557/// Given an affine expression of the form A*k + B, where k is an arbitrary
1558/// integer, infer the possible range of k based on the known range of the
1559/// affine expression. If we know A*k + B is non-negative, i.e.,
1560///
1561/// A*k + B >= 0
1562///
1563/// we can derive the following inequalities for k when A is positive:
1564///
1565/// k >= -B / A
1566///
1567/// Since k is an integer, it means k is greater than or equal to the
1568/// ceil(-B / A).
1569///
1570/// If the upper bound of the affine expression \p UB is passed, the following
1571/// inequality can be derived as well:
1572///
1573/// A*k + B <= UB
1574///
1575/// which leads to:
1576///
1577/// k <= (UB - B) / A
1578///
1579/// Again, as k is an integer, it means k is less than or equal to the
1580/// floor((UB - B) / A).
1581///
1582/// The similar logic applies when A is negative, but the inequalities sign flip
1583/// while working with them.
1584///
1585/// Preconditions: \p A is non-zero, and we know A*k + B is non-negative.
1586static std::pair<OverflowSafeSignedAPInt, OverflowSafeSignedAPInt>
1587inferDomainOfAffine(OverflowSafeSignedAPInt A, OverflowSafeSignedAPInt B,
1588 OverflowSafeSignedAPInt UB) {
1589 assert(A && B && "A and B must be available");
1590 assert(*A != 0 && "A must be non-zero");
1591 OverflowSafeSignedAPInt TL, TU;
1592 if (A->sgt(0)) {
1593 TL = ceilingOfQuotient(-B, A);
1594 LLVM_DEBUG(if (TL) dbgs() << "\t Possible TL = " << *TL << "\n");
1595
1596 // New bound check - modification to Banerjee's e3 check
1597 TU = floorOfQuotient(UB - B, A);
1598 LLVM_DEBUG(if (TU) dbgs() << "\t Possible TU = " << *TU << "\n");
1599 } else {
1600 TU = floorOfQuotient(-B, A);
1601 LLVM_DEBUG(if (TU) dbgs() << "\t Possible TU = " << *TU << "\n");
1602
1603 // New bound check - modification to Banerjee's e3 check
1604 TL = ceilingOfQuotient(UB - B, A);
1605 LLVM_DEBUG(if (TL) dbgs() << "\t Possible TL = " << *TL << "\n");
1606 }
1607 return std::make_pair(TL, TU);
1608}
1609
1610// exactSIVtest -
1611// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1612// where i is an induction variable, c1 and c2 are loop invariant, and a1
1613// and a2 are constant, we can solve it exactly using an algorithm developed
1614// by Banerjee and Wolfe. See Algorithm 6.2.1 (case 2.5) in:
1615//
1616// Dependence Analysis for Supercomputing
1617// Utpal Banerjee
1618// Kluwer Academic Publishers, 1988
1619//
1620// It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1621// so use them if possible. They're also a bit better with symbolics and,
1622// in the case of the strong SIV test, can compute Distances.
1623//
1624// Return true if dependence disproved.
1625//
1626// This is a modified version of the original Banerjee algorithm. The original
1627// only tested whether Dst depends on Src. This algorithm extends that and
1628// returns all the dependencies that exist between Dst and Src.
1629bool DependenceInfo::exactSIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1630 const SCEV *SrcConst, const SCEV *DstConst,
1631 const Loop *CurSrcLoop,
1632 const Loop *CurDstLoop, unsigned Level,
1633 FullDependence &Result) const {
1634 if (!isDependenceTestEnabled(DependenceTestType::ExactSIV))
1635 return false;
1636
1637 LLVM_DEBUG(dbgs() << "\tExact SIV test\n");
1638 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1639 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1640 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1641 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1642 ++ExactSIVapplications;
1643 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1644 Level--;
1645 const SCEV *Delta = minusSCEVNoSignedOverflow(DstConst, SrcConst, *SE);
1646 if (!Delta)
1647 return false;
1648 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1649 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1650 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1651 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1652 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1653 return false;
1654
1655 // find gcd
1656 APInt G, X, Y;
1657 APInt AM = ConstSrcCoeff->getAPInt();
1658 APInt BM = ConstDstCoeff->getAPInt();
1659 APInt CM = ConstDelta->getAPInt();
1660 unsigned Bits = AM.getBitWidth();
1661 if (findGCD(Bits, AM, BM, CM, G, X, Y)) {
1662 // gcd doesn't divide Delta, no dependence
1663 ++ExactSIVindependence;
1664 ++ExactSIVsuccesses;
1665 return true;
1666 }
1667
1668 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
1669
1670 // since SCEV construction normalizes, LM = 0
1671 std::optional<APInt> UM;
1672 // UM is perhaps unavailable, let's check
1673 if (const SCEVConstant *CUB =
1674 collectConstantUpperBound(CurSrcLoop, Delta->getType())) {
1675 UM = CUB->getAPInt();
1676 LLVM_DEBUG(dbgs() << "\t UM = " << *UM << "\n");
1677 }
1678
1679 APInt TU(APInt::getSignedMaxValue(Bits));
1680 APInt TL(APInt::getSignedMinValue(Bits));
1681 APInt TC = CM.sdiv(G);
1682 APInt TX = X * TC;
1683 APInt TY = Y * TC;
1684 LLVM_DEBUG(dbgs() << "\t TC = " << TC << "\n");
1685 LLVM_DEBUG(dbgs() << "\t TX = " << TX << "\n");
1686 LLVM_DEBUG(dbgs() << "\t TY = " << TY << "\n");
1687
1688 APInt TB = BM.sdiv(G);
1689 APInt TA = AM.sdiv(G);
1690
1691 // At this point, we have the following equations:
1692 //
1693 // TA*i0 - TB*i1 = TC
1694 //
1695 // Also, we know that the all pairs of (i0, i1) can be expressed as:
1696 //
1697 // (TX + k*TB, TY + k*TA)
1698 //
1699 // where k is an arbitrary integer.
1700 auto [TL0, TU0] = inferDomainOfAffine(TB, TX, UM);
1701 auto [TL1, TU1] = inferDomainOfAffine(TA, TY, UM);
1702
1703 auto CreateVec = [](const OverflowSafeSignedAPInt &V0,
1704 const OverflowSafeSignedAPInt &V1) {
1706 if (V0)
1707 Vec.push_back(*V0);
1708 if (V1)
1709 Vec.push_back(*V1);
1710 return Vec;
1711 };
1712
1713 SmallVector<APInt, 2> TLVec = CreateVec(TL0, TL1);
1714 SmallVector<APInt, 2> TUVec = CreateVec(TU0, TU1);
1715
1716 LLVM_DEBUG(dbgs() << "\t TA = " << TA << "\n");
1717 LLVM_DEBUG(dbgs() << "\t TB = " << TB << "\n");
1718
1719 if (TLVec.empty() || TUVec.empty())
1720 return false;
1721 TL = APIntOps::smax(TLVec.front(), TLVec.back());
1722 TU = APIntOps::smin(TUVec.front(), TUVec.back());
1723 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
1724 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
1725
1726 if (TL.sgt(TU)) {
1727 ++ExactSIVindependence;
1728 ++ExactSIVsuccesses;
1729 return true;
1730 }
1731
1732 // explore directions
1733 unsigned NewDirection = Dependence::DVEntry::NONE;
1734 OverflowSafeSignedAPInt LowerDistance, UpperDistance;
1735 OverflowSafeSignedAPInt OTY(TY), OTX(TX), OTA(TA), OTB(TB), OTL(TL), OTU(TU);
1736 // NOTE: It's unclear whether these calculations can overflow. At the moment,
1737 // we conservatively assume they can.
1738 if (TA.sgt(TB)) {
1739 LowerDistance = (OTY - OTX) + (OTA - OTB) * OTL;
1740 UpperDistance = (OTY - OTX) + (OTA - OTB) * OTU;
1741 } else {
1742 LowerDistance = (OTY - OTX) + (OTA - OTB) * OTU;
1743 UpperDistance = (OTY - OTX) + (OTA - OTB) * OTL;
1744 }
1745
1746 if (!LowerDistance || !UpperDistance)
1747 return false;
1748
1749 LLVM_DEBUG(dbgs() << "\t LowerDistance = " << *LowerDistance << "\n");
1750 LLVM_DEBUG(dbgs() << "\t UpperDistance = " << *UpperDistance << "\n");
1751
1752 if (LowerDistance->sle(0) && UpperDistance->sge(0)) {
1753 NewDirection |= Dependence::DVEntry::EQ;
1754 ++ExactSIVsuccesses;
1755 }
1756 if (LowerDistance->slt(0)) {
1757 NewDirection |= Dependence::DVEntry::GT;
1758 ++ExactSIVsuccesses;
1759 }
1760 if (UpperDistance->sgt(0)) {
1761 NewDirection |= Dependence::DVEntry::LT;
1762 ++ExactSIVsuccesses;
1763 }
1764
1765 // finished
1766 Result.DV[Level].Direction &= NewDirection;
1767 if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1768 ++ExactSIVindependence;
1769 LLVM_DEBUG(dbgs() << "\t Result = ");
1770 LLVM_DEBUG(Result.dump(dbgs()));
1771 return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1772}
1773
1774// Return true if the divisor evenly divides the dividend.
1775static bool isRemainderZero(const SCEVConstant *Dividend,
1776 const SCEVConstant *Divisor) {
1777 const APInt &ConstDividend = Dividend->getAPInt();
1778 const APInt &ConstDivisor = Divisor->getAPInt();
1779 return ConstDividend.srem(ConstDivisor) == 0;
1780}
1781
1782// weakZeroSrcSIVtest -
1783// From the paper, Practical Dependence Testing, Section 4.2.2
1784//
1785// When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1786// where i is an induction variable, c1 and c2 are loop invariant,
1787// and a is a constant, we can solve it exactly using the
1788// Weak-Zero SIV test.
1789//
1790// Given
1791//
1792// c1 = c2 + a*i
1793//
1794// we get
1795//
1796// (c1 - c2)/a = i
1797//
1798// If i is not an integer, there's no dependence.
1799// If i < 0 or > UB, there's no dependence.
1800// If i = 0, the direction is >= and peeling the
1801// 1st iteration will break the dependence.
1802// If i = UB, the direction is <= and peeling the
1803// last iteration will break the dependence.
1804// Otherwise, the direction is *.
1805//
1806// Can prove independence. Failing that, we can sometimes refine
1807// the directions. Can sometimes show that first or last
1808// iteration carries all the dependences (so worth peeling).
1809//
1810// (see also weakZeroDstSIVtest)
1811//
1812// Return true if dependence disproved.
1813bool DependenceInfo::weakZeroSrcSIVtest(const SCEV *DstCoeff,
1814 const SCEV *SrcConst,
1815 const SCEV *DstConst,
1816 const Loop *CurSrcLoop,
1817 const Loop *CurDstLoop, unsigned Level,
1818 FullDependence &Result) const {
1819 if (!isDependenceTestEnabled(DependenceTestType::WeakZeroSIV))
1820 return false;
1821
1822 // For the WeakSIV test, it's possible the loop isn't common to
1823 // the Src and Dst loops. If it isn't, then there's no need to
1824 // record a direction.
1825 LLVM_DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1826 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1827 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1828 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1829 ++WeakZeroSIVapplications;
1830 assert(0 < Level && Level <= MaxLevels && "Level out of range");
1831 Level--;
1832 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
1833 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1834 if (SrcConst == DstConst && SE->isKnownNonZero(DstCoeff)) {
1835 if (Level < CommonLevels) {
1836 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1837 ++WeakZeroSIVsuccesses;
1838 }
1839 return false; // dependences caused by first iteration
1840 }
1841 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1842 if (!ConstCoeff)
1843 return false;
1844
1845 // Since ConstCoeff is constant, !isKnownNegative means it's non-negative.
1846 // TODO: Bail out if it's a signed minimum value.
1847 const SCEV *AbsCoeff = SE->isKnownNegative(ConstCoeff)
1848 ? SE->getNegativeSCEV(ConstCoeff)
1849 : ConstCoeff;
1850 const SCEV *NewDelta =
1851 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1852
1853 // check that Delta/SrcCoeff < iteration count
1854 // really check NewDelta < count*AbsCoeff
1855 if (const SCEV *UpperBound =
1856 collectUpperBound(CurSrcLoop, Delta->getType())) {
1857 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1858 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1859 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1860 ++WeakZeroSIVindependence;
1861 ++WeakZeroSIVsuccesses;
1862 return true;
1863 }
1864 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1865 // dependences caused by last iteration
1866 if (Level < CommonLevels) {
1867 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1868 ++WeakZeroSIVsuccesses;
1869 }
1870 return false;
1871 }
1872 }
1873
1874 // check that Delta/SrcCoeff >= 0
1875 // really check that NewDelta >= 0
1876 if (SE->isKnownNegative(NewDelta)) {
1877 // No dependence, newDelta < 0
1878 ++WeakZeroSIVindependence;
1879 ++WeakZeroSIVsuccesses;
1880 return true;
1881 }
1882
1883 // if SrcCoeff doesn't divide Delta, then no dependence
1884 if (isa<SCEVConstant>(Delta) &&
1885 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1886 ++WeakZeroSIVindependence;
1887 ++WeakZeroSIVsuccesses;
1888 return true;
1889 }
1890 return false;
1891}
1892
1893// weakZeroDstSIVtest -
1894// From the paper, Practical Dependence Testing, Section 4.2.2
1895//
1896// When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1897// where i is an induction variable, c1 and c2 are loop invariant,
1898// and a is a constant, we can solve it exactly using the
1899// Weak-Zero SIV test.
1900//
1901// Given
1902//
1903// c1 + a*i = c2
1904//
1905// we get
1906//
1907// i = (c2 - c1)/a
1908//
1909// If i is not an integer, there's no dependence.
1910// If i < 0 or > UB, there's no dependence.
1911// If i = 0, the direction is <= and peeling the
1912// 1st iteration will break the dependence.
1913// If i = UB, the direction is >= and peeling the
1914// last iteration will break the dependence.
1915// Otherwise, the direction is *.
1916//
1917// Can prove independence. Failing that, we can sometimes refine
1918// the directions. Can sometimes show that first or last
1919// iteration carries all the dependences (so worth peeling).
1920//
1921// (see also weakZeroSrcSIVtest)
1922//
1923// Return true if dependence disproved.
1924bool DependenceInfo::weakZeroDstSIVtest(const SCEV *SrcCoeff,
1925 const SCEV *SrcConst,
1926 const SCEV *DstConst,
1927 const Loop *CurSrcLoop,
1928 const Loop *CurDstLoop, unsigned Level,
1929 FullDependence &Result) const {
1930 if (!isDependenceTestEnabled(DependenceTestType::WeakZeroSIV))
1931 return false;
1932
1933 // For the WeakSIV test, it's possible the loop isn't common to the
1934 // Src and Dst loops. If it isn't, then there's no need to record a direction.
1935 LLVM_DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1936 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1937 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1938 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
1939 ++WeakZeroSIVapplications;
1940 assert(0 < Level && Level <= SrcLevels && "Level out of range");
1941 Level--;
1942 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
1943 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1944 if (DstConst == SrcConst && SE->isKnownNonZero(SrcCoeff)) {
1945 if (Level < CommonLevels) {
1946 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1947 ++WeakZeroSIVsuccesses;
1948 }
1949 return false; // dependences caused by first iteration
1950 }
1951 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1952 if (!ConstCoeff)
1953 return false;
1954
1955 // Since ConstCoeff is constant, !isKnownNegative means it's non-negative.
1956 // TODO: Bail out if it's a signed minimum value.
1957 const SCEV *AbsCoeff = SE->isKnownNegative(ConstCoeff)
1958 ? SE->getNegativeSCEV(ConstCoeff)
1959 : ConstCoeff;
1960 const SCEV *NewDelta =
1961 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1962
1963 // check that Delta/SrcCoeff < iteration count
1964 // really check NewDelta < count*AbsCoeff
1965 if (const SCEV *UpperBound =
1966 collectUpperBound(CurSrcLoop, Delta->getType())) {
1967 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
1968 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1969 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1970 ++WeakZeroSIVindependence;
1971 ++WeakZeroSIVsuccesses;
1972 return true;
1973 }
1974 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1975 // dependences caused by last iteration
1976 if (Level < CommonLevels) {
1977 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1978 ++WeakZeroSIVsuccesses;
1979 }
1980 return false;
1981 }
1982 }
1983
1984 // check that Delta/SrcCoeff >= 0
1985 // really check that NewDelta >= 0
1986 if (SE->isKnownNegative(NewDelta)) {
1987 // No dependence, newDelta < 0
1988 ++WeakZeroSIVindependence;
1989 ++WeakZeroSIVsuccesses;
1990 return true;
1991 }
1992
1993 // if SrcCoeff doesn't divide Delta, then no dependence
1994 if (isa<SCEVConstant>(Delta) &&
1995 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1996 ++WeakZeroSIVindependence;
1997 ++WeakZeroSIVsuccesses;
1998 return true;
1999 }
2000 return false;
2001}
2002
2003// exactRDIVtest - Tests the RDIV subscript pair for dependence.
2004// Things of the form [c1 + a*i] and [c2 + b*j],
2005// where i and j are induction variable, c1 and c2 are loop invariant,
2006// and a and b are constants.
2007// Returns true if any possible dependence is disproved.
2008// Marks the result as inconsistent.
2009// Works in some cases that symbolicRDIVtest doesn't, and vice versa.
2010bool DependenceInfo::exactRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
2011 const SCEV *SrcConst, const SCEV *DstConst,
2012 const Loop *SrcLoop, const Loop *DstLoop,
2013 FullDependence &Result) const {
2014 if (!isDependenceTestEnabled(DependenceTestType::ExactRDIV))
2015 return false;
2016
2017 LLVM_DEBUG(dbgs() << "\tExact RDIV test\n");
2018 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
2019 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
2020 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
2021 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
2022 ++ExactRDIVapplications;
2023 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
2024 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
2025 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
2026 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
2027 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
2028 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
2029 return false;
2030
2031 // find gcd
2032 APInt G, X, Y;
2033 APInt AM = ConstSrcCoeff->getAPInt();
2034 APInt BM = ConstDstCoeff->getAPInt();
2035 APInt CM = ConstDelta->getAPInt();
2036 unsigned Bits = AM.getBitWidth();
2037 if (findGCD(Bits, AM, BM, CM, G, X, Y)) {
2038 // gcd doesn't divide Delta, no dependence
2039 ++ExactRDIVindependence;
2040 return true;
2041 }
2042
2043 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
2044
2045 // since SCEV construction seems to normalize, LM = 0
2046 std::optional<APInt> SrcUM;
2047 // SrcUM is perhaps unavailable, let's check
2048 if (const SCEVConstant *UpperBound =
2049 collectConstantUpperBound(SrcLoop, Delta->getType())) {
2050 SrcUM = UpperBound->getAPInt();
2051 LLVM_DEBUG(dbgs() << "\t SrcUM = " << *SrcUM << "\n");
2052 }
2053
2054 std::optional<APInt> DstUM;
2055 // UM is perhaps unavailable, let's check
2056 if (const SCEVConstant *UpperBound =
2057 collectConstantUpperBound(DstLoop, Delta->getType())) {
2058 DstUM = UpperBound->getAPInt();
2059 LLVM_DEBUG(dbgs() << "\t DstUM = " << *DstUM << "\n");
2060 }
2061
2062 APInt TU(APInt::getSignedMaxValue(Bits));
2063 APInt TL(APInt::getSignedMinValue(Bits));
2064 APInt TC = CM.sdiv(G);
2065 APInt TX = X * TC;
2066 APInt TY = Y * TC;
2067 LLVM_DEBUG(dbgs() << "\t TC = " << TC << "\n");
2068 LLVM_DEBUG(dbgs() << "\t TX = " << TX << "\n");
2069 LLVM_DEBUG(dbgs() << "\t TY = " << TY << "\n");
2070
2071 APInt TB = BM.sdiv(G);
2072 APInt TA = AM.sdiv(G);
2073
2074 // At this point, we have the following equations:
2075 //
2076 // TA*i - TB*j = TC
2077 //
2078 // Also, we know that the all pairs of (i, j) can be expressed as:
2079 //
2080 // (TX + k*TB, TY + k*TA)
2081 //
2082 // where k is an arbitrary integer.
2083 auto [TL0, TU0] = inferDomainOfAffine(TB, TX, SrcUM);
2084 auto [TL1, TU1] = inferDomainOfAffine(TA, TY, DstUM);
2085
2086 LLVM_DEBUG(dbgs() << "\t TA = " << TA << "\n");
2087 LLVM_DEBUG(dbgs() << "\t TB = " << TB << "\n");
2088
2089 auto CreateVec = [](const OverflowSafeSignedAPInt &V0,
2090 const OverflowSafeSignedAPInt &V1) {
2092 if (V0)
2093 Vec.push_back(*V0);
2094 if (V1)
2095 Vec.push_back(*V1);
2096 return Vec;
2097 };
2098
2099 SmallVector<APInt, 2> TLVec = CreateVec(TL0, TL1);
2100 SmallVector<APInt, 2> TUVec = CreateVec(TU0, TU1);
2101 if (TLVec.empty() || TUVec.empty())
2102 return false;
2103
2104 TL = APIntOps::smax(TLVec.front(), TLVec.back());
2105 TU = APIntOps::smin(TUVec.front(), TUVec.back());
2106 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
2107 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
2108
2109 if (TL.sgt(TU))
2110 ++ExactRDIVindependence;
2111 return TL.sgt(TU);
2112}
2113
2114// symbolicRDIVtest -
2115// In Section 4.5 of the Practical Dependence Testing paper,the authors
2116// introduce a special case of Banerjee's Inequalities (also called the
2117// Extreme-Value Test) that can handle some of the SIV and RDIV cases,
2118// particularly cases with symbolics. Since it's only able to disprove
2119// dependence (not compute distances or directions), we'll use it as a
2120// fall back for the other tests.
2121//
2122// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2123// where i and j are induction variables and c1 and c2 are loop invariants,
2124// we can use the symbolic tests to disprove some dependences, serving as a
2125// backup for the RDIV test. Note that i and j can be the same variable,
2126// letting this test serve as a backup for the various SIV tests.
2127//
2128// For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
2129// 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
2130// loop bounds for the i and j loops, respectively. So, ...
2131//
2132// c1 + a1*i = c2 + a2*j
2133// a1*i - a2*j = c2 - c1
2134//
2135// To test for a dependence, we compute c2 - c1 and make sure it's in the
2136// range of the maximum and minimum possible values of a1*i - a2*j.
2137// Considering the signs of a1 and a2, we have 4 possible cases:
2138//
2139// 1) If a1 >= 0 and a2 >= 0, then
2140// a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
2141// -a2*N2 <= c2 - c1 <= a1*N1
2142//
2143// 2) If a1 >= 0 and a2 <= 0, then
2144// a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
2145// 0 <= c2 - c1 <= a1*N1 - a2*N2
2146//
2147// 3) If a1 <= 0 and a2 >= 0, then
2148// a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
2149// a1*N1 - a2*N2 <= c2 - c1 <= 0
2150//
2151// 4) If a1 <= 0 and a2 <= 0, then
2152// a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2
2153// a1*N1 <= c2 - c1 <= -a2*N2
2154//
2155// return true if dependence disproved
2156bool DependenceInfo::symbolicRDIVtest(const SCEV *A1, const SCEV *A2,
2157 const SCEV *C1, const SCEV *C2,
2158 const Loop *Loop1,
2159 const Loop *Loop2) const {
2160 if (!isDependenceTestEnabled(DependenceTestType::SymbolicRDIV))
2161 return false;
2162
2163 ++SymbolicRDIVapplications;
2164 LLVM_DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
2165 LLVM_DEBUG(dbgs() << "\t A1 = " << *A1);
2166 LLVM_DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
2167 LLVM_DEBUG(dbgs() << "\t A2 = " << *A2 << "\n");
2168 LLVM_DEBUG(dbgs() << "\t C1 = " << *C1 << "\n");
2169 LLVM_DEBUG(dbgs() << "\t C2 = " << *C2 << "\n");
2170 const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
2171 const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
2172 LLVM_DEBUG(if (N1) dbgs() << "\t N1 = " << *N1 << "\n");
2173 LLVM_DEBUG(if (N2) dbgs() << "\t N2 = " << *N2 << "\n");
2174 const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
2175 const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
2176 LLVM_DEBUG(dbgs() << "\t C2 - C1 = " << *C2_C1 << "\n");
2177 LLVM_DEBUG(dbgs() << "\t C1 - C2 = " << *C1_C2 << "\n");
2178 if (SE->isKnownNonNegative(A1)) {
2179 if (SE->isKnownNonNegative(A2)) {
2180 // A1 >= 0 && A2 >= 0
2181 if (N1) {
2182 // make sure that c2 - c1 <= a1*N1
2183 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2184 LLVM_DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
2185 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
2186 ++SymbolicRDIVindependence;
2187 return true;
2188 }
2189 }
2190 if (N2) {
2191 // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
2192 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2193 LLVM_DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
2194 if (SE->isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
2195 ++SymbolicRDIVindependence;
2196 return true;
2197 }
2198 }
2199 } else if (SE->isKnownNonPositive(A2)) {
2200 // a1 >= 0 && a2 <= 0
2201 if (N1 && N2) {
2202 // make sure that c2 - c1 <= a1*N1 - a2*N2
2203 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2204 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2205 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
2206 LLVM_DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
2207 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
2208 ++SymbolicRDIVindependence;
2209 return true;
2210 }
2211 }
2212 // make sure that 0 <= c2 - c1
2213 if (SE->isKnownNegative(C2_C1)) {
2214 ++SymbolicRDIVindependence;
2215 return true;
2216 }
2217 }
2218 } else if (SE->isKnownNonPositive(A1)) {
2219 if (SE->isKnownNonNegative(A2)) {
2220 // a1 <= 0 && a2 >= 0
2221 if (N1 && N2) {
2222 // make sure that a1*N1 - a2*N2 <= c2 - c1
2223 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2224 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2225 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
2226 LLVM_DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
2227 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
2228 ++SymbolicRDIVindependence;
2229 return true;
2230 }
2231 }
2232 // make sure that c2 - c1 <= 0
2233 if (SE->isKnownPositive(C2_C1)) {
2234 ++SymbolicRDIVindependence;
2235 return true;
2236 }
2237 } else if (SE->isKnownNonPositive(A2)) {
2238 // a1 <= 0 && a2 <= 0
2239 if (N1) {
2240 // make sure that a1*N1 <= c2 - c1
2241 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2242 LLVM_DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
2243 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
2244 ++SymbolicRDIVindependence;
2245 return true;
2246 }
2247 }
2248 if (N2) {
2249 // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
2250 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2251 LLVM_DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
2252 if (SE->isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
2253 ++SymbolicRDIVindependence;
2254 return true;
2255 }
2256 }
2257 }
2258 }
2259 return false;
2260}
2261
2262// testSIV -
2263// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2264// where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2265// a2 are constant, we attack it with an SIV test. While they can all be
2266// solved with the Exact SIV test, it's worthwhile to use simpler tests when
2267// they apply; they're cheaper and sometimes more precise.
2268//
2269// Return true if dependence disproved.
2270bool DependenceInfo::testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
2271 FullDependence &Result,
2272 bool UnderRuntimeAssumptions) {
2273 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2274 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
2275 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2276 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2277 if (SrcAddRec && DstAddRec) {
2278 const SCEV *SrcConst = SrcAddRec->getStart();
2279 const SCEV *DstConst = DstAddRec->getStart();
2280 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2281 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2282 const Loop *CurSrcLoop = SrcAddRec->getLoop();
2283 const Loop *CurDstLoop = DstAddRec->getLoop();
2284 assert(haveSameSD(CurSrcLoop, CurDstLoop) &&
2285 "Loops in the SIV test should have the same iteration space and "
2286 "depth");
2287 Level = mapSrcLoop(CurSrcLoop);
2288 bool disproven;
2289 if (SrcCoeff == DstCoeff)
2290 disproven = strongSIVtest(SrcAddRec, DstAddRec, Level, Result,
2291 UnderRuntimeAssumptions);
2292 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2293 disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurSrcLoop,
2294 CurDstLoop, Level, Result);
2295 else
2296 disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst,
2297 CurSrcLoop, CurDstLoop, Level, Result);
2298 return disproven || gcdMIVtest(Src, Dst, Result) ||
2299 symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurSrcLoop,
2300 CurDstLoop);
2301 }
2302 if (SrcAddRec) {
2303 const SCEV *SrcConst = SrcAddRec->getStart();
2304 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2305 const SCEV *DstConst = Dst;
2306 const Loop *CurSrcLoop = SrcAddRec->getLoop();
2307 Level = mapSrcLoop(CurSrcLoop);
2308 return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurSrcLoop,
2309 CurSrcLoop, Level, Result) ||
2310 gcdMIVtest(Src, Dst, Result);
2311 }
2312 if (DstAddRec) {
2313 const SCEV *DstConst = DstAddRec->getStart();
2314 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2315 const SCEV *SrcConst = Src;
2316 const Loop *CurDstLoop = DstAddRec->getLoop();
2317 Level = mapDstLoop(CurDstLoop);
2318 return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst, CurDstLoop,
2319 CurDstLoop, Level, Result) ||
2320 gcdMIVtest(Src, Dst, Result);
2321 }
2322 llvm_unreachable("SIV test expected at least one AddRec");
2323 return false;
2324}
2325
2326// testRDIV -
2327// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2328// where i and j are induction variables, c1 and c2 are loop invariant,
2329// and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2330// of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2331// It doesn't make sense to talk about distance or direction in this case,
2332// so there's no point in making special versions of the Strong SIV test or
2333// the Weak-crossing SIV test.
2334//
2335// Return true if dependence disproved.
2336bool DependenceInfo::testRDIV(const SCEV *Src, const SCEV *Dst,
2337 FullDependence &Result) const {
2338 const SCEV *SrcConst, *DstConst;
2339 const SCEV *SrcCoeff, *DstCoeff;
2340 const Loop *SrcLoop, *DstLoop;
2341
2342 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2343 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
2344 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2345 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2346 if (SrcAddRec && DstAddRec) {
2347 SrcConst = SrcAddRec->getStart();
2348 SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2349 SrcLoop = SrcAddRec->getLoop();
2350 DstConst = DstAddRec->getStart();
2351 DstCoeff = DstAddRec->getStepRecurrence(*SE);
2352 DstLoop = DstAddRec->getLoop();
2353 } else
2354 llvm_unreachable("RDIV expected at least one AddRec");
2355 return exactRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, SrcLoop, DstLoop,
2356 Result) ||
2357 gcdMIVtest(Src, Dst, Result) ||
2358 symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, SrcLoop,
2359 DstLoop);
2360}
2361
2362// Tests the single-subscript MIV pair (Src and Dst) for dependence.
2363// Return true if dependence disproved.
2364// Can sometimes refine direction vectors.
2365bool DependenceInfo::testMIV(const SCEV *Src, const SCEV *Dst,
2366 const SmallBitVector &Loops,
2367 FullDependence &Result) const {
2368 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2369 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
2370 return gcdMIVtest(Src, Dst, Result) ||
2371 banerjeeMIVtest(Src, Dst, Loops, Result);
2372}
2373
2374/// Given a SCEVMulExpr, returns its first operand if its first operand is a
2375/// constant and the product doesn't overflow in a signed sense. Otherwise,
2376/// returns std::nullopt. For example, given (10 * X * Y)<nsw>, it returns 10.
2377/// Notably, if it doesn't have nsw, the multiplication may overflow, and if
2378/// so, it may not a multiple of 10.
2379static std::optional<APInt> getConstantCoefficient(const SCEV *Expr) {
2380 if (const auto *Constant = dyn_cast<SCEVConstant>(Expr))
2381 return Constant->getAPInt();
2382 if (const auto *Product = dyn_cast<SCEVMulExpr>(Expr))
2383 if (const auto *Constant = dyn_cast<SCEVConstant>(Product->getOperand(0)))
2384 if (Product->hasNoSignedWrap())
2385 return Constant->getAPInt();
2386 return std::nullopt;
2387}
2388
2389bool DependenceInfo::accumulateCoefficientsGCD(const SCEV *Expr,
2390 const Loop *CurLoop,
2391 const SCEV *&CurLoopCoeff,
2392 APInt &RunningGCD) const {
2393 // If RunningGCD is already 1, exit early.
2394 // TODO: It might be better to continue the recursion to find CurLoopCoeff.
2395 if (RunningGCD == 1)
2396 return true;
2397
2398 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2399 if (!AddRec) {
2400 assert(isLoopInvariant(Expr, CurLoop) &&
2401 "Expected loop invariant expression");
2402 return true;
2403 }
2404
2405 assert(AddRec->isAffine() && "Unexpected Expr");
2406 const SCEV *Start = AddRec->getStart();
2407 const SCEV *Step = AddRec->getStepRecurrence(*SE);
2408 if (AddRec->getLoop() == CurLoop) {
2409 CurLoopCoeff = Step;
2410 } else {
2411 std::optional<APInt> ConstCoeff = getConstantCoefficient(Step);
2412
2413 // If the coefficient is the product of a constant and other stuff, we can
2414 // use the constant in the GCD computation.
2415 if (!ConstCoeff)
2416 return false;
2417
2418 // TODO: What happens if ConstCoeff is the "most negative" signed number
2419 // (e.g. -128 for 8 bit wide APInt)?
2420 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
2421 }
2422
2423 return accumulateCoefficientsGCD(Start, CurLoop, CurLoopCoeff, RunningGCD);
2424}
2425
2426//===----------------------------------------------------------------------===//
2427// gcdMIVtest -
2428// Tests an MIV subscript pair for dependence.
2429// Returns true if any possible dependence is disproved.
2430// Marks the result as inconsistent.
2431// Can sometimes disprove the equal direction for 1 or more loops,
2432// as discussed in Michael Wolfe's book,
2433// High Performance Compilers for Parallel Computing, page 235.
2434//
2435// We spend some effort (code!) to handle cases like
2436// [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2437// but M and N are just loop-invariant variables.
2438// This should help us handle linearized subscripts;
2439// also makes this test a useful backup to the various SIV tests.
2440//
2441// It occurs to me that the presence of loop-invariant variables
2442// changes the nature of the test from "greatest common divisor"
2443// to "a common divisor".
2444bool DependenceInfo::gcdMIVtest(const SCEV *Src, const SCEV *Dst,
2445 FullDependence &Result) const {
2446 if (!isDependenceTestEnabled(DependenceTestType::GCDMIV))
2447 return false;
2448
2449 LLVM_DEBUG(dbgs() << "starting gcd\n");
2450 ++GCDapplications;
2451 unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
2452 APInt RunningGCD = APInt::getZero(BitWidth);
2453
2454 // Examine Src coefficients.
2455 // Compute running GCD and record source constant.
2456 // Because we're looking for the constant at the end of the chain,
2457 // we can't quit the loop just because the GCD == 1.
2458 const SCEV *Coefficients = Src;
2459 while (const SCEVAddRecExpr *AddRec =
2460 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2461 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2462 // If the coefficient is the product of a constant and other stuff,
2463 // we can use the constant in the GCD computation.
2464 std::optional<APInt> ConstCoeff = getConstantCoefficient(Coeff);
2465 if (!ConstCoeff)
2466 return false;
2467 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
2468 Coefficients = AddRec->getStart();
2469 }
2470 const SCEV *SrcConst = Coefficients;
2471
2472 // Examine Dst coefficients.
2473 // Compute running GCD and record destination constant.
2474 // Because we're looking for the constant at the end of the chain,
2475 // we can't quit the loop just because the GCD == 1.
2476 Coefficients = Dst;
2477 while (const SCEVAddRecExpr *AddRec =
2478 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2479 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2480 // If the coefficient is the product of a constant and other stuff,
2481 // we can use the constant in the GCD computation.
2482 std::optional<APInt> ConstCoeff = getConstantCoefficient(Coeff);
2483 if (!ConstCoeff)
2484 return false;
2485 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
2486 Coefficients = AddRec->getStart();
2487 }
2488 const SCEV *DstConst = Coefficients;
2489
2490 APInt ExtraGCD = APInt::getZero(BitWidth);
2491 const SCEV *Delta = minusSCEVNoSignedOverflow(DstConst, SrcConst, *SE);
2492 if (!Delta)
2493 return false;
2494 LLVM_DEBUG(dbgs() << " Delta = " << *Delta << "\n");
2495 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2496 if (!Constant)
2497 return false;
2498 APInt ConstDelta = cast<SCEVConstant>(Constant)->getAPInt();
2499 LLVM_DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
2500 if (ConstDelta == 0)
2501 return false;
2502 LLVM_DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
2503 APInt Remainder = ConstDelta.srem(RunningGCD);
2504 if (Remainder != 0) {
2505 ++GCDindependence;
2506 return true;
2507 }
2508
2509 // Try to disprove equal directions.
2510 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2511 // the code above can't disprove the dependence because the GCD = 1.
2512 // So we consider what happen if i = i' and what happens if j = j'.
2513 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2514 // which is infeasible, so we can disallow the = direction for the i level.
2515 // Setting j = j' doesn't help matters, so we end up with a direction vector
2516 // of [<>, *]
2517 //
2518 // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2519 // we need to remember that the constant part is 5 and the RunningGCD should
2520 // be initialized to ExtraGCD = 30.
2521 LLVM_DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n');
2522
2523 bool Improved = false;
2524 Coefficients = Src;
2525 while (const SCEVAddRecExpr *AddRec =
2526 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2527 Coefficients = AddRec->getStart();
2528 const Loop *CurLoop = AddRec->getLoop();
2529 RunningGCD = ExtraGCD;
2530 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2531 const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2532
2533 if (!accumulateCoefficientsGCD(Src, CurLoop, SrcCoeff, RunningGCD) ||
2534 !accumulateCoefficientsGCD(Dst, CurLoop, DstCoeff, RunningGCD))
2535 return false;
2536
2537 Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
2538 // If the coefficient is the product of a constant and other stuff,
2539 // we can use the constant in the GCD computation.
2540 std::optional<APInt> ConstCoeff = getConstantCoefficient(Delta);
2541 if (!ConstCoeff)
2542 // The difference of the two coefficients might not be a product
2543 // or constant, in which case we give up on this direction.
2544 continue;
2545 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff->abs());
2546 LLVM_DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
2547 if (RunningGCD != 0) {
2548 Remainder = ConstDelta.srem(RunningGCD);
2549 LLVM_DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
2550 if (Remainder != 0) {
2551 unsigned Level = mapSrcLoop(CurLoop);
2552 Result.DV[Level - 1].Direction &= ~Dependence::DVEntry::EQ;
2553 Improved = true;
2554 }
2555 }
2556 }
2557 if (Improved)
2558 ++GCDsuccesses;
2559 LLVM_DEBUG(dbgs() << "all done\n");
2560 return false;
2561}
2562
2563//===----------------------------------------------------------------------===//
2564// banerjeeMIVtest -
2565// Use Banerjee's Inequalities to test an MIV subscript pair.
2566// (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2567// Generally follows the discussion in Section 2.5.2 of
2568//
2569// Optimizing Supercompilers for Supercomputers
2570// Michael Wolfe
2571//
2572// The inequalities given on page 25 are simplified in that loops are
2573// normalized so that the lower bound is always 0 and the stride is always 1.
2574// For example, Wolfe gives
2575//
2576// LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2577//
2578// where A_k is the coefficient of the kth index in the source subscript,
2579// B_k is the coefficient of the kth index in the destination subscript,
2580// U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2581// index, and N_k is the stride of the kth index. Since all loops are normalized
2582// by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2583// equation to
2584//
2585// LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2586// = (A^-_k - B_k)^- (U_k - 1) - B_k
2587//
2588// Similar simplifications are possible for the other equations.
2589//
2590// When we can't determine the number of iterations for a loop,
2591// we use NULL as an indicator for the worst case, infinity.
2592// When computing the upper bound, NULL denotes +inf;
2593// for the lower bound, NULL denotes -inf.
2594//
2595// Return true if dependence disproved.
2596bool DependenceInfo::banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
2597 const SmallBitVector &Loops,
2598 FullDependence &Result) const {
2599 if (!isDependenceTestEnabled(DependenceTestType::BanerjeeMIV))
2600 return false;
2601
2602 LLVM_DEBUG(dbgs() << "starting Banerjee\n");
2603 ++BanerjeeApplications;
2604 LLVM_DEBUG(dbgs() << " Src = " << *Src << '\n');
2605 const SCEV *A0;
2606 CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
2607 LLVM_DEBUG(dbgs() << " Dst = " << *Dst << '\n');
2608 const SCEV *B0;
2609 CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2610 BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
2611 const SCEV *Delta = SE->getMinusSCEV(B0, A0);
2612 LLVM_DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
2613
2614 // Compute bounds for all the * directions.
2615 LLVM_DEBUG(dbgs() << "\tBounds[*]\n");
2616 for (unsigned K = 1; K <= MaxLevels; ++K) {
2617 Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2618 Bound[K].Direction = Dependence::DVEntry::ALL;
2619 Bound[K].DirSet = Dependence::DVEntry::NONE;
2620 findBoundsALL(A, B, Bound, K);
2621#ifndef NDEBUG
2622 LLVM_DEBUG(dbgs() << "\t " << K << '\t');
2623 if (Bound[K].Lower[Dependence::DVEntry::ALL])
2624 LLVM_DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
2625 else
2626 LLVM_DEBUG(dbgs() << "-inf\t");
2627 if (Bound[K].Upper[Dependence::DVEntry::ALL])
2628 LLVM_DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
2629 else
2630 LLVM_DEBUG(dbgs() << "+inf\n");
2631#endif
2632 }
2633
2634 // Test the *, *, *, ... case.
2635 bool Disproved = false;
2636 if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2637 // Explore the direction vector hierarchy.
2638 unsigned DepthExpanded = 0;
2639 unsigned NewDeps =
2640 exploreDirections(1, A, B, Bound, Loops, DepthExpanded, Delta);
2641 if (NewDeps > 0) {
2642 bool Improved = false;
2643 for (unsigned K = 1; K <= CommonLevels; ++K) {
2644 if (Loops[K]) {
2645 unsigned Old = Result.DV[K - 1].Direction;
2646 Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2647 Improved |= Old != Result.DV[K - 1].Direction;
2648 if (!Result.DV[K - 1].Direction) {
2649 Improved = false;
2650 Disproved = true;
2651 break;
2652 }
2653 }
2654 }
2655 if (Improved)
2656 ++BanerjeeSuccesses;
2657 } else {
2658 ++BanerjeeIndependence;
2659 Disproved = true;
2660 }
2661 } else {
2662 ++BanerjeeIndependence;
2663 Disproved = true;
2664 }
2665 delete[] Bound;
2666 delete[] A;
2667 delete[] B;
2668 return Disproved;
2669}
2670
2671// Hierarchically expands the direction vector
2672// search space, combining the directions of discovered dependences
2673// in the DirSet field of Bound. Returns the number of distinct
2674// dependences discovered. If the dependence is disproved,
2675// it will return 0.
2676unsigned DependenceInfo::exploreDirections(unsigned Level, CoefficientInfo *A,
2677 CoefficientInfo *B, BoundInfo *Bound,
2678 const SmallBitVector &Loops,
2679 unsigned &DepthExpanded,
2680 const SCEV *Delta) const {
2681 // This algorithm has worst case complexity of O(3^n), where 'n' is the number
2682 // of common loop levels. To avoid excessive compile-time, pessimize all the
2683 // results and immediately return when the number of common levels is beyond
2684 // the given threshold.
2685 if (CommonLevels > MIVMaxLevelThreshold) {
2686 LLVM_DEBUG(dbgs() << "Number of common levels exceeded the threshold. MIV "
2687 "direction exploration is terminated.\n");
2688 for (unsigned K = 1; K <= CommonLevels; ++K)
2689 if (Loops[K])
2690 Bound[K].DirSet = Dependence::DVEntry::ALL;
2691 return 1;
2692 }
2693
2694 if (Level > CommonLevels) {
2695 // record result
2696 LLVM_DEBUG(dbgs() << "\t[");
2697 for (unsigned K = 1; K <= CommonLevels; ++K) {
2698 if (Loops[K]) {
2699 Bound[K].DirSet |= Bound[K].Direction;
2700#ifndef NDEBUG
2701 switch (Bound[K].Direction) {
2703 LLVM_DEBUG(dbgs() << " <");
2704 break;
2706 LLVM_DEBUG(dbgs() << " =");
2707 break;
2709 LLVM_DEBUG(dbgs() << " >");
2710 break;
2712 LLVM_DEBUG(dbgs() << " *");
2713 break;
2714 default:
2715 llvm_unreachable("unexpected Bound[K].Direction");
2716 }
2717#endif
2718 }
2719 }
2720 LLVM_DEBUG(dbgs() << " ]\n");
2721 return 1;
2722 }
2723 if (Loops[Level]) {
2724 if (Level > DepthExpanded) {
2725 DepthExpanded = Level;
2726 // compute bounds for <, =, > at current level
2727 findBoundsLT(A, B, Bound, Level);
2728 findBoundsGT(A, B, Bound, Level);
2729 findBoundsEQ(A, B, Bound, Level);
2730#ifndef NDEBUG
2731 LLVM_DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2732 LLVM_DEBUG(dbgs() << "\t <\t");
2733 if (Bound[Level].Lower[Dependence::DVEntry::LT])
2734 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT]
2735 << '\t');
2736 else
2737 LLVM_DEBUG(dbgs() << "-inf\t");
2738 if (Bound[Level].Upper[Dependence::DVEntry::LT])
2739 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT]
2740 << '\n');
2741 else
2742 LLVM_DEBUG(dbgs() << "+inf\n");
2743 LLVM_DEBUG(dbgs() << "\t =\t");
2744 if (Bound[Level].Lower[Dependence::DVEntry::EQ])
2745 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ]
2746 << '\t');
2747 else
2748 LLVM_DEBUG(dbgs() << "-inf\t");
2749 if (Bound[Level].Upper[Dependence::DVEntry::EQ])
2750 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ]
2751 << '\n');
2752 else
2753 LLVM_DEBUG(dbgs() << "+inf\n");
2754 LLVM_DEBUG(dbgs() << "\t >\t");
2755 if (Bound[Level].Lower[Dependence::DVEntry::GT])
2756 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT]
2757 << '\t');
2758 else
2759 LLVM_DEBUG(dbgs() << "-inf\t");
2760 if (Bound[Level].Upper[Dependence::DVEntry::GT])
2761 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT]
2762 << '\n');
2763 else
2764 LLVM_DEBUG(dbgs() << "+inf\n");
2765#endif
2766 }
2767
2768 unsigned NewDeps = 0;
2769
2770 // test bounds for <, *, *, ...
2771 if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2772 NewDeps += exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded,
2773 Delta);
2774
2775 // Test bounds for =, *, *, ...
2776 if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2777 NewDeps += exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded,
2778 Delta);
2779
2780 // test bounds for >, *, *, ...
2781 if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2782 NewDeps += exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded,
2783 Delta);
2784
2785 Bound[Level].Direction = Dependence::DVEntry::ALL;
2786 return NewDeps;
2787 } else
2788 return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded,
2789 Delta);
2790}
2791
2792// Returns true iff the current bounds are plausible.
2793bool DependenceInfo::testBounds(unsigned char DirKind, unsigned Level,
2794 BoundInfo *Bound, const SCEV *Delta) const {
2795 Bound[Level].Direction = DirKind;
2796 if (const SCEV *LowerBound = getLowerBound(Bound))
2797 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2798 return false;
2799 if (const SCEV *UpperBound = getUpperBound(Bound))
2800 if (SE->isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2801 return false;
2802 return true;
2803}
2804
2805// Computes the upper and lower bounds for level K
2806// using the * direction. Records them in Bound.
2807// Wolfe gives the equations
2808//
2809// LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2810// UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2811//
2812// Since we normalize loops, we can simplify these equations to
2813//
2814// LB^*_k = (A^-_k - B^+_k)U_k
2815// UB^*_k = (A^+_k - B^-_k)U_k
2816//
2817// We must be careful to handle the case where the upper bound is unknown.
2818// Note that the lower bound is always <= 0
2819// and the upper bound is always >= 0.
2820void DependenceInfo::findBoundsALL(CoefficientInfo *A, CoefficientInfo *B,
2821 BoundInfo *Bound, unsigned K) const {
2822 Bound[K].Lower[Dependence::DVEntry::ALL] =
2823 nullptr; // Default value = -infinity.
2824 Bound[K].Upper[Dependence::DVEntry::ALL] =
2825 nullptr; // Default value = +infinity.
2826 if (Bound[K].Iterations) {
2827 Bound[K].Lower[Dependence::DVEntry::ALL] = SE->getMulExpr(
2828 SE->getMinusSCEV(A[K].NegPart, B[K].PosPart), Bound[K].Iterations);
2829 Bound[K].Upper[Dependence::DVEntry::ALL] = SE->getMulExpr(
2830 SE->getMinusSCEV(A[K].PosPart, B[K].NegPart), Bound[K].Iterations);
2831 } else {
2832 // If the difference is 0, we won't need to know the number of iterations.
2833 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2834 Bound[K].Lower[Dependence::DVEntry::ALL] =
2835 SE->getZero(A[K].Coeff->getType());
2836 if (SE->isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2837 Bound[K].Upper[Dependence::DVEntry::ALL] =
2838 SE->getZero(A[K].Coeff->getType());
2839 }
2840}
2841
2842// Computes the upper and lower bounds for level K
2843// using the = direction. Records them in Bound.
2844// Wolfe gives the equations
2845//
2846// LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2847// UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2848//
2849// Since we normalize loops, we can simplify these equations to
2850//
2851// LB^=_k = (A_k - B_k)^- U_k
2852// UB^=_k = (A_k - B_k)^+ U_k
2853//
2854// We must be careful to handle the case where the upper bound is unknown.
2855// Note that the lower bound is always <= 0
2856// and the upper bound is always >= 0.
2857void DependenceInfo::findBoundsEQ(CoefficientInfo *A, CoefficientInfo *B,
2858 BoundInfo *Bound, unsigned K) const {
2859 Bound[K].Lower[Dependence::DVEntry::EQ] =
2860 nullptr; // Default value = -infinity.
2861 Bound[K].Upper[Dependence::DVEntry::EQ] =
2862 nullptr; // Default value = +infinity.
2863 if (Bound[K].Iterations) {
2864 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2865 const SCEV *NegativePart = getNegativePart(Delta);
2866 Bound[K].Lower[Dependence::DVEntry::EQ] =
2867 SE->getMulExpr(NegativePart, Bound[K].Iterations);
2868 const SCEV *PositivePart = getPositivePart(Delta);
2869 Bound[K].Upper[Dependence::DVEntry::EQ] =
2870 SE->getMulExpr(PositivePart, Bound[K].Iterations);
2871 } else {
2872 // If the positive/negative part of the difference is 0,
2873 // we won't need to know the number of iterations.
2874 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2875 const SCEV *NegativePart = getNegativePart(Delta);
2876 if (NegativePart->isZero())
2877 Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2878 const SCEV *PositivePart = getPositivePart(Delta);
2879 if (PositivePart->isZero())
2880 Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2881 }
2882}
2883
2884// Computes the upper and lower bounds for level K
2885// using the < direction. Records them in Bound.
2886// Wolfe gives the equations
2887//
2888// LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2889// UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2890//
2891// Since we normalize loops, we can simplify these equations to
2892//
2893// LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2894// UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2895//
2896// We must be careful to handle the case where the upper bound is unknown.
2897void DependenceInfo::findBoundsLT(CoefficientInfo *A, CoefficientInfo *B,
2898 BoundInfo *Bound, unsigned K) const {
2899 Bound[K].Lower[Dependence::DVEntry::LT] =
2900 nullptr; // Default value = -infinity.
2901 Bound[K].Upper[Dependence::DVEntry::LT] =
2902 nullptr; // Default value = +infinity.
2903 if (Bound[K].Iterations) {
2904 const SCEV *Iter_1 = SE->getMinusSCEV(
2905 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2906 const SCEV *NegPart =
2907 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2908 Bound[K].Lower[Dependence::DVEntry::LT] =
2909 SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2910 const SCEV *PosPart =
2911 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2912 Bound[K].Upper[Dependence::DVEntry::LT] =
2913 SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2914 } else {
2915 // If the positive/negative part of the difference is 0,
2916 // we won't need to know the number of iterations.
2917 const SCEV *NegPart =
2918 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2919 if (NegPart->isZero())
2920 Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2921 const SCEV *PosPart =
2922 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2923 if (PosPart->isZero())
2924 Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2925 }
2926}
2927
2928// Computes the upper and lower bounds for level K
2929// using the > direction. Records them in Bound.
2930// Wolfe gives the equations
2931//
2932// LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2933// UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2934//
2935// Since we normalize loops, we can simplify these equations to
2936//
2937// LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2938// UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2939//
2940// We must be careful to handle the case where the upper bound is unknown.
2941void DependenceInfo::findBoundsGT(CoefficientInfo *A, CoefficientInfo *B,
2942 BoundInfo *Bound, unsigned K) const {
2943 Bound[K].Lower[Dependence::DVEntry::GT] =
2944 nullptr; // Default value = -infinity.
2945 Bound[K].Upper[Dependence::DVEntry::GT] =
2946 nullptr; // Default value = +infinity.
2947 if (Bound[K].Iterations) {
2948 const SCEV *Iter_1 = SE->getMinusSCEV(
2949 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
2950 const SCEV *NegPart =
2951 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2952 Bound[K].Lower[Dependence::DVEntry::GT] =
2953 SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2954 const SCEV *PosPart =
2955 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2956 Bound[K].Upper[Dependence::DVEntry::GT] =
2957 SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2958 } else {
2959 // If the positive/negative part of the difference is 0,
2960 // we won't need to know the number of iterations.
2961 const SCEV *NegPart =
2962 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2963 if (NegPart->isZero())
2964 Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2965 const SCEV *PosPart =
2966 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2967 if (PosPart->isZero())
2968 Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2969 }
2970}
2971
2972// X^+ = max(X, 0)
2973const SCEV *DependenceInfo::getPositivePart(const SCEV *X) const {
2974 return SE->getSMaxExpr(X, SE->getZero(X->getType()));
2975}
2976
2977// X^- = min(X, 0)
2978const SCEV *DependenceInfo::getNegativePart(const SCEV *X) const {
2979 return SE->getSMinExpr(X, SE->getZero(X->getType()));
2980}
2981
2982// Walks through the subscript,
2983// collecting each coefficient, the associated loop bounds,
2984// and recording its positive and negative parts for later use.
2985DependenceInfo::CoefficientInfo *
2986DependenceInfo::collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
2987 const SCEV *&Constant) const {
2988 const SCEV *Zero = SE->getZero(Subscript->getType());
2989 CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
2990 for (unsigned K = 1; K <= MaxLevels; ++K) {
2991 CI[K].Coeff = Zero;
2992 CI[K].PosPart = Zero;
2993 CI[K].NegPart = Zero;
2994 CI[K].Iterations = nullptr;
2995 }
2996 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2997 const Loop *L = AddRec->getLoop();
2998 unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2999 CI[K].Coeff = AddRec->getStepRecurrence(*SE);
3000 CI[K].PosPart = getPositivePart(CI[K].Coeff);
3001 CI[K].NegPart = getNegativePart(CI[K].Coeff);
3002 CI[K].Iterations = collectUpperBound(L, Subscript->getType());
3003 Subscript = AddRec->getStart();
3004 }
3005 Constant = Subscript;
3006#ifndef NDEBUG
3007 LLVM_DEBUG(dbgs() << "\tCoefficient Info\n");
3008 for (unsigned K = 1; K <= MaxLevels; ++K) {
3009 LLVM_DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff);
3010 LLVM_DEBUG(dbgs() << "\tPos Part = ");
3011 LLVM_DEBUG(dbgs() << *CI[K].PosPart);
3012 LLVM_DEBUG(dbgs() << "\tNeg Part = ");
3013 LLVM_DEBUG(dbgs() << *CI[K].NegPart);
3014 LLVM_DEBUG(dbgs() << "\tUpper Bound = ");
3015 if (CI[K].Iterations)
3016 LLVM_DEBUG(dbgs() << *CI[K].Iterations);
3017 else
3018 LLVM_DEBUG(dbgs() << "+inf");
3019 LLVM_DEBUG(dbgs() << '\n');
3020 }
3021 LLVM_DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n');
3022#endif
3023 return CI;
3024}
3025
3026// Looks through all the bounds info and
3027// computes the lower bound given the current direction settings
3028// at each level. If the lower bound for any level is -inf,
3029// the result is -inf.
3030const SCEV *DependenceInfo::getLowerBound(BoundInfo *Bound) const {
3031 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
3032 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
3033 if (Bound[K].Lower[Bound[K].Direction])
3034 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
3035 else
3036 Sum = nullptr;
3037 }
3038 return Sum;
3039}
3040
3041// Looks through all the bounds info and
3042// computes the upper bound given the current direction settings
3043// at each level. If the upper bound at any level is +inf,
3044// the result is +inf.
3045const SCEV *DependenceInfo::getUpperBound(BoundInfo *Bound) const {
3046 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
3047 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
3048 if (Bound[K].Upper[Bound[K].Direction])
3049 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
3050 else
3051 Sum = nullptr;
3052 }
3053 return Sum;
3054}
3055
3056/// Check if we can delinearize the subscripts. If the SCEVs representing the
3057/// source and destination array references are recurrences on a nested loop,
3058/// this function flattens the nested recurrences into separate recurrences
3059/// for each loop level.
3060bool DependenceInfo::tryDelinearize(Instruction *Src, Instruction *Dst,
3062 assert(isLoadOrStore(Src) && "instruction is not load or store");
3063 assert(isLoadOrStore(Dst) && "instruction is not load or store");
3064 Value *SrcPtr = getLoadStorePointerOperand(Src);
3065 Value *DstPtr = getLoadStorePointerOperand(Dst);
3066 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
3067 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
3068 const SCEV *SrcAccessFn = SE->getSCEVAtScope(SrcPtr, SrcLoop);
3069 const SCEV *DstAccessFn = SE->getSCEVAtScope(DstPtr, DstLoop);
3070 const SCEVUnknown *SrcBase =
3071 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3072 const SCEVUnknown *DstBase =
3073 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3074
3075 if (!SrcBase || !DstBase || SrcBase != DstBase)
3076 return false;
3077
3078 SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
3079
3080 if (!tryDelinearizeFixedSize(Src, Dst, SrcAccessFn, DstAccessFn,
3081 SrcSubscripts, DstSubscripts) &&
3082 !tryDelinearizeParametricSize(Src, Dst, SrcAccessFn, DstAccessFn,
3083 SrcSubscripts, DstSubscripts))
3084 return false;
3085
3086 assert(isLoopInvariant(SrcBase, SrcLoop) &&
3087 isLoopInvariant(DstBase, DstLoop) &&
3088 "Expected SrcBase and DstBase to be loop invariant");
3089
3090 int Size = SrcSubscripts.size();
3091 LLVM_DEBUG({
3092 dbgs() << "\nSrcSubscripts: ";
3093 for (int I = 0; I < Size; I++)
3094 dbgs() << *SrcSubscripts[I];
3095 dbgs() << "\nDstSubscripts: ";
3096 for (int I = 0; I < Size; I++)
3097 dbgs() << *DstSubscripts[I];
3098 });
3099
3100 // The delinearization transforms a single-subscript MIV dependence test into
3101 // a multi-subscript SIV dependence test that is easier to compute. So we
3102 // resize Pair to contain as many pairs of subscripts as the delinearization
3103 // has found, and then initialize the pairs following the delinearization.
3104 Pair.resize(Size);
3105 SCEVMonotonicityChecker MonChecker(SE);
3106 const Loop *OutermostLoop = SrcLoop ? SrcLoop->getOutermostLoop() : nullptr;
3107 for (int I = 0; I < Size; ++I) {
3108 Pair[I].Src = SrcSubscripts[I];
3109 Pair[I].Dst = DstSubscripts[I];
3110
3111 assert(Pair[I].Src->getType() == Pair[I].Dst->getType() &&
3112 "Unexpected different types for the subscripts");
3113
3115 if (MonChecker.checkMonotonicity(Pair[I].Src, OutermostLoop).isUnknown())
3116 return false;
3117 if (MonChecker.checkMonotonicity(Pair[I].Dst, OutermostLoop).isUnknown())
3118 return false;
3119 }
3120 }
3121
3122 return true;
3123}
3124
3125/// Try to delinearize \p SrcAccessFn and \p DstAccessFn if the underlying
3126/// arrays accessed are fixed-size arrays. Return true if delinearization was
3127/// successful.
3128bool DependenceInfo::tryDelinearizeFixedSize(
3129 Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
3130 const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
3131 SmallVectorImpl<const SCEV *> &DstSubscripts) {
3132 LLVM_DEBUG({
3133 const SCEVUnknown *SrcBase =
3134 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3135 const SCEVUnknown *DstBase =
3136 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3137 assert(SrcBase && DstBase && SrcBase == DstBase &&
3138 "expected src and dst scev unknowns to be equal");
3139 });
3140
3141 const SCEV *ElemSize = SE->getElementSize(Src);
3142 assert(ElemSize == SE->getElementSize(Dst) && "Different element sizes");
3143 SmallVector<const SCEV *, 4> SrcSizes, DstSizes;
3144 if (!delinearizeFixedSizeArray(*SE, SE->removePointerBase(SrcAccessFn),
3145 SrcSubscripts, SrcSizes, ElemSize) ||
3146 !delinearizeFixedSizeArray(*SE, SE->removePointerBase(DstAccessFn),
3147 DstSubscripts, DstSizes, ElemSize))
3148 return false;
3149
3150 // Check that the two size arrays are non-empty and equal in length and
3151 // value. SCEV expressions are uniqued, so we can compare pointers.
3152 if (SrcSizes.size() != DstSizes.size() ||
3153 !std::equal(SrcSizes.begin(), SrcSizes.end(), DstSizes.begin())) {
3154 SrcSubscripts.clear();
3155 DstSubscripts.clear();
3156 return false;
3157 }
3158
3159 assert(SrcSubscripts.size() == DstSubscripts.size() &&
3160 "Expected equal number of entries in the list of SrcSubscripts and "
3161 "DstSubscripts.");
3162
3163 // In general we cannot safely assume that the subscripts recovered from GEPs
3164 // are in the range of values defined for their corresponding array
3165 // dimensions. For example some C language usage/interpretation make it
3166 // impossible to verify this at compile-time. As such we can only delinearize
3167 // iff the subscripts are positive and are less than the range of the
3168 // dimension.
3170 if (!validateDelinearizationResult(*SE, SrcSizes, SrcSubscripts) ||
3171 !validateDelinearizationResult(*SE, DstSizes, DstSubscripts)) {
3172 SrcSubscripts.clear();
3173 DstSubscripts.clear();
3174 return false;
3175 }
3176 }
3177 LLVM_DEBUG({
3178 dbgs() << "Delinearized subscripts of fixed-size array\n"
3179 << "SrcGEP:" << *getLoadStorePointerOperand(Src) << "\n"
3180 << "DstGEP:" << *getLoadStorePointerOperand(Dst) << "\n";
3181 });
3182 return true;
3183}
3184
3185bool DependenceInfo::tryDelinearizeParametricSize(
3186 Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
3187 const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
3188 SmallVectorImpl<const SCEV *> &DstSubscripts) {
3189
3190 const SCEVUnknown *SrcBase =
3191 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
3192 const SCEVUnknown *DstBase =
3193 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
3194 assert(SrcBase && DstBase && SrcBase == DstBase &&
3195 "expected src and dst scev unknowns to be equal");
3196
3197 const SCEV *ElementSize = SE->getElementSize(Src);
3198 if (ElementSize != SE->getElementSize(Dst))
3199 return false;
3200
3201 const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
3202 const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
3203
3204 const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
3205 const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
3206 if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
3207 return false;
3208
3209 // First step: collect parametric terms in both array references.
3211 collectParametricTerms(*SE, SrcAR, Terms);
3212 collectParametricTerms(*SE, DstAR, Terms);
3213
3214 // Second step: find subscript sizes.
3216 findArrayDimensions(*SE, Terms, Sizes, ElementSize);
3217
3218 // Third step: compute the access functions for each subscript.
3219 computeAccessFunctions(*SE, SrcAR, SrcSubscripts, Sizes);
3220 computeAccessFunctions(*SE, DstAR, DstSubscripts, Sizes);
3221
3222 // Fail when there is only a subscript: that's a linearized access function.
3223 if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
3224 SrcSubscripts.size() != DstSubscripts.size())
3225 return false;
3226
3227 // Statically check that the array bounds are in-range. The first subscript we
3228 // don't have a size for and it cannot overflow into another subscript, so is
3229 // always safe. The others need to be 0 <= subscript[i] < bound, for both src
3230 // and dst.
3231 // FIXME: It may be better to record these sizes and add them as constraints
3232 // to the dependency checks.
3234 if (!validateDelinearizationResult(*SE, Sizes, SrcSubscripts) ||
3235 !validateDelinearizationResult(*SE, Sizes, DstSubscripts))
3236 return false;
3237
3238 return true;
3239}
3240
3241//===----------------------------------------------------------------------===//
3242
3243#ifndef NDEBUG
3244// For debugging purposes, dump a small bit vector to dbgs().
3246 dbgs() << "{";
3247 for (unsigned VI : BV.set_bits()) {
3248 dbgs() << VI;
3249 if (BV.find_next(VI) >= 0)
3250 dbgs() << ' ';
3251 }
3252 dbgs() << "}\n";
3253}
3254#endif
3255
3257 FunctionAnalysisManager::Invalidator &Inv) {
3258 // Check if the analysis itself has been invalidated.
3259 auto PAC = PA.getChecker<DependenceAnalysis>();
3260 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
3261 return true;
3262
3263 // Check transitive dependencies.
3264 return Inv.invalidate<AAManager>(F, PA) ||
3265 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
3266 Inv.invalidate<LoopAnalysis>(F, PA);
3267}
3268
3269// depends -
3270// Returns NULL if there is no dependence.
3271// Otherwise, return a Dependence with as many details as possible.
3272// Corresponds to Section 3.1 in the paper
3273//
3274// Practical Dependence Testing
3275// Goff, Kennedy, Tseng
3276// PLDI 1991
3277//
3278std::unique_ptr<Dependence>
3280 bool UnderRuntimeAssumptions) {
3282 bool PossiblyLoopIndependent = true;
3283 if (Src == Dst)
3284 PossiblyLoopIndependent = false;
3285
3286 if (!(Src->mayReadOrWriteMemory() && Dst->mayReadOrWriteMemory()))
3287 // if both instructions don't reference memory, there's no dependence
3288 return nullptr;
3289
3290 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
3291 // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
3292 LLVM_DEBUG(dbgs() << "can only handle simple loads and stores\n");
3293 return std::make_unique<Dependence>(Src, Dst,
3294 SCEVUnionPredicate(Assume, *SE));
3295 }
3296
3297 const MemoryLocation &DstLoc = MemoryLocation::get(Dst);
3298 const MemoryLocation &SrcLoc = MemoryLocation::get(Src);
3299
3300 switch (underlyingObjectsAlias(AA, F->getDataLayout(), DstLoc, SrcLoc)) {
3303 // cannot analyse objects if we don't understand their aliasing.
3304 LLVM_DEBUG(dbgs() << "can't analyze may or partial alias\n");
3305 return std::make_unique<Dependence>(Src, Dst,
3306 SCEVUnionPredicate(Assume, *SE));
3308 // If the objects noalias, they are distinct, accesses are independent.
3309 LLVM_DEBUG(dbgs() << "no alias\n");
3310 return nullptr;
3312 break; // The underlying objects alias; test accesses for dependence.
3313 }
3314
3315 if (DstLoc.Size != SrcLoc.Size || !DstLoc.Size.isPrecise() ||
3316 !SrcLoc.Size.isPrecise()) {
3317 // The dependence test gets confused if the size of the memory accesses
3318 // differ.
3319 LLVM_DEBUG(dbgs() << "can't analyze must alias with different sizes\n");
3320 return std::make_unique<Dependence>(Src, Dst,
3321 SCEVUnionPredicate(Assume, *SE));
3322 }
3323
3324 Value *SrcPtr = getLoadStorePointerOperand(Src);
3325 Value *DstPtr = getLoadStorePointerOperand(Dst);
3326 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3327 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3328 LLVM_DEBUG(dbgs() << " SrcSCEV = " << *SrcSCEV << "\n");
3329 LLVM_DEBUG(dbgs() << " DstSCEV = " << *DstSCEV << "\n");
3330 const SCEV *SrcBase = SE->getPointerBase(SrcSCEV);
3331 const SCEV *DstBase = SE->getPointerBase(DstSCEV);
3332 if (SrcBase != DstBase) {
3333 // If two pointers have different bases, trying to analyze indexes won't
3334 // work; we can't compare them to each other. This can happen, for example,
3335 // if one is produced by an LCSSA PHI node.
3336 //
3337 // We check this upfront so we don't crash in cases where getMinusSCEV()
3338 // returns a SCEVCouldNotCompute.
3339 LLVM_DEBUG(dbgs() << "can't analyze SCEV with different pointer base\n");
3340 return std::make_unique<Dependence>(Src, Dst,
3341 SCEVUnionPredicate(Assume, *SE));
3342 }
3343
3344 // Even if the base pointers are the same, they may not be loop-invariant. It
3345 // could lead to incorrect results, as we're analyzing loop-carried
3346 // dependencies. Src and Dst can be in different loops, so we need to check
3347 // the base pointer is invariant in both loops.
3348 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
3349 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
3350 if (!isLoopInvariant(SrcBase, SrcLoop) ||
3351 !isLoopInvariant(DstBase, DstLoop)) {
3352 LLVM_DEBUG(dbgs() << "The base pointer is not loop invariant.\n");
3353 return std::make_unique<Dependence>(Src, Dst,
3354 SCEVUnionPredicate(Assume, *SE));
3355 }
3356
3357 uint64_t EltSize = SrcLoc.Size.toRaw();
3358 const SCEV *SrcEv = SE->getMinusSCEV(SrcSCEV, SrcBase);
3359 const SCEV *DstEv = SE->getMinusSCEV(DstSCEV, DstBase);
3360
3361 // Check that memory access offsets are multiples of element sizes.
3362 if (!SE->isKnownMultipleOf(SrcEv, EltSize, Assume) ||
3363 !SE->isKnownMultipleOf(DstEv, EltSize, Assume)) {
3364 LLVM_DEBUG(dbgs() << "can't analyze SCEV with different offsets\n");
3365 return std::make_unique<Dependence>(Src, Dst,
3366 SCEVUnionPredicate(Assume, *SE));
3367 }
3368
3369 // Runtime assumptions needed but not allowed.
3370 if (!Assume.empty() && !UnderRuntimeAssumptions)
3371 return std::make_unique<Dependence>(Src, Dst,
3372 SCEVUnionPredicate(Assume, *SE));
3373
3374 unsigned Pairs = 1;
3375 SmallVector<Subscript, 2> Pair(Pairs);
3376 Pair[0].Src = SrcEv;
3377 Pair[0].Dst = DstEv;
3378
3379 SCEVMonotonicityChecker MonChecker(SE);
3380 const Loop *OutermostLoop = SrcLoop ? SrcLoop->getOutermostLoop() : nullptr;
3382 if (MonChecker.checkMonotonicity(Pair[0].Src, OutermostLoop).isUnknown() ||
3383 MonChecker.checkMonotonicity(Pair[0].Dst, OutermostLoop).isUnknown())
3384 return std::make_unique<Dependence>(Src, Dst,
3385 SCEVUnionPredicate(Assume, *SE));
3386
3387 if (Delinearize) {
3388 if (tryDelinearize(Src, Dst, Pair)) {
3389 LLVM_DEBUG(dbgs() << " delinearized\n");
3390 Pairs = Pair.size();
3391 }
3392 }
3393
3394 // Establish loop nesting levels considering SameSD loops as common
3395 establishNestingLevels(Src, Dst);
3396
3397 LLVM_DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n");
3398 LLVM_DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n");
3399 LLVM_DEBUG(dbgs() << " SameSD nesting levels = " << SameSDLevels << "\n");
3400
3401 // Modify common levels to consider the SameSD levels in the tests
3402 CommonLevels += SameSDLevels;
3403 MaxLevels -= SameSDLevels;
3404 if (SameSDLevels > 0) {
3405 // Not all tests are handled yet over SameSD loops
3406 // Revoke if there are any tests other than ZIV, SIV or RDIV
3407 for (unsigned P = 0; P < Pairs; ++P) {
3409 Subscript::ClassificationKind TestClass =
3410 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3411 Pair[P].Dst, LI->getLoopFor(Dst->getParent()), Loops);
3412
3413 if (TestClass != Subscript::ZIV && TestClass != Subscript::SIV &&
3414 TestClass != Subscript::RDIV) {
3415 // Revert the levels to not consider the SameSD levels
3416 CommonLevels -= SameSDLevels;
3417 MaxLevels += SameSDLevels;
3418 SameSDLevels = 0;
3419 break;
3420 }
3421 }
3422 }
3423
3424 if (SameSDLevels > 0)
3425 SameSDLoopsCount++;
3426
3427 FullDependence Result(Src, Dst, SCEVUnionPredicate(Assume, *SE),
3428 PossiblyLoopIndependent, CommonLevels);
3429 ++TotalArrayPairs;
3430
3431 for (unsigned P = 0; P < Pairs; ++P) {
3432 assert(Pair[P].Src->getType()->isIntegerTy() && "Src must be an integer");
3433 assert(Pair[P].Dst->getType()->isIntegerTy() && "Dst must be an integer");
3434 Pair[P].Loops.resize(MaxLevels + 1);
3435 Pair[P].GroupLoops.resize(MaxLevels + 1);
3436 Pair[P].Group.resize(Pairs);
3437 Pair[P].Classification =
3438 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()), Pair[P].Dst,
3439 LI->getLoopFor(Dst->getParent()), Pair[P].Loops);
3440 Pair[P].GroupLoops = Pair[P].Loops;
3441 Pair[P].Group.set(P);
3442 LLVM_DEBUG(dbgs() << " subscript " << P << "\n");
3443 LLVM_DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
3444 LLVM_DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
3445 LLVM_DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
3446 LLVM_DEBUG(dbgs() << "\tloops = ");
3448 }
3449
3450 // Test each subscript individually
3451 for (unsigned SI = 0; SI < Pairs; ++SI) {
3452 LLVM_DEBUG(dbgs() << "testing subscript " << SI);
3453 switch (Pair[SI].Classification) {
3454 case Subscript::NonLinear:
3455 // ignore these, but collect loops for later
3456 ++NonlinearSubscriptPairs;
3457 collectCommonLoops(Pair[SI].Src, LI->getLoopFor(Src->getParent()),
3458 Pair[SI].Loops);
3459 collectCommonLoops(Pair[SI].Dst, LI->getLoopFor(Dst->getParent()),
3460 Pair[SI].Loops);
3461 break;
3462 case Subscript::ZIV:
3463 LLVM_DEBUG(dbgs() << ", ZIV\n");
3464 if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
3465 return nullptr;
3466 break;
3467 case Subscript::SIV: {
3468 LLVM_DEBUG(dbgs() << ", SIV\n");
3469 unsigned Level;
3470 if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result,
3471 UnderRuntimeAssumptions))
3472 return nullptr;
3473 break;
3474 }
3475 case Subscript::RDIV:
3476 LLVM_DEBUG(dbgs() << ", RDIV\n");
3477 if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
3478 return nullptr;
3479 break;
3480 case Subscript::MIV:
3481 LLVM_DEBUG(dbgs() << ", MIV\n");
3482 if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
3483 return nullptr;
3484 break;
3485 }
3486 }
3487
3488 // Make sure the Scalar flags are set correctly.
3489 SmallBitVector CompleteLoops(MaxLevels + 1);
3490 for (unsigned SI = 0; SI < Pairs; ++SI)
3491 CompleteLoops |= Pair[SI].Loops;
3492 for (unsigned II = 1; II <= CommonLevels; ++II)
3493 if (CompleteLoops[II])
3494 Result.DV[II - 1].Scalar = false;
3495
3496 // Set the distance to zero if the direction is EQ.
3497 // TODO: Ideally, the distance should be set to 0 immediately simultaneously
3498 // with the corresponding direction being set to EQ.
3499 for (unsigned II = 1; II <= Result.getLevels(); ++II) {
3500 if (Result.getDirection(II) == Dependence::DVEntry::EQ) {
3501 if (Result.DV[II - 1].Distance == nullptr)
3502 Result.DV[II - 1].Distance = SE->getZero(SrcSCEV->getType());
3503 else
3504 assert(Result.DV[II - 1].Distance->isZero() &&
3505 "Inconsistency between distance and direction");
3506 }
3507
3508#ifndef NDEBUG
3509 // Check that the converse (i.e., if the distance is zero, then the
3510 // direction is EQ) holds.
3511 const SCEV *Distance = Result.getDistance(II);
3512 if (Distance && Distance->isZero())
3513 assert(Result.getDirection(II) == Dependence::DVEntry::EQ &&
3514 "Distance is zero, but direction is not EQ");
3515#endif
3516 }
3517
3518 if (SameSDLevels > 0) {
3519 // Extracting SameSD levels from the common levels
3520 // Reverting CommonLevels and MaxLevels to their original values
3521 assert(CommonLevels >= SameSDLevels);
3522 CommonLevels -= SameSDLevels;
3523 MaxLevels += SameSDLevels;
3524 std::unique_ptr<FullDependence::DVEntry[]> DV, DVSameSD;
3525 DV = std::make_unique<FullDependence::DVEntry[]>(CommonLevels);
3526 DVSameSD = std::make_unique<FullDependence::DVEntry[]>(SameSDLevels);
3527 for (unsigned Level = 0; Level < CommonLevels; ++Level)
3528 DV[Level] = Result.DV[Level];
3529 for (unsigned Level = 0; Level < SameSDLevels; ++Level)
3530 DVSameSD[Level] = Result.DV[CommonLevels + Level];
3531 Result.DV = std::move(DV);
3532 Result.DVSameSD = std::move(DVSameSD);
3533 Result.Levels = CommonLevels;
3534 Result.SameSDLevels = SameSDLevels;
3535 }
3536
3537 if (PossiblyLoopIndependent) {
3538 // Make sure the LoopIndependent flag is set correctly.
3539 // All directions must include equal, otherwise no
3540 // loop-independent dependence is possible.
3541 for (unsigned II = 1; II <= CommonLevels; ++II) {
3542 if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
3543 Result.LoopIndependent = false;
3544 break;
3545 }
3546 }
3547 } else {
3548 // On the other hand, if all directions are equal and there's no
3549 // loop-independent dependence possible, then no dependence exists.
3550 // However, if there are runtime assumptions, we must return the result.
3551 bool AllEqual = true;
3552 for (unsigned II = 1; II <= CommonLevels; ++II) {
3553 if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
3554 AllEqual = false;
3555 break;
3556 }
3557 }
3558 if (AllEqual && Result.Assumptions.getPredicates().empty())
3559 return nullptr;
3560 }
3561
3562 return std::make_unique<FullDependence>(std::move(Result));
3563}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Expand Atomic instructions
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")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static cl::opt< DependenceTestType > EnableDependenceTest("da-enable-dependence-test", cl::init(DependenceTestType::All), cl::ReallyHidden, cl::desc("Run only specified dependence test routine and disable others. " "The purpose is mainly to exclude the influence of other " "dependence test routines in regression tests. If set to All, all " "dependence test routines are enabled."), cl::values(clEnumValN(DependenceTestType::All, "all", "Enable all dependence test routines."), clEnumValN(DependenceTestType::StrongSIV, "strong-siv", "Enable only Strong SIV test."), clEnumValN(DependenceTestType::WeakCrossingSIV, "weak-crossing-siv", "Enable only Weak-Crossing SIV test."), clEnumValN(DependenceTestType::ExactSIV, "exact-siv", "Enable only Exact SIV test."), clEnumValN(DependenceTestType::WeakZeroSIV, "weak-zero-siv", "Enable only Weak-Zero SIV test."), clEnumValN(DependenceTestType::ExactRDIV, "exact-rdiv", "Enable only Exact RDIV test."), clEnumValN(DependenceTestType::SymbolicRDIV, "symbolic-rdiv", "Enable only Symbolic RDIV test."), clEnumValN(DependenceTestType::GCDMIV, "gcd-miv", "Enable only GCD MIV test."), clEnumValN(DependenceTestType::BanerjeeMIV, "banerjee-miv", "Enable only Banerjee MIV test.")))
static bool isLoadOrStore(const Instruction *I)
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 bool isDependenceTestEnabled(DependenceTestType Test)
Returns true iff Test is enabled.
static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM, const APInt &Delta, APInt &G, APInt &X, APInt &Y)
static void dumpSmallBitVector(SmallBitVector &BV)
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 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 bool isRemainderZero(const SCEVConstant *Dividend, const SCEVConstant *Divisor)
static cl::opt< bool > Delinearize("da-delinearize", cl::init(true), cl::Hidden, cl::desc("Try to delinearize array references."))
static cl::opt< bool > EnableMonotonicityCheck("da-enable-monotonicity-check", cl::init(false), cl::Hidden, cl::desc("Check if the subscripts are monotonic. If it's not, dependence " "is reported as unknown."))
static cl::opt< bool > DumpMonotonicityReport("da-dump-monotonicity-report", cl::init(false), cl::Hidden, cl::desc("When printing analysis, dump the results of monotonicity checks."))
static cl::opt< unsigned > MIVMaxLevelThreshold("da-miv-max-level-threshold", cl::init(7), cl::Hidden, cl::desc("Maximum depth allowed for the recursive algorithm used to " "explore MIV direction vectors."))
static cl::opt< bool > DisableDelinearizationChecks("da-disable-delinearization-checks", cl::Hidden, cl::desc("Disable checks that try to statically verify validity of " "delinearized subscripts. Enabling this option may result in incorrect " "dependence vectors for languages that allow the subscript of one " "dimension to underflow or overflow into another dimension."))
Hexagon Hardware Loops
Module.h This file contains the declarations for the Module class.
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:253
#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
#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
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
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:114
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
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
static LLVM_ABI void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder)
Definition APInt.cpp:1901
APInt abs() const
Get the absolute value.
Definition APInt.h:1810
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1208
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1503
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1655
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1747
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1137
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
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()
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_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ ICMP_NE
not equal
Definition InstrTypes.h:698
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
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:43
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 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.
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:314
FunctionPass(char &pid)
Definition Pass.h:316
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:569
bool isOutermost() const
Return true if the loop does not have a parent (natural) loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
unsigned getLoopDepth() const
Return the nesting level of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:596
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:67
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.
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values.
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.
LLVM_ABI 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 const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
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(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
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)
void push_back(const T &Elt)
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:45
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:53
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:165
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2263
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2268
LLVM_ABI APInt GreatestCommonDivisor(APInt A, APInt B)
Compute GCD of two unsigned APInt values.
Definition APInt.cpp:798
constexpr bool operator!(E Val)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ TB
TB - TwoByte - Set if this instruction has a two byte opcode, which starts with a 0x0F byte before th...
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
InstIterator< SymbolTableList< BasicBlock >, Function::iterator, BasicBlock::iterator, Instruction > inst_iterator
void collectParametricTerms(ScalarEvolution &SE, const SCEV *Expr, SmallVectorImpl< const SCEV * > &Terms)
Collect parametric terms occurring in step expressions (first step of delinearization).
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...
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:2250
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)
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.
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)...
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:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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:2203
APInt operator+(APInt a, const APInt &b)
Definition APInt.h:2208
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
#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...
This class defines a simple visitor class that may be used for various SCEV analysis purposes.