1 2 #include "polly/Support/SCEVValidator.h" 3 #include "polly/ScopInfo.h" 4 #include "llvm/Analysis/RegionInfo.h" 5 #include "llvm/Analysis/ScalarEvolution.h" 6 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 7 #include "llvm/Support/Debug.h" 8 9 using namespace llvm; 10 using namespace polly; 11 12 #define DEBUG_TYPE "polly-scev-validator" 13 14 namespace SCEVType { 15 /// The type of a SCEV 16 /// 17 /// To check for the validity of a SCEV we assign to each SCEV a type. The 18 /// possible types are INT, PARAM, IV and INVALID. The order of the types is 19 /// important. The subexpressions of SCEV with a type X can only have a type 20 /// that is smaller or equal than X. 21 enum TYPE { 22 // An integer value. 23 INT, 24 25 // An expression that is constant during the execution of the Scop, 26 // but that may depend on parameters unknown at compile time. 27 PARAM, 28 29 // An expression that may change during the execution of the SCoP. 30 IV, 31 32 // An invalid expression. 33 INVALID 34 }; 35 } // namespace SCEVType 36 37 /// The result the validator returns for a SCEV expression. 38 class ValidatorResult { 39 /// The type of the expression 40 SCEVType::TYPE Type; 41 42 /// The set of Parameters in the expression. 43 ParameterSetTy Parameters; 44 45 public: 46 /// The copy constructor 47 ValidatorResult(const ValidatorResult &Source) { 48 Type = Source.Type; 49 Parameters = Source.Parameters; 50 } 51 52 /// Construct a result with a certain type and no parameters. 53 ValidatorResult(SCEVType::TYPE Type) : Type(Type) { 54 assert(Type != SCEVType::PARAM && "Did you forget to pass the parameter"); 55 } 56 57 /// Construct a result with a certain type and a single parameter. 58 ValidatorResult(SCEVType::TYPE Type, const SCEV *Expr) : Type(Type) { 59 Parameters.insert(Expr); 60 } 61 62 /// Get the type of the ValidatorResult. 63 SCEVType::TYPE getType() { return Type; } 64 65 /// Is the analyzed SCEV constant during the execution of the SCoP. 66 bool isConstant() { return Type == SCEVType::INT || Type == SCEVType::PARAM; } 67 68 /// Is the analyzed SCEV valid. 69 bool isValid() { return Type != SCEVType::INVALID; } 70 71 /// Is the analyzed SCEV of Type IV. 72 bool isIV() { return Type == SCEVType::IV; } 73 74 /// Is the analyzed SCEV of Type INT. 75 bool isINT() { return Type == SCEVType::INT; } 76 77 /// Is the analyzed SCEV of Type PARAM. 78 bool isPARAM() { return Type == SCEVType::PARAM; } 79 80 /// Get the parameters of this validator result. 81 const ParameterSetTy &getParameters() { return Parameters; } 82 83 /// Add the parameters of Source to this result. 84 void addParamsFrom(const ValidatorResult &Source) { 85 Parameters.insert(Source.Parameters.begin(), Source.Parameters.end()); 86 } 87 88 /// Merge a result. 89 /// 90 /// This means to merge the parameters and to set the Type to the most 91 /// specific Type that matches both. 92 void merge(const ValidatorResult &ToMerge) { 93 Type = std::max(Type, ToMerge.Type); 94 addParamsFrom(ToMerge); 95 } 96 97 void print(raw_ostream &OS) { 98 switch (Type) { 99 case SCEVType::INT: 100 OS << "SCEVType::INT"; 101 break; 102 case SCEVType::PARAM: 103 OS << "SCEVType::PARAM"; 104 break; 105 case SCEVType::IV: 106 OS << "SCEVType::IV"; 107 break; 108 case SCEVType::INVALID: 109 OS << "SCEVType::INVALID"; 110 break; 111 } 112 } 113 }; 114 115 raw_ostream &operator<<(raw_ostream &OS, class ValidatorResult &VR) { 116 VR.print(OS); 117 return OS; 118 } 119 120 /// Check if a SCEV is valid in a SCoP. 121 struct SCEVValidator 122 : public SCEVVisitor<SCEVValidator, class ValidatorResult> { 123 private: 124 const Region *R; 125 Loop *Scope; 126 ScalarEvolution &SE; 127 InvariantLoadsSetTy *ILS; 128 129 public: 130 SCEVValidator(const Region *R, Loop *Scope, ScalarEvolution &SE, 131 InvariantLoadsSetTy *ILS) 132 : R(R), Scope(Scope), SE(SE), ILS(ILS) {} 133 134 class ValidatorResult visitConstant(const SCEVConstant *Constant) { 135 return ValidatorResult(SCEVType::INT); 136 } 137 138 class ValidatorResult visitTruncateExpr(const SCEVTruncateExpr *Expr) { 139 return visit(Expr->getOperand()); 140 } 141 142 class ValidatorResult visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { 143 return visit(Expr->getOperand()); 144 } 145 146 class ValidatorResult visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { 147 return visit(Expr->getOperand()); 148 } 149 150 class ValidatorResult visitAddExpr(const SCEVAddExpr *Expr) { 151 ValidatorResult Return(SCEVType::INT); 152 153 for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) { 154 ValidatorResult Op = visit(Expr->getOperand(i)); 155 Return.merge(Op); 156 157 // Early exit. 158 if (!Return.isValid()) 159 break; 160 } 161 162 return Return; 163 } 164 165 class ValidatorResult visitMulExpr(const SCEVMulExpr *Expr) { 166 ValidatorResult Return(SCEVType::INT); 167 168 bool HasMultipleParams = false; 169 170 for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) { 171 ValidatorResult Op = visit(Expr->getOperand(i)); 172 173 if (Op.isINT()) 174 continue; 175 176 if (Op.isPARAM() && Return.isPARAM()) { 177 HasMultipleParams = true; 178 continue; 179 } 180 181 if ((Op.isIV() || Op.isPARAM()) && !Return.isINT()) { 182 DEBUG(dbgs() << "INVALID: More than one non-int operand in MulExpr\n" 183 << "\tExpr: " << *Expr << "\n" 184 << "\tPrevious expression type: " << Return << "\n" 185 << "\tNext operand (" << Op 186 << "): " << *Expr->getOperand(i) << "\n"); 187 188 return ValidatorResult(SCEVType::INVALID); 189 } 190 191 Return.merge(Op); 192 } 193 194 if (HasMultipleParams && Return.isValid()) 195 return ValidatorResult(SCEVType::PARAM, Expr); 196 197 return Return; 198 } 199 200 class ValidatorResult visitAddRecExpr(const SCEVAddRecExpr *Expr) { 201 if (!Expr->isAffine()) { 202 DEBUG(dbgs() << "INVALID: AddRec is not affine"); 203 return ValidatorResult(SCEVType::INVALID); 204 } 205 206 ValidatorResult Start = visit(Expr->getStart()); 207 ValidatorResult Recurrence = visit(Expr->getStepRecurrence(SE)); 208 209 if (!Start.isValid()) 210 return Start; 211 212 if (!Recurrence.isValid()) 213 return Recurrence; 214 215 auto *L = Expr->getLoop(); 216 if (R->contains(L) && (!Scope || !L->contains(Scope))) { 217 DEBUG(dbgs() << "INVALID: Loop of AddRec expression boxed in an a " 218 "non-affine subregion or has a non-synthesizable exit " 219 "value."); 220 return ValidatorResult(SCEVType::INVALID); 221 } 222 223 if (R->contains(L)) { 224 if (Recurrence.isINT()) { 225 ValidatorResult Result(SCEVType::IV); 226 Result.addParamsFrom(Start); 227 return Result; 228 } 229 230 DEBUG(dbgs() << "INVALID: AddRec within scop has non-int" 231 "recurrence part"); 232 return ValidatorResult(SCEVType::INVALID); 233 } 234 235 assert(Recurrence.isConstant() && "Expected 'Recurrence' to be constant"); 236 237 // Directly generate ValidatorResult for Expr if 'start' is zero. 238 if (Expr->getStart()->isZero()) 239 return ValidatorResult(SCEVType::PARAM, Expr); 240 241 // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}' 242 // if 'start' is not zero. 243 const SCEV *ZeroStartExpr = SE.getAddRecExpr( 244 SE.getConstant(Expr->getStart()->getType(), 0), 245 Expr->getStepRecurrence(SE), Expr->getLoop(), Expr->getNoWrapFlags()); 246 247 ValidatorResult ZeroStartResult = 248 ValidatorResult(SCEVType::PARAM, ZeroStartExpr); 249 ZeroStartResult.addParamsFrom(Start); 250 251 return ZeroStartResult; 252 } 253 254 class ValidatorResult visitSMaxExpr(const SCEVSMaxExpr *Expr) { 255 ValidatorResult Return(SCEVType::INT); 256 257 for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) { 258 ValidatorResult Op = visit(Expr->getOperand(i)); 259 260 if (!Op.isValid()) 261 return Op; 262 263 Return.merge(Op); 264 } 265 266 return Return; 267 } 268 269 class ValidatorResult visitUMaxExpr(const SCEVUMaxExpr *Expr) { 270 // We do not support unsigned max operations. If 'Expr' is constant during 271 // Scop execution we treat this as a parameter, otherwise we bail out. 272 for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) { 273 ValidatorResult Op = visit(Expr->getOperand(i)); 274 275 if (!Op.isConstant()) { 276 DEBUG(dbgs() << "INVALID: UMaxExpr has a non-constant operand"); 277 return ValidatorResult(SCEVType::INVALID); 278 } 279 } 280 281 return ValidatorResult(SCEVType::PARAM, Expr); 282 } 283 284 ValidatorResult visitGenericInst(Instruction *I, const SCEV *S) { 285 if (R->contains(I)) { 286 DEBUG(dbgs() << "INVALID: UnknownExpr references an instruction " 287 "within the region\n"); 288 return ValidatorResult(SCEVType::INVALID); 289 } 290 291 return ValidatorResult(SCEVType::PARAM, S); 292 } 293 294 ValidatorResult visitLoadInstruction(Instruction *I, const SCEV *S) { 295 if (R->contains(I) && ILS) { 296 ILS->insert(cast<LoadInst>(I)); 297 return ValidatorResult(SCEVType::PARAM, S); 298 } 299 300 return visitGenericInst(I, S); 301 } 302 303 ValidatorResult visitDivision(const SCEV *Dividend, const SCEV *Divisor, 304 const SCEV *DivExpr, 305 Instruction *SDiv = nullptr) { 306 307 // First check if we might be able to model the division, thus if the 308 // divisor is constant. If so, check the dividend, otherwise check if 309 // the whole division can be seen as a parameter. 310 if (isa<SCEVConstant>(Divisor) && !Divisor->isZero()) 311 return visit(Dividend); 312 313 // For signed divisions use the SDiv instruction to check for a parameter 314 // division, for unsigned divisions check the operands. 315 if (SDiv) 316 return visitGenericInst(SDiv, DivExpr); 317 318 ValidatorResult LHS = visit(Dividend); 319 ValidatorResult RHS = visit(Divisor); 320 if (LHS.isConstant() && RHS.isConstant()) 321 return ValidatorResult(SCEVType::PARAM, DivExpr); 322 323 DEBUG(dbgs() << "INVALID: unsigned division of non-constant expressions"); 324 return ValidatorResult(SCEVType::INVALID); 325 } 326 327 ValidatorResult visitUDivExpr(const SCEVUDivExpr *Expr) { 328 auto *Dividend = Expr->getLHS(); 329 auto *Divisor = Expr->getRHS(); 330 return visitDivision(Dividend, Divisor, Expr); 331 } 332 333 ValidatorResult visitSDivInstruction(Instruction *SDiv, const SCEV *Expr) { 334 assert(SDiv->getOpcode() == Instruction::SDiv && 335 "Assumed SDiv instruction!"); 336 337 auto *Dividend = SE.getSCEV(SDiv->getOperand(0)); 338 auto *Divisor = SE.getSCEV(SDiv->getOperand(1)); 339 return visitDivision(Dividend, Divisor, Expr, SDiv); 340 } 341 342 ValidatorResult visitSRemInstruction(Instruction *SRem, const SCEV *S) { 343 assert(SRem->getOpcode() == Instruction::SRem && 344 "Assumed SRem instruction!"); 345 346 auto *Divisor = SRem->getOperand(1); 347 auto *CI = dyn_cast<ConstantInt>(Divisor); 348 if (!CI || CI->isZeroValue()) 349 return visitGenericInst(SRem, S); 350 351 auto *Dividend = SRem->getOperand(0); 352 auto *DividendSCEV = SE.getSCEV(Dividend); 353 return visit(DividendSCEV); 354 } 355 356 ValidatorResult visitUnknown(const SCEVUnknown *Expr) { 357 Value *V = Expr->getValue(); 358 359 if (!Expr->getType()->isIntegerTy() && !Expr->getType()->isPointerTy()) { 360 DEBUG(dbgs() << "INVALID: UnknownExpr is not an integer or pointer"); 361 return ValidatorResult(SCEVType::INVALID); 362 } 363 364 if (isa<UndefValue>(V)) { 365 DEBUG(dbgs() << "INVALID: UnknownExpr references an undef value"); 366 return ValidatorResult(SCEVType::INVALID); 367 } 368 369 if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) { 370 switch (I->getOpcode()) { 371 case Instruction::IntToPtr: 372 return visit(SE.getSCEVAtScope(I->getOperand(0), Scope)); 373 case Instruction::PtrToInt: 374 return visit(SE.getSCEVAtScope(I->getOperand(0), Scope)); 375 case Instruction::Load: 376 return visitLoadInstruction(I, Expr); 377 case Instruction::SDiv: 378 return visitSDivInstruction(I, Expr); 379 case Instruction::SRem: 380 return visitSRemInstruction(I, Expr); 381 default: 382 return visitGenericInst(I, Expr); 383 } 384 } 385 386 return ValidatorResult(SCEVType::PARAM, Expr); 387 } 388 }; 389 390 /// Check whether a SCEV refers to an SSA name defined inside a region. 391 class SCEVInRegionDependences { 392 const Region *R; 393 Loop *Scope; 394 bool AllowLoops; 395 bool HasInRegionDeps = false; 396 397 public: 398 SCEVInRegionDependences(const Region *R, Loop *Scope, bool AllowLoops) 399 : R(R), Scope(Scope), AllowLoops(AllowLoops) {} 400 401 bool follow(const SCEV *S) { 402 if (auto Unknown = dyn_cast<SCEVUnknown>(S)) { 403 Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue()); 404 405 // Return true when Inst is defined inside the region R. 406 if (Inst && R->contains(Inst)) { 407 HasInRegionDeps = true; 408 return false; 409 } 410 } else if (auto AddRec = dyn_cast<SCEVAddRecExpr>(S)) { 411 if (!AllowLoops) { 412 if (!Scope) { 413 HasInRegionDeps = true; 414 return false; 415 } 416 auto *L = AddRec->getLoop(); 417 if (R->contains(L) && !L->contains(Scope)) { 418 HasInRegionDeps = true; 419 return false; 420 } 421 } 422 } 423 return true; 424 } 425 bool isDone() { return false; } 426 bool hasDependences() { return HasInRegionDeps; } 427 }; 428 429 namespace polly { 430 /// Find all loops referenced in SCEVAddRecExprs. 431 class SCEVFindLoops { 432 SetVector<const Loop *> &Loops; 433 434 public: 435 SCEVFindLoops(SetVector<const Loop *> &Loops) : Loops(Loops) {} 436 437 bool follow(const SCEV *S) { 438 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) 439 Loops.insert(AddRec->getLoop()); 440 return true; 441 } 442 bool isDone() { return false; } 443 }; 444 445 void findLoops(const SCEV *Expr, SetVector<const Loop *> &Loops) { 446 SCEVFindLoops FindLoops(Loops); 447 SCEVTraversal<SCEVFindLoops> ST(FindLoops); 448 ST.visitAll(Expr); 449 } 450 451 /// Find all values referenced in SCEVUnknowns. 452 class SCEVFindValues { 453 ScalarEvolution &SE; 454 SetVector<Value *> &Values; 455 456 public: 457 SCEVFindValues(ScalarEvolution &SE, SetVector<Value *> &Values) 458 : SE(SE), Values(Values) {} 459 460 bool follow(const SCEV *S) { 461 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(S); 462 if (!Unknown) 463 return true; 464 465 Values.insert(Unknown->getValue()); 466 Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue()); 467 if (!Inst || (Inst->getOpcode() != Instruction::SRem && 468 Inst->getOpcode() != Instruction::SDiv)) 469 return false; 470 471 auto *Dividend = SE.getSCEV(Inst->getOperand(1)); 472 if (!isa<SCEVConstant>(Dividend)) 473 return false; 474 475 auto *Divisor = SE.getSCEV(Inst->getOperand(0)); 476 SCEVFindValues FindValues(SE, Values); 477 SCEVTraversal<SCEVFindValues> ST(FindValues); 478 ST.visitAll(Dividend); 479 ST.visitAll(Divisor); 480 481 return false; 482 } 483 bool isDone() { return false; } 484 }; 485 486 void findValues(const SCEV *Expr, ScalarEvolution &SE, 487 SetVector<Value *> &Values) { 488 SCEVFindValues FindValues(SE, Values); 489 SCEVTraversal<SCEVFindValues> ST(FindValues); 490 ST.visitAll(Expr); 491 } 492 493 bool hasScalarDepsInsideRegion(const SCEV *Expr, const Region *R, 494 llvm::Loop *Scope, bool AllowLoops) { 495 SCEVInRegionDependences InRegionDeps(R, Scope, AllowLoops); 496 SCEVTraversal<SCEVInRegionDependences> ST(InRegionDeps); 497 ST.visitAll(Expr); 498 return InRegionDeps.hasDependences(); 499 } 500 501 bool isAffineExpr(const Region *R, llvm::Loop *Scope, const SCEV *Expr, 502 ScalarEvolution &SE, InvariantLoadsSetTy *ILS) { 503 if (isa<SCEVCouldNotCompute>(Expr)) 504 return false; 505 506 SCEVValidator Validator(R, Scope, SE, ILS); 507 DEBUG({ 508 dbgs() << "\n"; 509 dbgs() << "Expr: " << *Expr << "\n"; 510 dbgs() << "Region: " << R->getNameStr() << "\n"; 511 dbgs() << " -> "; 512 }); 513 514 ValidatorResult Result = Validator.visit(Expr); 515 516 DEBUG({ 517 if (Result.isValid()) 518 dbgs() << "VALID\n"; 519 dbgs() << "\n"; 520 }); 521 522 return Result.isValid(); 523 } 524 525 static bool isAffineExpr(Value *V, const Region *R, Loop *Scope, 526 ScalarEvolution &SE, ParameterSetTy &Params) { 527 auto *E = SE.getSCEV(V); 528 if (isa<SCEVCouldNotCompute>(E)) 529 return false; 530 531 SCEVValidator Validator(R, Scope, SE, nullptr); 532 ValidatorResult Result = Validator.visit(E); 533 if (!Result.isValid()) 534 return false; 535 536 auto ResultParams = Result.getParameters(); 537 Params.insert(ResultParams.begin(), ResultParams.end()); 538 539 return true; 540 } 541 542 bool isAffineConstraint(Value *V, const Region *R, llvm::Loop *Scope, 543 ScalarEvolution &SE, ParameterSetTy &Params, 544 bool OrExpr) { 545 if (auto *ICmp = dyn_cast<ICmpInst>(V)) { 546 return isAffineConstraint(ICmp->getOperand(0), R, Scope, SE, Params, 547 true) && 548 isAffineConstraint(ICmp->getOperand(1), R, Scope, SE, Params, true); 549 } else if (auto *BinOp = dyn_cast<BinaryOperator>(V)) { 550 auto Opcode = BinOp->getOpcode(); 551 if (Opcode == Instruction::And || Opcode == Instruction::Or) 552 return isAffineConstraint(BinOp->getOperand(0), R, Scope, SE, Params, 553 false) && 554 isAffineConstraint(BinOp->getOperand(1), R, Scope, SE, Params, 555 false); 556 /* Fall through */ 557 } 558 559 if (!OrExpr) 560 return false; 561 562 return isAffineExpr(V, R, Scope, SE, Params); 563 } 564 565 ParameterSetTy getParamsInAffineExpr(const Region *R, Loop *Scope, 566 const SCEV *Expr, ScalarEvolution &SE) { 567 if (isa<SCEVCouldNotCompute>(Expr)) 568 return ParameterSetTy(); 569 570 InvariantLoadsSetTy ILS; 571 SCEVValidator Validator(R, Scope, SE, &ILS); 572 ValidatorResult Result = Validator.visit(Expr); 573 assert(Result.isValid() && "Requested parameters for an invalid SCEV!"); 574 575 return Result.getParameters(); 576 } 577 578 std::pair<const SCEVConstant *, const SCEV *> 579 extractConstantFactor(const SCEV *S, ScalarEvolution &SE) { 580 auto *ConstPart = cast<SCEVConstant>(SE.getConstant(S->getType(), 1)); 581 582 if (auto *Constant = dyn_cast<SCEVConstant>(S)) 583 return std::make_pair(Constant, SE.getConstant(S->getType(), 1)); 584 585 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S); 586 if (AddRec) { 587 auto *StartExpr = AddRec->getStart(); 588 if (StartExpr->isZero()) { 589 auto StepPair = extractConstantFactor(AddRec->getStepRecurrence(SE), SE); 590 auto *LeftOverAddRec = 591 SE.getAddRecExpr(StartExpr, StepPair.second, AddRec->getLoop(), 592 AddRec->getNoWrapFlags()); 593 return std::make_pair(StepPair.first, LeftOverAddRec); 594 } 595 return std::make_pair(ConstPart, S); 596 } 597 598 if (auto *Add = dyn_cast<SCEVAddExpr>(S)) { 599 SmallVector<const SCEV *, 4> LeftOvers; 600 auto Op0Pair = extractConstantFactor(Add->getOperand(0), SE); 601 auto *Factor = Op0Pair.first; 602 if (SE.isKnownNegative(Factor)) { 603 Factor = cast<SCEVConstant>(SE.getNegativeSCEV(Factor)); 604 LeftOvers.push_back(SE.getNegativeSCEV(Op0Pair.second)); 605 } else { 606 LeftOvers.push_back(Op0Pair.second); 607 } 608 609 for (unsigned u = 1, e = Add->getNumOperands(); u < e; u++) { 610 auto OpUPair = extractConstantFactor(Add->getOperand(u), SE); 611 // TODO: Use something smarter than equality here, e.g., gcd. 612 if (Factor == OpUPair.first) 613 LeftOvers.push_back(OpUPair.second); 614 else if (Factor == SE.getNegativeSCEV(OpUPair.first)) 615 LeftOvers.push_back(SE.getNegativeSCEV(OpUPair.second)); 616 else 617 return std::make_pair(ConstPart, S); 618 } 619 620 auto *NewAdd = SE.getAddExpr(LeftOvers, Add->getNoWrapFlags()); 621 return std::make_pair(Factor, NewAdd); 622 } 623 624 auto *Mul = dyn_cast<SCEVMulExpr>(S); 625 if (!Mul) 626 return std::make_pair(ConstPart, S); 627 628 SmallVector<const SCEV *, 4> LeftOvers; 629 for (auto *Op : Mul->operands()) 630 if (isa<SCEVConstant>(Op)) 631 ConstPart = cast<SCEVConstant>(SE.getMulExpr(ConstPart, Op)); 632 else 633 LeftOvers.push_back(Op); 634 635 return std::make_pair(ConstPart, SE.getMulExpr(LeftOvers)); 636 } 637 } // namespace polly 638