1 //===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // DependenceAnalysis is an LLVM pass that analyses dependences between memory 11 // accesses. Currently, it is an (incomplete) implementation of the approach 12 // described in 13 // 14 // Practical Dependence Testing 15 // Goff, Kennedy, Tseng 16 // PLDI 1991 17 // 18 // There's a single entry point that analyzes the dependence between a pair 19 // of memory references in a function, returning either NULL, for no dependence, 20 // or a more-or-less detailed description of the dependence between them. 21 // 22 // Currently, the implementation cannot propagate constraints between 23 // coupled RDIV subscripts and lacks a multi-subscript MIV test. 24 // Both of these are conservative weaknesses; 25 // that is, not a source of correctness problems. 26 // 27 // The implementation depends on the GEP instruction to 28 // differentiate subscripts. Since Clang linearizes subscripts 29 // for most arrays, we give up some precision (though the existing MIV tests 30 // will help). We trust that the GEP instruction will eventually be extended. 31 // In the meantime, we should explore Maslov's ideas about delinearization. 32 // 33 // We should pay some careful attention to the possibility of integer overflow 34 // in the implementation of the various tests. This could happen with Add, 35 // Subtract, or Multiply, with both APInt's and SCEV's. 36 // 37 // Some non-linear subscript pairs can be handled by the GCD test 38 // (and perhaps other tests). 39 // Should explore how often these things occur. 40 // 41 // Finally, it seems like certain test cases expose weaknesses in the SCEV 42 // simplification, especially in the handling of sign and zero extensions. 43 // It could be useful to spend time exploring these. 44 // 45 // Please note that this is work in progress and the interface is subject to 46 // change. 47 // 48 //===----------------------------------------------------------------------===// 49 // // 50 // In memory of Ken Kennedy, 1945 - 2007 // 51 // // 52 //===----------------------------------------------------------------------===// 53 54 #define DEBUG_TYPE "da" 55 56 #include "llvm/Analysis/DependenceAnalysis.h" 57 #include "llvm/ADT/Statistic.h" 58 #include "llvm/Operator.h" 59 #include "llvm/Analysis/AliasAnalysis.h" 60 #include "llvm/Analysis/LoopInfo.h" 61 #include "llvm/Analysis/ValueTracking.h" 62 #include "llvm/Analysis/ScalarEvolution.h" 63 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/InstIterator.h" 67 #include "llvm/Support/raw_ostream.h" 68 69 using namespace llvm; 70 71 //===----------------------------------------------------------------------===// 72 // statistics 73 74 STATISTIC(TotalArrayPairs, "Array pairs tested"); 75 STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs"); 76 STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs"); 77 STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs"); 78 STATISTIC(ZIVapplications, "ZIV applications"); 79 STATISTIC(ZIVindependence, "ZIV independence"); 80 STATISTIC(StrongSIVapplications, "Strong SIV applications"); 81 STATISTIC(StrongSIVsuccesses, "Strong SIV successes"); 82 STATISTIC(StrongSIVindependence, "Strong SIV independence"); 83 STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications"); 84 STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes"); 85 STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence"); 86 STATISTIC(ExactSIVapplications, "Exact SIV applications"); 87 STATISTIC(ExactSIVsuccesses, "Exact SIV successes"); 88 STATISTIC(ExactSIVindependence, "Exact SIV independence"); 89 STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications"); 90 STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes"); 91 STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence"); 92 STATISTIC(ExactRDIVapplications, "Exact RDIV applications"); 93 STATISTIC(ExactRDIVindependence, "Exact RDIV independence"); 94 STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications"); 95 STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence"); 96 STATISTIC(DeltaApplications, "Delta applications"); 97 STATISTIC(DeltaSuccesses, "Delta successes"); 98 STATISTIC(DeltaIndependence, "Delta independence"); 99 STATISTIC(DeltaPropagations, "Delta propagations"); 100 STATISTIC(GCDapplications, "GCD applications"); 101 STATISTIC(GCDsuccesses, "GCD successes"); 102 STATISTIC(GCDindependence, "GCD independence"); 103 STATISTIC(BanerjeeApplications, "Banerjee applications"); 104 STATISTIC(BanerjeeIndependence, "Banerjee independence"); 105 STATISTIC(BanerjeeSuccesses, "Banerjee successes"); 106 107 //===----------------------------------------------------------------------===// 108 // basics 109 110 INITIALIZE_PASS_BEGIN(DependenceAnalysis, "da", 111 "Dependence Analysis", true, true) 112 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 113 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 114 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 115 INITIALIZE_PASS_END(DependenceAnalysis, "da", 116 "Dependence Analysis", true, true) 117 118 char DependenceAnalysis::ID = 0; 119 120 121 FunctionPass *llvm::createDependenceAnalysisPass() { 122 return new DependenceAnalysis(); 123 } 124 125 126 bool DependenceAnalysis::runOnFunction(Function &F) { 127 this->F = &F; 128 AA = &getAnalysis<AliasAnalysis>(); 129 SE = &getAnalysis<ScalarEvolution>(); 130 LI = &getAnalysis<LoopInfo>(); 131 return false; 132 } 133 134 135 void DependenceAnalysis::releaseMemory() { 136 } 137 138 139 void DependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { 140 AU.setPreservesAll(); 141 AU.addRequiredTransitive<AliasAnalysis>(); 142 AU.addRequiredTransitive<ScalarEvolution>(); 143 AU.addRequiredTransitive<LoopInfo>(); 144 } 145 146 147 // Used to test the dependence analyzer. 148 // Looks through the function, noting loads and stores. 149 // Calls depends() on every possible pair and prints out the result. 150 // Ignores all other instructions. 151 static 152 void dumpExampleDependence(raw_ostream &OS, Function *F, 153 DependenceAnalysis *DA) { 154 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); 155 SrcI != SrcE; ++SrcI) { 156 if (isa<StoreInst>(*SrcI) || isa<LoadInst>(*SrcI)) { 157 for (inst_iterator DstI = SrcI, DstE = inst_end(F); 158 DstI != DstE; ++DstI) { 159 if (isa<StoreInst>(*DstI) || isa<LoadInst>(*DstI)) { 160 OS << "da analyze - "; 161 if (Dependence *D = DA->depends(&*SrcI, &*DstI, true)) { 162 D->dump(OS); 163 for (unsigned Level = 1; Level <= D->getLevels(); Level++) { 164 if (D->isSplitable(Level)) { 165 OS << "da analyze - split level = " << Level; 166 OS << ", iteration = " << *DA->getSplitIteration(D, Level); 167 OS << "!\n"; 168 } 169 } 170 delete D; 171 } 172 else 173 OS << "none!\n"; 174 } 175 } 176 } 177 } 178 } 179 180 181 void DependenceAnalysis::print(raw_ostream &OS, const Module*) const { 182 dumpExampleDependence(OS, F, const_cast<DependenceAnalysis *>(this)); 183 } 184 185 //===----------------------------------------------------------------------===// 186 // Dependence methods 187 188 // Returns true if this is an input dependence. 189 bool Dependence::isInput() const { 190 return Src->mayReadFromMemory() && Dst->mayReadFromMemory(); 191 } 192 193 194 // Returns true if this is an output dependence. 195 bool Dependence::isOutput() const { 196 return Src->mayWriteToMemory() && Dst->mayWriteToMemory(); 197 } 198 199 200 // Returns true if this is an flow (aka true) dependence. 201 bool Dependence::isFlow() const { 202 return Src->mayWriteToMemory() && Dst->mayReadFromMemory(); 203 } 204 205 206 // Returns true if this is an anti dependence. 207 bool Dependence::isAnti() const { 208 return Src->mayReadFromMemory() && Dst->mayWriteToMemory(); 209 } 210 211 212 // Returns true if a particular level is scalar; that is, 213 // if no subscript in the source or destination mention the induction 214 // variable associated with the loop at this level. 215 // Leave this out of line, so it will serve as a virtual method anchor 216 bool Dependence::isScalar(unsigned level) const { 217 return false; 218 } 219 220 221 //===----------------------------------------------------------------------===// 222 // FullDependence methods 223 224 FullDependence::FullDependence(Instruction *Source, 225 Instruction *Destination, 226 bool PossiblyLoopIndependent, 227 unsigned CommonLevels) : 228 Dependence(Source, Destination), 229 Levels(CommonLevels), 230 LoopIndependent(PossiblyLoopIndependent) { 231 Consistent = true; 232 DV = CommonLevels ? new DVEntry[CommonLevels] : NULL; 233 } 234 235 // The rest are simple getters that hide the implementation. 236 237 // getDirection - Returns the direction associated with a particular level. 238 unsigned FullDependence::getDirection(unsigned Level) const { 239 assert(0 < Level && Level <= Levels && "Level out of range"); 240 return DV[Level - 1].Direction; 241 } 242 243 244 // Returns the distance (or NULL) associated with a particular level. 245 const SCEV *FullDependence::getDistance(unsigned Level) const { 246 assert(0 < Level && Level <= Levels && "Level out of range"); 247 return DV[Level - 1].Distance; 248 } 249 250 251 // Returns true if a particular level is scalar; that is, 252 // if no subscript in the source or destination mention the induction 253 // variable associated with the loop at this level. 254 bool FullDependence::isScalar(unsigned Level) const { 255 assert(0 < Level && Level <= Levels && "Level out of range"); 256 return DV[Level - 1].Scalar; 257 } 258 259 260 // Returns true if peeling the first iteration from this loop 261 // will break this dependence. 262 bool FullDependence::isPeelFirst(unsigned Level) const { 263 assert(0 < Level && Level <= Levels && "Level out of range"); 264 return DV[Level - 1].PeelFirst; 265 } 266 267 268 // Returns true if peeling the last iteration from this loop 269 // will break this dependence. 270 bool FullDependence::isPeelLast(unsigned Level) const { 271 assert(0 < Level && Level <= Levels && "Level out of range"); 272 return DV[Level - 1].PeelLast; 273 } 274 275 276 // Returns true if splitting this loop will break the dependence. 277 bool FullDependence::isSplitable(unsigned Level) const { 278 assert(0 < Level && Level <= Levels && "Level out of range"); 279 return DV[Level - 1].Splitable; 280 } 281 282 283 //===----------------------------------------------------------------------===// 284 // DependenceAnalysis::Constraint methods 285 286 // If constraint is a point <X, Y>, returns X. 287 // Otherwise assert. 288 const SCEV *DependenceAnalysis::Constraint::getX() const { 289 assert(Kind == Point && "Kind should be Point"); 290 return A; 291 } 292 293 294 // If constraint is a point <X, Y>, returns Y. 295 // Otherwise assert. 296 const SCEV *DependenceAnalysis::Constraint::getY() const { 297 assert(Kind == Point && "Kind should be Point"); 298 return B; 299 } 300 301 302 // If constraint is a line AX + BY = C, returns A. 303 // Otherwise assert. 304 const SCEV *DependenceAnalysis::Constraint::getA() const { 305 assert((Kind == Line || Kind == Distance) && 306 "Kind should be Line (or Distance)"); 307 return A; 308 } 309 310 311 // If constraint is a line AX + BY = C, returns B. 312 // Otherwise assert. 313 const SCEV *DependenceAnalysis::Constraint::getB() const { 314 assert((Kind == Line || Kind == Distance) && 315 "Kind should be Line (or Distance)"); 316 return B; 317 } 318 319 320 // If constraint is a line AX + BY = C, returns C. 321 // Otherwise assert. 322 const SCEV *DependenceAnalysis::Constraint::getC() const { 323 assert((Kind == Line || Kind == Distance) && 324 "Kind should be Line (or Distance)"); 325 return C; 326 } 327 328 329 // If constraint is a distance, returns D. 330 // Otherwise assert. 331 const SCEV *DependenceAnalysis::Constraint::getD() const { 332 assert(Kind == Distance && "Kind should be Distance"); 333 return SE->getNegativeSCEV(C); 334 } 335 336 337 // Returns the loop associated with this constraint. 338 const Loop *DependenceAnalysis::Constraint::getAssociatedLoop() const { 339 assert((Kind == Distance || Kind == Line || Kind == Point) && 340 "Kind should be Distance, Line, or Point"); 341 return AssociatedLoop; 342 } 343 344 345 void DependenceAnalysis::Constraint::setPoint(const SCEV *X, 346 const SCEV *Y, 347 const Loop *CurLoop) { 348 Kind = Point; 349 A = X; 350 B = Y; 351 AssociatedLoop = CurLoop; 352 } 353 354 355 void DependenceAnalysis::Constraint::setLine(const SCEV *AA, 356 const SCEV *BB, 357 const SCEV *CC, 358 const Loop *CurLoop) { 359 Kind = Line; 360 A = AA; 361 B = BB; 362 C = CC; 363 AssociatedLoop = CurLoop; 364 } 365 366 367 void DependenceAnalysis::Constraint::setDistance(const SCEV *D, 368 const Loop *CurLoop) { 369 Kind = Distance; 370 A = SE->getConstant(D->getType(), 1); 371 B = SE->getNegativeSCEV(A); 372 C = SE->getNegativeSCEV(D); 373 AssociatedLoop = CurLoop; 374 } 375 376 377 void DependenceAnalysis::Constraint::setEmpty() { 378 Kind = Empty; 379 } 380 381 382 void DependenceAnalysis::Constraint::setAny(ScalarEvolution *NewSE) { 383 SE = NewSE; 384 Kind = Any; 385 } 386 387 388 // For debugging purposes. Dumps the constraint out to OS. 389 void DependenceAnalysis::Constraint::dump(raw_ostream &OS) const { 390 if (isEmpty()) 391 OS << " Empty\n"; 392 else if (isAny()) 393 OS << " Any\n"; 394 else if (isPoint()) 395 OS << " Point is <" << *getX() << ", " << *getY() << ">\n"; 396 else if (isDistance()) 397 OS << " Distance is " << *getD() << 398 " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n"; 399 else if (isLine()) 400 OS << " Line is " << *getA() << "*X + " << 401 *getB() << "*Y = " << *getC() << "\n"; 402 else 403 llvm_unreachable("unknown constraint type in Constraint::dump"); 404 } 405 406 407 // Updates X with the intersection 408 // of the Constraints X and Y. Returns true if X has changed. 409 // Corresponds to Figure 4 from the paper 410 // 411 // Practical Dependence Testing 412 // Goff, Kennedy, Tseng 413 // PLDI 1991 414 bool DependenceAnalysis::intersectConstraints(Constraint *X, 415 const Constraint *Y) { 416 ++DeltaApplications; 417 DEBUG(dbgs() << "\tintersect constraints\n"); 418 DEBUG(dbgs() << "\t X ="; X->dump(dbgs())); 419 DEBUG(dbgs() << "\t Y ="; Y->dump(dbgs())); 420 assert(!Y->isPoint() && "Y must not be a Point"); 421 if (X->isAny()) { 422 if (Y->isAny()) 423 return false; 424 *X = *Y; 425 return true; 426 } 427 if (X->isEmpty()) 428 return false; 429 if (Y->isEmpty()) { 430 X->setEmpty(); 431 return true; 432 } 433 434 if (X->isDistance() && Y->isDistance()) { 435 DEBUG(dbgs() << "\t intersect 2 distances\n"); 436 if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD())) 437 return false; 438 if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) { 439 X->setEmpty(); 440 ++DeltaSuccesses; 441 return true; 442 } 443 // Hmmm, interesting situation. 444 // I guess if either is constant, keep it and ignore the other. 445 if (isa<SCEVConstant>(Y->getD())) { 446 *X = *Y; 447 return true; 448 } 449 return false; 450 } 451 452 // At this point, the pseudo-code in Figure 4 of the paper 453 // checks if (X->isPoint() && Y->isPoint()). 454 // This case can't occur in our implementation, 455 // since a Point can only arise as the result of intersecting 456 // two Line constraints, and the right-hand value, Y, is never 457 // the result of an intersection. 458 assert(!(X->isPoint() && Y->isPoint()) && 459 "We shouldn't ever see X->isPoint() && Y->isPoint()"); 460 461 if (X->isLine() && Y->isLine()) { 462 DEBUG(dbgs() << "\t intersect 2 lines\n"); 463 const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB()); 464 const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA()); 465 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) { 466 // slopes are equal, so lines are parallel 467 DEBUG(dbgs() << "\t\tsame slope\n"); 468 Prod1 = SE->getMulExpr(X->getC(), Y->getB()); 469 Prod2 = SE->getMulExpr(X->getB(), Y->getC()); 470 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) 471 return false; 472 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) { 473 X->setEmpty(); 474 ++DeltaSuccesses; 475 return true; 476 } 477 return false; 478 } 479 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) { 480 // slopes differ, so lines intersect 481 DEBUG(dbgs() << "\t\tdifferent slopes\n"); 482 const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB()); 483 const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA()); 484 const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB()); 485 const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA()); 486 const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB()); 487 const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB()); 488 const SCEVConstant *C1A2_C2A1 = 489 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1)); 490 const SCEVConstant *C1B2_C2B1 = 491 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1)); 492 const SCEVConstant *A1B2_A2B1 = 493 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1)); 494 const SCEVConstant *A2B1_A1B2 = 495 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2)); 496 if (!C1B2_C2B1 || !C1A2_C2A1 || 497 !A1B2_A2B1 || !A2B1_A1B2) 498 return false; 499 APInt Xtop = C1B2_C2B1->getValue()->getValue(); 500 APInt Xbot = A1B2_A2B1->getValue()->getValue(); 501 APInt Ytop = C1A2_C2A1->getValue()->getValue(); 502 APInt Ybot = A2B1_A1B2->getValue()->getValue(); 503 DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n"); 504 DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n"); 505 DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n"); 506 DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n"); 507 APInt Xq = Xtop; // these need to be initialized, even 508 APInt Xr = Xtop; // though they're just going to be overwritten 509 APInt::sdivrem(Xtop, Xbot, Xq, Xr); 510 APInt Yq = Ytop; 511 APInt Yr = Ytop;; 512 APInt::sdivrem(Ytop, Ybot, Yq, Yr); 513 if (Xr != 0 || Yr != 0) { 514 X->setEmpty(); 515 ++DeltaSuccesses; 516 return true; 517 } 518 DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n"); 519 if (Xq.slt(0) || Yq.slt(0)) { 520 X->setEmpty(); 521 ++DeltaSuccesses; 522 return true; 523 } 524 if (const SCEVConstant *CUB = 525 collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) { 526 APInt UpperBound = CUB->getValue()->getValue(); 527 DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n"); 528 if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) { 529 X->setEmpty(); 530 ++DeltaSuccesses; 531 return true; 532 } 533 } 534 X->setPoint(SE->getConstant(Xq), 535 SE->getConstant(Yq), 536 X->getAssociatedLoop()); 537 ++DeltaSuccesses; 538 return true; 539 } 540 return false; 541 } 542 543 // if (X->isLine() && Y->isPoint()) This case can't occur. 544 assert(!(X->isLine() && Y->isPoint()) && "This case should never occur"); 545 546 if (X->isPoint() && Y->isLine()) { 547 DEBUG(dbgs() << "\t intersect Point and Line\n"); 548 const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX()); 549 const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY()); 550 const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1); 551 if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC())) 552 return false; 553 if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) { 554 X->setEmpty(); 555 ++DeltaSuccesses; 556 return true; 557 } 558 return false; 559 } 560 561 llvm_unreachable("shouldn't reach the end of Constraint intersection"); 562 return false; 563 } 564 565 566 //===----------------------------------------------------------------------===// 567 // DependenceAnalysis methods 568 569 // For debugging purposes. Dumps a dependence to OS. 570 void Dependence::dump(raw_ostream &OS) const { 571 bool Splitable = false; 572 if (isConfused()) 573 OS << "confused"; 574 else { 575 if (isConsistent()) 576 OS << "consistent "; 577 if (isFlow()) 578 OS << "flow"; 579 else if (isOutput()) 580 OS << "output"; 581 else if (isAnti()) 582 OS << "anti"; 583 else if (isInput()) 584 OS << "input"; 585 unsigned Levels = getLevels(); 586 if (Levels) { 587 OS << " ["; 588 for (unsigned II = 1; II <= Levels; ++II) { 589 if (isSplitable(II)) 590 Splitable = true; 591 if (isPeelFirst(II)) 592 OS << 'p'; 593 const SCEV *Distance = getDistance(II); 594 if (Distance) 595 OS << *Distance; 596 else if (isScalar(II)) 597 OS << "S"; 598 else { 599 unsigned Direction = getDirection(II); 600 if (Direction == DVEntry::ALL) 601 OS << "*"; 602 else { 603 if (Direction & DVEntry::LT) 604 OS << "<"; 605 if (Direction & DVEntry::EQ) 606 OS << "="; 607 if (Direction & DVEntry::GT) 608 OS << ">"; 609 } 610 } 611 if (isPeelLast(II)) 612 OS << 'p'; 613 if (II < Levels) 614 OS << " "; 615 } 616 if (isLoopIndependent()) 617 OS << "|<"; 618 OS << "]"; 619 if (Splitable) 620 OS << " splitable"; 621 } 622 } 623 OS << "!\n"; 624 } 625 626 627 628 static 629 AliasAnalysis::AliasResult underlyingObjectsAlias(AliasAnalysis *AA, 630 const Value *A, 631 const Value *B) { 632 const Value *AObj = GetUnderlyingObject(A); 633 const Value *BObj = GetUnderlyingObject(B); 634 return AA->alias(AObj, AA->getTypeStoreSize(AObj->getType()), 635 BObj, AA->getTypeStoreSize(BObj->getType())); 636 } 637 638 639 // Returns true if the load or store can be analyzed. Atomic and volatile 640 // operations have properties which this analysis does not understand. 641 static 642 bool isLoadOrStore(const Instruction *I) { 643 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) 644 return LI->isUnordered(); 645 else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) 646 return SI->isUnordered(); 647 return false; 648 } 649 650 651 static 652 Value *getPointerOperand(Instruction *I) { 653 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 654 return LI->getPointerOperand(); 655 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 656 return SI->getPointerOperand(); 657 llvm_unreachable("Value is not load or store instruction"); 658 return 0; 659 } 660 661 662 // Examines the loop nesting of the Src and Dst 663 // instructions and establishes their shared loops. Sets the variables 664 // CommonLevels, SrcLevels, and MaxLevels. 665 // The source and destination instructions needn't be contained in the same 666 // loop. The routine establishNestingLevels finds the level of most deeply 667 // nested loop that contains them both, CommonLevels. An instruction that's 668 // not contained in a loop is at level = 0. MaxLevels is equal to the level 669 // of the source plus the level of the destination, minus CommonLevels. 670 // This lets us allocate vectors MaxLevels in length, with room for every 671 // distinct loop referenced in both the source and destination subscripts. 672 // The variable SrcLevels is the nesting depth of the source instruction. 673 // It's used to help calculate distinct loops referenced by the destination. 674 // Here's the map from loops to levels: 675 // 0 - unused 676 // 1 - outermost common loop 677 // ... - other common loops 678 // CommonLevels - innermost common loop 679 // ... - loops containing Src but not Dst 680 // SrcLevels - innermost loop containing Src but not Dst 681 // ... - loops containing Dst but not Src 682 // MaxLevels - innermost loops containing Dst but not Src 683 // Consider the follow code fragment: 684 // for (a = ...) { 685 // for (b = ...) { 686 // for (c = ...) { 687 // for (d = ...) { 688 // A[] = ...; 689 // } 690 // } 691 // for (e = ...) { 692 // for (f = ...) { 693 // for (g = ...) { 694 // ... = A[]; 695 // } 696 // } 697 // } 698 // } 699 // } 700 // If we're looking at the possibility of a dependence between the store 701 // to A (the Src) and the load from A (the Dst), we'll note that they 702 // have 2 loops in common, so CommonLevels will equal 2 and the direction 703 // vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7. 704 // A map from loop names to loop numbers would look like 705 // a - 1 706 // b - 2 = CommonLevels 707 // c - 3 708 // d - 4 = SrcLevels 709 // e - 5 710 // f - 6 711 // g - 7 = MaxLevels 712 void DependenceAnalysis::establishNestingLevels(const Instruction *Src, 713 const Instruction *Dst) { 714 const BasicBlock *SrcBlock = Src->getParent(); 715 const BasicBlock *DstBlock = Dst->getParent(); 716 unsigned SrcLevel = LI->getLoopDepth(SrcBlock); 717 unsigned DstLevel = LI->getLoopDepth(DstBlock); 718 const Loop *SrcLoop = LI->getLoopFor(SrcBlock); 719 const Loop *DstLoop = LI->getLoopFor(DstBlock); 720 SrcLevels = SrcLevel; 721 MaxLevels = SrcLevel + DstLevel; 722 while (SrcLevel > DstLevel) { 723 SrcLoop = SrcLoop->getParentLoop(); 724 SrcLevel--; 725 } 726 while (DstLevel > SrcLevel) { 727 DstLoop = DstLoop->getParentLoop(); 728 DstLevel--; 729 } 730 while (SrcLoop != DstLoop) { 731 SrcLoop = SrcLoop->getParentLoop(); 732 DstLoop = DstLoop->getParentLoop(); 733 SrcLevel--; 734 } 735 CommonLevels = SrcLevel; 736 MaxLevels -= CommonLevels; 737 } 738 739 740 // Given one of the loops containing the source, return 741 // its level index in our numbering scheme. 742 unsigned DependenceAnalysis::mapSrcLoop(const Loop *SrcLoop) const { 743 return SrcLoop->getLoopDepth(); 744 } 745 746 747 // Given one of the loops containing the destination, 748 // return its level index in our numbering scheme. 749 unsigned DependenceAnalysis::mapDstLoop(const Loop *DstLoop) const { 750 unsigned D = DstLoop->getLoopDepth(); 751 if (D > CommonLevels) 752 return D - CommonLevels + SrcLevels; 753 else 754 return D; 755 } 756 757 758 // Returns true if Expression is loop invariant in LoopNest. 759 bool DependenceAnalysis::isLoopInvariant(const SCEV *Expression, 760 const Loop *LoopNest) const { 761 if (!LoopNest) 762 return true; 763 return SE->isLoopInvariant(Expression, LoopNest) && 764 isLoopInvariant(Expression, LoopNest->getParentLoop()); 765 } 766 767 768 769 // Finds the set of loops from the LoopNest that 770 // have a level <= CommonLevels and are referred to by the SCEV Expression. 771 void DependenceAnalysis::collectCommonLoops(const SCEV *Expression, 772 const Loop *LoopNest, 773 SmallBitVector &Loops) const { 774 while (LoopNest) { 775 unsigned Level = LoopNest->getLoopDepth(); 776 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest)) 777 Loops.set(Level); 778 LoopNest = LoopNest->getParentLoop(); 779 } 780 } 781 782 783 // removeMatchingExtensions - Examines a subscript pair. 784 // If the source and destination are identically sign (or zero) 785 // extended, it strips off the extension in an effect to simplify 786 // the actual analysis. 787 void DependenceAnalysis::removeMatchingExtensions(Subscript *Pair) { 788 const SCEV *Src = Pair->Src; 789 const SCEV *Dst = Pair->Dst; 790 if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) || 791 (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) { 792 const SCEVCastExpr *SrcCast = cast<SCEVCastExpr>(Src); 793 const SCEVCastExpr *DstCast = cast<SCEVCastExpr>(Dst); 794 if (SrcCast->getType() == DstCast->getType()) { 795 Pair->Src = SrcCast->getOperand(); 796 Pair->Dst = DstCast->getOperand(); 797 } 798 } 799 } 800 801 802 // Examine the scev and return true iff it's linear. 803 // Collect any loops mentioned in the set of "Loops". 804 bool DependenceAnalysis::checkSrcSubscript(const SCEV *Src, 805 const Loop *LoopNest, 806 SmallBitVector &Loops) { 807 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Src); 808 if (!AddRec) 809 return isLoopInvariant(Src, LoopNest); 810 const SCEV *Start = AddRec->getStart(); 811 const SCEV *Step = AddRec->getStepRecurrence(*SE); 812 if (!isLoopInvariant(Step, LoopNest)) 813 return false; 814 Loops.set(mapSrcLoop(AddRec->getLoop())); 815 return checkSrcSubscript(Start, LoopNest, Loops); 816 } 817 818 819 820 // Examine the scev and return true iff it's linear. 821 // Collect any loops mentioned in the set of "Loops". 822 bool DependenceAnalysis::checkDstSubscript(const SCEV *Dst, 823 const Loop *LoopNest, 824 SmallBitVector &Loops) { 825 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Dst); 826 if (!AddRec) 827 return isLoopInvariant(Dst, LoopNest); 828 const SCEV *Start = AddRec->getStart(); 829 const SCEV *Step = AddRec->getStepRecurrence(*SE); 830 if (!isLoopInvariant(Step, LoopNest)) 831 return false; 832 Loops.set(mapDstLoop(AddRec->getLoop())); 833 return checkDstSubscript(Start, LoopNest, Loops); 834 } 835 836 837 // Examines the subscript pair (the Src and Dst SCEVs) 838 // and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear. 839 // Collects the associated loops in a set. 840 DependenceAnalysis::Subscript::ClassificationKind 841 DependenceAnalysis::classifyPair(const SCEV *Src, const Loop *SrcLoopNest, 842 const SCEV *Dst, const Loop *DstLoopNest, 843 SmallBitVector &Loops) { 844 SmallBitVector SrcLoops(MaxLevels + 1); 845 SmallBitVector DstLoops(MaxLevels + 1); 846 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops)) 847 return Subscript::NonLinear; 848 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops)) 849 return Subscript::NonLinear; 850 Loops = SrcLoops; 851 Loops |= DstLoops; 852 unsigned N = Loops.count(); 853 if (N == 0) 854 return Subscript::ZIV; 855 if (N == 1) 856 return Subscript::SIV; 857 if (N == 2 && (SrcLoops.count() == 0 || 858 DstLoops.count() == 0 || 859 (SrcLoops.count() == 1 && DstLoops.count() == 1))) 860 return Subscript::RDIV; 861 return Subscript::MIV; 862 } 863 864 865 // A wrapper around SCEV::isKnownPredicate. 866 // Looks for cases where we're interested in comparing for equality. 867 // If both X and Y have been identically sign or zero extended, 868 // it strips off the (confusing) extensions before invoking 869 // SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package 870 // will be similarly updated. 871 // 872 // If SCEV::isKnownPredicate can't prove the predicate, 873 // we try simple subtraction, which seems to help in some cases 874 // involving symbolics. 875 bool DependenceAnalysis::isKnownPredicate(ICmpInst::Predicate Pred, 876 const SCEV *X, 877 const SCEV *Y) const { 878 if (Pred == CmpInst::ICMP_EQ || 879 Pred == CmpInst::ICMP_NE) { 880 if ((isa<SCEVSignExtendExpr>(X) && 881 isa<SCEVSignExtendExpr>(Y)) || 882 (isa<SCEVZeroExtendExpr>(X) && 883 isa<SCEVZeroExtendExpr>(Y))) { 884 const SCEVCastExpr *CX = cast<SCEVCastExpr>(X); 885 const SCEVCastExpr *CY = cast<SCEVCastExpr>(Y); 886 const SCEV *Xop = CX->getOperand(); 887 const SCEV *Yop = CY->getOperand(); 888 if (Xop->getType() == Yop->getType()) { 889 X = Xop; 890 Y = Yop; 891 } 892 } 893 } 894 if (SE->isKnownPredicate(Pred, X, Y)) 895 return true; 896 // If SE->isKnownPredicate can't prove the condition, 897 // we try the brute-force approach of subtracting 898 // and testing the difference. 899 // By testing with SE->isKnownPredicate first, we avoid 900 // the possibility of overflow when the arguments are constants. 901 const SCEV *Delta = SE->getMinusSCEV(X, Y); 902 switch (Pred) { 903 case CmpInst::ICMP_EQ: 904 return Delta->isZero(); 905 case CmpInst::ICMP_NE: 906 return SE->isKnownNonZero(Delta); 907 case CmpInst::ICMP_SGE: 908 return SE->isKnownNonNegative(Delta); 909 case CmpInst::ICMP_SLE: 910 return SE->isKnownNonPositive(Delta); 911 case CmpInst::ICMP_SGT: 912 return SE->isKnownPositive(Delta); 913 case CmpInst::ICMP_SLT: 914 return SE->isKnownNegative(Delta); 915 default: 916 llvm_unreachable("unexpected predicate in isKnownPredicate"); 917 } 918 } 919 920 921 // All subscripts are all the same type. 922 // Loop bound may be smaller (e.g., a char). 923 // Should zero extend loop bound, since it's always >= 0. 924 // This routine collects upper bound and extends if needed. 925 // Return null if no bound available. 926 const SCEV *DependenceAnalysis::collectUpperBound(const Loop *L, 927 Type *T) const { 928 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 929 const SCEV *UB = SE->getBackedgeTakenCount(L); 930 return SE->getNoopOrZeroExtend(UB, T); 931 } 932 return NULL; 933 } 934 935 936 // Calls collectUpperBound(), then attempts to cast it to SCEVConstant. 937 // If the cast fails, returns NULL. 938 const SCEVConstant *DependenceAnalysis::collectConstantUpperBound(const Loop *L, 939 Type *T 940 ) const { 941 if (const SCEV *UB = collectUpperBound(L, T)) 942 return dyn_cast<SCEVConstant>(UB); 943 return NULL; 944 } 945 946 947 // testZIV - 948 // When we have a pair of subscripts of the form [c1] and [c2], 949 // where c1 and c2 are both loop invariant, we attack it using 950 // the ZIV test. Basically, we test by comparing the two values, 951 // but there are actually three possible results: 952 // 1) the values are equal, so there's a dependence 953 // 2) the values are different, so there's no dependence 954 // 3) the values might be equal, so we have to assume a dependence. 955 // 956 // Return true if dependence disproved. 957 bool DependenceAnalysis::testZIV(const SCEV *Src, 958 const SCEV *Dst, 959 FullDependence &Result) const { 960 DEBUG(dbgs() << " src = " << *Src << "\n"); 961 DEBUG(dbgs() << " dst = " << *Dst << "\n"); 962 ++ZIVapplications; 963 if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) { 964 DEBUG(dbgs() << " provably dependent\n"); 965 return false; // provably dependent 966 } 967 if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) { 968 DEBUG(dbgs() << " provably independent\n"); 969 ++ZIVindependence; 970 return true; // provably independent 971 } 972 DEBUG(dbgs() << " possibly dependent\n"); 973 Result.Consistent = false; 974 return false; // possibly dependent 975 } 976 977 978 // strongSIVtest - 979 // From the paper, Practical Dependence Testing, Section 4.2.1 980 // 981 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i], 982 // where i is an induction variable, c1 and c2 are loop invariant, 983 // and a is a constant, we can solve it exactly using the Strong SIV test. 984 // 985 // Can prove independence. Failing that, can compute distance (and direction). 986 // In the presence of symbolic terms, we can sometimes make progress. 987 // 988 // If there's a dependence, 989 // 990 // c1 + a*i = c2 + a*i' 991 // 992 // The dependence distance is 993 // 994 // d = i' - i = (c1 - c2)/a 995 // 996 // A dependence only exists if d is an integer and abs(d) <= U, where U is the 997 // loop's upper bound. If a dependence exists, the dependence direction is 998 // defined as 999 // 1000 // { < if d > 0 1001 // direction = { = if d = 0 1002 // { > if d < 0 1003 // 1004 // Return true if dependence disproved. 1005 bool DependenceAnalysis::strongSIVtest(const SCEV *Coeff, 1006 const SCEV *SrcConst, 1007 const SCEV *DstConst, 1008 const Loop *CurLoop, 1009 unsigned Level, 1010 FullDependence &Result, 1011 Constraint &NewConstraint) const { 1012 DEBUG(dbgs() << "\tStrong SIV test\n"); 1013 DEBUG(dbgs() << "\t Coeff = " << *Coeff); 1014 DEBUG(dbgs() << ", " << *Coeff->getType() << "\n"); 1015 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst); 1016 DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n"); 1017 DEBUG(dbgs() << "\t DstConst = " << *DstConst); 1018 DEBUG(dbgs() << ", " << *DstConst->getType() << "\n"); 1019 ++StrongSIVapplications; 1020 assert(0 < Level && Level <= CommonLevels && "level out of range"); 1021 Level--; 1022 1023 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst); 1024 DEBUG(dbgs() << "\t Delta = " << *Delta); 1025 DEBUG(dbgs() << ", " << *Delta->getType() << "\n"); 1026 1027 // check that |Delta| < iteration count 1028 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) { 1029 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound); 1030 DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n"); 1031 const SCEV *AbsDelta = 1032 SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta); 1033 const SCEV *AbsCoeff = 1034 SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff); 1035 const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff); 1036 if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) { 1037 // Distance greater than trip count - no dependence 1038 ++StrongSIVindependence; 1039 ++StrongSIVsuccesses; 1040 return true; 1041 } 1042 } 1043 1044 // Can we compute distance? 1045 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) { 1046 APInt ConstDelta = cast<SCEVConstant>(Delta)->getValue()->getValue(); 1047 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getValue()->getValue(); 1048 APInt Distance = ConstDelta; // these need to be initialized 1049 APInt Remainder = ConstDelta; 1050 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder); 1051 DEBUG(dbgs() << "\t Distance = " << Distance << "\n"); 1052 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n"); 1053 // Make sure Coeff divides Delta exactly 1054 if (Remainder != 0) { 1055 // Coeff doesn't divide Distance, no dependence 1056 ++StrongSIVindependence; 1057 ++StrongSIVsuccesses; 1058 return true; 1059 } 1060 Result.DV[Level].Distance = SE->getConstant(Distance); 1061 NewConstraint.setDistance(SE->getConstant(Distance), CurLoop); 1062 if (Distance.sgt(0)) 1063 Result.DV[Level].Direction &= Dependence::DVEntry::LT; 1064 else if (Distance.slt(0)) 1065 Result.DV[Level].Direction &= Dependence::DVEntry::GT; 1066 else 1067 Result.DV[Level].Direction &= Dependence::DVEntry::EQ; 1068 ++StrongSIVsuccesses; 1069 } 1070 else if (Delta->isZero()) { 1071 // since 0/X == 0 1072 Result.DV[Level].Distance = Delta; 1073 NewConstraint.setDistance(Delta, CurLoop); 1074 Result.DV[Level].Direction &= Dependence::DVEntry::EQ; 1075 ++StrongSIVsuccesses; 1076 } 1077 else { 1078 if (Coeff->isOne()) { 1079 DEBUG(dbgs() << "\t Distance = " << *Delta << "\n"); 1080 Result.DV[Level].Distance = Delta; // since X/1 == X 1081 NewConstraint.setDistance(Delta, CurLoop); 1082 } 1083 else { 1084 Result.Consistent = false; 1085 NewConstraint.setLine(Coeff, 1086 SE->getNegativeSCEV(Coeff), 1087 SE->getNegativeSCEV(Delta), CurLoop); 1088 } 1089 1090 // maybe we can get a useful direction 1091 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta); 1092 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta); 1093 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta); 1094 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff); 1095 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff); 1096 // The double negatives above are confusing. 1097 // It helps to read !SE->isKnownNonZero(Delta) 1098 // as "Delta might be Zero" 1099 unsigned NewDirection = Dependence::DVEntry::NONE; 1100 if ((DeltaMaybePositive && CoeffMaybePositive) || 1101 (DeltaMaybeNegative && CoeffMaybeNegative)) 1102 NewDirection = Dependence::DVEntry::LT; 1103 if (DeltaMaybeZero) 1104 NewDirection |= Dependence::DVEntry::EQ; 1105 if ((DeltaMaybeNegative && CoeffMaybePositive) || 1106 (DeltaMaybePositive && CoeffMaybeNegative)) 1107 NewDirection |= Dependence::DVEntry::GT; 1108 if (NewDirection < Result.DV[Level].Direction) 1109 ++StrongSIVsuccesses; 1110 Result.DV[Level].Direction &= NewDirection; 1111 } 1112 return false; 1113 } 1114 1115 1116 // weakCrossingSIVtest - 1117 // From the paper, Practical Dependence Testing, Section 4.2.2 1118 // 1119 // When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i], 1120 // where i is an induction variable, c1 and c2 are loop invariant, 1121 // and a is a constant, we can solve it exactly using the 1122 // Weak-Crossing SIV test. 1123 // 1124 // Given c1 + a*i = c2 - a*i', we can look for the intersection of 1125 // the two lines, where i = i', yielding 1126 // 1127 // c1 + a*i = c2 - a*i 1128 // 2a*i = c2 - c1 1129 // i = (c2 - c1)/2a 1130 // 1131 // If i < 0, there is no dependence. 1132 // If i > upperbound, there is no dependence. 1133 // If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0. 1134 // If i = upperbound, there's a dependence with distance = 0. 1135 // If i is integral, there's a dependence (all directions). 1136 // If the non-integer part = 1/2, there's a dependence (<> directions). 1137 // Otherwise, there's no dependence. 1138 // 1139 // Can prove independence. Failing that, 1140 // can sometimes refine the directions. 1141 // Can determine iteration for splitting. 1142 // 1143 // Return true if dependence disproved. 1144 bool DependenceAnalysis::weakCrossingSIVtest(const SCEV *Coeff, 1145 const SCEV *SrcConst, 1146 const SCEV *DstConst, 1147 const Loop *CurLoop, 1148 unsigned Level, 1149 FullDependence &Result, 1150 Constraint &NewConstraint, 1151 const SCEV *&SplitIter) const { 1152 DEBUG(dbgs() << "\tWeak-Crossing SIV test\n"); 1153 DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n"); 1154 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n"); 1155 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n"); 1156 ++WeakCrossingSIVapplications; 1157 assert(0 < Level && Level <= CommonLevels && "Level out of range"); 1158 Level--; 1159 Result.Consistent = false; 1160 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst); 1161 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n"); 1162 NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop); 1163 if (Delta->isZero()) { 1164 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT); 1165 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT); 1166 ++WeakCrossingSIVsuccesses; 1167 if (!Result.DV[Level].Direction) { 1168 ++WeakCrossingSIVindependence; 1169 return true; 1170 } 1171 Result.DV[Level].Distance = Delta; // = 0 1172 return false; 1173 } 1174 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff); 1175 if (!ConstCoeff) 1176 return false; 1177 1178 Result.DV[Level].Splitable = true; 1179 if (SE->isKnownNegative(ConstCoeff)) { 1180 ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff)); 1181 assert(ConstCoeff && 1182 "dynamic cast of negative of ConstCoeff should yield constant"); 1183 Delta = SE->getNegativeSCEV(Delta); 1184 } 1185 assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive"); 1186 1187 // compute SplitIter for use by DependenceAnalysis::getSplitIteration() 1188 SplitIter = 1189 SE->getUDivExpr(SE->getSMaxExpr(SE->getConstant(Delta->getType(), 0), 1190 Delta), 1191 SE->getMulExpr(SE->getConstant(Delta->getType(), 2), 1192 ConstCoeff)); 1193 DEBUG(dbgs() << "\t Split iter = " << *SplitIter << "\n"); 1194 1195 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta); 1196 if (!ConstDelta) 1197 return false; 1198 1199 // We're certain that ConstCoeff > 0; therefore, 1200 // if Delta < 0, then no dependence. 1201 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n"); 1202 DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n"); 1203 if (SE->isKnownNegative(Delta)) { 1204 // No dependence, Delta < 0 1205 ++WeakCrossingSIVindependence; 1206 ++WeakCrossingSIVsuccesses; 1207 return true; 1208 } 1209 1210 // We're certain that Delta > 0 and ConstCoeff > 0. 1211 // Check Delta/(2*ConstCoeff) against upper loop bound 1212 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) { 1213 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n"); 1214 const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2); 1215 const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound), 1216 ConstantTwo); 1217 DEBUG(dbgs() << "\t ML = " << *ML << "\n"); 1218 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) { 1219 // Delta too big, no dependence 1220 ++WeakCrossingSIVindependence; 1221 ++WeakCrossingSIVsuccesses; 1222 return true; 1223 } 1224 if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) { 1225 // i = i' = UB 1226 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT); 1227 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT); 1228 ++WeakCrossingSIVsuccesses; 1229 if (!Result.DV[Level].Direction) { 1230 ++WeakCrossingSIVindependence; 1231 return true; 1232 } 1233 Result.DV[Level].Splitable = false; 1234 Result.DV[Level].Distance = SE->getConstant(Delta->getType(), 0); 1235 return false; 1236 } 1237 } 1238 1239 // check that Coeff divides Delta 1240 APInt APDelta = ConstDelta->getValue()->getValue(); 1241 APInt APCoeff = ConstCoeff->getValue()->getValue(); 1242 APInt Distance = APDelta; // these need to be initialzed 1243 APInt Remainder = APDelta; 1244 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder); 1245 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n"); 1246 if (Remainder != 0) { 1247 // Coeff doesn't divide Delta, no dependence 1248 ++WeakCrossingSIVindependence; 1249 ++WeakCrossingSIVsuccesses; 1250 return true; 1251 } 1252 DEBUG(dbgs() << "\t Distance = " << Distance << "\n"); 1253 1254 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible 1255 APInt Two = APInt(Distance.getBitWidth(), 2, true); 1256 Remainder = Distance.srem(Two); 1257 DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n"); 1258 if (Remainder != 0) { 1259 // Equal direction isn't possible 1260 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ); 1261 ++WeakCrossingSIVsuccesses; 1262 } 1263 return false; 1264 } 1265 1266 1267 // Kirch's algorithm, from 1268 // 1269 // Optimizing Supercompilers for Supercomputers 1270 // Michael Wolfe 1271 // MIT Press, 1989 1272 // 1273 // Program 2.1, page 29. 1274 // Computes the GCD of AM and BM. 1275 // Also finds a solution to the equation ax - by = gdc(a, b). 1276 // Returns true iff the gcd divides Delta. 1277 static 1278 bool findGCD(unsigned Bits, APInt AM, APInt BM, APInt Delta, 1279 APInt &G, APInt &X, APInt &Y) { 1280 APInt A0(Bits, 1, true), A1(Bits, 0, true); 1281 APInt B0(Bits, 0, true), B1(Bits, 1, true); 1282 APInt G0 = AM.abs(); 1283 APInt G1 = BM.abs(); 1284 APInt Q = G0; // these need to be initialized 1285 APInt R = G0; 1286 APInt::sdivrem(G0, G1, Q, R); 1287 while (R != 0) { 1288 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2; 1289 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2; 1290 G0 = G1; G1 = R; 1291 APInt::sdivrem(G0, G1, Q, R); 1292 } 1293 G = G1; 1294 DEBUG(dbgs() << "\t GCD = " << G << "\n"); 1295 X = AM.slt(0) ? -A1 : A1; 1296 Y = BM.slt(0) ? B1 : -B1; 1297 1298 // make sure gcd divides Delta 1299 R = Delta.srem(G); 1300 if (R != 0) 1301 return true; // gcd doesn't divide Delta, no dependence 1302 Q = Delta.sdiv(G); 1303 X *= Q; 1304 Y *= Q; 1305 return false; 1306 } 1307 1308 1309 static 1310 APInt floorOfQuotient(APInt A, APInt B) { 1311 APInt Q = A; // these need to be initialized 1312 APInt R = A; 1313 APInt::sdivrem(A, B, Q, R); 1314 if (R == 0) 1315 return Q; 1316 if ((A.sgt(0) && B.sgt(0)) || 1317 (A.slt(0) && B.slt(0))) 1318 return Q; 1319 else 1320 return Q - 1; 1321 } 1322 1323 1324 static 1325 APInt ceilingOfQuotient(APInt A, APInt B) { 1326 APInt Q = A; // these need to be initialized 1327 APInt R = A; 1328 APInt::sdivrem(A, B, Q, R); 1329 if (R == 0) 1330 return Q; 1331 if ((A.sgt(0) && B.sgt(0)) || 1332 (A.slt(0) && B.slt(0))) 1333 return Q + 1; 1334 else 1335 return Q; 1336 } 1337 1338 1339 static 1340 APInt maxAPInt(APInt A, APInt B) { 1341 return A.sgt(B) ? A : B; 1342 } 1343 1344 1345 static 1346 APInt minAPInt(APInt A, APInt B) { 1347 return A.slt(B) ? A : B; 1348 } 1349 1350 1351 // exactSIVtest - 1352 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i], 1353 // where i is an induction variable, c1 and c2 are loop invariant, and a1 1354 // and a2 are constant, we can solve it exactly using an algorithm developed 1355 // by Banerjee and Wolfe. See Section 2.5.3 in 1356 // 1357 // Optimizing Supercompilers for Supercomputers 1358 // Michael Wolfe 1359 // MIT Press, 1989 1360 // 1361 // It's slower than the specialized tests (strong SIV, weak-zero SIV, etc), 1362 // so use them if possible. They're also a bit better with symbolics and, 1363 // in the case of the strong SIV test, can compute Distances. 1364 // 1365 // Return true if dependence disproved. 1366 bool DependenceAnalysis::exactSIVtest(const SCEV *SrcCoeff, 1367 const SCEV *DstCoeff, 1368 const SCEV *SrcConst, 1369 const SCEV *DstConst, 1370 const Loop *CurLoop, 1371 unsigned Level, 1372 FullDependence &Result, 1373 Constraint &NewConstraint) const { 1374 DEBUG(dbgs() << "\tExact SIV test\n"); 1375 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n"); 1376 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n"); 1377 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n"); 1378 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n"); 1379 ++ExactSIVapplications; 1380 assert(0 < Level && Level <= CommonLevels && "Level out of range"); 1381 Level--; 1382 Result.Consistent = false; 1383 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst); 1384 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n"); 1385 NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff), 1386 Delta, CurLoop); 1387 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta); 1388 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff); 1389 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff); 1390 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff) 1391 return false; 1392 1393 // find gcd 1394 APInt G, X, Y; 1395 APInt AM = ConstSrcCoeff->getValue()->getValue(); 1396 APInt BM = ConstDstCoeff->getValue()->getValue(); 1397 unsigned Bits = AM.getBitWidth(); 1398 if (findGCD(Bits, AM, BM, ConstDelta->getValue()->getValue(), G, X, Y)) { 1399 // gcd doesn't divide Delta, no dependence 1400 ++ExactSIVindependence; 1401 ++ExactSIVsuccesses; 1402 return true; 1403 } 1404 1405 DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n"); 1406 1407 // since SCEV construction normalizes, LM = 0 1408 APInt UM(Bits, 1, true); 1409 bool UMvalid = false; 1410 // UM is perhaps unavailable, let's check 1411 if (const SCEVConstant *CUB = 1412 collectConstantUpperBound(CurLoop, Delta->getType())) { 1413 UM = CUB->getValue()->getValue(); 1414 DEBUG(dbgs() << "\t UM = " << UM << "\n"); 1415 UMvalid = true; 1416 } 1417 1418 APInt TU(APInt::getSignedMaxValue(Bits)); 1419 APInt TL(APInt::getSignedMinValue(Bits)); 1420 1421 // test(BM/G, LM-X) and test(-BM/G, X-UM) 1422 APInt TMUL = BM.sdiv(G); 1423 if (TMUL.sgt(0)) { 1424 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL)); 1425 DEBUG(dbgs() << "\t TL = " << TL << "\n"); 1426 if (UMvalid) { 1427 TU = minAPInt(TU, floorOfQuotient(UM - X, TMUL)); 1428 DEBUG(dbgs() << "\t TU = " << TU << "\n"); 1429 } 1430 } 1431 else { 1432 TU = minAPInt(TU, floorOfQuotient(-X, TMUL)); 1433 DEBUG(dbgs() << "\t TU = " << TU << "\n"); 1434 if (UMvalid) { 1435 TL = maxAPInt(TL, ceilingOfQuotient(UM - X, TMUL)); 1436 DEBUG(dbgs() << "\t TL = " << TL << "\n"); 1437 } 1438 } 1439 1440 // test(AM/G, LM-Y) and test(-AM/G, Y-UM) 1441 TMUL = AM.sdiv(G); 1442 if (TMUL.sgt(0)) { 1443 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL)); 1444 DEBUG(dbgs() << "\t TL = " << TL << "\n"); 1445 if (UMvalid) { 1446 TU = minAPInt(TU, floorOfQuotient(UM - Y, TMUL)); 1447 DEBUG(dbgs() << "\t TU = " << TU << "\n"); 1448 } 1449 } 1450 else { 1451 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL)); 1452 DEBUG(dbgs() << "\t TU = " << TU << "\n"); 1453 if (UMvalid) { 1454 TL = maxAPInt(TL, ceilingOfQuotient(UM - Y, TMUL)); 1455 DEBUG(dbgs() << "\t TL = " << TL << "\n"); 1456 } 1457 } 1458 if (TL.sgt(TU)) { 1459 ++ExactSIVindependence; 1460 ++ExactSIVsuccesses; 1461 return true; 1462 } 1463 1464 // explore directions 1465 unsigned NewDirection = Dependence::DVEntry::NONE; 1466 1467 // less than 1468 APInt SaveTU(TU); // save these 1469 APInt SaveTL(TL); 1470 DEBUG(dbgs() << "\t exploring LT direction\n"); 1471 TMUL = AM - BM; 1472 if (TMUL.sgt(0)) { 1473 TL = maxAPInt(TL, ceilingOfQuotient(X - Y + 1, TMUL)); 1474 DEBUG(dbgs() << "\t\t TL = " << TL << "\n"); 1475 } 1476 else { 1477 TU = minAPInt(TU, floorOfQuotient(X - Y + 1, TMUL)); 1478 DEBUG(dbgs() << "\t\t TU = " << TU << "\n"); 1479 } 1480 if (TL.sle(TU)) { 1481 NewDirection |= Dependence::DVEntry::LT; 1482 ++ExactSIVsuccesses; 1483 } 1484 1485 // equal 1486 TU = SaveTU; // restore 1487 TL = SaveTL; 1488 DEBUG(dbgs() << "\t exploring EQ direction\n"); 1489 if (TMUL.sgt(0)) { 1490 TL = maxAPInt(TL, ceilingOfQuotient(X - Y, TMUL)); 1491 DEBUG(dbgs() << "\t\t TL = " << TL << "\n"); 1492 } 1493 else { 1494 TU = minAPInt(TU, floorOfQuotient(X - Y, TMUL)); 1495 DEBUG(dbgs() << "\t\t TU = " << TU << "\n"); 1496 } 1497 TMUL = BM - AM; 1498 if (TMUL.sgt(0)) { 1499 TL = maxAPInt(TL, ceilingOfQuotient(Y - X, TMUL)); 1500 DEBUG(dbgs() << "\t\t TL = " << TL << "\n"); 1501 } 1502 else { 1503 TU = minAPInt(TU, floorOfQuotient(Y - X, TMUL)); 1504 DEBUG(dbgs() << "\t\t TU = " << TU << "\n"); 1505 } 1506 if (TL.sle(TU)) { 1507 NewDirection |= Dependence::DVEntry::EQ; 1508 ++ExactSIVsuccesses; 1509 } 1510 1511 // greater than 1512 TU = SaveTU; // restore 1513 TL = SaveTL; 1514 DEBUG(dbgs() << "\t exploring GT direction\n"); 1515 if (TMUL.sgt(0)) { 1516 TL = maxAPInt(TL, ceilingOfQuotient(Y - X + 1, TMUL)); 1517 DEBUG(dbgs() << "\t\t TL = " << TL << "\n"); 1518 } 1519 else { 1520 TU = minAPInt(TU, floorOfQuotient(Y - X + 1, TMUL)); 1521 DEBUG(dbgs() << "\t\t TU = " << TU << "\n"); 1522 } 1523 if (TL.sle(TU)) { 1524 NewDirection |= Dependence::DVEntry::GT; 1525 ++ExactSIVsuccesses; 1526 } 1527 1528 // finished 1529 Result.DV[Level].Direction &= NewDirection; 1530 if (Result.DV[Level].Direction == Dependence::DVEntry::NONE) 1531 ++ExactSIVindependence; 1532 return Result.DV[Level].Direction == Dependence::DVEntry::NONE; 1533 } 1534 1535 1536 1537 // Return true if the divisor evenly divides the dividend. 1538 static 1539 bool isRemainderZero(const SCEVConstant *Dividend, 1540 const SCEVConstant *Divisor) { 1541 APInt ConstDividend = Dividend->getValue()->getValue(); 1542 APInt ConstDivisor = Divisor->getValue()->getValue(); 1543 return ConstDividend.srem(ConstDivisor) == 0; 1544 } 1545 1546 1547 // weakZeroSrcSIVtest - 1548 // From the paper, Practical Dependence Testing, Section 4.2.2 1549 // 1550 // When we have a pair of subscripts of the form [c1] and [c2 + a*i], 1551 // where i is an induction variable, c1 and c2 are loop invariant, 1552 // and a is a constant, we can solve it exactly using the 1553 // Weak-Zero SIV test. 1554 // 1555 // Given 1556 // 1557 // c1 = c2 + a*i 1558 // 1559 // we get 1560 // 1561 // (c1 - c2)/a = i 1562 // 1563 // If i is not an integer, there's no dependence. 1564 // If i < 0 or > UB, there's no dependence. 1565 // If i = 0, the direction is <= and peeling the 1566 // 1st iteration will break the dependence. 1567 // If i = UB, the direction is >= and peeling the 1568 // last iteration will break the dependence. 1569 // Otherwise, the direction is *. 1570 // 1571 // Can prove independence. Failing that, we can sometimes refine 1572 // the directions. Can sometimes show that first or last 1573 // iteration carries all the dependences (so worth peeling). 1574 // 1575 // (see also weakZeroDstSIVtest) 1576 // 1577 // Return true if dependence disproved. 1578 bool DependenceAnalysis::weakZeroSrcSIVtest(const SCEV *DstCoeff, 1579 const SCEV *SrcConst, 1580 const SCEV *DstConst, 1581 const Loop *CurLoop, 1582 unsigned Level, 1583 FullDependence &Result, 1584 Constraint &NewConstraint) const { 1585 // For the WeakSIV test, it's possible the loop isn't common to 1586 // the Src and Dst loops. If it isn't, then there's no need to 1587 // record a direction. 1588 DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n"); 1589 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n"); 1590 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n"); 1591 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n"); 1592 ++WeakZeroSIVapplications; 1593 assert(0 < Level && Level <= MaxLevels && "Level out of range"); 1594 Level--; 1595 Result.Consistent = false; 1596 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst); 1597 NewConstraint.setLine(SE->getConstant(Delta->getType(), 0), 1598 DstCoeff, Delta, CurLoop); 1599 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n"); 1600 if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) { 1601 if (Level < CommonLevels) { 1602 Result.DV[Level].Direction &= Dependence::DVEntry::LE; 1603 Result.DV[Level].PeelFirst = true; 1604 ++WeakZeroSIVsuccesses; 1605 } 1606 return false; // dependences caused by first iteration 1607 } 1608 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff); 1609 if (!ConstCoeff) 1610 return false; 1611 const SCEV *AbsCoeff = 1612 SE->isKnownNegative(ConstCoeff) ? 1613 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff; 1614 const SCEV *NewDelta = 1615 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta; 1616 1617 // check that Delta/SrcCoeff < iteration count 1618 // really check NewDelta < count*AbsCoeff 1619 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) { 1620 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n"); 1621 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound); 1622 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) { 1623 ++WeakZeroSIVindependence; 1624 ++WeakZeroSIVsuccesses; 1625 return true; 1626 } 1627 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) { 1628 // dependences caused by last iteration 1629 if (Level < CommonLevels) { 1630 Result.DV[Level].Direction &= Dependence::DVEntry::GE; 1631 Result.DV[Level].PeelLast = true; 1632 ++WeakZeroSIVsuccesses; 1633 } 1634 return false; 1635 } 1636 } 1637 1638 // check that Delta/SrcCoeff >= 0 1639 // really check that NewDelta >= 0 1640 if (SE->isKnownNegative(NewDelta)) { 1641 // No dependence, newDelta < 0 1642 ++WeakZeroSIVindependence; 1643 ++WeakZeroSIVsuccesses; 1644 return true; 1645 } 1646 1647 // if SrcCoeff doesn't divide Delta, then no dependence 1648 if (isa<SCEVConstant>(Delta) && 1649 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) { 1650 ++WeakZeroSIVindependence; 1651 ++WeakZeroSIVsuccesses; 1652 return true; 1653 } 1654 return false; 1655 } 1656 1657 1658 // weakZeroDstSIVtest - 1659 // From the paper, Practical Dependence Testing, Section 4.2.2 1660 // 1661 // When we have a pair of subscripts of the form [c1 + a*i] and [c2], 1662 // where i is an induction variable, c1 and c2 are loop invariant, 1663 // and a is a constant, we can solve it exactly using the 1664 // Weak-Zero SIV test. 1665 // 1666 // Given 1667 // 1668 // c1 + a*i = c2 1669 // 1670 // we get 1671 // 1672 // i = (c2 - c1)/a 1673 // 1674 // If i is not an integer, there's no dependence. 1675 // If i < 0 or > UB, there's no dependence. 1676 // If i = 0, the direction is <= and peeling the 1677 // 1st iteration will break the dependence. 1678 // If i = UB, the direction is >= and peeling the 1679 // last iteration will break the dependence. 1680 // Otherwise, the direction is *. 1681 // 1682 // Can prove independence. Failing that, we can sometimes refine 1683 // the directions. Can sometimes show that first or last 1684 // iteration carries all the dependences (so worth peeling). 1685 // 1686 // (see also weakZeroSrcSIVtest) 1687 // 1688 // Return true if dependence disproved. 1689 bool DependenceAnalysis::weakZeroDstSIVtest(const SCEV *SrcCoeff, 1690 const SCEV *SrcConst, 1691 const SCEV *DstConst, 1692 const Loop *CurLoop, 1693 unsigned Level, 1694 FullDependence &Result, 1695 Constraint &NewConstraint) const { 1696 // For the WeakSIV test, it's possible the loop isn't common to the 1697 // Src and Dst loops. If it isn't, then there's no need to record a direction. 1698 DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n"); 1699 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n"); 1700 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n"); 1701 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n"); 1702 ++WeakZeroSIVapplications; 1703 assert(0 < Level && Level <= SrcLevels && "Level out of range"); 1704 Level--; 1705 Result.Consistent = false; 1706 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst); 1707 NewConstraint.setLine(SrcCoeff, SE->getConstant(Delta->getType(), 0), 1708 Delta, CurLoop); 1709 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n"); 1710 if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) { 1711 if (Level < CommonLevels) { 1712 Result.DV[Level].Direction &= Dependence::DVEntry::LE; 1713 Result.DV[Level].PeelFirst = true; 1714 ++WeakZeroSIVsuccesses; 1715 } 1716 return false; // dependences caused by first iteration 1717 } 1718 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff); 1719 if (!ConstCoeff) 1720 return false; 1721 const SCEV *AbsCoeff = 1722 SE->isKnownNegative(ConstCoeff) ? 1723 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff; 1724 const SCEV *NewDelta = 1725 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta; 1726 1727 // check that Delta/SrcCoeff < iteration count 1728 // really check NewDelta < count*AbsCoeff 1729 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) { 1730 DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n"); 1731 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound); 1732 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) { 1733 ++WeakZeroSIVindependence; 1734 ++WeakZeroSIVsuccesses; 1735 return true; 1736 } 1737 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) { 1738 // dependences caused by last iteration 1739 if (Level < CommonLevels) { 1740 Result.DV[Level].Direction &= Dependence::DVEntry::GE; 1741 Result.DV[Level].PeelLast = true; 1742 ++WeakZeroSIVsuccesses; 1743 } 1744 return false; 1745 } 1746 } 1747 1748 // check that Delta/SrcCoeff >= 0 1749 // really check that NewDelta >= 0 1750 if (SE->isKnownNegative(NewDelta)) { 1751 // No dependence, newDelta < 0 1752 ++WeakZeroSIVindependence; 1753 ++WeakZeroSIVsuccesses; 1754 return true; 1755 } 1756 1757 // if SrcCoeff doesn't divide Delta, then no dependence 1758 if (isa<SCEVConstant>(Delta) && 1759 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) { 1760 ++WeakZeroSIVindependence; 1761 ++WeakZeroSIVsuccesses; 1762 return true; 1763 } 1764 return false; 1765 } 1766 1767 1768 // exactRDIVtest - Tests the RDIV subscript pair for dependence. 1769 // Things of the form [c1 + a*i] and [c2 + b*j], 1770 // where i and j are induction variable, c1 and c2 are loop invariant, 1771 // and a and b are constants. 1772 // Returns true if any possible dependence is disproved. 1773 // Marks the result as inconsistent. 1774 // Works in some cases that symbolicRDIVtest doesn't, and vice versa. 1775 bool DependenceAnalysis::exactRDIVtest(const SCEV *SrcCoeff, 1776 const SCEV *DstCoeff, 1777 const SCEV *SrcConst, 1778 const SCEV *DstConst, 1779 const Loop *SrcLoop, 1780 const Loop *DstLoop, 1781 FullDependence &Result) const { 1782 DEBUG(dbgs() << "\tExact RDIV test\n"); 1783 DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n"); 1784 DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n"); 1785 DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n"); 1786 DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n"); 1787 ++ExactRDIVapplications; 1788 Result.Consistent = false; 1789 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst); 1790 DEBUG(dbgs() << "\t Delta = " << *Delta << "\n"); 1791 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta); 1792 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff); 1793 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff); 1794 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff) 1795 return false; 1796 1797 // find gcd 1798 APInt G, X, Y; 1799 APInt AM = ConstSrcCoeff->getValue()->getValue(); 1800 APInt BM = ConstDstCoeff->getValue()->getValue(); 1801 unsigned Bits = AM.getBitWidth(); 1802 if (findGCD(Bits, AM, BM, ConstDelta->getValue()->getValue(), G, X, Y)) { 1803 // gcd doesn't divide Delta, no dependence 1804 ++ExactRDIVindependence; 1805 return true; 1806 } 1807 1808 DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n"); 1809 1810 // since SCEV construction seems to normalize, LM = 0 1811 APInt SrcUM(Bits, 1, true); 1812 bool SrcUMvalid = false; 1813 // SrcUM is perhaps unavailable, let's check 1814 if (const SCEVConstant *UpperBound = 1815 collectConstantUpperBound(SrcLoop, Delta->getType())) { 1816 SrcUM = UpperBound->getValue()->getValue(); 1817 DEBUG(dbgs() << "\t SrcUM = " << SrcUM << "\n"); 1818 SrcUMvalid = true; 1819 } 1820 1821 APInt DstUM(Bits, 1, true); 1822 bool DstUMvalid = false; 1823 // UM is perhaps unavailable, let's check 1824 if (const SCEVConstant *UpperBound = 1825 collectConstantUpperBound(DstLoop, Delta->getType())) { 1826 DstUM = UpperBound->getValue()->getValue(); 1827 DEBUG(dbgs() << "\t DstUM = " << DstUM << "\n"); 1828 DstUMvalid = true; 1829 } 1830 1831 APInt TU(APInt::getSignedMaxValue(Bits)); 1832 APInt TL(APInt::getSignedMinValue(Bits)); 1833 1834 // test(BM/G, LM-X) and test(-BM/G, X-UM) 1835 APInt TMUL = BM.sdiv(G); 1836 if (TMUL.sgt(0)) { 1837 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL)); 1838 DEBUG(dbgs() << "\t TL = " << TL << "\n"); 1839 if (SrcUMvalid) { 1840 TU = minAPInt(TU, floorOfQuotient(SrcUM - X, TMUL)); 1841 DEBUG(dbgs() << "\t TU = " << TU << "\n"); 1842 } 1843 } 1844 else { 1845 TU = minAPInt(TU, floorOfQuotient(-X, TMUL)); 1846 DEBUG(dbgs() << "\t TU = " << TU << "\n"); 1847 if (SrcUMvalid) { 1848 TL = maxAPInt(TL, ceilingOfQuotient(SrcUM - X, TMUL)); 1849 DEBUG(dbgs() << "\t TL = " << TL << "\n"); 1850 } 1851 } 1852 1853 // test(AM/G, LM-Y) and test(-AM/G, Y-UM) 1854 TMUL = AM.sdiv(G); 1855 if (TMUL.sgt(0)) { 1856 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL)); 1857 DEBUG(dbgs() << "\t TL = " << TL << "\n"); 1858 if (DstUMvalid) { 1859 TU = minAPInt(TU, floorOfQuotient(DstUM - Y, TMUL)); 1860 DEBUG(dbgs() << "\t TU = " << TU << "\n"); 1861 } 1862 } 1863 else { 1864 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL)); 1865 DEBUG(dbgs() << "\t TU = " << TU << "\n"); 1866 if (DstUMvalid) { 1867 TL = maxAPInt(TL, ceilingOfQuotient(DstUM - Y, TMUL)); 1868 DEBUG(dbgs() << "\t TL = " << TL << "\n"); 1869 } 1870 } 1871 if (TL.sgt(TU)) 1872 ++ExactRDIVindependence; 1873 return TL.sgt(TU); 1874 } 1875 1876 1877 // symbolicRDIVtest - 1878 // In Section 4.5 of the Practical Dependence Testing paper,the authors 1879 // introduce a special case of Banerjee's Inequalities (also called the 1880 // Extreme-Value Test) that can handle some of the SIV and RDIV cases, 1881 // particularly cases with symbolics. Since it's only able to disprove 1882 // dependence (not compute distances or directions), we'll use it as a 1883 // fall back for the other tests. 1884 // 1885 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j] 1886 // where i and j are induction variables and c1 and c2 are loop invariants, 1887 // we can use the symbolic tests to disprove some dependences, serving as a 1888 // backup for the RDIV test. Note that i and j can be the same variable, 1889 // letting this test serve as a backup for the various SIV tests. 1890 // 1891 // For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some 1892 // 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized) 1893 // loop bounds for the i and j loops, respectively. So, ... 1894 // 1895 // c1 + a1*i = c2 + a2*j 1896 // a1*i - a2*j = c2 - c1 1897 // 1898 // To test for a dependence, we compute c2 - c1 and make sure it's in the 1899 // range of the maximum and minimum possible values of a1*i - a2*j. 1900 // Considering the signs of a1 and a2, we have 4 possible cases: 1901 // 1902 // 1) If a1 >= 0 and a2 >= 0, then 1903 // a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0 1904 // -a2*N2 <= c2 - c1 <= a1*N1 1905 // 1906 // 2) If a1 >= 0 and a2 <= 0, then 1907 // a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2 1908 // 0 <= c2 - c1 <= a1*N1 - a2*N2 1909 // 1910 // 3) If a1 <= 0 and a2 >= 0, then 1911 // a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0 1912 // a1*N1 - a2*N2 <= c2 - c1 <= 0 1913 // 1914 // 4) If a1 <= 0 and a2 <= 0, then 1915 // a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2 1916 // a1*N1 <= c2 - c1 <= -a2*N2 1917 // 1918 // return true if dependence disproved 1919 bool DependenceAnalysis::symbolicRDIVtest(const SCEV *A1, 1920 const SCEV *A2, 1921 const SCEV *C1, 1922 const SCEV *C2, 1923 const Loop *Loop1, 1924 const Loop *Loop2) const { 1925 ++SymbolicRDIVapplications; 1926 DEBUG(dbgs() << "\ttry symbolic RDIV test\n"); 1927 DEBUG(dbgs() << "\t A1 = " << *A1); 1928 DEBUG(dbgs() << ", type = " << *A1->getType() << "\n"); 1929 DEBUG(dbgs() << "\t A2 = " << *A2 << "\n"); 1930 DEBUG(dbgs() << "\t C1 = " << *C1 << "\n"); 1931 DEBUG(dbgs() << "\t C2 = " << *C2 << "\n"); 1932 const SCEV *N1 = collectUpperBound(Loop1, A1->getType()); 1933 const SCEV *N2 = collectUpperBound(Loop2, A1->getType()); 1934 DEBUG(if (N1) dbgs() << "\t N1 = " << *N1 << "\n"); 1935 DEBUG(if (N2) dbgs() << "\t N2 = " << *N2 << "\n"); 1936 const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1); 1937 const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2); 1938 DEBUG(dbgs() << "\t C2 - C1 = " << *C2_C1 << "\n"); 1939 DEBUG(dbgs() << "\t C1 - C2 = " << *C1_C2 << "\n"); 1940 if (SE->isKnownNonNegative(A1)) { 1941 if (SE->isKnownNonNegative(A2)) { 1942 // A1 >= 0 && A2 >= 0 1943 if (N1) { 1944 // make sure that c2 - c1 <= a1*N1 1945 const SCEV *A1N1 = SE->getMulExpr(A1, N1); 1946 DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n"); 1947 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) { 1948 ++SymbolicRDIVindependence; 1949 return true; 1950 } 1951 } 1952 if (N2) { 1953 // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2 1954 const SCEV *A2N2 = SE->getMulExpr(A2, N2); 1955 DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n"); 1956 if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) { 1957 ++SymbolicRDIVindependence; 1958 return true; 1959 } 1960 } 1961 } 1962 else if (SE->isKnownNonPositive(A2)) { 1963 // a1 >= 0 && a2 <= 0 1964 if (N1 && N2) { 1965 // make sure that c2 - c1 <= a1*N1 - a2*N2 1966 const SCEV *A1N1 = SE->getMulExpr(A1, N1); 1967 const SCEV *A2N2 = SE->getMulExpr(A2, N2); 1968 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2); 1969 DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n"); 1970 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) { 1971 ++SymbolicRDIVindependence; 1972 return true; 1973 } 1974 } 1975 // make sure that 0 <= c2 - c1 1976 if (SE->isKnownNegative(C2_C1)) { 1977 ++SymbolicRDIVindependence; 1978 return true; 1979 } 1980 } 1981 } 1982 else if (SE->isKnownNonPositive(A1)) { 1983 if (SE->isKnownNonNegative(A2)) { 1984 // a1 <= 0 && a2 >= 0 1985 if (N1 && N2) { 1986 // make sure that a1*N1 - a2*N2 <= c2 - c1 1987 const SCEV *A1N1 = SE->getMulExpr(A1, N1); 1988 const SCEV *A2N2 = SE->getMulExpr(A2, N2); 1989 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2); 1990 DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n"); 1991 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) { 1992 ++SymbolicRDIVindependence; 1993 return true; 1994 } 1995 } 1996 // make sure that c2 - c1 <= 0 1997 if (SE->isKnownPositive(C2_C1)) { 1998 ++SymbolicRDIVindependence; 1999 return true; 2000 } 2001 } 2002 else if (SE->isKnownNonPositive(A2)) { 2003 // a1 <= 0 && a2 <= 0 2004 if (N1) { 2005 // make sure that a1*N1 <= c2 - c1 2006 const SCEV *A1N1 = SE->getMulExpr(A1, N1); 2007 DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n"); 2008 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) { 2009 ++SymbolicRDIVindependence; 2010 return true; 2011 } 2012 } 2013 if (N2) { 2014 // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2 2015 const SCEV *A2N2 = SE->getMulExpr(A2, N2); 2016 DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n"); 2017 if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) { 2018 ++SymbolicRDIVindependence; 2019 return true; 2020 } 2021 } 2022 } 2023 } 2024 return false; 2025 } 2026 2027 2028 // testSIV - 2029 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i] 2030 // where i is an induction variable, c1 and c2 are loop invariant, and a1 and 2031 // a2 are constant, we attack it with an SIV test. While they can all be 2032 // solved with the Exact SIV test, it's worthwhile to use simpler tests when 2033 // they apply; they're cheaper and sometimes more precise. 2034 // 2035 // Return true if dependence disproved. 2036 bool DependenceAnalysis::testSIV(const SCEV *Src, 2037 const SCEV *Dst, 2038 unsigned &Level, 2039 FullDependence &Result, 2040 Constraint &NewConstraint, 2041 const SCEV *&SplitIter) const { 2042 DEBUG(dbgs() << " src = " << *Src << "\n"); 2043 DEBUG(dbgs() << " dst = " << *Dst << "\n"); 2044 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src); 2045 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst); 2046 if (SrcAddRec && DstAddRec) { 2047 const SCEV *SrcConst = SrcAddRec->getStart(); 2048 const SCEV *DstConst = DstAddRec->getStart(); 2049 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE); 2050 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE); 2051 const Loop *CurLoop = SrcAddRec->getLoop(); 2052 assert(CurLoop == DstAddRec->getLoop() && 2053 "both loops in SIV should be same"); 2054 Level = mapSrcLoop(CurLoop); 2055 bool disproven; 2056 if (SrcCoeff == DstCoeff) 2057 disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop, 2058 Level, Result, NewConstraint); 2059 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff)) 2060 disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop, 2061 Level, Result, NewConstraint, SplitIter); 2062 else 2063 disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, 2064 Level, Result, NewConstraint); 2065 return disproven || 2066 gcdMIVtest(Src, Dst, Result) || 2067 symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop); 2068 } 2069 if (SrcAddRec) { 2070 const SCEV *SrcConst = SrcAddRec->getStart(); 2071 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE); 2072 const SCEV *DstConst = Dst; 2073 const Loop *CurLoop = SrcAddRec->getLoop(); 2074 Level = mapSrcLoop(CurLoop); 2075 return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop, 2076 Level, Result, NewConstraint) || 2077 gcdMIVtest(Src, Dst, Result); 2078 } 2079 if (DstAddRec) { 2080 const SCEV *DstConst = DstAddRec->getStart(); 2081 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE); 2082 const SCEV *SrcConst = Src; 2083 const Loop *CurLoop = DstAddRec->getLoop(); 2084 Level = mapDstLoop(CurLoop); 2085 return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst, 2086 CurLoop, Level, Result, NewConstraint) || 2087 gcdMIVtest(Src, Dst, Result); 2088 } 2089 llvm_unreachable("SIV test expected at least one AddRec"); 2090 return false; 2091 } 2092 2093 2094 // testRDIV - 2095 // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j] 2096 // where i and j are induction variables, c1 and c2 are loop invariant, 2097 // and a1 and a2 are constant, we can solve it exactly with an easy adaptation 2098 // of the Exact SIV test, the Restricted Double Index Variable (RDIV) test. 2099 // It doesn't make sense to talk about distance or direction in this case, 2100 // so there's no point in making special versions of the Strong SIV test or 2101 // the Weak-crossing SIV test. 2102 // 2103 // With minor algebra, this test can also be used for things like 2104 // [c1 + a1*i + a2*j][c2]. 2105 // 2106 // Return true if dependence disproved. 2107 bool DependenceAnalysis::testRDIV(const SCEV *Src, 2108 const SCEV *Dst, 2109 FullDependence &Result) const { 2110 // we have 3 possible situations here: 2111 // 1) [a*i + b] and [c*j + d] 2112 // 2) [a*i + c*j + b] and [d] 2113 // 3) [b] and [a*i + c*j + d] 2114 // We need to find what we've got and get organized 2115 2116 const SCEV *SrcConst, *DstConst; 2117 const SCEV *SrcCoeff, *DstCoeff; 2118 const Loop *SrcLoop, *DstLoop; 2119 2120 DEBUG(dbgs() << " src = " << *Src << "\n"); 2121 DEBUG(dbgs() << " dst = " << *Dst << "\n"); 2122 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src); 2123 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst); 2124 if (SrcAddRec && DstAddRec) { 2125 SrcConst = SrcAddRec->getStart(); 2126 SrcCoeff = SrcAddRec->getStepRecurrence(*SE); 2127 SrcLoop = SrcAddRec->getLoop(); 2128 DstConst = DstAddRec->getStart(); 2129 DstCoeff = DstAddRec->getStepRecurrence(*SE); 2130 DstLoop = DstAddRec->getLoop(); 2131 } 2132 else if (SrcAddRec) { 2133 if (const SCEVAddRecExpr *tmpAddRec = 2134 dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) { 2135 SrcConst = tmpAddRec->getStart(); 2136 SrcCoeff = tmpAddRec->getStepRecurrence(*SE); 2137 SrcLoop = tmpAddRec->getLoop(); 2138 DstConst = Dst; 2139 DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE)); 2140 DstLoop = SrcAddRec->getLoop(); 2141 } 2142 else 2143 llvm_unreachable("RDIV reached by surprising SCEVs"); 2144 } 2145 else if (DstAddRec) { 2146 if (const SCEVAddRecExpr *tmpAddRec = 2147 dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) { 2148 DstConst = tmpAddRec->getStart(); 2149 DstCoeff = tmpAddRec->getStepRecurrence(*SE); 2150 DstLoop = tmpAddRec->getLoop(); 2151 SrcConst = Src; 2152 SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE)); 2153 SrcLoop = DstAddRec->getLoop(); 2154 } 2155 else 2156 llvm_unreachable("RDIV reached by surprising SCEVs"); 2157 } 2158 else 2159 llvm_unreachable("RDIV expected at least one AddRec"); 2160 return exactRDIVtest(SrcCoeff, DstCoeff, 2161 SrcConst, DstConst, 2162 SrcLoop, DstLoop, 2163 Result) || 2164 gcdMIVtest(Src, Dst, Result) || 2165 symbolicRDIVtest(SrcCoeff, DstCoeff, 2166 SrcConst, DstConst, 2167 SrcLoop, DstLoop); 2168 } 2169 2170 2171 // Tests the single-subscript MIV pair (Src and Dst) for dependence. 2172 // Return true if dependence disproved. 2173 // Can sometimes refine direction vectors. 2174 bool DependenceAnalysis::testMIV(const SCEV *Src, 2175 const SCEV *Dst, 2176 const SmallBitVector &Loops, 2177 FullDependence &Result) const { 2178 DEBUG(dbgs() << " src = " << *Src << "\n"); 2179 DEBUG(dbgs() << " dst = " << *Dst << "\n"); 2180 Result.Consistent = false; 2181 return gcdMIVtest(Src, Dst, Result) || 2182 banerjeeMIVtest(Src, Dst, Loops, Result); 2183 } 2184 2185 2186 // Given a product, e.g., 10*X*Y, returns the first constant operand, 2187 // in this case 10. If there is no constant part, returns NULL. 2188 static 2189 const SCEVConstant *getConstantPart(const SCEVMulExpr *Product) { 2190 for (unsigned Op = 0, Ops = Product->getNumOperands(); Op < Ops; Op++) { 2191 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Product->getOperand(Op))) 2192 return Constant; 2193 } 2194 return NULL; 2195 } 2196 2197 2198 //===----------------------------------------------------------------------===// 2199 // gcdMIVtest - 2200 // Tests an MIV subscript pair for dependence. 2201 // Returns true if any possible dependence is disproved. 2202 // Marks the result as inconsistent. 2203 // Can sometimes disprove the equal direction for 1 or more loops, 2204 // as discussed in Michael Wolfe's book, 2205 // High Performance Compilers for Parallel Computing, page 235. 2206 // 2207 // We spend some effort (code!) to handle cases like 2208 // [10*i + 5*N*j + 15*M + 6], where i and j are induction variables, 2209 // but M and N are just loop-invariant variables. 2210 // This should help us handle linearized subscripts; 2211 // also makes this test a useful backup to the various SIV tests. 2212 // 2213 // It occurs to me that the presence of loop-invariant variables 2214 // changes the nature of the test from "greatest common divisor" 2215 // to "a common divisor!" 2216 bool DependenceAnalysis::gcdMIVtest(const SCEV *Src, 2217 const SCEV *Dst, 2218 FullDependence &Result) const { 2219 DEBUG(dbgs() << "starting gcd\n"); 2220 ++GCDapplications; 2221 unsigned BitWidth = SE->getTypeSizeInBits(Src->getType()); 2222 APInt RunningGCD = APInt::getNullValue(BitWidth); 2223 2224 // Examine Src coefficients. 2225 // Compute running GCD and record source constant. 2226 // Because we're looking for the constant at the end of the chain, 2227 // we can't quit the loop just because the GCD == 1. 2228 const SCEV *Coefficients = Src; 2229 while (const SCEVAddRecExpr *AddRec = 2230 dyn_cast<SCEVAddRecExpr>(Coefficients)) { 2231 const SCEV *Coeff = AddRec->getStepRecurrence(*SE); 2232 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff); 2233 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff)) 2234 // If the coefficient is the product of a constant and other stuff, 2235 // we can use the constant in the GCD computation. 2236 Constant = getConstantPart(Product); 2237 if (!Constant) 2238 return false; 2239 APInt ConstCoeff = Constant->getValue()->getValue(); 2240 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs()); 2241 Coefficients = AddRec->getStart(); 2242 } 2243 const SCEV *SrcConst = Coefficients; 2244 2245 // Examine Dst coefficients. 2246 // Compute running GCD and record destination constant. 2247 // Because we're looking for the constant at the end of the chain, 2248 // we can't quit the loop just because the GCD == 1. 2249 Coefficients = Dst; 2250 while (const SCEVAddRecExpr *AddRec = 2251 dyn_cast<SCEVAddRecExpr>(Coefficients)) { 2252 const SCEV *Coeff = AddRec->getStepRecurrence(*SE); 2253 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Coeff); 2254 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff)) 2255 // If the coefficient is the product of a constant and other stuff, 2256 // we can use the constant in the GCD computation. 2257 Constant = getConstantPart(Product); 2258 if (!Constant) 2259 return false; 2260 APInt ConstCoeff = Constant->getValue()->getValue(); 2261 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs()); 2262 Coefficients = AddRec->getStart(); 2263 } 2264 const SCEV *DstConst = Coefficients; 2265 2266 APInt ExtraGCD = APInt::getNullValue(BitWidth); 2267 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst); 2268 DEBUG(dbgs() << " Delta = " << *Delta << "\n"); 2269 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta); 2270 if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) { 2271 // If Delta is a sum of products, we may be able to make further progress. 2272 for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) { 2273 const SCEV *Operand = Sum->getOperand(Op); 2274 if (isa<SCEVConstant>(Operand)) { 2275 assert(!Constant && "Surprised to find multiple constants"); 2276 Constant = cast<SCEVConstant>(Operand); 2277 } 2278 else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) { 2279 // Search for constant operand to participate in GCD; 2280 // If none found; return false. 2281 const SCEVConstant *ConstOp = getConstantPart(Product); 2282 if (!ConstOp) 2283 return false; 2284 APInt ConstOpValue = ConstOp->getValue()->getValue(); 2285 ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD, 2286 ConstOpValue.abs()); 2287 } 2288 else 2289 return false; 2290 } 2291 } 2292 if (!Constant) 2293 return false; 2294 APInt ConstDelta = cast<SCEVConstant>(Constant)->getValue()->getValue(); 2295 DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n"); 2296 if (ConstDelta == 0) 2297 return false; 2298 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD); 2299 DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n"); 2300 APInt Remainder = ConstDelta.srem(RunningGCD); 2301 if (Remainder != 0) { 2302 ++GCDindependence; 2303 return true; 2304 } 2305 2306 // Try to disprove equal directions. 2307 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1], 2308 // the code above can't disprove the dependence because the GCD = 1. 2309 // So we consider what happen if i = i' and what happens if j = j'. 2310 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1], 2311 // which is infeasible, so we can disallow the = direction for the i level. 2312 // Setting j = j' doesn't help matters, so we end up with a direction vector 2313 // of [<>, *] 2314 // 2315 // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5], 2316 // we need to remember that the constant part is 5 and the RunningGCD should 2317 // be initialized to ExtraGCD = 30. 2318 DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n'); 2319 2320 bool Improved = false; 2321 Coefficients = Src; 2322 while (const SCEVAddRecExpr *AddRec = 2323 dyn_cast<SCEVAddRecExpr>(Coefficients)) { 2324 Coefficients = AddRec->getStart(); 2325 const Loop *CurLoop = AddRec->getLoop(); 2326 RunningGCD = ExtraGCD; 2327 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE); 2328 const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff); 2329 const SCEV *Inner = Src; 2330 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) { 2331 AddRec = cast<SCEVAddRecExpr>(Inner); 2332 const SCEV *Coeff = AddRec->getStepRecurrence(*SE); 2333 if (CurLoop == AddRec->getLoop()) 2334 ; // SrcCoeff == Coeff 2335 else { 2336 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff)) 2337 // If the coefficient is the product of a constant and other stuff, 2338 // we can use the constant in the GCD computation. 2339 Constant = getConstantPart(Product); 2340 else 2341 Constant = cast<SCEVConstant>(Coeff); 2342 APInt ConstCoeff = Constant->getValue()->getValue(); 2343 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs()); 2344 } 2345 Inner = AddRec->getStart(); 2346 } 2347 Inner = Dst; 2348 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) { 2349 AddRec = cast<SCEVAddRecExpr>(Inner); 2350 const SCEV *Coeff = AddRec->getStepRecurrence(*SE); 2351 if (CurLoop == AddRec->getLoop()) 2352 DstCoeff = Coeff; 2353 else { 2354 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Coeff)) 2355 // If the coefficient is the product of a constant and other stuff, 2356 // we can use the constant in the GCD computation. 2357 Constant = getConstantPart(Product); 2358 else 2359 Constant = cast<SCEVConstant>(Coeff); 2360 APInt ConstCoeff = Constant->getValue()->getValue(); 2361 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs()); 2362 } 2363 Inner = AddRec->getStart(); 2364 } 2365 Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff); 2366 if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Delta)) 2367 // If the coefficient is the product of a constant and other stuff, 2368 // we can use the constant in the GCD computation. 2369 Constant = getConstantPart(Product); 2370 else if (isa<SCEVConstant>(Delta)) 2371 Constant = cast<SCEVConstant>(Delta); 2372 else { 2373 // The difference of the two coefficients might not be a product 2374 // or constant, in which case we give up on this direction. 2375 continue; 2376 } 2377 APInt ConstCoeff = Constant->getValue()->getValue(); 2378 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs()); 2379 DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n"); 2380 if (RunningGCD != 0) { 2381 Remainder = ConstDelta.srem(RunningGCD); 2382 DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n"); 2383 if (Remainder != 0) { 2384 unsigned Level = mapSrcLoop(CurLoop); 2385 Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ); 2386 Improved = true; 2387 } 2388 } 2389 } 2390 if (Improved) 2391 ++GCDsuccesses; 2392 DEBUG(dbgs() << "all done\n"); 2393 return false; 2394 } 2395 2396 2397 //===----------------------------------------------------------------------===// 2398 // banerjeeMIVtest - 2399 // Use Banerjee's Inequalities to test an MIV subscript pair. 2400 // (Wolfe, in the race-car book, calls this the Extreme Value Test.) 2401 // Generally follows the discussion in Section 2.5.2 of 2402 // 2403 // Optimizing Supercompilers for Supercomputers 2404 // Michael Wolfe 2405 // 2406 // The inequalities given on page 25 are simplified in that loops are 2407 // normalized so that the lower bound is always 0 and the stride is always 1. 2408 // For example, Wolfe gives 2409 // 2410 // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k 2411 // 2412 // where A_k is the coefficient of the kth index in the source subscript, 2413 // B_k is the coefficient of the kth index in the destination subscript, 2414 // U_k is the upper bound of the kth index, L_k is the lower bound of the Kth 2415 // index, and N_k is the stride of the kth index. Since all loops are normalized 2416 // by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the 2417 // equation to 2418 // 2419 // LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1 2420 // = (A^-_k - B_k)^- (U_k - 1) - B_k 2421 // 2422 // Similar simplifications are possible for the other equations. 2423 // 2424 // When we can't determine the number of iterations for a loop, 2425 // we use NULL as an indicator for the worst case, infinity. 2426 // When computing the upper bound, NULL denotes +inf; 2427 // for the lower bound, NULL denotes -inf. 2428 // 2429 // Return true if dependence disproved. 2430 bool DependenceAnalysis::banerjeeMIVtest(const SCEV *Src, 2431 const SCEV *Dst, 2432 const SmallBitVector &Loops, 2433 FullDependence &Result) const { 2434 DEBUG(dbgs() << "starting Banerjee\n"); 2435 ++BanerjeeApplications; 2436 DEBUG(dbgs() << " Src = " << *Src << '\n'); 2437 const SCEV *A0; 2438 CoefficientInfo *A = collectCoeffInfo(Src, true, A0); 2439 DEBUG(dbgs() << " Dst = " << *Dst << '\n'); 2440 const SCEV *B0; 2441 CoefficientInfo *B = collectCoeffInfo(Dst, false, B0); 2442 BoundInfo *Bound = new BoundInfo[MaxLevels + 1]; 2443 const SCEV *Delta = SE->getMinusSCEV(B0, A0); 2444 DEBUG(dbgs() << "\tDelta = " << *Delta << '\n'); 2445 2446 // Compute bounds for all the * directions. 2447 DEBUG(dbgs() << "\tBounds[*]\n"); 2448 for (unsigned K = 1; K <= MaxLevels; ++K) { 2449 Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations; 2450 Bound[K].Direction = Dependence::DVEntry::ALL; 2451 Bound[K].DirSet = Dependence::DVEntry::NONE; 2452 findBoundsALL(A, B, Bound, K); 2453 #ifndef NDEBUG 2454 DEBUG(dbgs() << "\t " << K << '\t'); 2455 if (Bound[K].Lower[Dependence::DVEntry::ALL]) 2456 DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t'); 2457 else 2458 DEBUG(dbgs() << "-inf\t"); 2459 if (Bound[K].Upper[Dependence::DVEntry::ALL]) 2460 DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n'); 2461 else 2462 DEBUG(dbgs() << "+inf\n"); 2463 #endif 2464 } 2465 2466 // Test the *, *, *, ... case. 2467 bool Disproved = false; 2468 if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) { 2469 // Explore the direction vector hierarchy. 2470 unsigned DepthExpanded = 0; 2471 unsigned NewDeps = exploreDirections(1, A, B, Bound, 2472 Loops, DepthExpanded, Delta); 2473 if (NewDeps > 0) { 2474 bool Improved = false; 2475 for (unsigned K = 1; K <= CommonLevels; ++K) { 2476 if (Loops[K]) { 2477 unsigned Old = Result.DV[K - 1].Direction; 2478 Result.DV[K - 1].Direction = Old & Bound[K].DirSet; 2479 Improved |= Old != Result.DV[K - 1].Direction; 2480 if (!Result.DV[K - 1].Direction) { 2481 Improved = false; 2482 Disproved = true; 2483 break; 2484 } 2485 } 2486 } 2487 if (Improved) 2488 ++BanerjeeSuccesses; 2489 } 2490 else { 2491 ++BanerjeeIndependence; 2492 Disproved = true; 2493 } 2494 } 2495 else { 2496 ++BanerjeeIndependence; 2497 Disproved = true; 2498 } 2499 delete [] Bound; 2500 delete [] A; 2501 delete [] B; 2502 return Disproved; 2503 } 2504 2505 2506 // Hierarchically expands the direction vector 2507 // search space, combining the directions of discovered dependences 2508 // in the DirSet field of Bound. Returns the number of distinct 2509 // dependences discovered. If the dependence is disproved, 2510 // it will return 0. 2511 unsigned DependenceAnalysis::exploreDirections(unsigned Level, 2512 CoefficientInfo *A, 2513 CoefficientInfo *B, 2514 BoundInfo *Bound, 2515 const SmallBitVector &Loops, 2516 unsigned &DepthExpanded, 2517 const SCEV *Delta) const { 2518 if (Level > CommonLevels) { 2519 // record result 2520 DEBUG(dbgs() << "\t["); 2521 for (unsigned K = 1; K <= CommonLevels; ++K) { 2522 if (Loops[K]) { 2523 Bound[K].DirSet |= Bound[K].Direction; 2524 #ifndef NDEBUG 2525 switch (Bound[K].Direction) { 2526 case Dependence::DVEntry::LT: 2527 DEBUG(dbgs() << " <"); 2528 break; 2529 case Dependence::DVEntry::EQ: 2530 DEBUG(dbgs() << " ="); 2531 break; 2532 case Dependence::DVEntry::GT: 2533 DEBUG(dbgs() << " >"); 2534 break; 2535 case Dependence::DVEntry::ALL: 2536 DEBUG(dbgs() << " *"); 2537 break; 2538 default: 2539 llvm_unreachable("unexpected Bound[K].Direction"); 2540 } 2541 #endif 2542 } 2543 } 2544 DEBUG(dbgs() << " ]\n"); 2545 return 1; 2546 } 2547 if (Loops[Level]) { 2548 if (Level > DepthExpanded) { 2549 DepthExpanded = Level; 2550 // compute bounds for <, =, > at current level 2551 findBoundsLT(A, B, Bound, Level); 2552 findBoundsGT(A, B, Bound, Level); 2553 findBoundsEQ(A, B, Bound, Level); 2554 #ifndef NDEBUG 2555 DEBUG(dbgs() << "\tBound for level = " << Level << '\n'); 2556 DEBUG(dbgs() << "\t <\t"); 2557 if (Bound[Level].Lower[Dependence::DVEntry::LT]) 2558 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT] << '\t'); 2559 else 2560 DEBUG(dbgs() << "-inf\t"); 2561 if (Bound[Level].Upper[Dependence::DVEntry::LT]) 2562 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT] << '\n'); 2563 else 2564 DEBUG(dbgs() << "+inf\n"); 2565 DEBUG(dbgs() << "\t =\t"); 2566 if (Bound[Level].Lower[Dependence::DVEntry::EQ]) 2567 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ] << '\t'); 2568 else 2569 DEBUG(dbgs() << "-inf\t"); 2570 if (Bound[Level].Upper[Dependence::DVEntry::EQ]) 2571 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ] << '\n'); 2572 else 2573 DEBUG(dbgs() << "+inf\n"); 2574 DEBUG(dbgs() << "\t >\t"); 2575 if (Bound[Level].Lower[Dependence::DVEntry::GT]) 2576 DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT] << '\t'); 2577 else 2578 DEBUG(dbgs() << "-inf\t"); 2579 if (Bound[Level].Upper[Dependence::DVEntry::GT]) 2580 DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT] << '\n'); 2581 else 2582 DEBUG(dbgs() << "+inf\n"); 2583 #endif 2584 } 2585 2586 unsigned NewDeps = 0; 2587 2588 // test bounds for <, *, *, ... 2589 if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta)) 2590 NewDeps += exploreDirections(Level + 1, A, B, Bound, 2591 Loops, DepthExpanded, Delta); 2592 2593 // Test bounds for =, *, *, ... 2594 if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta)) 2595 NewDeps += exploreDirections(Level + 1, A, B, Bound, 2596 Loops, DepthExpanded, Delta); 2597 2598 // test bounds for >, *, *, ... 2599 if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta)) 2600 NewDeps += exploreDirections(Level + 1, A, B, Bound, 2601 Loops, DepthExpanded, Delta); 2602 2603 Bound[Level].Direction = Dependence::DVEntry::ALL; 2604 return NewDeps; 2605 } 2606 else 2607 return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta); 2608 } 2609 2610 2611 // Returns true iff the current bounds are plausible. 2612 bool DependenceAnalysis::testBounds(unsigned char DirKind, 2613 unsigned Level, 2614 BoundInfo *Bound, 2615 const SCEV *Delta) const { 2616 Bound[Level].Direction = DirKind; 2617 if (const SCEV *LowerBound = getLowerBound(Bound)) 2618 if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta)) 2619 return false; 2620 if (const SCEV *UpperBound = getUpperBound(Bound)) 2621 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound)) 2622 return false; 2623 return true; 2624 } 2625 2626 2627 // Computes the upper and lower bounds for level K 2628 // using the * direction. Records them in Bound. 2629 // Wolfe gives the equations 2630 // 2631 // LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k 2632 // UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k 2633 // 2634 // Since we normalize loops, we can simplify these equations to 2635 // 2636 // LB^*_k = (A^-_k - B^+_k)U_k 2637 // UB^*_k = (A^+_k - B^-_k)U_k 2638 // 2639 // We must be careful to handle the case where the upper bound is unknown. 2640 // Note that the lower bound is always <= 0 2641 // and the upper bound is always >= 0. 2642 void DependenceAnalysis::findBoundsALL(CoefficientInfo *A, 2643 CoefficientInfo *B, 2644 BoundInfo *Bound, 2645 unsigned K) const { 2646 Bound[K].Lower[Dependence::DVEntry::ALL] = NULL; // Default value = -infinity. 2647 Bound[K].Upper[Dependence::DVEntry::ALL] = NULL; // Default value = +infinity. 2648 if (Bound[K].Iterations) { 2649 Bound[K].Lower[Dependence::DVEntry::ALL] = 2650 SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart), 2651 Bound[K].Iterations); 2652 Bound[K].Upper[Dependence::DVEntry::ALL] = 2653 SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart), 2654 Bound[K].Iterations); 2655 } 2656 else { 2657 // If the difference is 0, we won't need to know the number of iterations. 2658 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart)) 2659 Bound[K].Lower[Dependence::DVEntry::ALL] = 2660 SE->getConstant(A[K].Coeff->getType(), 0); 2661 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart)) 2662 Bound[K].Upper[Dependence::DVEntry::ALL] = 2663 SE->getConstant(A[K].Coeff->getType(), 0); 2664 } 2665 } 2666 2667 2668 // Computes the upper and lower bounds for level K 2669 // using the = direction. Records them in Bound. 2670 // Wolfe gives the equations 2671 // 2672 // LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k 2673 // UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k 2674 // 2675 // Since we normalize loops, we can simplify these equations to 2676 // 2677 // LB^=_k = (A_k - B_k)^- U_k 2678 // UB^=_k = (A_k - B_k)^+ U_k 2679 // 2680 // We must be careful to handle the case where the upper bound is unknown. 2681 // Note that the lower bound is always <= 0 2682 // and the upper bound is always >= 0. 2683 void DependenceAnalysis::findBoundsEQ(CoefficientInfo *A, 2684 CoefficientInfo *B, 2685 BoundInfo *Bound, 2686 unsigned K) const { 2687 Bound[K].Lower[Dependence::DVEntry::EQ] = NULL; // Default value = -infinity. 2688 Bound[K].Upper[Dependence::DVEntry::EQ] = NULL; // Default value = +infinity. 2689 if (Bound[K].Iterations) { 2690 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff); 2691 const SCEV *NegativePart = getNegativePart(Delta); 2692 Bound[K].Lower[Dependence::DVEntry::EQ] = 2693 SE->getMulExpr(NegativePart, Bound[K].Iterations); 2694 const SCEV *PositivePart = getPositivePart(Delta); 2695 Bound[K].Upper[Dependence::DVEntry::EQ] = 2696 SE->getMulExpr(PositivePart, Bound[K].Iterations); 2697 } 2698 else { 2699 // If the positive/negative part of the difference is 0, 2700 // we won't need to know the number of iterations. 2701 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff); 2702 const SCEV *NegativePart = getNegativePart(Delta); 2703 if (NegativePart->isZero()) 2704 Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero 2705 const SCEV *PositivePart = getPositivePart(Delta); 2706 if (PositivePart->isZero()) 2707 Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero 2708 } 2709 } 2710 2711 2712 // Computes the upper and lower bounds for level K 2713 // using the < direction. Records them in Bound. 2714 // Wolfe gives the equations 2715 // 2716 // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k 2717 // UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k 2718 // 2719 // Since we normalize loops, we can simplify these equations to 2720 // 2721 // LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k 2722 // UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k 2723 // 2724 // We must be careful to handle the case where the upper bound is unknown. 2725 void DependenceAnalysis::findBoundsLT(CoefficientInfo *A, 2726 CoefficientInfo *B, 2727 BoundInfo *Bound, 2728 unsigned K) const { 2729 Bound[K].Lower[Dependence::DVEntry::LT] = NULL; // Default value = -infinity. 2730 Bound[K].Upper[Dependence::DVEntry::LT] = NULL; // Default value = +infinity. 2731 if (Bound[K].Iterations) { 2732 const SCEV *Iter_1 = 2733 SE->getMinusSCEV(Bound[K].Iterations, 2734 SE->getConstant(Bound[K].Iterations->getType(), 1)); 2735 const SCEV *NegPart = 2736 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff)); 2737 Bound[K].Lower[Dependence::DVEntry::LT] = 2738 SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff); 2739 const SCEV *PosPart = 2740 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff)); 2741 Bound[K].Upper[Dependence::DVEntry::LT] = 2742 SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff); 2743 } 2744 else { 2745 // If the positive/negative part of the difference is 0, 2746 // we won't need to know the number of iterations. 2747 const SCEV *NegPart = 2748 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff)); 2749 if (NegPart->isZero()) 2750 Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff); 2751 const SCEV *PosPart = 2752 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff)); 2753 if (PosPart->isZero()) 2754 Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff); 2755 } 2756 } 2757 2758 2759 // Computes the upper and lower bounds for level K 2760 // using the > direction. Records them in Bound. 2761 // Wolfe gives the equations 2762 // 2763 // LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k 2764 // UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k 2765 // 2766 // Since we normalize loops, we can simplify these equations to 2767 // 2768 // LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k 2769 // UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k 2770 // 2771 // We must be careful to handle the case where the upper bound is unknown. 2772 void DependenceAnalysis::findBoundsGT(CoefficientInfo *A, 2773 CoefficientInfo *B, 2774 BoundInfo *Bound, 2775 unsigned K) const { 2776 Bound[K].Lower[Dependence::DVEntry::GT] = NULL; // Default value = -infinity. 2777 Bound[K].Upper[Dependence::DVEntry::GT] = NULL; // Default value = +infinity. 2778 if (Bound[K].Iterations) { 2779 const SCEV *Iter_1 = 2780 SE->getMinusSCEV(Bound[K].Iterations, 2781 SE->getConstant(Bound[K].Iterations->getType(), 1)); 2782 const SCEV *NegPart = 2783 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart)); 2784 Bound[K].Lower[Dependence::DVEntry::GT] = 2785 SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff); 2786 const SCEV *PosPart = 2787 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart)); 2788 Bound[K].Upper[Dependence::DVEntry::GT] = 2789 SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff); 2790 } 2791 else { 2792 // If the positive/negative part of the difference is 0, 2793 // we won't need to know the number of iterations. 2794 const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart)); 2795 if (NegPart->isZero()) 2796 Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff; 2797 const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart)); 2798 if (PosPart->isZero()) 2799 Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff; 2800 } 2801 } 2802 2803 2804 // X^+ = max(X, 0) 2805 const SCEV *DependenceAnalysis::getPositivePart(const SCEV *X) const { 2806 return SE->getSMaxExpr(X, SE->getConstant(X->getType(), 0)); 2807 } 2808 2809 2810 // X^- = min(X, 0) 2811 const SCEV *DependenceAnalysis::getNegativePart(const SCEV *X) const { 2812 return SE->getSMinExpr(X, SE->getConstant(X->getType(), 0)); 2813 } 2814 2815 2816 // Walks through the subscript, 2817 // collecting each coefficient, the associated loop bounds, 2818 // and recording its positive and negative parts for later use. 2819 DependenceAnalysis::CoefficientInfo * 2820 DependenceAnalysis::collectCoeffInfo(const SCEV *Subscript, 2821 bool SrcFlag, 2822 const SCEV *&Constant) const { 2823 const SCEV *Zero = SE->getConstant(Subscript->getType(), 0); 2824 CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1]; 2825 for (unsigned K = 1; K <= MaxLevels; ++K) { 2826 CI[K].Coeff = Zero; 2827 CI[K].PosPart = Zero; 2828 CI[K].NegPart = Zero; 2829 CI[K].Iterations = NULL; 2830 } 2831 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) { 2832 const Loop *L = AddRec->getLoop(); 2833 unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L); 2834 CI[K].Coeff = AddRec->getStepRecurrence(*SE); 2835 CI[K].PosPart = getPositivePart(CI[K].Coeff); 2836 CI[K].NegPart = getNegativePart(CI[K].Coeff); 2837 CI[K].Iterations = collectUpperBound(L, Subscript->getType()); 2838 Subscript = AddRec->getStart(); 2839 } 2840 Constant = Subscript; 2841 #ifndef NDEBUG 2842 DEBUG(dbgs() << "\tCoefficient Info\n"); 2843 for (unsigned K = 1; K <= MaxLevels; ++K) { 2844 DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff); 2845 DEBUG(dbgs() << "\tPos Part = "); 2846 DEBUG(dbgs() << *CI[K].PosPart); 2847 DEBUG(dbgs() << "\tNeg Part = "); 2848 DEBUG(dbgs() << *CI[K].NegPart); 2849 DEBUG(dbgs() << "\tUpper Bound = "); 2850 if (CI[K].Iterations) 2851 DEBUG(dbgs() << *CI[K].Iterations); 2852 else 2853 DEBUG(dbgs() << "+inf"); 2854 DEBUG(dbgs() << '\n'); 2855 } 2856 DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n'); 2857 #endif 2858 return CI; 2859 } 2860 2861 2862 // Looks through all the bounds info and 2863 // computes the lower bound given the current direction settings 2864 // at each level. If the lower bound for any level is -inf, 2865 // the result is -inf. 2866 const SCEV *DependenceAnalysis::getLowerBound(BoundInfo *Bound) const { 2867 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction]; 2868 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) { 2869 if (Bound[K].Lower[Bound[K].Direction]) 2870 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]); 2871 else 2872 Sum = NULL; 2873 } 2874 return Sum; 2875 } 2876 2877 2878 // Looks through all the bounds info and 2879 // computes the upper bound given the current direction settings 2880 // at each level. If the upper bound at any level is +inf, 2881 // the result is +inf. 2882 const SCEV *DependenceAnalysis::getUpperBound(BoundInfo *Bound) const { 2883 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction]; 2884 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) { 2885 if (Bound[K].Upper[Bound[K].Direction]) 2886 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]); 2887 else 2888 Sum = NULL; 2889 } 2890 return Sum; 2891 } 2892 2893 2894 //===----------------------------------------------------------------------===// 2895 // Constraint manipulation for Delta test. 2896 2897 // Given a linear SCEV, 2898 // return the coefficient (the step) 2899 // corresponding to the specified loop. 2900 // If there isn't one, return 0. 2901 // For example, given a*i + b*j + c*k, zeroing the coefficient 2902 // corresponding to the j loop would yield b. 2903 const SCEV *DependenceAnalysis::findCoefficient(const SCEV *Expr, 2904 const Loop *TargetLoop) const { 2905 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr); 2906 if (!AddRec) 2907 return SE->getConstant(Expr->getType(), 0); 2908 if (AddRec->getLoop() == TargetLoop) 2909 return AddRec->getStepRecurrence(*SE); 2910 return findCoefficient(AddRec->getStart(), TargetLoop); 2911 } 2912 2913 2914 // Given a linear SCEV, 2915 // return the SCEV given by zeroing out the coefficient 2916 // corresponding to the specified loop. 2917 // For example, given a*i + b*j + c*k, zeroing the coefficient 2918 // corresponding to the j loop would yield a*i + c*k. 2919 const SCEV *DependenceAnalysis::zeroCoefficient(const SCEV *Expr, 2920 const Loop *TargetLoop) const { 2921 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr); 2922 if (!AddRec) 2923 return Expr; // ignore 2924 if (AddRec->getLoop() == TargetLoop) 2925 return AddRec->getStart(); 2926 return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop), 2927 AddRec->getStepRecurrence(*SE), 2928 AddRec->getLoop(), 2929 AddRec->getNoWrapFlags()); 2930 } 2931 2932 2933 // Given a linear SCEV Expr, 2934 // return the SCEV given by adding some Value to the 2935 // coefficient corresponding to the specified TargetLoop. 2936 // For example, given a*i + b*j + c*k, adding 1 to the coefficient 2937 // corresponding to the j loop would yield a*i + (b+1)*j + c*k. 2938 const SCEV *DependenceAnalysis::addToCoefficient(const SCEV *Expr, 2939 const Loop *TargetLoop, 2940 const SCEV *Value) const { 2941 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr); 2942 if (!AddRec) // create a new addRec 2943 return SE->getAddRecExpr(Expr, 2944 Value, 2945 TargetLoop, 2946 SCEV::FlagAnyWrap); // Worst case, with no info. 2947 if (AddRec->getLoop() == TargetLoop) { 2948 const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value); 2949 if (Sum->isZero()) 2950 return AddRec->getStart(); 2951 return SE->getAddRecExpr(AddRec->getStart(), 2952 Sum, 2953 AddRec->getLoop(), 2954 AddRec->getNoWrapFlags()); 2955 } 2956 return SE->getAddRecExpr(addToCoefficient(AddRec->getStart(), 2957 TargetLoop, Value), 2958 AddRec->getStepRecurrence(*SE), 2959 AddRec->getLoop(), 2960 AddRec->getNoWrapFlags()); 2961 } 2962 2963 2964 // Review the constraints, looking for opportunities 2965 // to simplify a subscript pair (Src and Dst). 2966 // Return true if some simplification occurs. 2967 // If the simplification isn't exact (that is, if it is conservative 2968 // in terms of dependence), set consistent to false. 2969 // Corresponds to Figure 5 from the paper 2970 // 2971 // Practical Dependence Testing 2972 // Goff, Kennedy, Tseng 2973 // PLDI 1991 2974 bool DependenceAnalysis::propagate(const SCEV *&Src, 2975 const SCEV *&Dst, 2976 SmallBitVector &Loops, 2977 SmallVector<Constraint, 4> &Constraints, 2978 bool &Consistent) { 2979 bool Result = false; 2980 for (int LI = Loops.find_first(); LI >= 0; LI = Loops.find_next(LI)) { 2981 DEBUG(dbgs() << "\t Constraint[" << LI << "] is"); 2982 DEBUG(Constraints[LI].dump(dbgs())); 2983 if (Constraints[LI].isDistance()) 2984 Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent); 2985 else if (Constraints[LI].isLine()) 2986 Result |= propagateLine(Src, Dst, Constraints[LI], Consistent); 2987 else if (Constraints[LI].isPoint()) 2988 Result |= propagatePoint(Src, Dst, Constraints[LI]); 2989 } 2990 return Result; 2991 } 2992 2993 2994 // Attempt to propagate a distance 2995 // constraint into a subscript pair (Src and Dst). 2996 // Return true if some simplification occurs. 2997 // If the simplification isn't exact (that is, if it is conservative 2998 // in terms of dependence), set consistent to false. 2999 bool DependenceAnalysis::propagateDistance(const SCEV *&Src, 3000 const SCEV *&Dst, 3001 Constraint &CurConstraint, 3002 bool &Consistent) { 3003 const Loop *CurLoop = CurConstraint.getAssociatedLoop(); 3004 DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n"); 3005 const SCEV *A_K = findCoefficient(Src, CurLoop); 3006 if (A_K->isZero()) 3007 return false; 3008 const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD()); 3009 Src = SE->getMinusSCEV(Src, DA_K); 3010 Src = zeroCoefficient(Src, CurLoop); 3011 DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n"); 3012 DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n"); 3013 Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K)); 3014 DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n"); 3015 if (!findCoefficient(Dst, CurLoop)->isZero()) 3016 Consistent = false; 3017 return true; 3018 } 3019 3020 3021 // Attempt to propagate a line 3022 // constraint into a subscript pair (Src and Dst). 3023 // Return true if some simplification occurs. 3024 // If the simplification isn't exact (that is, if it is conservative 3025 // in terms of dependence), set consistent to false. 3026 bool DependenceAnalysis::propagateLine(const SCEV *&Src, 3027 const SCEV *&Dst, 3028 Constraint &CurConstraint, 3029 bool &Consistent) { 3030 const Loop *CurLoop = CurConstraint.getAssociatedLoop(); 3031 const SCEV *A = CurConstraint.getA(); 3032 const SCEV *B = CurConstraint.getB(); 3033 const SCEV *C = CurConstraint.getC(); 3034 DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C << "\n"); 3035 DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n"); 3036 DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n"); 3037 if (A->isZero()) { 3038 const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B); 3039 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C); 3040 if (!Bconst || !Cconst) return false; 3041 APInt Beta = Bconst->getValue()->getValue(); 3042 APInt Charlie = Cconst->getValue()->getValue(); 3043 APInt CdivB = Charlie.sdiv(Beta); 3044 assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B"); 3045 const SCEV *AP_K = findCoefficient(Dst, CurLoop); 3046 // Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB))); 3047 Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB))); 3048 Dst = zeroCoefficient(Dst, CurLoop); 3049 if (!findCoefficient(Src, CurLoop)->isZero()) 3050 Consistent = false; 3051 } 3052 else if (B->isZero()) { 3053 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A); 3054 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C); 3055 if (!Aconst || !Cconst) return false; 3056 APInt Alpha = Aconst->getValue()->getValue(); 3057 APInt Charlie = Cconst->getValue()->getValue(); 3058 APInt CdivA = Charlie.sdiv(Alpha); 3059 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A"); 3060 const SCEV *A_K = findCoefficient(Src, CurLoop); 3061 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA))); 3062 Src = zeroCoefficient(Src, CurLoop); 3063 if (!findCoefficient(Dst, CurLoop)->isZero()) 3064 Consistent = false; 3065 } 3066 else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) { 3067 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A); 3068 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C); 3069 if (!Aconst || !Cconst) return false; 3070 APInt Alpha = Aconst->getValue()->getValue(); 3071 APInt Charlie = Cconst->getValue()->getValue(); 3072 APInt CdivA = Charlie.sdiv(Alpha); 3073 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A"); 3074 const SCEV *A_K = findCoefficient(Src, CurLoop); 3075 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA))); 3076 Src = zeroCoefficient(Src, CurLoop); 3077 Dst = addToCoefficient(Dst, CurLoop, A_K); 3078 if (!findCoefficient(Dst, CurLoop)->isZero()) 3079 Consistent = false; 3080 } 3081 else { 3082 // paper is incorrect here, or perhaps just misleading 3083 const SCEV *A_K = findCoefficient(Src, CurLoop); 3084 Src = SE->getMulExpr(Src, A); 3085 Dst = SE->getMulExpr(Dst, A); 3086 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C)); 3087 Src = zeroCoefficient(Src, CurLoop); 3088 Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B)); 3089 if (!findCoefficient(Dst, CurLoop)->isZero()) 3090 Consistent = false; 3091 } 3092 DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n"); 3093 DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n"); 3094 return true; 3095 } 3096 3097 3098 // Attempt to propagate a point 3099 // constraint into a subscript pair (Src and Dst). 3100 // Return true if some simplification occurs. 3101 bool DependenceAnalysis::propagatePoint(const SCEV *&Src, 3102 const SCEV *&Dst, 3103 Constraint &CurConstraint) { 3104 const Loop *CurLoop = CurConstraint.getAssociatedLoop(); 3105 const SCEV *A_K = findCoefficient(Src, CurLoop); 3106 const SCEV *AP_K = findCoefficient(Dst, CurLoop); 3107 const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX()); 3108 const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY()); 3109 DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n"); 3110 Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K)); 3111 Src = zeroCoefficient(Src, CurLoop); 3112 DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n"); 3113 DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n"); 3114 Dst = zeroCoefficient(Dst, CurLoop); 3115 DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n"); 3116 return true; 3117 } 3118 3119 3120 // Update direction vector entry based on the current constraint. 3121 void DependenceAnalysis::updateDirection(Dependence::DVEntry &Level, 3122 const Constraint &CurConstraint 3123 ) const { 3124 DEBUG(dbgs() << "\tUpdate direction, constraint ="); 3125 DEBUG(CurConstraint.dump(dbgs())); 3126 if (CurConstraint.isAny()) 3127 ; // use defaults 3128 else if (CurConstraint.isDistance()) { 3129 // this one is consistent, the others aren't 3130 Level.Scalar = false; 3131 Level.Distance = CurConstraint.getD(); 3132 unsigned NewDirection = Dependence::DVEntry::NONE; 3133 if (!SE->isKnownNonZero(Level.Distance)) // if may be zero 3134 NewDirection = Dependence::DVEntry::EQ; 3135 if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive 3136 NewDirection |= Dependence::DVEntry::LT; 3137 if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative 3138 NewDirection |= Dependence::DVEntry::GT; 3139 Level.Direction &= NewDirection; 3140 } 3141 else if (CurConstraint.isLine()) { 3142 Level.Scalar = false; 3143 Level.Distance = NULL; 3144 // direction should be accurate 3145 } 3146 else if (CurConstraint.isPoint()) { 3147 Level.Scalar = false; 3148 Level.Distance = NULL; 3149 unsigned NewDirection = Dependence::DVEntry::NONE; 3150 if (!isKnownPredicate(CmpInst::ICMP_NE, 3151 CurConstraint.getY(), 3152 CurConstraint.getX())) 3153 // if X may be = Y 3154 NewDirection |= Dependence::DVEntry::EQ; 3155 if (!isKnownPredicate(CmpInst::ICMP_SLE, 3156 CurConstraint.getY(), 3157 CurConstraint.getX())) 3158 // if Y may be > X 3159 NewDirection |= Dependence::DVEntry::LT; 3160 if (!isKnownPredicate(CmpInst::ICMP_SGE, 3161 CurConstraint.getY(), 3162 CurConstraint.getX())) 3163 // if Y may be < X 3164 NewDirection |= Dependence::DVEntry::GT; 3165 Level.Direction &= NewDirection; 3166 } 3167 else 3168 llvm_unreachable("constraint has unexpected kind"); 3169 } 3170 3171 3172 //===----------------------------------------------------------------------===// 3173 3174 #ifndef NDEBUG 3175 // For debugging purposes, dump a small bit vector to dbgs(). 3176 static void dumpSmallBitVector(SmallBitVector &BV) { 3177 dbgs() << "{"; 3178 for (int VI = BV.find_first(); VI >= 0; VI = BV.find_next(VI)) { 3179 dbgs() << VI; 3180 if (BV.find_next(VI) >= 0) 3181 dbgs() << ' '; 3182 } 3183 dbgs() << "}\n"; 3184 } 3185 #endif 3186 3187 3188 // depends - 3189 // Returns NULL if there is no dependence. 3190 // Otherwise, return a Dependence with as many details as possible. 3191 // Corresponds to Section 3.1 in the paper 3192 // 3193 // Practical Dependence Testing 3194 // Goff, Kennedy, Tseng 3195 // PLDI 1991 3196 // 3197 // Care is required to keep the routine below, getSplitIteration(), 3198 // up to date with respect to this routine. 3199 Dependence *DependenceAnalysis::depends(Instruction *Src, 3200 Instruction *Dst, 3201 bool PossiblyLoopIndependent) { 3202 if (Src == Dst) 3203 PossiblyLoopIndependent = false; 3204 3205 if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) || 3206 (!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory())) 3207 // if both instructions don't reference memory, there's no dependence 3208 return NULL; 3209 3210 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) { 3211 // can only analyze simple loads and stores, i.e., no calls, invokes, etc. 3212 DEBUG(dbgs() << "can only handle simple loads and stores\n"); 3213 return new Dependence(Src, Dst); 3214 } 3215 3216 Value *SrcPtr = getPointerOperand(Src); 3217 Value *DstPtr = getPointerOperand(Dst); 3218 3219 switch (underlyingObjectsAlias(AA, DstPtr, SrcPtr)) { 3220 case AliasAnalysis::MayAlias: 3221 case AliasAnalysis::PartialAlias: 3222 // cannot analyse objects if we don't understand their aliasing. 3223 DEBUG(dbgs() << "can't analyze may or partial alias\n"); 3224 return new Dependence(Src, Dst); 3225 case AliasAnalysis::NoAlias: 3226 // If the objects noalias, they are distinct, accesses are independent. 3227 DEBUG(dbgs() << "no alias\n"); 3228 return NULL; 3229 case AliasAnalysis::MustAlias: 3230 break; // The underlying objects alias; test accesses for dependence. 3231 } 3232 3233 // establish loop nesting levels 3234 establishNestingLevels(Src, Dst); 3235 DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n"); 3236 DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n"); 3237 3238 FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels); 3239 ++TotalArrayPairs; 3240 3241 // See if there are GEPs we can use. 3242 bool UsefulGEP = false; 3243 GEPOperator *SrcGEP = dyn_cast<GEPOperator>(SrcPtr); 3244 GEPOperator *DstGEP = dyn_cast<GEPOperator>(DstPtr); 3245 if (SrcGEP && DstGEP && 3246 SrcGEP->getPointerOperandType() == DstGEP->getPointerOperandType()) { 3247 const SCEV *SrcPtrSCEV = SE->getSCEV(SrcGEP->getPointerOperand()); 3248 const SCEV *DstPtrSCEV = SE->getSCEV(DstGEP->getPointerOperand()); 3249 DEBUG(dbgs() << " SrcPtrSCEV = " << *SrcPtrSCEV << "\n"); 3250 DEBUG(dbgs() << " DstPtrSCEV = " << *DstPtrSCEV << "\n"); 3251 3252 UsefulGEP = 3253 isLoopInvariant(SrcPtrSCEV, LI->getLoopFor(Src->getParent())) && 3254 isLoopInvariant(DstPtrSCEV, LI->getLoopFor(Dst->getParent())); 3255 } 3256 unsigned Pairs = UsefulGEP ? SrcGEP->idx_end() - SrcGEP->idx_begin() : 1; 3257 SmallVector<Subscript, 4> Pair(Pairs); 3258 if (UsefulGEP) { 3259 DEBUG(dbgs() << " using GEPs\n"); 3260 unsigned P = 0; 3261 for (GEPOperator::const_op_iterator SrcIdx = SrcGEP->idx_begin(), 3262 SrcEnd = SrcGEP->idx_end(), 3263 DstIdx = DstGEP->idx_begin(); 3264 SrcIdx != SrcEnd; 3265 ++SrcIdx, ++DstIdx, ++P) { 3266 Pair[P].Src = SE->getSCEV(*SrcIdx); 3267 Pair[P].Dst = SE->getSCEV(*DstIdx); 3268 } 3269 } 3270 else { 3271 DEBUG(dbgs() << " ignoring GEPs\n"); 3272 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr); 3273 const SCEV *DstSCEV = SE->getSCEV(DstPtr); 3274 DEBUG(dbgs() << " SrcSCEV = " << *SrcSCEV << "\n"); 3275 DEBUG(dbgs() << " DstSCEV = " << *DstSCEV << "\n"); 3276 Pair[0].Src = SrcSCEV; 3277 Pair[0].Dst = DstSCEV; 3278 } 3279 3280 for (unsigned P = 0; P < Pairs; ++P) { 3281 Pair[P].Loops.resize(MaxLevels + 1); 3282 Pair[P].GroupLoops.resize(MaxLevels + 1); 3283 Pair[P].Group.resize(Pairs); 3284 removeMatchingExtensions(&Pair[P]); 3285 Pair[P].Classification = 3286 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()), 3287 Pair[P].Dst, LI->getLoopFor(Dst->getParent()), 3288 Pair[P].Loops); 3289 Pair[P].GroupLoops = Pair[P].Loops; 3290 Pair[P].Group.set(P); 3291 DEBUG(dbgs() << " subscript " << P << "\n"); 3292 DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n"); 3293 DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n"); 3294 DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n"); 3295 DEBUG(dbgs() << "\tloops = "); 3296 DEBUG(dumpSmallBitVector(Pair[P].Loops)); 3297 } 3298 3299 SmallBitVector Separable(Pairs); 3300 SmallBitVector Coupled(Pairs); 3301 3302 // Partition subscripts into separable and minimally-coupled groups 3303 // Algorithm in paper is algorithmically better; 3304 // this may be faster in practice. Check someday. 3305 // 3306 // Here's an example of how it works. Consider this code: 3307 // 3308 // for (i = ...) { 3309 // for (j = ...) { 3310 // for (k = ...) { 3311 // for (l = ...) { 3312 // for (m = ...) { 3313 // A[i][j][k][m] = ...; 3314 // ... = A[0][j][l][i + j]; 3315 // } 3316 // } 3317 // } 3318 // } 3319 // } 3320 // 3321 // There are 4 subscripts here: 3322 // 0 [i] and [0] 3323 // 1 [j] and [j] 3324 // 2 [k] and [l] 3325 // 3 [m] and [i + j] 3326 // 3327 // We've already classified each subscript pair as ZIV, SIV, etc., 3328 // and collected all the loops mentioned by pair P in Pair[P].Loops. 3329 // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops 3330 // and set Pair[P].Group = {P}. 3331 // 3332 // Src Dst Classification Loops GroupLoops Group 3333 // 0 [i] [0] SIV {1} {1} {0} 3334 // 1 [j] [j] SIV {2} {2} {1} 3335 // 2 [k] [l] RDIV {3,4} {3,4} {2} 3336 // 3 [m] [i + j] MIV {1,2,5} {1,2,5} {3} 3337 // 3338 // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ. 3339 // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc. 3340 // 3341 // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty. 3342 // Next, 0 and 2. Again, the intersection of their GroupLoops is empty. 3343 // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty, 3344 // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added 3345 // to either Separable or Coupled). 3346 // 3347 // Next, we consider 1 and 2. The intersection of the GroupLoops is empty. 3348 // Next, 1 and 3. The intersectionof their GroupLoops = {2}, not empty, 3349 // so Pair[3].Group = {0, 1, 3} and Done = false. 3350 // 3351 // Next, we compare 2 against 3. The intersection of the GroupLoops is empty. 3352 // Since Done remains true, we add 2 to the set of Separable pairs. 3353 // 3354 // Finally, we consider 3. There's nothing to compare it with, 3355 // so Done remains true and we add it to the Coupled set. 3356 // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}. 3357 // 3358 // In the end, we've got 1 separable subscript and 1 coupled group. 3359 for (unsigned SI = 0; SI < Pairs; ++SI) { 3360 if (Pair[SI].Classification == Subscript::NonLinear) { 3361 // ignore these, but collect loops for later 3362 ++NonlinearSubscriptPairs; 3363 collectCommonLoops(Pair[SI].Src, 3364 LI->getLoopFor(Src->getParent()), 3365 Pair[SI].Loops); 3366 collectCommonLoops(Pair[SI].Dst, 3367 LI->getLoopFor(Dst->getParent()), 3368 Pair[SI].Loops); 3369 Result.Consistent = false; 3370 } 3371 else if (Pair[SI].Classification == Subscript::ZIV) { 3372 // always separable 3373 Separable.set(SI); 3374 } 3375 else { 3376 // SIV, RDIV, or MIV, so check for coupled group 3377 bool Done = true; 3378 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) { 3379 SmallBitVector Intersection = Pair[SI].GroupLoops; 3380 Intersection &= Pair[SJ].GroupLoops; 3381 if (Intersection.any()) { 3382 // accumulate set of all the loops in group 3383 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops; 3384 // accumulate set of all subscripts in group 3385 Pair[SJ].Group |= Pair[SI].Group; 3386 Done = false; 3387 } 3388 } 3389 if (Done) { 3390 if (Pair[SI].Group.count() == 1) { 3391 Separable.set(SI); 3392 ++SeparableSubscriptPairs; 3393 } 3394 else { 3395 Coupled.set(SI); 3396 ++CoupledSubscriptPairs; 3397 } 3398 } 3399 } 3400 } 3401 3402 DEBUG(dbgs() << " Separable = "); 3403 DEBUG(dumpSmallBitVector(Separable)); 3404 DEBUG(dbgs() << " Coupled = "); 3405 DEBUG(dumpSmallBitVector(Coupled)); 3406 3407 Constraint NewConstraint; 3408 NewConstraint.setAny(SE); 3409 3410 // test separable subscripts 3411 for (int SI = Separable.find_first(); SI >= 0; SI = Separable.find_next(SI)) { 3412 DEBUG(dbgs() << "testing subscript " << SI); 3413 switch (Pair[SI].Classification) { 3414 case Subscript::ZIV: 3415 DEBUG(dbgs() << ", ZIV\n"); 3416 if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result)) 3417 return NULL; 3418 break; 3419 case Subscript::SIV: { 3420 DEBUG(dbgs() << ", SIV\n"); 3421 unsigned Level; 3422 const SCEV *SplitIter = NULL; 3423 if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, 3424 Result, NewConstraint, SplitIter)) 3425 return NULL; 3426 break; 3427 } 3428 case Subscript::RDIV: 3429 DEBUG(dbgs() << ", RDIV\n"); 3430 if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result)) 3431 return NULL; 3432 break; 3433 case Subscript::MIV: 3434 DEBUG(dbgs() << ", MIV\n"); 3435 if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result)) 3436 return NULL; 3437 break; 3438 default: 3439 llvm_unreachable("subscript has unexpected classification"); 3440 } 3441 } 3442 3443 if (Coupled.count()) { 3444 // test coupled subscript groups 3445 DEBUG(dbgs() << "starting on coupled subscripts\n"); 3446 DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n"); 3447 SmallVector<Constraint, 4> Constraints(MaxLevels + 1); 3448 for (unsigned II = 0; II <= MaxLevels; ++II) 3449 Constraints[II].setAny(SE); 3450 for (int SI = Coupled.find_first(); SI >= 0; SI = Coupled.find_next(SI)) { 3451 DEBUG(dbgs() << "testing subscript group " << SI << " { "); 3452 SmallBitVector Group(Pair[SI].Group); 3453 SmallBitVector Sivs(Pairs); 3454 SmallBitVector Mivs(Pairs); 3455 SmallBitVector ConstrainedLevels(MaxLevels + 1); 3456 for (int SJ = Group.find_first(); SJ >= 0; SJ = Group.find_next(SJ)) { 3457 DEBUG(dbgs() << SJ << " "); 3458 if (Pair[SJ].Classification == Subscript::SIV) 3459 Sivs.set(SJ); 3460 else 3461 Mivs.set(SJ); 3462 } 3463 DEBUG(dbgs() << "}\n"); 3464 while (Sivs.any()) { 3465 bool Changed = false; 3466 for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) { 3467 DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n"); 3468 // SJ is an SIV subscript that's part of the current coupled group 3469 unsigned Level; 3470 const SCEV *SplitIter = NULL; 3471 DEBUG(dbgs() << "SIV\n"); 3472 if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level, 3473 Result, NewConstraint, SplitIter)) 3474 return NULL; 3475 ConstrainedLevels.set(Level); 3476 if (intersectConstraints(&Constraints[Level], &NewConstraint)) { 3477 if (Constraints[Level].isEmpty()) { 3478 ++DeltaIndependence; 3479 return NULL; 3480 } 3481 Changed = true; 3482 } 3483 Sivs.reset(SJ); 3484 } 3485 if (Changed) { 3486 // propagate, possibly creating new SIVs and ZIVs 3487 DEBUG(dbgs() << " propagating\n"); 3488 DEBUG(dbgs() << "\tMivs = "); 3489 DEBUG(dumpSmallBitVector(Mivs)); 3490 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) { 3491 // SJ is an MIV subscript that's part of the current coupled group 3492 DEBUG(dbgs() << "\tSJ = " << SJ << "\n"); 3493 if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, 3494 Constraints, Result.Consistent)) { 3495 DEBUG(dbgs() << "\t Changed\n"); 3496 ++DeltaPropagations; 3497 Pair[SJ].Classification = 3498 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()), 3499 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()), 3500 Pair[SJ].Loops); 3501 switch (Pair[SJ].Classification) { 3502 case Subscript::ZIV: 3503 DEBUG(dbgs() << "ZIV\n"); 3504 if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result)) 3505 return NULL; 3506 Mivs.reset(SJ); 3507 break; 3508 case Subscript::SIV: 3509 Sivs.set(SJ); 3510 Mivs.reset(SJ); 3511 break; 3512 case Subscript::RDIV: 3513 case Subscript::MIV: 3514 break; 3515 default: 3516 llvm_unreachable("bad subscript classification"); 3517 } 3518 } 3519 } 3520 } 3521 } 3522 3523 // test & propagate remaining RDIVs 3524 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) { 3525 if (Pair[SJ].Classification == Subscript::RDIV) { 3526 DEBUG(dbgs() << "RDIV test\n"); 3527 if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result)) 3528 return NULL; 3529 // I don't yet understand how to propagate RDIV results 3530 Mivs.reset(SJ); 3531 } 3532 } 3533 3534 // test remaining MIVs 3535 // This code is temporary. 3536 // Better to somehow test all remaining subscripts simultaneously. 3537 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) { 3538 if (Pair[SJ].Classification == Subscript::MIV) { 3539 DEBUG(dbgs() << "MIV test\n"); 3540 if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result)) 3541 return NULL; 3542 } 3543 else 3544 llvm_unreachable("expected only MIV subscripts at this point"); 3545 } 3546 3547 // update Result.DV from constraint vector 3548 DEBUG(dbgs() << " updating\n"); 3549 for (int SJ = ConstrainedLevels.find_first(); 3550 SJ >= 0; SJ = ConstrainedLevels.find_next(SJ)) { 3551 updateDirection(Result.DV[SJ - 1], Constraints[SJ]); 3552 if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE) 3553 return NULL; 3554 } 3555 } 3556 } 3557 3558 // make sure Scalar flags are set correctly 3559 SmallBitVector CompleteLoops(MaxLevels + 1); 3560 for (unsigned SI = 0; SI < Pairs; ++SI) 3561 CompleteLoops |= Pair[SI].Loops; 3562 for (unsigned II = 1; II <= CommonLevels; ++II) 3563 if (CompleteLoops[II]) 3564 Result.DV[II - 1].Scalar = false; 3565 3566 if (PossiblyLoopIndependent) { 3567 // Make sure the LoopIndependent flag is set correctly. 3568 // All directions must include equal, otherwise no 3569 // loop-independent dependence is possible. 3570 for (unsigned II = 1; II <= CommonLevels; ++II) { 3571 if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) { 3572 Result.LoopIndependent = false; 3573 break; 3574 } 3575 } 3576 } 3577 else { 3578 // On the other hand, if all directions are equal and there's no 3579 // loop-independent dependence possible, then no dependence exists. 3580 bool AllEqual = true; 3581 for (unsigned II = 1; II <= CommonLevels; ++II) { 3582 if (Result.getDirection(II) != Dependence::DVEntry::EQ) { 3583 AllEqual = false; 3584 break; 3585 } 3586 } 3587 if (AllEqual) 3588 return NULL; 3589 } 3590 3591 FullDependence *Final = new FullDependence(Result); 3592 Result.DV = NULL; 3593 return Final; 3594 } 3595 3596 3597 3598 //===----------------------------------------------------------------------===// 3599 // getSplitIteration - 3600 // Rather than spend rarely-used space recording the splitting iteration 3601 // during the Weak-Crossing SIV test, we re-compute it on demand. 3602 // The re-computation is basically a repeat of the entire dependence test, 3603 // though simplified since we know that the dependence exists. 3604 // It's tedious, since we must go through all propagations, etc. 3605 // 3606 // Care is required to keep this code up to date with respect to the routine 3607 // above, depends(). 3608 // 3609 // Generally, the dependence analyzer will be used to build 3610 // a dependence graph for a function (basically a map from instructions 3611 // to dependences). Looking for cycles in the graph shows us loops 3612 // that cannot be trivially vectorized/parallelized. 3613 // 3614 // We can try to improve the situation by examining all the dependences 3615 // that make up the cycle, looking for ones we can break. 3616 // Sometimes, peeling the first or last iteration of a loop will break 3617 // dependences, and we've got flags for those possibilities. 3618 // Sometimes, splitting a loop at some other iteration will do the trick, 3619 // and we've got a flag for that case. Rather than waste the space to 3620 // record the exact iteration (since we rarely know), we provide 3621 // a method that calculates the iteration. It's a drag that it must work 3622 // from scratch, but wonderful in that it's possible. 3623 // 3624 // Here's an example: 3625 // 3626 // for (i = 0; i < 10; i++) 3627 // A[i] = ... 3628 // ... = A[11 - i] 3629 // 3630 // There's a loop-carried flow dependence from the store to the load, 3631 // found by the weak-crossing SIV test. The dependence will have a flag, 3632 // indicating that the dependence can be broken by splitting the loop. 3633 // Calling getSplitIteration will return 5. 3634 // Splitting the loop breaks the dependence, like so: 3635 // 3636 // for (i = 0; i <= 5; i++) 3637 // A[i] = ... 3638 // ... = A[11 - i] 3639 // for (i = 6; i < 10; i++) 3640 // A[i] = ... 3641 // ... = A[11 - i] 3642 // 3643 // breaks the dependence and allows us to vectorize/parallelize 3644 // both loops. 3645 const SCEV *DependenceAnalysis::getSplitIteration(const Dependence *Dep, 3646 unsigned SplitLevel) { 3647 assert(Dep && "expected a pointer to a Dependence"); 3648 assert(Dep->isSplitable(SplitLevel) && 3649 "Dep should be splitable at SplitLevel"); 3650 Instruction *Src = Dep->getSrc(); 3651 Instruction *Dst = Dep->getDst(); 3652 assert(Src->mayReadFromMemory() || Src->mayWriteToMemory()); 3653 assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory()); 3654 assert(isLoadOrStore(Src)); 3655 assert(isLoadOrStore(Dst)); 3656 Value *SrcPtr = getPointerOperand(Src); 3657 Value *DstPtr = getPointerOperand(Dst); 3658 assert(underlyingObjectsAlias(AA, DstPtr, SrcPtr) == 3659 AliasAnalysis::MustAlias); 3660 3661 // establish loop nesting levels 3662 establishNestingLevels(Src, Dst); 3663 3664 FullDependence Result(Src, Dst, false, CommonLevels); 3665 3666 // See if there are GEPs we can use. 3667 bool UsefulGEP = false; 3668 GEPOperator *SrcGEP = dyn_cast<GEPOperator>(SrcPtr); 3669 GEPOperator *DstGEP = dyn_cast<GEPOperator>(DstPtr); 3670 if (SrcGEP && DstGEP && 3671 SrcGEP->getPointerOperandType() == DstGEP->getPointerOperandType()) { 3672 const SCEV *SrcPtrSCEV = SE->getSCEV(SrcGEP->getPointerOperand()); 3673 const SCEV *DstPtrSCEV = SE->getSCEV(DstGEP->getPointerOperand()); 3674 UsefulGEP = 3675 isLoopInvariant(SrcPtrSCEV, LI->getLoopFor(Src->getParent())) && 3676 isLoopInvariant(DstPtrSCEV, LI->getLoopFor(Dst->getParent())); 3677 } 3678 unsigned Pairs = UsefulGEP ? SrcGEP->idx_end() - SrcGEP->idx_begin() : 1; 3679 SmallVector<Subscript, 4> Pair(Pairs); 3680 if (UsefulGEP) { 3681 unsigned P = 0; 3682 for (GEPOperator::const_op_iterator SrcIdx = SrcGEP->idx_begin(), 3683 SrcEnd = SrcGEP->idx_end(), 3684 DstIdx = DstGEP->idx_begin(); 3685 SrcIdx != SrcEnd; 3686 ++SrcIdx, ++DstIdx, ++P) { 3687 Pair[P].Src = SE->getSCEV(*SrcIdx); 3688 Pair[P].Dst = SE->getSCEV(*DstIdx); 3689 } 3690 } 3691 else { 3692 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr); 3693 const SCEV *DstSCEV = SE->getSCEV(DstPtr); 3694 Pair[0].Src = SrcSCEV; 3695 Pair[0].Dst = DstSCEV; 3696 } 3697 3698 for (unsigned P = 0; P < Pairs; ++P) { 3699 Pair[P].Loops.resize(MaxLevels + 1); 3700 Pair[P].GroupLoops.resize(MaxLevels + 1); 3701 Pair[P].Group.resize(Pairs); 3702 removeMatchingExtensions(&Pair[P]); 3703 Pair[P].Classification = 3704 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()), 3705 Pair[P].Dst, LI->getLoopFor(Dst->getParent()), 3706 Pair[P].Loops); 3707 Pair[P].GroupLoops = Pair[P].Loops; 3708 Pair[P].Group.set(P); 3709 } 3710 3711 SmallBitVector Separable(Pairs); 3712 SmallBitVector Coupled(Pairs); 3713 3714 // partition subscripts into separable and minimally-coupled groups 3715 for (unsigned SI = 0; SI < Pairs; ++SI) { 3716 if (Pair[SI].Classification == Subscript::NonLinear) { 3717 // ignore these, but collect loops for later 3718 collectCommonLoops(Pair[SI].Src, 3719 LI->getLoopFor(Src->getParent()), 3720 Pair[SI].Loops); 3721 collectCommonLoops(Pair[SI].Dst, 3722 LI->getLoopFor(Dst->getParent()), 3723 Pair[SI].Loops); 3724 Result.Consistent = false; 3725 } 3726 else if (Pair[SI].Classification == Subscript::ZIV) 3727 Separable.set(SI); 3728 else { 3729 // SIV, RDIV, or MIV, so check for coupled group 3730 bool Done = true; 3731 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) { 3732 SmallBitVector Intersection = Pair[SI].GroupLoops; 3733 Intersection &= Pair[SJ].GroupLoops; 3734 if (Intersection.any()) { 3735 // accumulate set of all the loops in group 3736 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops; 3737 // accumulate set of all subscripts in group 3738 Pair[SJ].Group |= Pair[SI].Group; 3739 Done = false; 3740 } 3741 } 3742 if (Done) { 3743 if (Pair[SI].Group.count() == 1) 3744 Separable.set(SI); 3745 else 3746 Coupled.set(SI); 3747 } 3748 } 3749 } 3750 3751 Constraint NewConstraint; 3752 NewConstraint.setAny(SE); 3753 3754 // test separable subscripts 3755 for (int SI = Separable.find_first(); SI >= 0; SI = Separable.find_next(SI)) { 3756 switch (Pair[SI].Classification) { 3757 case Subscript::SIV: { 3758 unsigned Level; 3759 const SCEV *SplitIter = NULL; 3760 (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level, 3761 Result, NewConstraint, SplitIter); 3762 if (Level == SplitLevel) { 3763 assert(SplitIter != NULL); 3764 return SplitIter; 3765 } 3766 break; 3767 } 3768 case Subscript::ZIV: 3769 case Subscript::RDIV: 3770 case Subscript::MIV: 3771 break; 3772 default: 3773 llvm_unreachable("subscript has unexpected classification"); 3774 } 3775 } 3776 3777 if (Coupled.count()) { 3778 // test coupled subscript groups 3779 SmallVector<Constraint, 4> Constraints(MaxLevels + 1); 3780 for (unsigned II = 0; II <= MaxLevels; ++II) 3781 Constraints[II].setAny(SE); 3782 for (int SI = Coupled.find_first(); SI >= 0; SI = Coupled.find_next(SI)) { 3783 SmallBitVector Group(Pair[SI].Group); 3784 SmallBitVector Sivs(Pairs); 3785 SmallBitVector Mivs(Pairs); 3786 SmallBitVector ConstrainedLevels(MaxLevels + 1); 3787 for (int SJ = Group.find_first(); SJ >= 0; SJ = Group.find_next(SJ)) { 3788 if (Pair[SJ].Classification == Subscript::SIV) 3789 Sivs.set(SJ); 3790 else 3791 Mivs.set(SJ); 3792 } 3793 while (Sivs.any()) { 3794 bool Changed = false; 3795 for (int SJ = Sivs.find_first(); SJ >= 0; SJ = Sivs.find_next(SJ)) { 3796 // SJ is an SIV subscript that's part of the current coupled group 3797 unsigned Level; 3798 const SCEV *SplitIter = NULL; 3799 (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level, 3800 Result, NewConstraint, SplitIter); 3801 if (Level == SplitLevel && SplitIter) 3802 return SplitIter; 3803 ConstrainedLevels.set(Level); 3804 if (intersectConstraints(&Constraints[Level], &NewConstraint)) 3805 Changed = true; 3806 Sivs.reset(SJ); 3807 } 3808 if (Changed) { 3809 // propagate, possibly creating new SIVs and ZIVs 3810 for (int SJ = Mivs.find_first(); SJ >= 0; SJ = Mivs.find_next(SJ)) { 3811 // SJ is an MIV subscript that's part of the current coupled group 3812 if (propagate(Pair[SJ].Src, Pair[SJ].Dst, 3813 Pair[SJ].Loops, Constraints, Result.Consistent)) { 3814 Pair[SJ].Classification = 3815 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()), 3816 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()), 3817 Pair[SJ].Loops); 3818 switch (Pair[SJ].Classification) { 3819 case Subscript::ZIV: 3820 Mivs.reset(SJ); 3821 break; 3822 case Subscript::SIV: 3823 Sivs.set(SJ); 3824 Mivs.reset(SJ); 3825 break; 3826 case Subscript::RDIV: 3827 case Subscript::MIV: 3828 break; 3829 default: 3830 llvm_unreachable("bad subscript classification"); 3831 } 3832 } 3833 } 3834 } 3835 } 3836 } 3837 } 3838 llvm_unreachable("somehow reached end of routine"); 3839 return NULL; 3840 } 3841