1 //===- ScopDetection.cpp - Detect Scops -----------------------------------===// 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 // Detect the maximal Scops of a function. 11 // 12 // A static control part (Scop) is a subgraph of the control flow graph (CFG) 13 // that only has statically known control flow and can therefore be described 14 // within the polyhedral model. 15 // 16 // Every Scop fulfills these restrictions: 17 // 18 // * It is a single entry single exit region 19 // 20 // * Only affine linear bounds in the loops 21 // 22 // Every natural loop in a Scop must have a number of loop iterations that can 23 // be described as an affine linear function in surrounding loop iterators or 24 // parameters. (A parameter is a scalar that does not change its value during 25 // execution of the Scop). 26 // 27 // * Only comparisons of affine linear expressions in conditions 28 // 29 // * All loops and conditions perfectly nested 30 // 31 // The control flow needs to be structured such that it could be written using 32 // just 'for' and 'if' statements, without the need for any 'goto', 'break' or 33 // 'continue'. 34 // 35 // * Side effect free functions call 36 // 37 // Function calls and intrinsics that do not have side effects (readnone) 38 // or memory intrinsics (memset, memcpy, memmove) are allowed. 39 // 40 // The Scop detection finds the largest Scops by checking if the largest 41 // region is a Scop. If this is not the case, its canonical subregions are 42 // checked until a region is a Scop. It is now tried to extend this Scop by 43 // creating a larger non canonical region. 44 // 45 //===----------------------------------------------------------------------===// 46 47 #include "polly/ScopDetection.h" 48 #include "polly/LinkAllPasses.h" 49 #include "polly/Options.h" 50 #include "polly/ScopDetectionDiagnostic.h" 51 #include "polly/Support/SCEVValidator.h" 52 #include "polly/Support/ScopHelper.h" 53 #include "polly/Support/ScopLocation.h" 54 #include "llvm/ADT/DenseMap.h" 55 #include "llvm/ADT/SetVector.h" 56 #include "llvm/ADT/SmallPtrSet.h" 57 #include "llvm/ADT/SmallVector.h" 58 #include "llvm/ADT/Statistic.h" 59 #include "llvm/ADT/StringRef.h" 60 #include "llvm/Analysis/AliasAnalysis.h" 61 #include "llvm/Analysis/Loads.h" 62 #include "llvm/Analysis/LoopInfo.h" 63 #include "llvm/Analysis/MemoryLocation.h" 64 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 65 #include "llvm/Analysis/RegionInfo.h" 66 #include "llvm/Analysis/ScalarEvolution.h" 67 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 68 #include "llvm/IR/BasicBlock.h" 69 #include "llvm/IR/Constants.h" 70 #include "llvm/IR/DebugLoc.h" 71 #include "llvm/IR/DerivedTypes.h" 72 #include "llvm/IR/DiagnosticInfo.h" 73 #include "llvm/IR/DiagnosticPrinter.h" 74 #include "llvm/IR/Dominators.h" 75 #include "llvm/IR/Function.h" 76 #include "llvm/IR/InstrTypes.h" 77 #include "llvm/IR/Instruction.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/Intrinsics.h" 81 #include "llvm/IR/LLVMContext.h" 82 #include "llvm/IR/Metadata.h" 83 #include "llvm/IR/Module.h" 84 #include "llvm/IR/PassManager.h" 85 #include "llvm/IR/Type.h" 86 #include "llvm/IR/Value.h" 87 #include "llvm/Pass.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/ErrorHandling.h" 92 #include "llvm/Support/Regex.h" 93 #include "llvm/Support/raw_ostream.h" 94 #include <algorithm> 95 #include <cassert> 96 #include <memory> 97 #include <stack> 98 #include <string> 99 #include <utility> 100 #include <vector> 101 102 using namespace llvm; 103 using namespace polly; 104 105 #define DEBUG_TYPE "polly-detect" 106 107 // This option is set to a very high value, as analyzing such loops increases 108 // compile time on several cases. For experiments that enable this option, 109 // a value of around 40 has been working to avoid run-time regressions with 110 // Polly while still exposing interesting optimization opportunities. 111 static cl::opt<int> ProfitabilityMinPerLoopInstructions( 112 "polly-detect-profitability-min-per-loop-insts", 113 cl::desc("The minimal number of per-loop instructions before a single loop " 114 "region is considered profitable"), 115 cl::Hidden, cl::ValueRequired, cl::init(100000000), cl::cat(PollyCategory)); 116 117 bool polly::PollyProcessUnprofitable; 118 119 static cl::opt<bool, true> XPollyProcessUnprofitable( 120 "polly-process-unprofitable", 121 cl::desc( 122 "Process scops that are unlikely to benefit from Polly optimizations."), 123 cl::location(PollyProcessUnprofitable), cl::init(false), cl::ZeroOrMore, 124 cl::cat(PollyCategory)); 125 126 static cl::list<std::string> OnlyFunctions( 127 "polly-only-func", 128 cl::desc("Only run on functions that match a regex. " 129 "Multiple regexes can be comma separated. " 130 "Scop detection will run on all functions that match " 131 "ANY of the regexes provided."), 132 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory)); 133 134 static cl::list<std::string> IgnoredFunctions( 135 "polly-ignore-func", 136 cl::desc("Ignore functions that match a regex. " 137 "Multiple regexes can be comma separated. " 138 "Scop detection will ignore all functions that match " 139 "ANY of the regexes provided."), 140 cl::ZeroOrMore, cl::CommaSeparated, cl::cat(PollyCategory)); 141 142 bool polly::PollyAllowFullFunction; 143 144 static cl::opt<bool, true> 145 XAllowFullFunction("polly-detect-full-functions", 146 cl::desc("Allow the detection of full functions"), 147 cl::location(polly::PollyAllowFullFunction), 148 cl::init(false), cl::cat(PollyCategory)); 149 150 static cl::opt<std::string> OnlyRegion( 151 "polly-only-region", 152 cl::desc("Only run on certain regions (The provided identifier must " 153 "appear in the name of the region's entry block"), 154 cl::value_desc("identifier"), cl::ValueRequired, cl::init(""), 155 cl::cat(PollyCategory)); 156 157 static cl::opt<bool> 158 IgnoreAliasing("polly-ignore-aliasing", 159 cl::desc("Ignore possible aliasing of the array bases"), 160 cl::Hidden, cl::init(false), cl::ZeroOrMore, 161 cl::cat(PollyCategory)); 162 163 bool polly::PollyAllowUnsignedOperations; 164 165 static cl::opt<bool, true> XPollyAllowUnsignedOperations( 166 "polly-allow-unsigned-operations", 167 cl::desc("Allow unsigned operations such as comparisons or zero-extends."), 168 cl::location(PollyAllowUnsignedOperations), cl::Hidden, cl::ZeroOrMore, 169 cl::init(true), cl::cat(PollyCategory)); 170 171 bool polly::PollyUseRuntimeAliasChecks; 172 173 static cl::opt<bool, true> XPollyUseRuntimeAliasChecks( 174 "polly-use-runtime-alias-checks", 175 cl::desc("Use runtime alias checks to resolve possible aliasing."), 176 cl::location(PollyUseRuntimeAliasChecks), cl::Hidden, cl::ZeroOrMore, 177 cl::init(true), cl::cat(PollyCategory)); 178 179 static cl::opt<bool> 180 ReportLevel("polly-report", 181 cl::desc("Print information about the activities of Polly"), 182 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 183 184 static cl::opt<bool> AllowDifferentTypes( 185 "polly-allow-differing-element-types", 186 cl::desc("Allow different element types for array accesses"), cl::Hidden, 187 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory)); 188 189 static cl::opt<bool> 190 AllowNonAffine("polly-allow-nonaffine", 191 cl::desc("Allow non affine access functions in arrays"), 192 cl::Hidden, cl::init(false), cl::ZeroOrMore, 193 cl::cat(PollyCategory)); 194 195 static cl::opt<bool> 196 AllowModrefCall("polly-allow-modref-calls", 197 cl::desc("Allow functions with known modref behavior"), 198 cl::Hidden, cl::init(false), cl::ZeroOrMore, 199 cl::cat(PollyCategory)); 200 201 static cl::opt<bool> AllowNonAffineSubRegions( 202 "polly-allow-nonaffine-branches", 203 cl::desc("Allow non affine conditions for branches"), cl::Hidden, 204 cl::init(true), cl::ZeroOrMore, cl::cat(PollyCategory)); 205 206 static cl::opt<bool> 207 AllowNonAffineSubLoops("polly-allow-nonaffine-loops", 208 cl::desc("Allow non affine conditions for loops"), 209 cl::Hidden, cl::init(false), cl::ZeroOrMore, 210 cl::cat(PollyCategory)); 211 212 static cl::opt<bool, true> 213 TrackFailures("polly-detect-track-failures", 214 cl::desc("Track failure strings in detecting scop regions"), 215 cl::location(PollyTrackFailures), cl::Hidden, cl::ZeroOrMore, 216 cl::init(true), cl::cat(PollyCategory)); 217 218 static cl::opt<bool> KeepGoing("polly-detect-keep-going", 219 cl::desc("Do not fail on the first error."), 220 cl::Hidden, cl::ZeroOrMore, cl::init(false), 221 cl::cat(PollyCategory)); 222 223 static cl::opt<bool, true> 224 PollyDelinearizeX("polly-delinearize", 225 cl::desc("Delinearize array access functions"), 226 cl::location(PollyDelinearize), cl::Hidden, 227 cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory)); 228 229 static cl::opt<bool> 230 VerifyScops("polly-detect-verify", 231 cl::desc("Verify the detected SCoPs after each transformation"), 232 cl::Hidden, cl::init(false), cl::ZeroOrMore, 233 cl::cat(PollyCategory)); 234 235 bool polly::PollyInvariantLoadHoisting; 236 237 static cl::opt<bool, true> XPollyInvariantLoadHoisting( 238 "polly-invariant-load-hoisting", cl::desc("Hoist invariant loads."), 239 cl::location(PollyInvariantLoadHoisting), cl::Hidden, cl::ZeroOrMore, 240 cl::init(false), cl::cat(PollyCategory)); 241 242 /// The minimal trip count under which loops are considered unprofitable. 243 static const unsigned MIN_LOOP_TRIP_COUNT = 8; 244 245 bool polly::PollyTrackFailures = false; 246 bool polly::PollyDelinearize = false; 247 StringRef polly::PollySkipFnAttr = "polly.skip.fn"; 248 249 //===----------------------------------------------------------------------===// 250 // Statistics. 251 252 STATISTIC(NumScopRegions, "Number of scops"); 253 STATISTIC(NumLoopsInScop, "Number of loops in scops"); 254 STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0"); 255 STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1"); 256 STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2"); 257 STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3"); 258 STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4"); 259 STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5"); 260 STATISTIC(NumScopsDepthLarger, 261 "Number of scops with maximal loop depth 6 and larger"); 262 STATISTIC(NumProfScopRegions, "Number of scops (profitable scops only)"); 263 STATISTIC(NumLoopsInProfScop, 264 "Number of loops in scops (profitable scops only)"); 265 STATISTIC(NumLoopsOverall, "Number of total loops"); 266 STATISTIC(NumProfScopsDepthZero, 267 "Number of scops with maximal loop depth 0 (profitable scops only)"); 268 STATISTIC(NumProfScopsDepthOne, 269 "Number of scops with maximal loop depth 1 (profitable scops only)"); 270 STATISTIC(NumProfScopsDepthTwo, 271 "Number of scops with maximal loop depth 2 (profitable scops only)"); 272 STATISTIC(NumProfScopsDepthThree, 273 "Number of scops with maximal loop depth 3 (profitable scops only)"); 274 STATISTIC(NumProfScopsDepthFour, 275 "Number of scops with maximal loop depth 4 (profitable scops only)"); 276 STATISTIC(NumProfScopsDepthFive, 277 "Number of scops with maximal loop depth 5 (profitable scops only)"); 278 STATISTIC(NumProfScopsDepthLarger, 279 "Number of scops with maximal loop depth 6 and larger " 280 "(profitable scops only)"); 281 STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops"); 282 STATISTIC(MaxNumLoopsInProfScop, 283 "Maximal number of loops in scops (profitable scops only)"); 284 285 static void updateLoopCountStatistic(ScopDetection::LoopStats Stats, 286 bool OnlyProfitable); 287 288 namespace { 289 290 class DiagnosticScopFound : public DiagnosticInfo { 291 private: 292 static int PluginDiagnosticKind; 293 294 Function &F; 295 std::string FileName; 296 unsigned EntryLine, ExitLine; 297 298 public: 299 DiagnosticScopFound(Function &F, std::string FileName, unsigned EntryLine, 300 unsigned ExitLine) 301 : DiagnosticInfo(PluginDiagnosticKind, DS_Note), F(F), FileName(FileName), 302 EntryLine(EntryLine), ExitLine(ExitLine) {} 303 304 void print(DiagnosticPrinter &DP) const override; 305 306 static bool classof(const DiagnosticInfo *DI) { 307 return DI->getKind() == PluginDiagnosticKind; 308 } 309 }; 310 } // namespace 311 312 int DiagnosticScopFound::PluginDiagnosticKind = 313 getNextAvailablePluginDiagnosticKind(); 314 315 void DiagnosticScopFound::print(DiagnosticPrinter &DP) const { 316 DP << "Polly detected an optimizable loop region (scop) in function '" << F 317 << "'\n"; 318 319 if (FileName.empty()) { 320 DP << "Scop location is unknown. Compile with debug info " 321 "(-g) to get more precise information. "; 322 return; 323 } 324 325 DP << FileName << ":" << EntryLine << ": Start of scop\n"; 326 DP << FileName << ":" << ExitLine << ": End of scop"; 327 } 328 329 /// Check if a string matches any regex in a list of regexes. 330 /// @param Str the input string to match against. 331 /// @param RegexList a list of strings that are regular expressions. 332 static bool doesStringMatchAnyRegex(StringRef Str, 333 const cl::list<std::string> &RegexList) { 334 for (auto RegexStr : RegexList) { 335 Regex R(RegexStr); 336 337 std::string Err; 338 if (!R.isValid(Err)) 339 report_fatal_error("invalid regex given as input to polly: " + Err, true); 340 341 if (R.match(Str)) 342 return true; 343 } 344 return false; 345 } 346 //===----------------------------------------------------------------------===// 347 // ScopDetection. 348 349 ScopDetection::ScopDetection(Function &F, const DominatorTree &DT, 350 ScalarEvolution &SE, LoopInfo &LI, RegionInfo &RI, 351 AliasAnalysis &AA, OptimizationRemarkEmitter &ORE) 352 : DT(DT), SE(SE), LI(LI), RI(RI), AA(AA), ORE(ORE) { 353 if (!PollyProcessUnprofitable && LI.empty()) 354 return; 355 356 Region *TopRegion = RI.getTopLevelRegion(); 357 358 if (!OnlyFunctions.empty() && 359 !doesStringMatchAnyRegex(F.getName(), OnlyFunctions)) 360 return; 361 362 if (doesStringMatchAnyRegex(F.getName(), IgnoredFunctions)) 363 return; 364 365 if (!isValidFunction(F)) 366 return; 367 368 findScops(*TopRegion); 369 370 NumScopRegions += ValidRegions.size(); 371 372 // Prune non-profitable regions. 373 for (auto &DIt : DetectionContextMap) { 374 auto &DC = DIt.getSecond(); 375 if (DC.Log.hasErrors()) 376 continue; 377 if (!ValidRegions.count(&DC.CurRegion)) 378 continue; 379 LoopStats Stats = countBeneficialLoops(&DC.CurRegion, SE, LI, 0); 380 updateLoopCountStatistic(Stats, false /* OnlyProfitable */); 381 if (isProfitableRegion(DC)) { 382 updateLoopCountStatistic(Stats, true /* OnlyProfitable */); 383 continue; 384 } 385 386 ValidRegions.remove(&DC.CurRegion); 387 } 388 389 NumProfScopRegions += ValidRegions.size(); 390 NumLoopsOverall += countBeneficialLoops(TopRegion, SE, LI, 0).NumLoops; 391 392 // Only makes sense when we tracked errors. 393 if (PollyTrackFailures) 394 emitMissedRemarks(F); 395 396 if (ReportLevel) 397 printLocations(F); 398 399 assert(ValidRegions.size() <= DetectionContextMap.size() && 400 "Cached more results than valid regions"); 401 } 402 403 template <class RR, typename... Args> 404 inline bool ScopDetection::invalid(DetectionContext &Context, bool Assert, 405 Args &&... Arguments) const { 406 if (!Context.Verifying) { 407 RejectLog &Log = Context.Log; 408 std::shared_ptr<RR> RejectReason = std::make_shared<RR>(Arguments...); 409 410 if (PollyTrackFailures) 411 Log.report(RejectReason); 412 413 LLVM_DEBUG(dbgs() << RejectReason->getMessage()); 414 LLVM_DEBUG(dbgs() << "\n"); 415 } else { 416 assert(!Assert && "Verification of detected scop failed"); 417 } 418 419 return false; 420 } 421 422 bool ScopDetection::isMaxRegionInScop(const Region &R, bool Verify) const { 423 if (!ValidRegions.count(&R)) 424 return false; 425 426 if (Verify) { 427 DetectionContextMap.erase(getBBPairForRegion(&R)); 428 const auto &It = DetectionContextMap.insert(std::make_pair( 429 getBBPairForRegion(&R), 430 DetectionContext(const_cast<Region &>(R), AA, false /*verifying*/))); 431 DetectionContext &Context = It.first->second; 432 return isValidRegion(Context); 433 } 434 435 return true; 436 } 437 438 std::string ScopDetection::regionIsInvalidBecause(const Region *R) const { 439 // Get the first error we found. Even in keep-going mode, this is the first 440 // reason that caused the candidate to be rejected. 441 auto *Log = lookupRejectionLog(R); 442 443 // This can happen when we marked a region invalid, but didn't track 444 // an error for it. 445 if (!Log || !Log->hasErrors()) 446 return ""; 447 448 RejectReasonPtr RR = *Log->begin(); 449 return RR->getMessage(); 450 } 451 452 bool ScopDetection::addOverApproximatedRegion(Region *AR, 453 DetectionContext &Context) const { 454 // If we already know about Ar we can exit. 455 if (!Context.NonAffineSubRegionSet.insert(AR)) 456 return true; 457 458 // All loops in the region have to be overapproximated too if there 459 // are accesses that depend on the iteration count. 460 461 for (BasicBlock *BB : AR->blocks()) { 462 Loop *L = LI.getLoopFor(BB); 463 if (AR->contains(L)) 464 Context.BoxedLoopsSet.insert(L); 465 } 466 467 return (AllowNonAffineSubLoops || Context.BoxedLoopsSet.empty()); 468 } 469 470 bool ScopDetection::onlyValidRequiredInvariantLoads( 471 InvariantLoadsSetTy &RequiredILS, DetectionContext &Context) const { 472 Region &CurRegion = Context.CurRegion; 473 const DataLayout &DL = CurRegion.getEntry()->getModule()->getDataLayout(); 474 475 if (!PollyInvariantLoadHoisting && !RequiredILS.empty()) 476 return false; 477 478 for (LoadInst *Load : RequiredILS) { 479 // If we already know a load has been accepted as required invariant, we 480 // already run the validation below once and consequently don't need to 481 // run it again. Hence, we return early. For certain test cases (e.g., 482 // COSMO this avoids us spending 50% of scop-detection time in this 483 // very function (and its children). 484 if (Context.RequiredILS.count(Load)) 485 continue; 486 if (!isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS)) 487 return false; 488 489 for (auto NonAffineRegion : Context.NonAffineSubRegionSet) { 490 if (isSafeToLoadUnconditionally(Load->getPointerOperand(), 491 Load->getAlignment(), DL)) 492 continue; 493 494 if (NonAffineRegion->contains(Load) && 495 Load->getParent() != NonAffineRegion->getEntry()) 496 return false; 497 } 498 } 499 500 Context.RequiredILS.insert(RequiredILS.begin(), RequiredILS.end()); 501 502 return true; 503 } 504 505 bool ScopDetection::involvesMultiplePtrs(const SCEV *S0, const SCEV *S1, 506 Loop *Scope) const { 507 SetVector<Value *> Values; 508 findValues(S0, SE, Values); 509 if (S1) 510 findValues(S1, SE, Values); 511 512 SmallPtrSet<Value *, 8> PtrVals; 513 for (auto *V : Values) { 514 if (auto *P2I = dyn_cast<PtrToIntInst>(V)) 515 V = P2I->getOperand(0); 516 517 if (!V->getType()->isPointerTy()) 518 continue; 519 520 auto *PtrSCEV = SE.getSCEVAtScope(V, Scope); 521 if (isa<SCEVConstant>(PtrSCEV)) 522 continue; 523 524 auto *BasePtr = dyn_cast<SCEVUnknown>(SE.getPointerBase(PtrSCEV)); 525 if (!BasePtr) 526 return true; 527 528 auto *BasePtrVal = BasePtr->getValue(); 529 if (PtrVals.insert(BasePtrVal).second) { 530 for (auto *PtrVal : PtrVals) 531 if (PtrVal != BasePtrVal && !AA.isNoAlias(PtrVal, BasePtrVal)) 532 return true; 533 } 534 } 535 536 return false; 537 } 538 539 bool ScopDetection::isAffine(const SCEV *S, Loop *Scope, 540 DetectionContext &Context) const { 541 InvariantLoadsSetTy AccessILS; 542 if (!isAffineExpr(&Context.CurRegion, Scope, S, SE, &AccessILS)) 543 return false; 544 545 if (!onlyValidRequiredInvariantLoads(AccessILS, Context)) 546 return false; 547 548 return true; 549 } 550 551 bool ScopDetection::isValidSwitch(BasicBlock &BB, SwitchInst *SI, 552 Value *Condition, bool IsLoopBranch, 553 DetectionContext &Context) const { 554 Loop *L = LI.getLoopFor(&BB); 555 const SCEV *ConditionSCEV = SE.getSCEVAtScope(Condition, L); 556 557 if (IsLoopBranch && L->isLoopLatch(&BB)) 558 return false; 559 560 // Check for invalid usage of different pointers in one expression. 561 if (involvesMultiplePtrs(ConditionSCEV, nullptr, L)) 562 return false; 563 564 if (isAffine(ConditionSCEV, L, Context)) 565 return true; 566 567 if (AllowNonAffineSubRegions && 568 addOverApproximatedRegion(RI.getRegionFor(&BB), Context)) 569 return true; 570 571 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, 572 ConditionSCEV, ConditionSCEV, SI); 573 } 574 575 bool ScopDetection::isValidBranch(BasicBlock &BB, BranchInst *BI, 576 Value *Condition, bool IsLoopBranch, 577 DetectionContext &Context) const { 578 // Constant integer conditions are always affine. 579 if (isa<ConstantInt>(Condition)) 580 return true; 581 582 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) { 583 auto Opcode = BinOp->getOpcode(); 584 if (Opcode == Instruction::And || Opcode == Instruction::Or) { 585 Value *Op0 = BinOp->getOperand(0); 586 Value *Op1 = BinOp->getOperand(1); 587 return isValidBranch(BB, BI, Op0, IsLoopBranch, Context) && 588 isValidBranch(BB, BI, Op1, IsLoopBranch, Context); 589 } 590 } 591 592 if (auto PHI = dyn_cast<PHINode>(Condition)) { 593 auto *Unique = dyn_cast_or_null<ConstantInt>( 594 getUniqueNonErrorValue(PHI, &Context.CurRegion, LI, DT)); 595 if (Unique && (Unique->isZero() || Unique->isOne())) 596 return true; 597 } 598 599 if (auto Load = dyn_cast<LoadInst>(Condition)) 600 if (!IsLoopBranch && Context.CurRegion.contains(Load)) { 601 Context.RequiredILS.insert(Load); 602 return true; 603 } 604 605 // Non constant conditions of branches need to be ICmpInst. 606 if (!isa<ICmpInst>(Condition)) { 607 if (!IsLoopBranch && AllowNonAffineSubRegions && 608 addOverApproximatedRegion(RI.getRegionFor(&BB), Context)) 609 return true; 610 return invalid<ReportInvalidCond>(Context, /*Assert=*/true, BI, &BB); 611 } 612 613 ICmpInst *ICmp = cast<ICmpInst>(Condition); 614 615 // Are both operands of the ICmp affine? 616 if (isa<UndefValue>(ICmp->getOperand(0)) || 617 isa<UndefValue>(ICmp->getOperand(1))) 618 return invalid<ReportUndefOperand>(Context, /*Assert=*/true, &BB, ICmp); 619 620 Loop *L = LI.getLoopFor(&BB); 621 const SCEV *LHS = SE.getSCEVAtScope(ICmp->getOperand(0), L); 622 const SCEV *RHS = SE.getSCEVAtScope(ICmp->getOperand(1), L); 623 624 LHS = tryForwardThroughPHI(LHS, Context.CurRegion, SE, LI, DT); 625 RHS = tryForwardThroughPHI(RHS, Context.CurRegion, SE, LI, DT); 626 627 // If unsigned operations are not allowed try to approximate the region. 628 if (ICmp->isUnsigned() && !PollyAllowUnsignedOperations) 629 return !IsLoopBranch && AllowNonAffineSubRegions && 630 addOverApproximatedRegion(RI.getRegionFor(&BB), Context); 631 632 // Check for invalid usage of different pointers in one expression. 633 if (ICmp->isEquality() && involvesMultiplePtrs(LHS, nullptr, L) && 634 involvesMultiplePtrs(RHS, nullptr, L)) 635 return false; 636 637 // Check for invalid usage of different pointers in a relational comparison. 638 if (ICmp->isRelational() && involvesMultiplePtrs(LHS, RHS, L)) 639 return false; 640 641 if (isAffine(LHS, L, Context) && isAffine(RHS, L, Context)) 642 return true; 643 644 if (!IsLoopBranch && AllowNonAffineSubRegions && 645 addOverApproximatedRegion(RI.getRegionFor(&BB), Context)) 646 return true; 647 648 if (IsLoopBranch) 649 return false; 650 651 return invalid<ReportNonAffBranch>(Context, /*Assert=*/true, &BB, LHS, RHS, 652 ICmp); 653 } 654 655 bool ScopDetection::isValidCFG(BasicBlock &BB, bool IsLoopBranch, 656 bool AllowUnreachable, 657 DetectionContext &Context) const { 658 Region &CurRegion = Context.CurRegion; 659 660 TerminatorInst *TI = BB.getTerminator(); 661 662 if (AllowUnreachable && isa<UnreachableInst>(TI)) 663 return true; 664 665 // Return instructions are only valid if the region is the top level region. 666 if (isa<ReturnInst>(TI) && CurRegion.isTopLevelRegion()) 667 return true; 668 669 Value *Condition = getConditionFromTerminator(TI); 670 671 if (!Condition) 672 return invalid<ReportInvalidTerminator>(Context, /*Assert=*/true, &BB); 673 674 // UndefValue is not allowed as condition. 675 if (isa<UndefValue>(Condition)) 676 return invalid<ReportUndefCond>(Context, /*Assert=*/true, TI, &BB); 677 678 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) 679 return isValidBranch(BB, BI, Condition, IsLoopBranch, Context); 680 681 SwitchInst *SI = dyn_cast<SwitchInst>(TI); 682 assert(SI && "Terminator was neither branch nor switch"); 683 684 return isValidSwitch(BB, SI, Condition, IsLoopBranch, Context); 685 } 686 687 bool ScopDetection::isValidCallInst(CallInst &CI, 688 DetectionContext &Context) const { 689 if (CI.doesNotReturn()) 690 return false; 691 692 if (CI.doesNotAccessMemory()) 693 return true; 694 695 if (auto *II = dyn_cast<IntrinsicInst>(&CI)) 696 if (isValidIntrinsicInst(*II, Context)) 697 return true; 698 699 Function *CalledFunction = CI.getCalledFunction(); 700 701 // Indirect calls are not supported. 702 if (CalledFunction == nullptr) 703 return false; 704 705 if (isDebugCall(&CI)) { 706 LLVM_DEBUG(dbgs() << "Allow call to debug function: " 707 << CalledFunction->getName() << '\n'); 708 return true; 709 } 710 711 if (AllowModrefCall) { 712 switch (AA.getModRefBehavior(CalledFunction)) { 713 case FMRB_UnknownModRefBehavior: 714 return false; 715 case FMRB_DoesNotAccessMemory: 716 case FMRB_OnlyReadsMemory: 717 // Implicitly disable delinearization since we have an unknown 718 // accesses with an unknown access function. 719 Context.HasUnknownAccess = true; 720 Context.AST.add(&CI); 721 return true; 722 case FMRB_OnlyReadsArgumentPointees: 723 case FMRB_OnlyAccessesArgumentPointees: 724 for (const auto &Arg : CI.arg_operands()) { 725 if (!Arg->getType()->isPointerTy()) 726 continue; 727 728 // Bail if a pointer argument has a base address not known to 729 // ScalarEvolution. Note that a zero pointer is acceptable. 730 auto *ArgSCEV = SE.getSCEVAtScope(Arg, LI.getLoopFor(CI.getParent())); 731 if (ArgSCEV->isZero()) 732 continue; 733 734 auto *BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV)); 735 if (!BP) 736 return false; 737 738 // Implicitly disable delinearization since we have an unknown 739 // accesses with an unknown access function. 740 Context.HasUnknownAccess = true; 741 } 742 743 Context.AST.add(&CI); 744 return true; 745 case FMRB_DoesNotReadMemory: 746 case FMRB_OnlyAccessesInaccessibleMem: 747 case FMRB_OnlyAccessesInaccessibleOrArgMem: 748 return false; 749 } 750 } 751 752 return false; 753 } 754 755 bool ScopDetection::isValidIntrinsicInst(IntrinsicInst &II, 756 DetectionContext &Context) const { 757 if (isIgnoredIntrinsic(&II)) 758 return true; 759 760 // The closest loop surrounding the call instruction. 761 Loop *L = LI.getLoopFor(II.getParent()); 762 763 // The access function and base pointer for memory intrinsics. 764 const SCEV *AF; 765 const SCEVUnknown *BP; 766 767 switch (II.getIntrinsicID()) { 768 // Memory intrinsics that can be represented are supported. 769 case Intrinsic::memmove: 770 case Intrinsic::memcpy: 771 AF = SE.getSCEVAtScope(cast<MemTransferInst>(II).getSource(), L); 772 if (!AF->isZero()) { 773 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF)); 774 // Bail if the source pointer is not valid. 775 if (!isValidAccess(&II, AF, BP, Context)) 776 return false; 777 } 778 // Fall through 779 case Intrinsic::memset: 780 AF = SE.getSCEVAtScope(cast<MemIntrinsic>(II).getDest(), L); 781 if (!AF->isZero()) { 782 BP = dyn_cast<SCEVUnknown>(SE.getPointerBase(AF)); 783 // Bail if the destination pointer is not valid. 784 if (!isValidAccess(&II, AF, BP, Context)) 785 return false; 786 } 787 788 // Bail if the length is not affine. 789 if (!isAffine(SE.getSCEVAtScope(cast<MemIntrinsic>(II).getLength(), L), L, 790 Context)) 791 return false; 792 793 return true; 794 default: 795 break; 796 } 797 798 return false; 799 } 800 801 bool ScopDetection::isInvariant(Value &Val, const Region &Reg, 802 DetectionContext &Ctx) const { 803 // A reference to function argument or constant value is invariant. 804 if (isa<Argument>(Val) || isa<Constant>(Val)) 805 return true; 806 807 Instruction *I = dyn_cast<Instruction>(&Val); 808 if (!I) 809 return false; 810 811 if (!Reg.contains(I)) 812 return true; 813 814 // Loads within the SCoP may read arbitrary values, need to hoist them. If it 815 // is not hoistable, it will be rejected later, but here we assume it is and 816 // that makes the value invariant. 817 if (auto LI = dyn_cast<LoadInst>(I)) { 818 Ctx.RequiredILS.insert(LI); 819 return true; 820 } 821 822 return false; 823 } 824 825 namespace { 826 827 /// Remove smax of smax(0, size) expressions from a SCEV expression and 828 /// register the '...' components. 829 /// 830 /// Array access expressions as they are generated by GFortran contain smax(0, 831 /// size) expressions that confuse the 'normal' delinearization algorithm. 832 /// However, if we extract such expressions before the normal delinearization 833 /// takes place they can actually help to identify array size expressions in 834 /// Fortran accesses. For the subsequently following delinearization the smax(0, 835 /// size) component can be replaced by just 'size'. This is correct as we will 836 /// always add and verify the assumption that for all subscript expressions 837 /// 'exp' the inequality 0 <= exp < size holds. Hence, we will also verify 838 /// that 0 <= size, which means smax(0, size) == size. 839 class SCEVRemoveMax : public SCEVRewriteVisitor<SCEVRemoveMax> { 840 public: 841 SCEVRemoveMax(ScalarEvolution &SE, std::vector<const SCEV *> *Terms) 842 : SCEVRewriteVisitor(SE), Terms(Terms) {} 843 844 static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE, 845 std::vector<const SCEV *> *Terms = nullptr) { 846 SCEVRemoveMax Rewriter(SE, Terms); 847 return Rewriter.visit(Scev); 848 } 849 850 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) { 851 if ((Expr->getNumOperands() == 2) && Expr->getOperand(0)->isZero()) { 852 auto Res = visit(Expr->getOperand(1)); 853 if (Terms) 854 (*Terms).push_back(Res); 855 return Res; 856 } 857 858 return Expr; 859 } 860 861 private: 862 std::vector<const SCEV *> *Terms; 863 }; 864 } // namespace 865 866 SmallVector<const SCEV *, 4> 867 ScopDetection::getDelinearizationTerms(DetectionContext &Context, 868 const SCEVUnknown *BasePointer) const { 869 SmallVector<const SCEV *, 4> Terms; 870 for (const auto &Pair : Context.Accesses[BasePointer]) { 871 std::vector<const SCEV *> MaxTerms; 872 SCEVRemoveMax::rewrite(Pair.second, SE, &MaxTerms); 873 if (!MaxTerms.empty()) { 874 Terms.insert(Terms.begin(), MaxTerms.begin(), MaxTerms.end()); 875 continue; 876 } 877 // In case the outermost expression is a plain add, we check if any of its 878 // terms has the form 4 * %inst * %param * %param ..., aka a term that 879 // contains a product between a parameter and an instruction that is 880 // inside the scop. Such instructions, if allowed at all, are instructions 881 // SCEV can not represent, but Polly is still looking through. As a 882 // result, these instructions can depend on induction variables and are 883 // most likely no array sizes. However, terms that are multiplied with 884 // them are likely candidates for array sizes. 885 if (auto *AF = dyn_cast<SCEVAddExpr>(Pair.second)) { 886 for (auto Op : AF->operands()) { 887 if (auto *AF2 = dyn_cast<SCEVAddRecExpr>(Op)) 888 SE.collectParametricTerms(AF2, Terms); 889 if (auto *AF2 = dyn_cast<SCEVMulExpr>(Op)) { 890 SmallVector<const SCEV *, 0> Operands; 891 892 for (auto *MulOp : AF2->operands()) { 893 if (auto *Const = dyn_cast<SCEVConstant>(MulOp)) 894 Operands.push_back(Const); 895 if (auto *Unknown = dyn_cast<SCEVUnknown>(MulOp)) { 896 if (auto *Inst = dyn_cast<Instruction>(Unknown->getValue())) { 897 if (!Context.CurRegion.contains(Inst)) 898 Operands.push_back(MulOp); 899 900 } else { 901 Operands.push_back(MulOp); 902 } 903 } 904 } 905 if (Operands.size()) 906 Terms.push_back(SE.getMulExpr(Operands)); 907 } 908 } 909 } 910 if (Terms.empty()) 911 SE.collectParametricTerms(Pair.second, Terms); 912 } 913 return Terms; 914 } 915 916 bool ScopDetection::hasValidArraySizes(DetectionContext &Context, 917 SmallVectorImpl<const SCEV *> &Sizes, 918 const SCEVUnknown *BasePointer, 919 Loop *Scope) const { 920 // If no sizes were found, all sizes are trivially valid. We allow this case 921 // to make it possible to pass known-affine accesses to the delinearization to 922 // try to recover some interesting multi-dimensional accesses, but to still 923 // allow the already known to be affine access in case the delinearization 924 // fails. In such situations, the delinearization will just return a Sizes 925 // array of size zero. 926 if (Sizes.size() == 0) 927 return true; 928 929 Value *BaseValue = BasePointer->getValue(); 930 Region &CurRegion = Context.CurRegion; 931 for (const SCEV *DelinearizedSize : Sizes) { 932 if (!isAffine(DelinearizedSize, Scope, Context)) { 933 Sizes.clear(); 934 break; 935 } 936 if (auto *Unknown = dyn_cast<SCEVUnknown>(DelinearizedSize)) { 937 auto *V = dyn_cast<Value>(Unknown->getValue()); 938 if (auto *Load = dyn_cast<LoadInst>(V)) { 939 if (Context.CurRegion.contains(Load) && 940 isHoistableLoad(Load, CurRegion, LI, SE, DT, Context.RequiredILS)) 941 Context.RequiredILS.insert(Load); 942 continue; 943 } 944 } 945 if (hasScalarDepsInsideRegion(DelinearizedSize, &CurRegion, Scope, false, 946 Context.RequiredILS)) 947 return invalid<ReportNonAffineAccess>( 948 Context, /*Assert=*/true, DelinearizedSize, 949 Context.Accesses[BasePointer].front().first, BaseValue); 950 } 951 952 // No array shape derived. 953 if (Sizes.empty()) { 954 if (AllowNonAffine) 955 return true; 956 957 for (const auto &Pair : Context.Accesses[BasePointer]) { 958 const Instruction *Insn = Pair.first; 959 const SCEV *AF = Pair.second; 960 961 if (!isAffine(AF, Scope, Context)) { 962 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Insn, 963 BaseValue); 964 if (!KeepGoing) 965 return false; 966 } 967 } 968 return false; 969 } 970 return true; 971 } 972 973 // We first store the resulting memory accesses in TempMemoryAccesses. Only 974 // if the access functions for all memory accesses have been successfully 975 // delinearized we continue. Otherwise, we either report a failure or, if 976 // non-affine accesses are allowed, we drop the information. In case the 977 // information is dropped the memory accesses need to be overapproximated 978 // when translated to a polyhedral representation. 979 bool ScopDetection::computeAccessFunctions( 980 DetectionContext &Context, const SCEVUnknown *BasePointer, 981 std::shared_ptr<ArrayShape> Shape) const { 982 Value *BaseValue = BasePointer->getValue(); 983 bool BasePtrHasNonAffine = false; 984 MapInsnToMemAcc TempMemoryAccesses; 985 for (const auto &Pair : Context.Accesses[BasePointer]) { 986 const Instruction *Insn = Pair.first; 987 auto *AF = Pair.second; 988 AF = SCEVRemoveMax::rewrite(AF, SE); 989 bool IsNonAffine = false; 990 TempMemoryAccesses.insert(std::make_pair(Insn, MemAcc(Insn, Shape))); 991 MemAcc *Acc = &TempMemoryAccesses.find(Insn)->second; 992 auto *Scope = LI.getLoopFor(Insn->getParent()); 993 994 if (!AF) { 995 if (isAffine(Pair.second, Scope, Context)) 996 Acc->DelinearizedSubscripts.push_back(Pair.second); 997 else 998 IsNonAffine = true; 999 } else { 1000 if (Shape->DelinearizedSizes.size() == 0) { 1001 Acc->DelinearizedSubscripts.push_back(AF); 1002 } else { 1003 SE.computeAccessFunctions(AF, Acc->DelinearizedSubscripts, 1004 Shape->DelinearizedSizes); 1005 if (Acc->DelinearizedSubscripts.size() == 0) 1006 IsNonAffine = true; 1007 } 1008 for (const SCEV *S : Acc->DelinearizedSubscripts) 1009 if (!isAffine(S, Scope, Context)) 1010 IsNonAffine = true; 1011 } 1012 1013 // (Possibly) report non affine access 1014 if (IsNonAffine) { 1015 BasePtrHasNonAffine = true; 1016 if (!AllowNonAffine) 1017 invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, Pair.second, 1018 Insn, BaseValue); 1019 if (!KeepGoing && !AllowNonAffine) 1020 return false; 1021 } 1022 } 1023 1024 if (!BasePtrHasNonAffine) 1025 Context.InsnToMemAcc.insert(TempMemoryAccesses.begin(), 1026 TempMemoryAccesses.end()); 1027 1028 return true; 1029 } 1030 1031 bool ScopDetection::hasBaseAffineAccesses(DetectionContext &Context, 1032 const SCEVUnknown *BasePointer, 1033 Loop *Scope) const { 1034 auto Shape = std::shared_ptr<ArrayShape>(new ArrayShape(BasePointer)); 1035 1036 auto Terms = getDelinearizationTerms(Context, BasePointer); 1037 1038 SE.findArrayDimensions(Terms, Shape->DelinearizedSizes, 1039 Context.ElementSize[BasePointer]); 1040 1041 if (!hasValidArraySizes(Context, Shape->DelinearizedSizes, BasePointer, 1042 Scope)) 1043 return false; 1044 1045 return computeAccessFunctions(Context, BasePointer, Shape); 1046 } 1047 1048 bool ScopDetection::hasAffineMemoryAccesses(DetectionContext &Context) const { 1049 // TODO: If we have an unknown access and other non-affine accesses we do 1050 // not try to delinearize them for now. 1051 if (Context.HasUnknownAccess && !Context.NonAffineAccesses.empty()) 1052 return AllowNonAffine; 1053 1054 for (auto &Pair : Context.NonAffineAccesses) { 1055 auto *BasePointer = Pair.first; 1056 auto *Scope = Pair.second; 1057 if (!hasBaseAffineAccesses(Context, BasePointer, Scope)) { 1058 if (KeepGoing) 1059 continue; 1060 else 1061 return false; 1062 } 1063 } 1064 return true; 1065 } 1066 1067 bool ScopDetection::isValidAccess(Instruction *Inst, const SCEV *AF, 1068 const SCEVUnknown *BP, 1069 DetectionContext &Context) const { 1070 1071 if (!BP) 1072 return invalid<ReportNoBasePtr>(Context, /*Assert=*/true, Inst); 1073 1074 auto *BV = BP->getValue(); 1075 if (isa<UndefValue>(BV)) 1076 return invalid<ReportUndefBasePtr>(Context, /*Assert=*/true, Inst); 1077 1078 // FIXME: Think about allowing IntToPtrInst 1079 if (IntToPtrInst *Inst = dyn_cast<IntToPtrInst>(BV)) 1080 return invalid<ReportIntToPtr>(Context, /*Assert=*/true, Inst); 1081 1082 // Check that the base address of the access is invariant in the current 1083 // region. 1084 if (!isInvariant(*BV, Context.CurRegion, Context)) 1085 return invalid<ReportVariantBasePtr>(Context, /*Assert=*/true, BV, Inst); 1086 1087 AF = SE.getMinusSCEV(AF, BP); 1088 1089 const SCEV *Size; 1090 if (!isa<MemIntrinsic>(Inst)) { 1091 Size = SE.getElementSize(Inst); 1092 } else { 1093 auto *SizeTy = 1094 SE.getEffectiveSCEVType(PointerType::getInt8PtrTy(SE.getContext())); 1095 Size = SE.getConstant(SizeTy, 8); 1096 } 1097 1098 if (Context.ElementSize[BP]) { 1099 if (!AllowDifferentTypes && Context.ElementSize[BP] != Size) 1100 return invalid<ReportDifferentArrayElementSize>(Context, /*Assert=*/true, 1101 Inst, BV); 1102 1103 Context.ElementSize[BP] = SE.getSMinExpr(Size, Context.ElementSize[BP]); 1104 } else { 1105 Context.ElementSize[BP] = Size; 1106 } 1107 1108 bool IsVariantInNonAffineLoop = false; 1109 SetVector<const Loop *> Loops; 1110 findLoops(AF, Loops); 1111 for (const Loop *L : Loops) 1112 if (Context.BoxedLoopsSet.count(L)) 1113 IsVariantInNonAffineLoop = true; 1114 1115 auto *Scope = LI.getLoopFor(Inst->getParent()); 1116 bool IsAffine = !IsVariantInNonAffineLoop && isAffine(AF, Scope, Context); 1117 // Do not try to delinearize memory intrinsics and force them to be affine. 1118 if (isa<MemIntrinsic>(Inst) && !IsAffine) { 1119 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst, 1120 BV); 1121 } else if (PollyDelinearize && !IsVariantInNonAffineLoop) { 1122 Context.Accesses[BP].push_back({Inst, AF}); 1123 1124 if (!IsAffine || hasIVParams(AF)) 1125 Context.NonAffineAccesses.insert( 1126 std::make_pair(BP, LI.getLoopFor(Inst->getParent()))); 1127 } else if (!AllowNonAffine && !IsAffine) { 1128 return invalid<ReportNonAffineAccess>(Context, /*Assert=*/true, AF, Inst, 1129 BV); 1130 } 1131 1132 if (IgnoreAliasing) 1133 return true; 1134 1135 // Check if the base pointer of the memory access does alias with 1136 // any other pointer. This cannot be handled at the moment. 1137 AAMDNodes AATags; 1138 Inst->getAAMetadata(AATags); 1139 AliasSet &AS = Context.AST.getAliasSetForPointer( 1140 BP->getValue(), MemoryLocation::UnknownSize, AATags); 1141 1142 if (!AS.isMustAlias()) { 1143 if (PollyUseRuntimeAliasChecks) { 1144 bool CanBuildRunTimeCheck = true; 1145 // The run-time alias check places code that involves the base pointer at 1146 // the beginning of the SCoP. This breaks if the base pointer is defined 1147 // inside the scop. Hence, we can only create a run-time check if we are 1148 // sure the base pointer is not an instruction defined inside the scop. 1149 // However, we can ignore loads that will be hoisted. 1150 1151 InvariantLoadsSetTy VariantLS, InvariantLS; 1152 // In order to detect loads which are dependent on other invariant loads 1153 // as invariant, we use fixed-point iteration method here i.e we iterate 1154 // over the alias set for arbitrary number of times until it is safe to 1155 // assume that all the invariant loads have been detected 1156 while (1) { 1157 const unsigned int VariantSize = VariantLS.size(), 1158 InvariantSize = InvariantLS.size(); 1159 1160 for (const auto &Ptr : AS) { 1161 Instruction *Inst = dyn_cast<Instruction>(Ptr.getValue()); 1162 if (Inst && Context.CurRegion.contains(Inst)) { 1163 auto *Load = dyn_cast<LoadInst>(Inst); 1164 if (Load && InvariantLS.count(Load)) 1165 continue; 1166 if (Load && isHoistableLoad(Load, Context.CurRegion, LI, SE, DT, 1167 InvariantLS)) { 1168 if (VariantLS.count(Load)) 1169 VariantLS.remove(Load); 1170 Context.RequiredILS.insert(Load); 1171 InvariantLS.insert(Load); 1172 } else { 1173 CanBuildRunTimeCheck = false; 1174 VariantLS.insert(Load); 1175 } 1176 } 1177 } 1178 1179 if (InvariantSize == InvariantLS.size() && 1180 VariantSize == VariantLS.size()) 1181 break; 1182 } 1183 1184 if (CanBuildRunTimeCheck) 1185 return true; 1186 } 1187 return invalid<ReportAlias>(Context, /*Assert=*/true, Inst, AS); 1188 } 1189 1190 return true; 1191 } 1192 1193 bool ScopDetection::isValidMemoryAccess(MemAccInst Inst, 1194 DetectionContext &Context) const { 1195 Value *Ptr = Inst.getPointerOperand(); 1196 Loop *L = LI.getLoopFor(Inst->getParent()); 1197 const SCEV *AccessFunction = SE.getSCEVAtScope(Ptr, L); 1198 const SCEVUnknown *BasePointer; 1199 1200 BasePointer = dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 1201 1202 return isValidAccess(Inst, AccessFunction, BasePointer, Context); 1203 } 1204 1205 bool ScopDetection::isValidInstruction(Instruction &Inst, 1206 DetectionContext &Context) const { 1207 for (auto &Op : Inst.operands()) { 1208 auto *OpInst = dyn_cast<Instruction>(&Op); 1209 1210 if (!OpInst) 1211 continue; 1212 1213 if (isErrorBlock(*OpInst->getParent(), Context.CurRegion, LI, DT)) { 1214 auto *PHI = dyn_cast<PHINode>(OpInst); 1215 if (PHI) { 1216 for (User *U : PHI->users()) { 1217 if (!isa<TerminatorInst>(U)) 1218 return false; 1219 } 1220 } else { 1221 return false; 1222 } 1223 } 1224 } 1225 1226 if (isa<LandingPadInst>(&Inst) || isa<ResumeInst>(&Inst)) 1227 return false; 1228 1229 // We only check the call instruction but not invoke instruction. 1230 if (CallInst *CI = dyn_cast<CallInst>(&Inst)) { 1231 if (isValidCallInst(*CI, Context)) 1232 return true; 1233 1234 return invalid<ReportFuncCall>(Context, /*Assert=*/true, &Inst); 1235 } 1236 1237 if (!Inst.mayReadOrWriteMemory()) { 1238 if (!isa<AllocaInst>(Inst)) 1239 return true; 1240 1241 return invalid<ReportAlloca>(Context, /*Assert=*/true, &Inst); 1242 } 1243 1244 // Check the access function. 1245 if (auto MemInst = MemAccInst::dyn_cast(Inst)) { 1246 Context.hasStores |= isa<StoreInst>(MemInst); 1247 Context.hasLoads |= isa<LoadInst>(MemInst); 1248 if (!MemInst.isSimple()) 1249 return invalid<ReportNonSimpleMemoryAccess>(Context, /*Assert=*/true, 1250 &Inst); 1251 1252 return isValidMemoryAccess(MemInst, Context); 1253 } 1254 1255 // We do not know this instruction, therefore we assume it is invalid. 1256 return invalid<ReportUnknownInst>(Context, /*Assert=*/true, &Inst); 1257 } 1258 1259 /// Check whether @p L has exiting blocks. 1260 /// 1261 /// @param L The loop of interest 1262 /// 1263 /// @return True if the loop has exiting blocks, false otherwise. 1264 static bool hasExitingBlocks(Loop *L) { 1265 SmallVector<BasicBlock *, 4> ExitingBlocks; 1266 L->getExitingBlocks(ExitingBlocks); 1267 return !ExitingBlocks.empty(); 1268 } 1269 1270 bool ScopDetection::canUseISLTripCount(Loop *L, 1271 DetectionContext &Context) const { 1272 // Ensure the loop has valid exiting blocks as well as latches, otherwise we 1273 // need to overapproximate it as a boxed loop. 1274 SmallVector<BasicBlock *, 4> LoopControlBlocks; 1275 L->getExitingBlocks(LoopControlBlocks); 1276 L->getLoopLatches(LoopControlBlocks); 1277 for (BasicBlock *ControlBB : LoopControlBlocks) { 1278 if (!isValidCFG(*ControlBB, true, false, Context)) 1279 return false; 1280 } 1281 1282 // We can use ISL to compute the trip count of L. 1283 return true; 1284 } 1285 1286 bool ScopDetection::isValidLoop(Loop *L, DetectionContext &Context) const { 1287 // Loops that contain part but not all of the blocks of a region cannot be 1288 // handled by the schedule generation. Such loop constructs can happen 1289 // because a region can contain BBs that have no path to the exit block 1290 // (Infinite loops, UnreachableInst), but such blocks are never part of a 1291 // loop. 1292 // 1293 // _______________ 1294 // | Loop Header | <-----------. 1295 // --------------- | 1296 // | | 1297 // _______________ ______________ 1298 // | RegionEntry |-----> | RegionExit |-----> 1299 // --------------- -------------- 1300 // | 1301 // _______________ 1302 // | EndlessLoop | <--. 1303 // --------------- | 1304 // | | 1305 // \------------/ 1306 // 1307 // In the example above, the loop (LoopHeader,RegionEntry,RegionExit) is 1308 // neither entirely contained in the region RegionEntry->RegionExit 1309 // (containing RegionEntry,EndlessLoop) nor is the region entirely contained 1310 // in the loop. 1311 // The block EndlessLoop is contained in the region because Region::contains 1312 // tests whether it is not dominated by RegionExit. This is probably to not 1313 // having to query the PostdominatorTree. Instead of an endless loop, a dead 1314 // end can also be formed by an UnreachableInst. This case is already caught 1315 // by isErrorBlock(). We hence only have to reject endless loops here. 1316 if (!hasExitingBlocks(L)) 1317 return invalid<ReportLoopHasNoExit>(Context, /*Assert=*/true, L); 1318 1319 // The algorithm for domain construction assumes that loops has only a single 1320 // exit block (and hence corresponds to a subregion). Note that we cannot use 1321 // L->getExitBlock() because it does not check whether all exiting edges point 1322 // to the same BB. 1323 SmallVector<BasicBlock *, 4> ExitBlocks; 1324 L->getExitBlocks(ExitBlocks); 1325 BasicBlock *TheExitBlock = ExitBlocks[0]; 1326 for (BasicBlock *ExitBB : ExitBlocks) { 1327 if (TheExitBlock != ExitBB) 1328 return invalid<ReportLoopHasMultipleExits>(Context, /*Assert=*/true, L); 1329 } 1330 1331 if (canUseISLTripCount(L, Context)) 1332 return true; 1333 1334 if (AllowNonAffineSubLoops && AllowNonAffineSubRegions) { 1335 Region *R = RI.getRegionFor(L->getHeader()); 1336 while (R != &Context.CurRegion && !R->contains(L)) 1337 R = R->getParent(); 1338 1339 if (addOverApproximatedRegion(R, Context)) 1340 return true; 1341 } 1342 1343 const SCEV *LoopCount = SE.getBackedgeTakenCount(L); 1344 return invalid<ReportLoopBound>(Context, /*Assert=*/true, L, LoopCount); 1345 } 1346 1347 /// Return the number of loops in @p L (incl. @p L) that have a trip 1348 /// count that is not known to be less than @MinProfitableTrips. 1349 ScopDetection::LoopStats 1350 ScopDetection::countBeneficialSubLoops(Loop *L, ScalarEvolution &SE, 1351 unsigned MinProfitableTrips) { 1352 auto *TripCount = SE.getBackedgeTakenCount(L); 1353 1354 int NumLoops = 1; 1355 int MaxLoopDepth = 1; 1356 if (MinProfitableTrips > 0) 1357 if (auto *TripCountC = dyn_cast<SCEVConstant>(TripCount)) 1358 if (TripCountC->getType()->getScalarSizeInBits() <= 64) 1359 if (TripCountC->getValue()->getZExtValue() <= MinProfitableTrips) 1360 NumLoops -= 1; 1361 1362 for (auto &SubLoop : *L) { 1363 LoopStats Stats = countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips); 1364 NumLoops += Stats.NumLoops; 1365 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth + 1); 1366 } 1367 1368 return {NumLoops, MaxLoopDepth}; 1369 } 1370 1371 ScopDetection::LoopStats 1372 ScopDetection::countBeneficialLoops(Region *R, ScalarEvolution &SE, 1373 LoopInfo &LI, unsigned MinProfitableTrips) { 1374 int LoopNum = 0; 1375 int MaxLoopDepth = 0; 1376 1377 auto L = LI.getLoopFor(R->getEntry()); 1378 1379 // If L is fully contained in R, move to first loop surrounding R. Otherwise, 1380 // L is either nullptr or already surrounding R. 1381 if (L && R->contains(L)) { 1382 L = R->outermostLoopInRegion(L); 1383 L = L->getParentLoop(); 1384 } 1385 1386 auto SubLoops = 1387 L ? L->getSubLoopsVector() : std::vector<Loop *>(LI.begin(), LI.end()); 1388 1389 for (auto &SubLoop : SubLoops) 1390 if (R->contains(SubLoop)) { 1391 LoopStats Stats = 1392 countBeneficialSubLoops(SubLoop, SE, MinProfitableTrips); 1393 LoopNum += Stats.NumLoops; 1394 MaxLoopDepth = std::max(MaxLoopDepth, Stats.MaxDepth); 1395 } 1396 1397 return {LoopNum, MaxLoopDepth}; 1398 } 1399 1400 Region *ScopDetection::expandRegion(Region &R) { 1401 // Initial no valid region was found (greater than R) 1402 std::unique_ptr<Region> LastValidRegion; 1403 auto ExpandedRegion = std::unique_ptr<Region>(R.getExpandedRegion()); 1404 1405 LLVM_DEBUG(dbgs() << "\tExpanding " << R.getNameStr() << "\n"); 1406 1407 while (ExpandedRegion) { 1408 const auto &It = DetectionContextMap.insert(std::make_pair( 1409 getBBPairForRegion(ExpandedRegion.get()), 1410 DetectionContext(*ExpandedRegion, AA, false /*verifying*/))); 1411 DetectionContext &Context = It.first->second; 1412 LLVM_DEBUG(dbgs() << "\t\tTrying " << ExpandedRegion->getNameStr() << "\n"); 1413 // Only expand when we did not collect errors. 1414 1415 if (!Context.Log.hasErrors()) { 1416 // If the exit is valid check all blocks 1417 // - if true, a valid region was found => store it + keep expanding 1418 // - if false, .tbd. => stop (should this really end the loop?) 1419 if (!allBlocksValid(Context) || Context.Log.hasErrors()) { 1420 removeCachedResults(*ExpandedRegion); 1421 DetectionContextMap.erase(It.first); 1422 break; 1423 } 1424 1425 // Store this region, because it is the greatest valid (encountered so 1426 // far). 1427 if (LastValidRegion) { 1428 removeCachedResults(*LastValidRegion); 1429 DetectionContextMap.erase(getBBPairForRegion(LastValidRegion.get())); 1430 } 1431 LastValidRegion = std::move(ExpandedRegion); 1432 1433 // Create and test the next greater region (if any) 1434 ExpandedRegion = 1435 std::unique_ptr<Region>(LastValidRegion->getExpandedRegion()); 1436 1437 } else { 1438 // Create and test the next greater region (if any) 1439 removeCachedResults(*ExpandedRegion); 1440 DetectionContextMap.erase(It.first); 1441 ExpandedRegion = 1442 std::unique_ptr<Region>(ExpandedRegion->getExpandedRegion()); 1443 } 1444 } 1445 1446 LLVM_DEBUG({ 1447 if (LastValidRegion) 1448 dbgs() << "\tto " << LastValidRegion->getNameStr() << "\n"; 1449 else 1450 dbgs() << "\tExpanding " << R.getNameStr() << " failed\n"; 1451 }); 1452 1453 return LastValidRegion.release(); 1454 } 1455 1456 static bool regionWithoutLoops(Region &R, LoopInfo &LI) { 1457 for (const BasicBlock *BB : R.blocks()) 1458 if (R.contains(LI.getLoopFor(BB))) 1459 return false; 1460 1461 return true; 1462 } 1463 1464 void ScopDetection::removeCachedResultsRecursively(const Region &R) { 1465 for (auto &SubRegion : R) { 1466 if (ValidRegions.count(SubRegion.get())) { 1467 removeCachedResults(*SubRegion.get()); 1468 } else 1469 removeCachedResultsRecursively(*SubRegion); 1470 } 1471 } 1472 1473 void ScopDetection::removeCachedResults(const Region &R) { 1474 ValidRegions.remove(&R); 1475 } 1476 1477 void ScopDetection::findScops(Region &R) { 1478 const auto &It = DetectionContextMap.insert(std::make_pair( 1479 getBBPairForRegion(&R), DetectionContext(R, AA, false /*verifying*/))); 1480 DetectionContext &Context = It.first->second; 1481 1482 bool RegionIsValid = false; 1483 if (!PollyProcessUnprofitable && regionWithoutLoops(R, LI)) 1484 invalid<ReportUnprofitable>(Context, /*Assert=*/true, &R); 1485 else 1486 RegionIsValid = isValidRegion(Context); 1487 1488 bool HasErrors = !RegionIsValid || Context.Log.size() > 0; 1489 1490 if (HasErrors) { 1491 removeCachedResults(R); 1492 } else { 1493 ValidRegions.insert(&R); 1494 return; 1495 } 1496 1497 for (auto &SubRegion : R) 1498 findScops(*SubRegion); 1499 1500 // Try to expand regions. 1501 // 1502 // As the region tree normally only contains canonical regions, non canonical 1503 // regions that form a Scop are not found. Therefore, those non canonical 1504 // regions are checked by expanding the canonical ones. 1505 1506 std::vector<Region *> ToExpand; 1507 1508 for (auto &SubRegion : R) 1509 ToExpand.push_back(SubRegion.get()); 1510 1511 for (Region *CurrentRegion : ToExpand) { 1512 // Skip invalid regions. Regions may become invalid, if they are element of 1513 // an already expanded region. 1514 if (!ValidRegions.count(CurrentRegion)) 1515 continue; 1516 1517 // Skip regions that had errors. 1518 bool HadErrors = lookupRejectionLog(CurrentRegion)->hasErrors(); 1519 if (HadErrors) 1520 continue; 1521 1522 Region *ExpandedR = expandRegion(*CurrentRegion); 1523 1524 if (!ExpandedR) 1525 continue; 1526 1527 R.addSubRegion(ExpandedR, true); 1528 ValidRegions.insert(ExpandedR); 1529 removeCachedResults(*CurrentRegion); 1530 removeCachedResultsRecursively(*ExpandedR); 1531 } 1532 } 1533 1534 bool ScopDetection::allBlocksValid(DetectionContext &Context) const { 1535 Region &CurRegion = Context.CurRegion; 1536 1537 for (const BasicBlock *BB : CurRegion.blocks()) { 1538 Loop *L = LI.getLoopFor(BB); 1539 if (L && L->getHeader() == BB) { 1540 if (CurRegion.contains(L)) { 1541 if (!isValidLoop(L, Context) && !KeepGoing) 1542 return false; 1543 } else { 1544 SmallVector<BasicBlock *, 1> Latches; 1545 L->getLoopLatches(Latches); 1546 for (BasicBlock *Latch : Latches) 1547 if (CurRegion.contains(Latch)) 1548 return invalid<ReportLoopOnlySomeLatches>(Context, /*Assert=*/true, 1549 L); 1550 } 1551 } 1552 } 1553 1554 for (BasicBlock *BB : CurRegion.blocks()) { 1555 bool IsErrorBlock = isErrorBlock(*BB, CurRegion, LI, DT); 1556 1557 // Also check exception blocks (and possibly register them as non-affine 1558 // regions). Even though exception blocks are not modeled, we use them 1559 // to forward-propagate domain constraints during ScopInfo construction. 1560 if (!isValidCFG(*BB, false, IsErrorBlock, Context) && !KeepGoing) 1561 return false; 1562 1563 if (IsErrorBlock) 1564 continue; 1565 1566 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I) 1567 if (!isValidInstruction(*I, Context) && !KeepGoing) 1568 return false; 1569 } 1570 1571 if (!hasAffineMemoryAccesses(Context)) 1572 return false; 1573 1574 return true; 1575 } 1576 1577 bool ScopDetection::hasSufficientCompute(DetectionContext &Context, 1578 int NumLoops) const { 1579 int InstCount = 0; 1580 1581 if (NumLoops == 0) 1582 return false; 1583 1584 for (auto *BB : Context.CurRegion.blocks()) 1585 if (Context.CurRegion.contains(LI.getLoopFor(BB))) 1586 InstCount += BB->size(); 1587 1588 InstCount = InstCount / NumLoops; 1589 1590 return InstCount >= ProfitabilityMinPerLoopInstructions; 1591 } 1592 1593 bool ScopDetection::hasPossiblyDistributableLoop( 1594 DetectionContext &Context) const { 1595 for (auto *BB : Context.CurRegion.blocks()) { 1596 auto *L = LI.getLoopFor(BB); 1597 if (!Context.CurRegion.contains(L)) 1598 continue; 1599 if (Context.BoxedLoopsSet.count(L)) 1600 continue; 1601 unsigned StmtsWithStoresInLoops = 0; 1602 for (auto *LBB : L->blocks()) { 1603 bool MemStore = false; 1604 for (auto &I : *LBB) 1605 MemStore |= isa<StoreInst>(&I); 1606 StmtsWithStoresInLoops += MemStore; 1607 } 1608 return (StmtsWithStoresInLoops > 1); 1609 } 1610 return false; 1611 } 1612 1613 bool ScopDetection::isProfitableRegion(DetectionContext &Context) const { 1614 Region &CurRegion = Context.CurRegion; 1615 1616 if (PollyProcessUnprofitable) 1617 return true; 1618 1619 // We can probably not do a lot on scops that only write or only read 1620 // data. 1621 if (!Context.hasStores || !Context.hasLoads) 1622 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion); 1623 1624 int NumLoops = 1625 countBeneficialLoops(&CurRegion, SE, LI, MIN_LOOP_TRIP_COUNT).NumLoops; 1626 int NumAffineLoops = NumLoops - Context.BoxedLoopsSet.size(); 1627 1628 // Scops with at least two loops may allow either loop fusion or tiling and 1629 // are consequently interesting to look at. 1630 if (NumAffineLoops >= 2) 1631 return true; 1632 1633 // A loop with multiple non-trivial blocks might be amendable to distribution. 1634 if (NumAffineLoops == 1 && hasPossiblyDistributableLoop(Context)) 1635 return true; 1636 1637 // Scops that contain a loop with a non-trivial amount of computation per 1638 // loop-iteration are interesting as we may be able to parallelize such 1639 // loops. Individual loops that have only a small amount of computation 1640 // per-iteration are performance-wise very fragile as any change to the 1641 // loop induction variables may affect performance. To not cause spurious 1642 // performance regressions, we do not consider such loops. 1643 if (NumAffineLoops == 1 && hasSufficientCompute(Context, NumLoops)) 1644 return true; 1645 1646 return invalid<ReportUnprofitable>(Context, /*Assert=*/true, &CurRegion); 1647 } 1648 1649 bool ScopDetection::isValidRegion(DetectionContext &Context) const { 1650 Region &CurRegion = Context.CurRegion; 1651 1652 LLVM_DEBUG(dbgs() << "Checking region: " << CurRegion.getNameStr() << "\n\t"); 1653 1654 if (!PollyAllowFullFunction && CurRegion.isTopLevelRegion()) { 1655 LLVM_DEBUG(dbgs() << "Top level region is invalid\n"); 1656 return false; 1657 } 1658 1659 DebugLoc DbgLoc; 1660 if (CurRegion.getExit() && 1661 isa<UnreachableInst>(CurRegion.getExit()->getTerminator())) { 1662 LLVM_DEBUG(dbgs() << "Unreachable in exit\n"); 1663 return invalid<ReportUnreachableInExit>(Context, /*Assert=*/true, 1664 CurRegion.getExit(), DbgLoc); 1665 } 1666 1667 if (!CurRegion.getEntry()->getName().count(OnlyRegion)) { 1668 LLVM_DEBUG({ 1669 dbgs() << "Region entry does not match -polly-region-only"; 1670 dbgs() << "\n"; 1671 }); 1672 return false; 1673 } 1674 1675 // SCoP cannot contain the entry block of the function, because we need 1676 // to insert alloca instruction there when translate scalar to array. 1677 if (!PollyAllowFullFunction && 1678 CurRegion.getEntry() == 1679 &(CurRegion.getEntry()->getParent()->getEntryBlock())) 1680 return invalid<ReportEntry>(Context, /*Assert=*/true, CurRegion.getEntry()); 1681 1682 if (!allBlocksValid(Context)) 1683 return false; 1684 1685 if (!isReducibleRegion(CurRegion, DbgLoc)) 1686 return invalid<ReportIrreducibleRegion>(Context, /*Assert=*/true, 1687 &CurRegion, DbgLoc); 1688 1689 LLVM_DEBUG(dbgs() << "OK\n"); 1690 return true; 1691 } 1692 1693 void ScopDetection::markFunctionAsInvalid(Function *F) { 1694 F->addFnAttr(PollySkipFnAttr); 1695 } 1696 1697 bool ScopDetection::isValidFunction(Function &F) { 1698 return !F.hasFnAttribute(PollySkipFnAttr); 1699 } 1700 1701 void ScopDetection::printLocations(Function &F) { 1702 for (const Region *R : *this) { 1703 unsigned LineEntry, LineExit; 1704 std::string FileName; 1705 1706 getDebugLocation(R, LineEntry, LineExit, FileName); 1707 DiagnosticScopFound Diagnostic(F, FileName, LineEntry, LineExit); 1708 F.getContext().diagnose(Diagnostic); 1709 } 1710 } 1711 1712 void ScopDetection::emitMissedRemarks(const Function &F) { 1713 for (auto &DIt : DetectionContextMap) { 1714 auto &DC = DIt.getSecond(); 1715 if (DC.Log.hasErrors()) 1716 emitRejectionRemarks(DIt.getFirst(), DC.Log, ORE); 1717 } 1718 } 1719 1720 bool ScopDetection::isReducibleRegion(Region &R, DebugLoc &DbgLoc) const { 1721 /// Enum for coloring BBs in Region. 1722 /// 1723 /// WHITE - Unvisited BB in DFS walk. 1724 /// GREY - BBs which are currently on the DFS stack for processing. 1725 /// BLACK - Visited and completely processed BB. 1726 enum Color { WHITE, GREY, BLACK }; 1727 1728 BasicBlock *REntry = R.getEntry(); 1729 BasicBlock *RExit = R.getExit(); 1730 // Map to match the color of a BasicBlock during the DFS walk. 1731 DenseMap<const BasicBlock *, Color> BBColorMap; 1732 // Stack keeping track of current BB and index of next child to be processed. 1733 std::stack<std::pair<BasicBlock *, unsigned>> DFSStack; 1734 1735 unsigned AdjacentBlockIndex = 0; 1736 BasicBlock *CurrBB, *SuccBB; 1737 CurrBB = REntry; 1738 1739 // Initialize the map for all BB with WHITE color. 1740 for (auto *BB : R.blocks()) 1741 BBColorMap[BB] = WHITE; 1742 1743 // Process the entry block of the Region. 1744 BBColorMap[CurrBB] = GREY; 1745 DFSStack.push(std::make_pair(CurrBB, 0)); 1746 1747 while (!DFSStack.empty()) { 1748 // Get next BB on stack to be processed. 1749 CurrBB = DFSStack.top().first; 1750 AdjacentBlockIndex = DFSStack.top().second; 1751 DFSStack.pop(); 1752 1753 // Loop to iterate over the successors of current BB. 1754 const TerminatorInst *TInst = CurrBB->getTerminator(); 1755 unsigned NSucc = TInst->getNumSuccessors(); 1756 for (unsigned I = AdjacentBlockIndex; I < NSucc; 1757 ++I, ++AdjacentBlockIndex) { 1758 SuccBB = TInst->getSuccessor(I); 1759 1760 // Checks for region exit block and self-loops in BB. 1761 if (SuccBB == RExit || SuccBB == CurrBB) 1762 continue; 1763 1764 // WHITE indicates an unvisited BB in DFS walk. 1765 if (BBColorMap[SuccBB] == WHITE) { 1766 // Push the current BB and the index of the next child to be visited. 1767 DFSStack.push(std::make_pair(CurrBB, I + 1)); 1768 // Push the next BB to be processed. 1769 DFSStack.push(std::make_pair(SuccBB, 0)); 1770 // First time the BB is being processed. 1771 BBColorMap[SuccBB] = GREY; 1772 break; 1773 } else if (BBColorMap[SuccBB] == GREY) { 1774 // GREY indicates a loop in the control flow. 1775 // If the destination dominates the source, it is a natural loop 1776 // else, an irreducible control flow in the region is detected. 1777 if (!DT.dominates(SuccBB, CurrBB)) { 1778 // Get debug info of instruction which causes irregular control flow. 1779 DbgLoc = TInst->getDebugLoc(); 1780 return false; 1781 } 1782 } 1783 } 1784 1785 // If all children of current BB have been processed, 1786 // then mark that BB as fully processed. 1787 if (AdjacentBlockIndex == NSucc) 1788 BBColorMap[CurrBB] = BLACK; 1789 } 1790 1791 return true; 1792 } 1793 1794 static void updateLoopCountStatistic(ScopDetection::LoopStats Stats, 1795 bool OnlyProfitable) { 1796 if (!OnlyProfitable) { 1797 NumLoopsInScop += Stats.NumLoops; 1798 MaxNumLoopsInScop = 1799 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops); 1800 if (Stats.MaxDepth == 0) 1801 NumScopsDepthZero++; 1802 else if (Stats.MaxDepth == 1) 1803 NumScopsDepthOne++; 1804 else if (Stats.MaxDepth == 2) 1805 NumScopsDepthTwo++; 1806 else if (Stats.MaxDepth == 3) 1807 NumScopsDepthThree++; 1808 else if (Stats.MaxDepth == 4) 1809 NumScopsDepthFour++; 1810 else if (Stats.MaxDepth == 5) 1811 NumScopsDepthFive++; 1812 else 1813 NumScopsDepthLarger++; 1814 } else { 1815 NumLoopsInProfScop += Stats.NumLoops; 1816 MaxNumLoopsInProfScop = 1817 std::max(MaxNumLoopsInProfScop.getValue(), (unsigned)Stats.NumLoops); 1818 if (Stats.MaxDepth == 0) 1819 NumProfScopsDepthZero++; 1820 else if (Stats.MaxDepth == 1) 1821 NumProfScopsDepthOne++; 1822 else if (Stats.MaxDepth == 2) 1823 NumProfScopsDepthTwo++; 1824 else if (Stats.MaxDepth == 3) 1825 NumProfScopsDepthThree++; 1826 else if (Stats.MaxDepth == 4) 1827 NumProfScopsDepthFour++; 1828 else if (Stats.MaxDepth == 5) 1829 NumProfScopsDepthFive++; 1830 else 1831 NumProfScopsDepthLarger++; 1832 } 1833 } 1834 1835 ScopDetection::DetectionContext * 1836 ScopDetection::getDetectionContext(const Region *R) const { 1837 auto DCMIt = DetectionContextMap.find(getBBPairForRegion(R)); 1838 if (DCMIt == DetectionContextMap.end()) 1839 return nullptr; 1840 return &DCMIt->second; 1841 } 1842 1843 const RejectLog *ScopDetection::lookupRejectionLog(const Region *R) const { 1844 const DetectionContext *DC = getDetectionContext(R); 1845 return DC ? &DC->Log : nullptr; 1846 } 1847 1848 void ScopDetection::verifyRegion(const Region &R) const { 1849 assert(isMaxRegionInScop(R) && "Expect R is a valid region."); 1850 1851 DetectionContext Context(const_cast<Region &>(R), AA, true /*verifying*/); 1852 isValidRegion(Context); 1853 } 1854 1855 void ScopDetection::verifyAnalysis() const { 1856 if (!VerifyScops) 1857 return; 1858 1859 for (const Region *R : ValidRegions) 1860 verifyRegion(*R); 1861 } 1862 1863 bool ScopDetectionWrapperPass::runOnFunction(Function &F) { 1864 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1865 auto &RI = getAnalysis<RegionInfoPass>().getRegionInfo(); 1866 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 1867 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1868 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1869 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 1870 Result.reset(new ScopDetection(F, DT, SE, LI, RI, AA, ORE)); 1871 return false; 1872 } 1873 1874 void ScopDetectionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1875 AU.addRequired<LoopInfoWrapperPass>(); 1876 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>(); 1877 AU.addRequired<DominatorTreeWrapperPass>(); 1878 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 1879 // We also need AA and RegionInfo when we are verifying analysis. 1880 AU.addRequiredTransitive<AAResultsWrapperPass>(); 1881 AU.addRequiredTransitive<RegionInfoPass>(); 1882 AU.setPreservesAll(); 1883 } 1884 1885 void ScopDetectionWrapperPass::print(raw_ostream &OS, const Module *) const { 1886 for (const Region *R : Result->ValidRegions) 1887 OS << "Valid Region for Scop: " << R->getNameStr() << '\n'; 1888 1889 OS << "\n"; 1890 } 1891 1892 ScopDetectionWrapperPass::ScopDetectionWrapperPass() : FunctionPass(ID) { 1893 // Disable runtime alias checks if we ignore aliasing all together. 1894 if (IgnoreAliasing) 1895 PollyUseRuntimeAliasChecks = false; 1896 } 1897 1898 ScopAnalysis::ScopAnalysis() { 1899 // Disable runtime alias checks if we ignore aliasing all together. 1900 if (IgnoreAliasing) 1901 PollyUseRuntimeAliasChecks = false; 1902 } 1903 1904 void ScopDetectionWrapperPass::releaseMemory() { Result.reset(); } 1905 1906 char ScopDetectionWrapperPass::ID; 1907 1908 AnalysisKey ScopAnalysis::Key; 1909 1910 ScopDetection ScopAnalysis::run(Function &F, FunctionAnalysisManager &FAM) { 1911 auto &LI = FAM.getResult<LoopAnalysis>(F); 1912 auto &RI = FAM.getResult<RegionInfoAnalysis>(F); 1913 auto &AA = FAM.getResult<AAManager>(F); 1914 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F); 1915 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F); 1916 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1917 return {F, DT, SE, LI, RI, AA, ORE}; 1918 } 1919 1920 PreservedAnalyses ScopAnalysisPrinterPass::run(Function &F, 1921 FunctionAnalysisManager &FAM) { 1922 OS << "Detected Scops in Function " << F.getName() << "\n"; 1923 auto &SD = FAM.getResult<ScopAnalysis>(F); 1924 for (const Region *R : SD.ValidRegions) 1925 OS << "Valid Region for Scop: " << R->getNameStr() << '\n'; 1926 1927 OS << "\n"; 1928 return PreservedAnalyses::all(); 1929 } 1930 1931 Pass *polly::createScopDetectionWrapperPassPass() { 1932 return new ScopDetectionWrapperPass(); 1933 } 1934 1935 INITIALIZE_PASS_BEGIN(ScopDetectionWrapperPass, "polly-detect", 1936 "Polly - Detect static control parts (SCoPs)", false, 1937 false); 1938 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass); 1939 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 1940 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 1941 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 1942 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 1943 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass); 1944 INITIALIZE_PASS_END(ScopDetectionWrapperPass, "polly-detect", 1945 "Polly - Detect static control parts (SCoPs)", false, false) 1946