1 //===--------- ScopInfo.cpp ----------------------------------------------===// 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 // Create a polyhedral description for a static control flow region. 11 // 12 // The pass creates a polyhedral description of the Scops detected by the Scop 13 // detection derived from their LLVM-IR code. 14 // 15 // This representation is shared among several tools in the polyhedral 16 // community, which are e.g. Cloog, Pluto, Loopo, Graphite. 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "polly/ScopInfo.h" 21 #include "polly/LinkAllPasses.h" 22 #include "polly/Options.h" 23 #include "polly/ScopBuilder.h" 24 #include "polly/Support/GICHelper.h" 25 #include "polly/Support/SCEVValidator.h" 26 #include "polly/Support/ScopHelper.h" 27 #include "llvm/ADT/DepthFirstIterator.h" 28 #include "llvm/ADT/MapVector.h" 29 #include "llvm/ADT/PostOrderIterator.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SetVector.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/ADT/StringExtras.h" 34 #include "llvm/Analysis/AliasAnalysis.h" 35 #include "llvm/Analysis/AssumptionCache.h" 36 #include "llvm/Analysis/Loads.h" 37 #include "llvm/Analysis/LoopInfo.h" 38 #include "llvm/Analysis/LoopIterator.h" 39 #include "llvm/Analysis/RegionIterator.h" 40 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 41 #include "llvm/IR/DiagnosticInfo.h" 42 #include "llvm/Support/Debug.h" 43 #include "isl/aff.h" 44 #include "isl/constraint.h" 45 #include "isl/local_space.h" 46 #include "isl/map.h" 47 #include "isl/options.h" 48 #include "isl/printer.h" 49 #include "isl/schedule.h" 50 #include "isl/schedule_node.h" 51 #include "isl/set.h" 52 #include "isl/union_map.h" 53 #include "isl/union_set.h" 54 #include "isl/val.h" 55 #include <sstream> 56 #include <string> 57 #include <vector> 58 59 using namespace llvm; 60 using namespace polly; 61 62 #define DEBUG_TYPE "polly-scops" 63 64 // The maximal number of basic sets we allow during domain construction to 65 // be created. More complex scops will result in very high compile time and 66 // are also unlikely to result in good code 67 static int const MaxDisjunctionsInDomain = 20; 68 69 static cl::opt<bool> PollyRemarksMinimal( 70 "polly-remarks-minimal", 71 cl::desc("Do not emit remarks about assumptions that are known"), 72 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory)); 73 74 // Multiplicative reductions can be disabled separately as these kind of 75 // operations can overflow easily. Additive reductions and bit operations 76 // are in contrast pretty stable. 77 static cl::opt<bool> DisableMultiplicativeReductions( 78 "polly-disable-multiplicative-reductions", 79 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore, 80 cl::init(false), cl::cat(PollyCategory)); 81 82 static cl::opt<unsigned> RunTimeChecksMaxParameters( 83 "polly-rtc-max-parameters", 84 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden, 85 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory)); 86 87 static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup( 88 "polly-rtc-max-arrays-per-group", 89 cl::desc("The maximal number of arrays to compare in each alias group."), 90 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory)); 91 92 static cl::opt<std::string> UserContextStr( 93 "polly-context", cl::value_desc("isl parameter set"), 94 cl::desc("Provide additional constraints on the context parameters"), 95 cl::init(""), cl::cat(PollyCategory)); 96 97 static cl::opt<bool> DetectReductions("polly-detect-reductions", 98 cl::desc("Detect and exploit reductions"), 99 cl::Hidden, cl::ZeroOrMore, 100 cl::init(true), cl::cat(PollyCategory)); 101 102 static cl::opt<bool> 103 IslOnErrorAbort("polly-on-isl-error-abort", 104 cl::desc("Abort if an isl error is encountered"), 105 cl::init(true), cl::cat(PollyCategory)); 106 107 //===----------------------------------------------------------------------===// 108 109 // Create a sequence of two schedules. Either argument may be null and is 110 // interpreted as the empty schedule. Can also return null if both schedules are 111 // empty. 112 static __isl_give isl_schedule * 113 combineInSequence(__isl_take isl_schedule *Prev, 114 __isl_take isl_schedule *Succ) { 115 if (!Prev) 116 return Succ; 117 if (!Succ) 118 return Prev; 119 120 return isl_schedule_sequence(Prev, Succ); 121 } 122 123 static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S, 124 const ConstantRange &Range, 125 int dim, 126 enum isl_dim_type type) { 127 isl_val *V; 128 isl_ctx *ctx = isl_set_get_ctx(S); 129 130 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet(); 131 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin(); 132 V = isl_valFromAPInt(ctx, LB, true); 133 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V); 134 135 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax(); 136 V = isl_valFromAPInt(ctx, UB, true); 137 if (useLowerUpperBound) 138 V = isl_val_sub_ui(V, 1); 139 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V); 140 141 if (useLowerUpperBound) 142 return isl_set_union(SLB, SUB); 143 else 144 return isl_set_intersect(SLB, SUB); 145 } 146 147 static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) { 148 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr); 149 if (!BasePtrLI) 150 return nullptr; 151 152 if (!S->contains(BasePtrLI)) 153 return nullptr; 154 155 ScalarEvolution &SE = *S->getSE(); 156 157 auto *OriginBaseSCEV = 158 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand())); 159 if (!OriginBaseSCEV) 160 return nullptr; 161 162 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV); 163 if (!OriginBaseSCEVUnknown) 164 return nullptr; 165 166 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(), 167 ScopArrayInfo::MK_Array); 168 } 169 170 ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx, 171 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind, 172 const DataLayout &DL, Scop *S, 173 const char *BaseName) 174 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) { 175 std::string BasePtrName = 176 BaseName ? BaseName : getIslCompatibleName("MemRef_", BasePtr, 177 Kind == MK_PHI ? "__phi" : ""); 178 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this); 179 180 updateSizes(Sizes); 181 182 if (!BasePtr) { 183 BasePtrOriginSAI = nullptr; 184 return; 185 } 186 187 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr); 188 if (BasePtrOriginSAI) 189 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this); 190 } 191 192 __isl_give isl_space *ScopArrayInfo::getSpace() const { 193 auto *Space = 194 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions()); 195 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id)); 196 return Space; 197 } 198 199 void ScopArrayInfo::updateElementType(Type *NewElementType) { 200 if (NewElementType == ElementType) 201 return; 202 203 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType); 204 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType); 205 206 if (NewElementSize == OldElementSize || NewElementSize == 0) 207 return; 208 209 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) { 210 ElementType = NewElementType; 211 } else { 212 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize); 213 ElementType = IntegerType::get(ElementType->getContext(), GCD); 214 } 215 } 216 217 bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) { 218 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size()); 219 int ExtraDimsNew = NewSizes.size() - SharedDims; 220 int ExtraDimsOld = DimensionSizes.size() - SharedDims; 221 222 for (int i = 0; i < SharedDims; i++) { 223 auto *NewSize = NewSizes[i + ExtraDimsNew]; 224 auto *KnownSize = DimensionSizes[i + ExtraDimsOld]; 225 if (NewSize && KnownSize && NewSize != KnownSize) 226 return false; 227 } 228 229 if (DimensionSizes.size() >= NewSizes.size()) 230 return true; 231 232 DimensionSizes.clear(); 233 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(), 234 NewSizes.end()); 235 for (isl_pw_aff *Size : DimensionSizesPw) 236 isl_pw_aff_free(Size); 237 DimensionSizesPw.clear(); 238 for (const SCEV *Expr : DimensionSizes) { 239 if (!Expr) { 240 DimensionSizesPw.push_back(nullptr); 241 continue; 242 } 243 isl_pw_aff *Size = S.getPwAffOnly(Expr); 244 DimensionSizesPw.push_back(Size); 245 } 246 return true; 247 } 248 249 ScopArrayInfo::~ScopArrayInfo() { 250 isl_id_free(Id); 251 for (isl_pw_aff *Size : DimensionSizesPw) 252 isl_pw_aff_free(Size); 253 } 254 255 std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); } 256 257 int ScopArrayInfo::getElemSizeInBytes() const { 258 return DL.getTypeAllocSize(ElementType); 259 } 260 261 __isl_give isl_id *ScopArrayInfo::getBasePtrId() const { 262 return isl_id_copy(Id); 263 } 264 265 void ScopArrayInfo::dump() const { print(errs()); } 266 267 void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const { 268 OS.indent(8) << *getElementType() << " " << getName(); 269 unsigned u = 0; 270 if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) { 271 OS << "[*]"; 272 u++; 273 } 274 for (; u < getNumberOfDimensions(); u++) { 275 OS << "["; 276 277 if (SizeAsPwAff) { 278 auto *Size = getDimensionSizePw(u); 279 OS << " " << Size << " "; 280 isl_pw_aff_free(Size); 281 } else { 282 OS << *getDimensionSize(u); 283 } 284 285 OS << "]"; 286 } 287 288 OS << ";"; 289 290 if (BasePtrOriginSAI) 291 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]"; 292 293 OS << " // Element size " << getElemSizeInBytes() << "\n"; 294 } 295 296 const ScopArrayInfo * 297 ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) { 298 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out); 299 assert(Id && "Output dimension didn't have an ID"); 300 return getFromId(Id); 301 } 302 303 const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) { 304 void *User = isl_id_get_user(Id); 305 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User); 306 isl_id_free(Id); 307 return SAI; 308 } 309 310 void MemoryAccess::wrapConstantDimensions() { 311 auto *SAI = getScopArrayInfo(); 312 auto *ArraySpace = SAI->getSpace(); 313 auto *Ctx = isl_space_get_ctx(ArraySpace); 314 unsigned DimsArray = SAI->getNumberOfDimensions(); 315 316 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range( 317 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace))); 318 auto *LArraySpace = isl_local_space_from_space(ArraySpace); 319 320 // Begin with last dimension, to iteratively carry into higher dimensions. 321 for (int i = DimsArray - 1; i > 0; i--) { 322 auto *DimSize = SAI->getDimensionSize(i); 323 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize); 324 325 // This transformation is not applicable to dimensions with dynamic size. 326 if (!DimSizeCst) 327 continue; 328 329 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false); 330 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace), 331 isl_dim_set, i); 332 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace), 333 isl_dim_set, i - 1); 334 335 // Compute: index % size 336 // Modulo must apply in the divide of the previous iteration, if any. 337 auto *Modulo = isl_aff_copy(Var); 338 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal)); 339 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff)); 340 341 // Compute: floor(index / size) 342 auto *Divide = Var; 343 Divide = isl_aff_div( 344 Divide, 345 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal)); 346 Divide = isl_aff_floor(Divide); 347 Divide = isl_aff_add(Divide, PrevVar); 348 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff)); 349 350 // Apply Modulo and Divide. 351 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo); 352 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide); 353 } 354 355 // Apply all modulo/divides on the accesses. 356 AccessRelation = 357 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff)); 358 AccessRelation = isl_map_detect_equalities(AccessRelation); 359 isl_local_space_free(LArraySpace); 360 } 361 362 void MemoryAccess::updateDimensionality() { 363 auto *SAI = getScopArrayInfo(); 364 auto *ArraySpace = SAI->getSpace(); 365 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation)); 366 auto *Ctx = isl_space_get_ctx(AccessSpace); 367 368 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set); 369 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set); 370 auto DimsMissing = DimsArray - DimsAccess; 371 372 auto *BB = getStatement()->getEntryBlock(); 373 auto &DL = BB->getModule()->getDataLayout(); 374 unsigned ArrayElemSize = SAI->getElemSizeInBytes(); 375 unsigned ElemBytes = DL.getTypeAllocSize(getElementType()); 376 377 auto *Map = isl_map_from_domain_and_range( 378 isl_set_universe(AccessSpace), 379 isl_set_universe(isl_space_copy(ArraySpace))); 380 381 for (unsigned i = 0; i < DimsMissing; i++) 382 Map = isl_map_fix_si(Map, isl_dim_out, i, 0); 383 384 for (unsigned i = DimsMissing; i < DimsArray; i++) 385 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i); 386 387 AccessRelation = isl_map_apply_range(AccessRelation, Map); 388 389 // For the non delinearized arrays, divide the access function of the last 390 // subscript by the size of the elements in the array. 391 // 392 // A stride one array access in C expressed as A[i] is expressed in 393 // LLVM-IR as something like A[i * elementsize]. This hides the fact that 394 // two subsequent values of 'i' index two values that are stored next to 395 // each other in memory. By this division we make this characteristic 396 // obvious again. If the base pointer was accessed with offsets not divisible 397 // by the accesses element size, we will have chosen a smaller ArrayElemSize 398 // that divides the offsets of all accesses to this base pointer. 399 if (DimsAccess == 1) { 400 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize); 401 AccessRelation = isl_map_floordiv_val(AccessRelation, V); 402 } 403 404 // We currently do this only if we added at least one dimension, which means 405 // some dimension's indices have not been specified, an indicator that some 406 // index values have been added together. 407 // TODO: Investigate general usefulness; Effect on unit tests is to make index 408 // expressions more complicated. 409 if (DimsMissing) 410 wrapConstantDimensions(); 411 412 if (!isAffine()) 413 computeBoundsOnAccessRelation(ArrayElemSize); 414 415 // Introduce multi-element accesses in case the type loaded by this memory 416 // access is larger than the canonical element type of the array. 417 // 418 // An access ((float *)A)[i] to an array char *A is modeled as 419 // {[i] -> A[o] : 4 i <= o <= 4 i + 3 420 if (ElemBytes > ArrayElemSize) { 421 assert(ElemBytes % ArrayElemSize == 0 && 422 "Loaded element size should be multiple of canonical element size"); 423 auto *Map = isl_map_from_domain_and_range( 424 isl_set_universe(isl_space_copy(ArraySpace)), 425 isl_set_universe(isl_space_copy(ArraySpace))); 426 for (unsigned i = 0; i < DimsArray - 1; i++) 427 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i); 428 429 isl_constraint *C; 430 isl_local_space *LS; 431 432 LS = isl_local_space_from_space(isl_map_get_space(Map)); 433 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes(); 434 435 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS)); 436 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1)); 437 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1); 438 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1); 439 Map = isl_map_add_constraint(Map, C); 440 441 C = isl_constraint_alloc_inequality(LS); 442 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1); 443 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1); 444 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0)); 445 Map = isl_map_add_constraint(Map, C); 446 AccessRelation = isl_map_apply_range(AccessRelation, Map); 447 } 448 449 isl_space_free(ArraySpace); 450 451 assumeNoOutOfBound(); 452 } 453 454 const std::string 455 MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) { 456 switch (RT) { 457 case MemoryAccess::RT_NONE: 458 llvm_unreachable("Requested a reduction operator string for a memory " 459 "access which isn't a reduction"); 460 case MemoryAccess::RT_ADD: 461 return "+"; 462 case MemoryAccess::RT_MUL: 463 return "*"; 464 case MemoryAccess::RT_BOR: 465 return "|"; 466 case MemoryAccess::RT_BXOR: 467 return "^"; 468 case MemoryAccess::RT_BAND: 469 return "&"; 470 } 471 llvm_unreachable("Unknown reduction type"); 472 return ""; 473 } 474 475 /// Return the reduction type for a given binary operator. 476 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp, 477 const Instruction *Load) { 478 if (!BinOp) 479 return MemoryAccess::RT_NONE; 480 switch (BinOp->getOpcode()) { 481 case Instruction::FAdd: 482 if (!BinOp->hasUnsafeAlgebra()) 483 return MemoryAccess::RT_NONE; 484 // Fall through 485 case Instruction::Add: 486 return MemoryAccess::RT_ADD; 487 case Instruction::Or: 488 return MemoryAccess::RT_BOR; 489 case Instruction::Xor: 490 return MemoryAccess::RT_BXOR; 491 case Instruction::And: 492 return MemoryAccess::RT_BAND; 493 case Instruction::FMul: 494 if (!BinOp->hasUnsafeAlgebra()) 495 return MemoryAccess::RT_NONE; 496 // Fall through 497 case Instruction::Mul: 498 if (DisableMultiplicativeReductions) 499 return MemoryAccess::RT_NONE; 500 return MemoryAccess::RT_MUL; 501 default: 502 return MemoryAccess::RT_NONE; 503 } 504 } 505 506 MemoryAccess::~MemoryAccess() { 507 isl_id_free(Id); 508 isl_set_free(InvalidDomain); 509 isl_map_free(AccessRelation); 510 isl_map_free(NewAccessRelation); 511 } 512 513 const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const { 514 isl_id *ArrayId = getArrayId(); 515 void *User = isl_id_get_user(ArrayId); 516 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User); 517 isl_id_free(ArrayId); 518 return SAI; 519 } 520 521 const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const { 522 isl_id *ArrayId = getLatestArrayId(); 523 void *User = isl_id_get_user(ArrayId); 524 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User); 525 isl_id_free(ArrayId); 526 return SAI; 527 } 528 529 __isl_give isl_id *MemoryAccess::getOriginalArrayId() const { 530 return isl_map_get_tuple_id(AccessRelation, isl_dim_out); 531 } 532 533 __isl_give isl_id *MemoryAccess::getLatestArrayId() const { 534 if (!hasNewAccessRelation()) 535 return getOriginalArrayId(); 536 return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out); 537 } 538 539 __isl_give isl_map *MemoryAccess::getAddressFunction() const { 540 return isl_map_lexmin(getAccessRelation()); 541 } 542 543 __isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation( 544 __isl_take isl_union_map *USchedule) const { 545 isl_map *Schedule, *ScheduledAccRel; 546 isl_union_set *UDomain; 547 548 UDomain = isl_union_set_from_set(getStatement()->getDomain()); 549 USchedule = isl_union_map_intersect_domain(USchedule, UDomain); 550 Schedule = isl_map_from_union_map(USchedule); 551 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule); 552 return isl_pw_multi_aff_from_map(ScheduledAccRel); 553 } 554 555 __isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const { 556 return isl_map_copy(AccessRelation); 557 } 558 559 std::string MemoryAccess::getOriginalAccessRelationStr() const { 560 return stringFromIslObj(AccessRelation); 561 } 562 563 __isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const { 564 return isl_map_get_space(AccessRelation); 565 } 566 567 __isl_give isl_map *MemoryAccess::getNewAccessRelation() const { 568 return isl_map_copy(NewAccessRelation); 569 } 570 571 std::string MemoryAccess::getNewAccessRelationStr() const { 572 return stringFromIslObj(NewAccessRelation); 573 } 574 575 __isl_give isl_basic_map * 576 MemoryAccess::createBasicAccessMap(ScopStmt *Statement) { 577 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1); 578 Space = isl_space_align_params(Space, Statement->getDomainSpace()); 579 580 return isl_basic_map_from_domain_and_range( 581 isl_basic_set_universe(Statement->getDomainSpace()), 582 isl_basic_set_universe(Space)); 583 } 584 585 // Formalize no out-of-bound access assumption 586 // 587 // When delinearizing array accesses we optimistically assume that the 588 // delinearized accesses do not access out of bound locations (the subscript 589 // expression of each array evaluates for each statement instance that is 590 // executed to a value that is larger than zero and strictly smaller than the 591 // size of the corresponding dimension). The only exception is the outermost 592 // dimension for which we do not need to assume any upper bound. At this point 593 // we formalize this assumption to ensure that at code generation time the 594 // relevant run-time checks can be generated. 595 // 596 // To find the set of constraints necessary to avoid out of bound accesses, we 597 // first build the set of data locations that are not within array bounds. We 598 // then apply the reverse access relation to obtain the set of iterations that 599 // may contain invalid accesses and reduce this set of iterations to the ones 600 // that are actually executed by intersecting them with the domain of the 601 // statement. If we now project out all loop dimensions, we obtain a set of 602 // parameters that may cause statement instances to be executed that may 603 // possibly yield out of bound memory accesses. The complement of these 604 // constraints is the set of constraints that needs to be assumed to ensure such 605 // statement instances are never executed. 606 void MemoryAccess::assumeNoOutOfBound() { 607 auto *SAI = getScopArrayInfo(); 608 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace()); 609 isl_set *Outside = isl_set_empty(isl_space_copy(Space)); 610 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) { 611 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space)); 612 isl_pw_aff *Var = 613 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i); 614 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS); 615 616 isl_set *DimOutside; 617 618 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero); 619 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i); 620 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in, 621 isl_space_dim(Space, isl_dim_set)); 622 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in, 623 isl_space_get_tuple_id(Space, isl_dim_set)); 624 625 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var)); 626 627 Outside = isl_set_union(Outside, DimOutside); 628 } 629 630 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation())); 631 Outside = isl_set_intersect(Outside, Statement->getDomain()); 632 Outside = isl_set_params(Outside); 633 634 // Remove divs to avoid the construction of overly complicated assumptions. 635 // Doing so increases the set of parameter combinations that are assumed to 636 // not appear. This is always save, but may make the resulting run-time check 637 // bail out more often than strictly necessary. 638 Outside = isl_set_remove_divs(Outside); 639 Outside = isl_set_complement(Outside); 640 const auto &Loc = getAccessInstruction() 641 ? getAccessInstruction()->getDebugLoc() 642 : DebugLoc(); 643 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc, 644 AS_ASSUMPTION); 645 isl_space_free(Space); 646 } 647 648 void MemoryAccess::buildMemIntrinsicAccessRelation() { 649 assert(isa<MemIntrinsic>(getAccessInstruction())); 650 assert(Subscripts.size() == 2 && Sizes.size() == 1); 651 652 auto *SubscriptPWA = getPwAff(Subscripts[0]); 653 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA); 654 655 isl_map *LengthMap; 656 if (Subscripts[1] == nullptr) { 657 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap)); 658 } else { 659 auto *LengthPWA = getPwAff(Subscripts[1]); 660 LengthMap = isl_map_from_pw_aff(LengthPWA); 661 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap)); 662 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace)); 663 } 664 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0); 665 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap)); 666 SubscriptMap = 667 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap)); 668 LengthMap = isl_map_sum(LengthMap, SubscriptMap); 669 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in, 670 getStatement()->getDomainId()); 671 } 672 673 void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) { 674 ScalarEvolution *SE = Statement->getParent()->getSE(); 675 676 auto MAI = MemAccInst(getAccessInstruction()); 677 if (isa<MemIntrinsic>(MAI)) 678 return; 679 680 Value *Ptr = MAI.getPointerOperand(); 681 if (!Ptr || !SE->isSCEVable(Ptr->getType())) 682 return; 683 684 auto *PtrSCEV = SE->getSCEV(Ptr); 685 if (isa<SCEVCouldNotCompute>(PtrSCEV)) 686 return; 687 688 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV); 689 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV)) 690 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV); 691 692 const ConstantRange &Range = SE->getSignedRange(PtrSCEV); 693 if (Range.isFullSet()) 694 return; 695 696 bool isWrapping = Range.isSignWrappedSet(); 697 unsigned BW = Range.getBitWidth(); 698 const auto One = APInt(BW, 1); 699 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin(); 700 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax(); 701 702 auto Min = LB.sdiv(APInt(BW, ElementSize)); 703 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One; 704 705 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation)); 706 AccessRange = 707 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set); 708 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange); 709 } 710 711 __isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation, 712 ScopStmt *Statement) { 713 int Size = Subscripts.size(); 714 715 for (int i = Size - 2; i >= 0; --i) { 716 isl_space *Space; 717 isl_map *MapOne, *MapTwo; 718 isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]); 719 720 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize); 721 isl_pw_aff_free(DimSize); 722 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0); 723 724 Space = isl_map_get_space(AccessRelation); 725 Space = isl_space_map_from_set(isl_space_range(Space)); 726 Space = isl_space_align_params(Space, SpaceSize); 727 728 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId); 729 isl_id_free(ParamId); 730 731 MapOne = isl_map_universe(isl_space_copy(Space)); 732 for (int j = 0; j < Size; ++j) 733 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j); 734 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0); 735 736 MapTwo = isl_map_universe(isl_space_copy(Space)); 737 for (int j = 0; j < Size; ++j) 738 if (j < i || j > i + 1) 739 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j); 740 741 isl_local_space *LS = isl_local_space_from_space(Space); 742 isl_constraint *C; 743 C = isl_equality_alloc(isl_local_space_copy(LS)); 744 C = isl_constraint_set_constant_si(C, -1); 745 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1); 746 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1); 747 MapTwo = isl_map_add_constraint(MapTwo, C); 748 C = isl_equality_alloc(LS); 749 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1); 750 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1); 751 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1); 752 MapTwo = isl_map_add_constraint(MapTwo, C); 753 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1); 754 755 MapOne = isl_map_union(MapOne, MapTwo); 756 AccessRelation = isl_map_apply_range(AccessRelation, MapOne); 757 } 758 return AccessRelation; 759 } 760 761 /// Check if @p Expr is divisible by @p Size. 762 static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) { 763 assert(Size != 0); 764 if (Size == 1) 765 return true; 766 767 // Only one factor needs to be divisible. 768 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) { 769 for (auto *FactorExpr : MulExpr->operands()) 770 if (isDivisible(FactorExpr, Size, SE)) 771 return true; 772 return false; 773 } 774 775 // For other n-ary expressions (Add, AddRec, Max,...) all operands need 776 // to be divisble. 777 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) { 778 for (auto *OpExpr : NAryExpr->operands()) 779 if (!isDivisible(OpExpr, Size, SE)) 780 return false; 781 return true; 782 } 783 784 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size); 785 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV); 786 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV); 787 return MulSCEV == Expr; 788 } 789 790 void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) { 791 assert(!AccessRelation && "AccessReltation already built"); 792 793 // Initialize the invalid domain which describes all iterations for which the 794 // access relation is not modeled correctly. 795 auto *StmtInvalidDomain = getStatement()->getInvalidDomain(); 796 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain)); 797 isl_set_free(StmtInvalidDomain); 798 799 isl_ctx *Ctx = isl_id_get_ctx(Id); 800 isl_id *BaseAddrId = SAI->getBasePtrId(); 801 802 if (!isAffine()) { 803 if (isa<MemIntrinsic>(getAccessInstruction())) 804 buildMemIntrinsicAccessRelation(); 805 806 // We overapproximate non-affine accesses with a possible access to the 807 // whole array. For read accesses it does not make a difference, if an 808 // access must or may happen. However, for write accesses it is important to 809 // differentiate between writes that must happen and writes that may happen. 810 if (!AccessRelation) 811 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement)); 812 813 AccessRelation = 814 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId); 815 return; 816 } 817 818 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0); 819 AccessRelation = isl_map_universe(Space); 820 821 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) { 822 isl_pw_aff *Affine = getPwAff(Subscripts[i]); 823 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine); 824 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap); 825 } 826 827 if (Sizes.size() >= 2 && !isa<SCEVConstant>(Sizes[1])) 828 AccessRelation = foldAccess(AccessRelation, Statement); 829 830 Space = Statement->getDomainSpace(); 831 AccessRelation = isl_map_set_tuple_id( 832 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set)); 833 AccessRelation = 834 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId); 835 836 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain()); 837 isl_space_free(Space); 838 } 839 840 MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst, 841 AccessType AccType, Value *BaseAddress, 842 Type *ElementType, bool Affine, 843 ArrayRef<const SCEV *> Subscripts, 844 ArrayRef<const SCEV *> Sizes, Value *AccessValue, 845 ScopArrayInfo::MemoryKind Kind, StringRef BaseName) 846 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt), 847 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName), 848 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()), 849 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine), 850 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr), 851 NewAccessRelation(nullptr) { 852 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"}; 853 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_"; 854 855 std::string IdName = 856 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName); 857 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this); 858 } 859 860 MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, 861 __isl_take isl_map *AccRel) 862 : Kind(ScopArrayInfo::MemoryKind::MK_Array), AccType(AccType), 863 RedType(RT_NONE), Statement(Stmt), InvalidDomain(nullptr), 864 AccessInstruction(nullptr), IsAffine(true), AccessRelation(nullptr), 865 NewAccessRelation(AccRel) { 866 auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out); 867 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId); 868 Sizes.push_back(nullptr); 869 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++) 870 Sizes.push_back(SAI->getDimensionSize(i)); 871 ElementType = SAI->getElementType(); 872 BaseAddr = SAI->getBasePtr(); 873 BaseName = SAI->getName(); 874 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"}; 875 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_"; 876 877 std::string IdName = 878 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName); 879 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this); 880 } 881 882 void MemoryAccess::realignParams() { 883 auto *Ctx = Statement->getParent()->getContext(); 884 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx)); 885 AccessRelation = isl_map_gist_params(AccessRelation, Ctx); 886 } 887 888 const std::string MemoryAccess::getReductionOperatorStr() const { 889 return MemoryAccess::getReductionOperatorStr(getReductionType()); 890 } 891 892 __isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); } 893 894 raw_ostream &polly::operator<<(raw_ostream &OS, 895 MemoryAccess::ReductionType RT) { 896 if (RT == MemoryAccess::RT_NONE) 897 OS << "NONE"; 898 else 899 OS << MemoryAccess::getReductionOperatorStr(RT); 900 return OS; 901 } 902 903 void MemoryAccess::print(raw_ostream &OS) const { 904 switch (AccType) { 905 case READ: 906 OS.indent(12) << "ReadAccess :=\t"; 907 break; 908 case MUST_WRITE: 909 OS.indent(12) << "MustWriteAccess :=\t"; 910 break; 911 case MAY_WRITE: 912 OS.indent(12) << "MayWriteAccess :=\t"; 913 break; 914 } 915 OS << "[Reduction Type: " << getReductionType() << "] "; 916 OS << "[Scalar: " << isScalarKind() << "]\n"; 917 OS.indent(16) << getOriginalAccessRelationStr() << ";\n"; 918 if (hasNewAccessRelation()) 919 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n"; 920 } 921 922 void MemoryAccess::dump() const { print(errs()); } 923 924 __isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) { 925 auto *Stmt = getStatement(); 926 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock()); 927 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain()); 928 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second); 929 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom); 930 return PWAC.first; 931 } 932 933 // Create a map in the size of the provided set domain, that maps from the 934 // one element of the provided set domain to another element of the provided 935 // set domain. 936 // The mapping is limited to all points that are equal in all but the last 937 // dimension and for which the last dimension of the input is strict smaller 938 // than the last dimension of the output. 939 // 940 // getEqualAndLarger(set[i0, i1, ..., iX]): 941 // 942 // set[i0, i1, ..., iX] -> set[o0, o1, ..., oX] 943 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX 944 // 945 static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) { 946 isl_space *Space = isl_space_map_from_set(setDomain); 947 isl_map *Map = isl_map_universe(Space); 948 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1; 949 950 // Set all but the last dimension to be equal for the input and output 951 // 952 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX] 953 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1) 954 for (unsigned i = 0; i < lastDimension; ++i) 955 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i); 956 957 // Set the last dimension of the input to be strict smaller than the 958 // last dimension of the output. 959 // 960 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX 961 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out, 962 lastDimension); 963 return Map; 964 } 965 966 __isl_give isl_set * 967 MemoryAccess::getStride(__isl_take const isl_map *Schedule) const { 968 isl_map *S = const_cast<isl_map *>(Schedule); 969 isl_map *AccessRelation = getAccessRelation(); 970 isl_space *Space = isl_space_range(isl_map_get_space(S)); 971 isl_map *NextScatt = getEqualAndLarger(Space); 972 973 S = isl_map_reverse(S); 974 NextScatt = isl_map_lexmin(NextScatt); 975 976 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S)); 977 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation)); 978 NextScatt = isl_map_apply_domain(NextScatt, S); 979 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation); 980 981 isl_set *Deltas = isl_map_deltas(NextScatt); 982 return Deltas; 983 } 984 985 bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule, 986 int StrideWidth) const { 987 isl_set *Stride, *StrideX; 988 bool IsStrideX; 989 990 Stride = getStride(Schedule); 991 StrideX = isl_set_universe(isl_set_get_space(Stride)); 992 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++) 993 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0); 994 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 995 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth); 996 IsStrideX = isl_set_is_subset(Stride, StrideX); 997 998 isl_set_free(StrideX); 999 isl_set_free(Stride); 1000 1001 return IsStrideX; 1002 } 1003 1004 bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const { 1005 return isStrideX(Schedule, 0); 1006 } 1007 1008 bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const { 1009 return isStrideX(Schedule, 1); 1010 } 1011 1012 void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) { 1013 assert(NewAccess); 1014 1015 #ifndef NDEBUG 1016 // Check domain space compatibility. 1017 auto *NewSpace = isl_map_get_space(NewAccess); 1018 auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace)); 1019 auto *OriginalDomainSpace = getStatement()->getDomainSpace(); 1020 assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace)); 1021 isl_space_free(NewDomainSpace); 1022 isl_space_free(OriginalDomainSpace); 1023 1024 // Check whether there is an access for every statement instance. 1025 auto *StmtDomain = getStatement()->getDomain(); 1026 StmtDomain = isl_set_intersect_params( 1027 StmtDomain, getStatement()->getParent()->getContext()); 1028 auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess)); 1029 assert(isl_set_is_subset(StmtDomain, NewDomain) && 1030 "Partial accesses not supported"); 1031 isl_set_free(NewDomain); 1032 isl_set_free(StmtDomain); 1033 1034 // Check whether access dimensions correspond to number of dimensions of the 1035 // accesses array. 1036 auto *NewAccessSpace = isl_space_range(NewSpace); 1037 assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) && 1038 "Must specify the array that is accessed"); 1039 auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set); 1040 auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId)); 1041 assert(SAI && "Must set a ScopArrayInfo"); 1042 assert(!SAI->getBasePtrOriginSAI() && 1043 "Indirect array not supported by codegen"); 1044 auto Dims = SAI->getNumberOfDimensions(); 1045 assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims && 1046 "Access dims must match array dims"); 1047 isl_space_free(NewAccessSpace); 1048 isl_id_free(NewArrayId); 1049 #endif 1050 1051 isl_map_free(NewAccessRelation); 1052 NewAccessRelation = NewAccess; 1053 } 1054 1055 //===----------------------------------------------------------------------===// 1056 1057 __isl_give isl_map *ScopStmt::getSchedule() const { 1058 isl_set *Domain = getDomain(); 1059 if (isl_set_is_empty(Domain)) { 1060 isl_set_free(Domain); 1061 return isl_map_from_aff( 1062 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace()))); 1063 } 1064 auto *Schedule = getParent()->getSchedule(); 1065 if (!Schedule) { 1066 isl_set_free(Domain); 1067 return nullptr; 1068 } 1069 Schedule = isl_union_map_intersect_domain( 1070 Schedule, isl_union_set_from_set(isl_set_copy(Domain))); 1071 if (isl_union_map_is_empty(Schedule)) { 1072 isl_set_free(Domain); 1073 isl_union_map_free(Schedule); 1074 return isl_map_from_aff( 1075 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace()))); 1076 } 1077 auto *M = isl_map_from_union_map(Schedule); 1078 M = isl_map_coalesce(M); 1079 M = isl_map_gist_domain(M, Domain); 1080 M = isl_map_coalesce(M); 1081 return M; 1082 } 1083 1084 __isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) { 1085 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative); 1086 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second); 1087 return PWAC.first; 1088 } 1089 1090 void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) { 1091 assert(isl_set_is_subset(NewDomain, Domain) && 1092 "New domain is not a subset of old domain!"); 1093 isl_set_free(Domain); 1094 Domain = NewDomain; 1095 } 1096 1097 void ScopStmt::buildAccessRelations() { 1098 Scop &S = *getParent(); 1099 for (MemoryAccess *Access : MemAccs) { 1100 Type *ElementType = Access->getElementType(); 1101 1102 ScopArrayInfo::MemoryKind Ty; 1103 if (Access->isPHIKind()) 1104 Ty = ScopArrayInfo::MK_PHI; 1105 else if (Access->isExitPHIKind()) 1106 Ty = ScopArrayInfo::MK_ExitPHI; 1107 else if (Access->isValueKind()) 1108 Ty = ScopArrayInfo::MK_Value; 1109 else 1110 Ty = ScopArrayInfo::MK_Array; 1111 1112 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType, 1113 Access->Sizes, Ty); 1114 Access->buildAccessRelation(SAI); 1115 } 1116 } 1117 1118 void ScopStmt::addAccess(MemoryAccess *Access) { 1119 Instruction *AccessInst = Access->getAccessInstruction(); 1120 1121 if (Access->isArrayKind()) { 1122 MemoryAccessList &MAL = InstructionToAccess[AccessInst]; 1123 MAL.emplace_front(Access); 1124 } else if (Access->isValueKind() && Access->isWrite()) { 1125 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue()); 1126 assert(Parent.getStmtFor(AccessVal) == this); 1127 assert(!ValueWrites.lookup(AccessVal)); 1128 1129 ValueWrites[AccessVal] = Access; 1130 } else if (Access->isValueKind() && Access->isRead()) { 1131 Value *AccessVal = Access->getAccessValue(); 1132 assert(!ValueReads.lookup(AccessVal)); 1133 1134 ValueReads[AccessVal] = Access; 1135 } else if (Access->isAnyPHIKind() && Access->isWrite()) { 1136 PHINode *PHI = cast<PHINode>(Access->getBaseAddr()); 1137 assert(!PHIWrites.lookup(PHI)); 1138 1139 PHIWrites[PHI] = Access; 1140 } 1141 1142 MemAccs.push_back(Access); 1143 } 1144 1145 void ScopStmt::realignParams() { 1146 for (MemoryAccess *MA : *this) 1147 MA->realignParams(); 1148 1149 auto *Ctx = Parent.getContext(); 1150 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx)); 1151 Domain = isl_set_gist_params(Domain, Ctx); 1152 } 1153 1154 /// Add @p BSet to the set @p User if @p BSet is bounded. 1155 static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet, 1156 void *User) { 1157 isl_set **BoundedParts = static_cast<isl_set **>(User); 1158 if (isl_basic_set_is_bounded(BSet)) 1159 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet)); 1160 else 1161 isl_basic_set_free(BSet); 1162 return isl_stat_ok; 1163 } 1164 1165 /// Return the bounded parts of @p S. 1166 static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) { 1167 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S)); 1168 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts); 1169 isl_set_free(S); 1170 return BoundedParts; 1171 } 1172 1173 /// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim. 1174 /// 1175 /// @returns A separation of @p S into first an unbounded then a bounded subset, 1176 /// both with regards to the dimension @p Dim. 1177 static std::pair<__isl_give isl_set *, __isl_give isl_set *> 1178 partitionSetParts(__isl_take isl_set *S, unsigned Dim) { 1179 1180 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++) 1181 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0); 1182 1183 unsigned NumDimsS = isl_set_n_dim(S); 1184 isl_set *OnlyDimS = isl_set_copy(S); 1185 1186 // Remove dimensions that are greater than Dim as they are not interesting. 1187 assert(NumDimsS >= Dim + 1); 1188 OnlyDimS = 1189 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1); 1190 1191 // Create artificial parametric upper bounds for dimensions smaller than Dim 1192 // as we are not interested in them. 1193 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim); 1194 for (unsigned u = 0; u < Dim; u++) { 1195 isl_constraint *C = isl_inequality_alloc( 1196 isl_local_space_from_space(isl_set_get_space(OnlyDimS))); 1197 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1); 1198 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1); 1199 OnlyDimS = isl_set_add_constraint(OnlyDimS, C); 1200 } 1201 1202 // Collect all bounded parts of OnlyDimS. 1203 isl_set *BoundedParts = collectBoundedParts(OnlyDimS); 1204 1205 // Create the dimensions greater than Dim again. 1206 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1, 1207 NumDimsS - Dim - 1); 1208 1209 // Remove the artificial upper bound parameters again. 1210 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim); 1211 1212 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts)); 1213 return std::make_pair(UnboundedParts, BoundedParts); 1214 } 1215 1216 /// Set the dimension Ids from @p From in @p To. 1217 static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From, 1218 __isl_take isl_set *To) { 1219 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) { 1220 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u); 1221 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId); 1222 } 1223 return To; 1224 } 1225 1226 /// Create the conditions under which @p L @p Pred @p R is true. 1227 static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred, 1228 __isl_take isl_pw_aff *L, 1229 __isl_take isl_pw_aff *R) { 1230 switch (Pred) { 1231 case ICmpInst::ICMP_EQ: 1232 return isl_pw_aff_eq_set(L, R); 1233 case ICmpInst::ICMP_NE: 1234 return isl_pw_aff_ne_set(L, R); 1235 case ICmpInst::ICMP_SLT: 1236 return isl_pw_aff_lt_set(L, R); 1237 case ICmpInst::ICMP_SLE: 1238 return isl_pw_aff_le_set(L, R); 1239 case ICmpInst::ICMP_SGT: 1240 return isl_pw_aff_gt_set(L, R); 1241 case ICmpInst::ICMP_SGE: 1242 return isl_pw_aff_ge_set(L, R); 1243 case ICmpInst::ICMP_ULT: 1244 return isl_pw_aff_lt_set(L, R); 1245 case ICmpInst::ICMP_UGT: 1246 return isl_pw_aff_gt_set(L, R); 1247 case ICmpInst::ICMP_ULE: 1248 return isl_pw_aff_le_set(L, R); 1249 case ICmpInst::ICMP_UGE: 1250 return isl_pw_aff_ge_set(L, R); 1251 default: 1252 llvm_unreachable("Non integer predicate not supported"); 1253 } 1254 } 1255 1256 /// Create the conditions under which @p L @p Pred @p R is true. 1257 /// 1258 /// Helper function that will make sure the dimensions of the result have the 1259 /// same isl_id's as the @p Domain. 1260 static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred, 1261 __isl_take isl_pw_aff *L, 1262 __isl_take isl_pw_aff *R, 1263 __isl_keep isl_set *Domain) { 1264 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R); 1265 return setDimensionIds(Domain, ConsequenceCondSet); 1266 } 1267 1268 /// Build the conditions sets for the switch @p SI in the @p Domain. 1269 /// 1270 /// This will fill @p ConditionSets with the conditions under which control 1271 /// will be moved from @p SI to its successors. Hence, @p ConditionSets will 1272 /// have as many elements as @p SI has successors. 1273 static bool 1274 buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L, 1275 __isl_keep isl_set *Domain, 1276 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 1277 1278 Value *Condition = getConditionFromTerminator(SI); 1279 assert(Condition && "No condition for switch"); 1280 1281 Scop &S = *Stmt.getParent(); 1282 ScalarEvolution &SE = *S.getSE(); 1283 isl_pw_aff *LHS, *RHS; 1284 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L)); 1285 1286 unsigned NumSuccessors = SI->getNumSuccessors(); 1287 ConditionSets.resize(NumSuccessors); 1288 for (auto &Case : SI->cases()) { 1289 unsigned Idx = Case.getSuccessorIndex(); 1290 ConstantInt *CaseValue = Case.getCaseValue(); 1291 1292 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue)); 1293 isl_set *CaseConditionSet = 1294 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain); 1295 ConditionSets[Idx] = isl_set_coalesce( 1296 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain))); 1297 } 1298 1299 assert(ConditionSets[0] == nullptr && "Default condition set was set"); 1300 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]); 1301 for (unsigned u = 2; u < NumSuccessors; u++) 1302 ConditionSetUnion = 1303 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u])); 1304 ConditionSets[0] = setDimensionIds( 1305 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion)); 1306 1307 isl_pw_aff_free(LHS); 1308 1309 return true; 1310 } 1311 1312 /// Build the conditions sets for the branch condition @p Condition in 1313 /// the @p Domain. 1314 /// 1315 /// This will fill @p ConditionSets with the conditions under which control 1316 /// will be moved from @p TI to its successors. Hence, @p ConditionSets will 1317 /// have as many elements as @p TI has successors. If @p TI is nullptr the 1318 /// context under which @p Condition is true/false will be returned as the 1319 /// new elements of @p ConditionSets. 1320 static bool 1321 buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI, 1322 Loop *L, __isl_keep isl_set *Domain, 1323 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 1324 1325 Scop &S = *Stmt.getParent(); 1326 isl_set *ConsequenceCondSet = nullptr; 1327 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) { 1328 if (CCond->isZero()) 1329 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain)); 1330 else 1331 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain)); 1332 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) { 1333 auto Opcode = BinOp->getOpcode(); 1334 assert(Opcode == Instruction::And || Opcode == Instruction::Or); 1335 1336 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain, 1337 ConditionSets) && 1338 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain, 1339 ConditionSets); 1340 if (!Valid) { 1341 while (!ConditionSets.empty()) 1342 isl_set_free(ConditionSets.pop_back_val()); 1343 return false; 1344 } 1345 1346 isl_set_free(ConditionSets.pop_back_val()); 1347 isl_set *ConsCondPart0 = ConditionSets.pop_back_val(); 1348 isl_set_free(ConditionSets.pop_back_val()); 1349 isl_set *ConsCondPart1 = ConditionSets.pop_back_val(); 1350 1351 if (Opcode == Instruction::And) 1352 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1); 1353 else 1354 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1); 1355 } else { 1356 auto *ICond = dyn_cast<ICmpInst>(Condition); 1357 assert(ICond && 1358 "Condition of exiting branch was neither constant nor ICmp!"); 1359 1360 ScalarEvolution &SE = *S.getSE(); 1361 isl_pw_aff *LHS, *RHS; 1362 // For unsigned comparisons we assumed the signed bit of neither operand 1363 // to be set. The comparison is equal to a signed comparison under this 1364 // assumption. 1365 bool NonNeg = ICond->isUnsigned(); 1366 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg); 1367 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg); 1368 ConsequenceCondSet = 1369 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain); 1370 } 1371 1372 // If no terminator was given we are only looking for parameter constraints 1373 // under which @p Condition is true/false. 1374 if (!TI) 1375 ConsequenceCondSet = isl_set_params(ConsequenceCondSet); 1376 assert(ConsequenceCondSet); 1377 ConsequenceCondSet = isl_set_coalesce( 1378 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))); 1379 1380 isl_set *AlternativeCondSet = nullptr; 1381 bool TooComplex = 1382 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain; 1383 1384 if (!TooComplex) { 1385 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain), 1386 isl_set_copy(ConsequenceCondSet)); 1387 TooComplex = 1388 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain; 1389 } 1390 1391 if (TooComplex) { 1392 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc()); 1393 isl_set_free(AlternativeCondSet); 1394 isl_set_free(ConsequenceCondSet); 1395 return false; 1396 } 1397 1398 ConditionSets.push_back(ConsequenceCondSet); 1399 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet)); 1400 1401 return true; 1402 } 1403 1404 /// Build the conditions sets for the terminator @p TI in the @p Domain. 1405 /// 1406 /// This will fill @p ConditionSets with the conditions under which control 1407 /// will be moved from @p TI to its successors. Hence, @p ConditionSets will 1408 /// have as many elements as @p TI has successors. 1409 static bool 1410 buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L, 1411 __isl_keep isl_set *Domain, 1412 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 1413 1414 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) 1415 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets); 1416 1417 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch."); 1418 1419 if (TI->getNumSuccessors() == 1) { 1420 ConditionSets.push_back(isl_set_copy(Domain)); 1421 return true; 1422 } 1423 1424 Value *Condition = getConditionFromTerminator(TI); 1425 assert(Condition && "No condition for Terminator"); 1426 1427 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets); 1428 } 1429 1430 void ScopStmt::buildDomain() { 1431 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this); 1432 1433 Domain = getParent()->getDomainConditions(this); 1434 Domain = isl_set_set_tuple_id(Domain, Id); 1435 } 1436 1437 void ScopStmt::collectSurroundingLoops() { 1438 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) { 1439 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u); 1440 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId))); 1441 isl_id_free(DimId); 1442 } 1443 } 1444 1445 ScopStmt::ScopStmt(Scop &parent, Region &R) 1446 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr), 1447 R(&R), Build(nullptr) { 1448 1449 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), ""); 1450 } 1451 1452 ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb) 1453 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb), 1454 R(nullptr), Build(nullptr) { 1455 1456 BaseName = getIslCompatibleName("Stmt_", &bb, ""); 1457 } 1458 1459 ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel, 1460 __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain) 1461 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr), 1462 R(nullptr), Build(nullptr) { 1463 BaseName = getIslCompatibleName("CopyStmt_", "", 1464 std::to_string(parent.getCopyStmtsNum())); 1465 auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this); 1466 Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id)); 1467 TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id); 1468 auto *Access = 1469 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel); 1470 parent.addAccessFunction(Access); 1471 addAccess(Access); 1472 SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id)); 1473 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel); 1474 parent.addAccessFunction(Access); 1475 addAccess(Access); 1476 } 1477 1478 void ScopStmt::init(LoopInfo &LI) { 1479 assert(!Domain && "init must be called only once"); 1480 1481 buildDomain(); 1482 collectSurroundingLoops(); 1483 buildAccessRelations(); 1484 1485 if (DetectReductions) 1486 checkForReductions(); 1487 } 1488 1489 /// Collect loads which might form a reduction chain with @p StoreMA. 1490 /// 1491 /// Check if the stored value for @p StoreMA is a binary operator with one or 1492 /// two loads as operands. If the binary operand is commutative & associative, 1493 /// used only once (by @p StoreMA) and its load operands are also used only 1494 /// once, we have found a possible reduction chain. It starts at an operand 1495 /// load and includes the binary operator and @p StoreMA. 1496 /// 1497 /// Note: We allow only one use to ensure the load and binary operator cannot 1498 /// escape this block or into any other store except @p StoreMA. 1499 void ScopStmt::collectCandiateReductionLoads( 1500 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) { 1501 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction()); 1502 if (!Store) 1503 return; 1504 1505 // Skip if there is not one binary operator between the load and the store 1506 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand()); 1507 if (!BinOp) 1508 return; 1509 1510 // Skip if the binary operators has multiple uses 1511 if (BinOp->getNumUses() != 1) 1512 return; 1513 1514 // Skip if the opcode of the binary operator is not commutative/associative 1515 if (!BinOp->isCommutative() || !BinOp->isAssociative()) 1516 return; 1517 1518 // Skip if the binary operator is outside the current SCoP 1519 if (BinOp->getParent() != Store->getParent()) 1520 return; 1521 1522 // Skip if it is a multiplicative reduction and we disabled them 1523 if (DisableMultiplicativeReductions && 1524 (BinOp->getOpcode() == Instruction::Mul || 1525 BinOp->getOpcode() == Instruction::FMul)) 1526 return; 1527 1528 // Check the binary operator operands for a candidate load 1529 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0)); 1530 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1)); 1531 if (!PossibleLoad0 && !PossibleLoad1) 1532 return; 1533 1534 // A load is only a candidate if it cannot escape (thus has only this use) 1535 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1) 1536 if (PossibleLoad0->getParent() == Store->getParent()) 1537 Loads.push_back(&getArrayAccessFor(PossibleLoad0)); 1538 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1) 1539 if (PossibleLoad1->getParent() == Store->getParent()) 1540 Loads.push_back(&getArrayAccessFor(PossibleLoad1)); 1541 } 1542 1543 /// Check for reductions in this ScopStmt. 1544 /// 1545 /// Iterate over all store memory accesses and check for valid binary reduction 1546 /// like chains. For all candidates we check if they have the same base address 1547 /// and there are no other accesses which overlap with them. The base address 1548 /// check rules out impossible reductions candidates early. The overlap check, 1549 /// together with the "only one user" check in collectCandiateReductionLoads, 1550 /// guarantees that none of the intermediate results will escape during 1551 /// execution of the loop nest. We basically check here that no other memory 1552 /// access can access the same memory as the potential reduction. 1553 void ScopStmt::checkForReductions() { 1554 SmallVector<MemoryAccess *, 2> Loads; 1555 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates; 1556 1557 // First collect candidate load-store reduction chains by iterating over all 1558 // stores and collecting possible reduction loads. 1559 for (MemoryAccess *StoreMA : MemAccs) { 1560 if (StoreMA->isRead()) 1561 continue; 1562 1563 Loads.clear(); 1564 collectCandiateReductionLoads(StoreMA, Loads); 1565 for (MemoryAccess *LoadMA : Loads) 1566 Candidates.push_back(std::make_pair(LoadMA, StoreMA)); 1567 } 1568 1569 // Then check each possible candidate pair. 1570 for (const auto &CandidatePair : Candidates) { 1571 bool Valid = true; 1572 isl_map *LoadAccs = CandidatePair.first->getAccessRelation(); 1573 isl_map *StoreAccs = CandidatePair.second->getAccessRelation(); 1574 1575 // Skip those with obviously unequal base addresses. 1576 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) { 1577 isl_map_free(LoadAccs); 1578 isl_map_free(StoreAccs); 1579 continue; 1580 } 1581 1582 // And check if the remaining for overlap with other memory accesses. 1583 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs); 1584 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain()); 1585 isl_set *AllAccs = isl_map_range(AllAccsRel); 1586 1587 for (MemoryAccess *MA : MemAccs) { 1588 if (MA == CandidatePair.first || MA == CandidatePair.second) 1589 continue; 1590 1591 isl_map *AccRel = 1592 isl_map_intersect_domain(MA->getAccessRelation(), getDomain()); 1593 isl_set *Accs = isl_map_range(AccRel); 1594 1595 if (isl_set_has_equal_space(AllAccs, Accs)) { 1596 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs)); 1597 Valid = Valid && isl_set_is_empty(OverlapAccs); 1598 isl_set_free(OverlapAccs); 1599 } else { 1600 isl_set_free(Accs); 1601 } 1602 } 1603 1604 isl_set_free(AllAccs); 1605 if (!Valid) 1606 continue; 1607 1608 const LoadInst *Load = 1609 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction()); 1610 MemoryAccess::ReductionType RT = 1611 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load); 1612 1613 // If no overlapping access was found we mark the load and store as 1614 // reduction like. 1615 CandidatePair.first->markAsReductionLike(RT); 1616 CandidatePair.second->markAsReductionLike(RT); 1617 } 1618 } 1619 1620 std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); } 1621 1622 std::string ScopStmt::getScheduleStr() const { 1623 auto *S = getSchedule(); 1624 if (!S) 1625 return ""; 1626 auto Str = stringFromIslObj(S); 1627 isl_map_free(S); 1628 return Str; 1629 } 1630 1631 void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) { 1632 isl_set_free(InvalidDomain); 1633 InvalidDomain = ID; 1634 } 1635 1636 BasicBlock *ScopStmt::getEntryBlock() const { 1637 if (isBlockStmt()) 1638 return getBasicBlock(); 1639 return getRegion()->getEntry(); 1640 } 1641 1642 unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); } 1643 1644 const char *ScopStmt::getBaseName() const { return BaseName.c_str(); } 1645 1646 Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const { 1647 return NestLoops[Dimension]; 1648 } 1649 1650 isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); } 1651 1652 __isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); } 1653 1654 __isl_give isl_space *ScopStmt::getDomainSpace() const { 1655 return isl_set_get_space(Domain); 1656 } 1657 1658 __isl_give isl_id *ScopStmt::getDomainId() const { 1659 return isl_set_get_tuple_id(Domain); 1660 } 1661 1662 ScopStmt::~ScopStmt() { 1663 isl_set_free(Domain); 1664 isl_set_free(InvalidDomain); 1665 } 1666 1667 void ScopStmt::print(raw_ostream &OS) const { 1668 OS << "\t" << getBaseName() << "\n"; 1669 OS.indent(12) << "Domain :=\n"; 1670 1671 if (Domain) { 1672 OS.indent(16) << getDomainStr() << ";\n"; 1673 } else 1674 OS.indent(16) << "n/a\n"; 1675 1676 OS.indent(12) << "Schedule :=\n"; 1677 1678 if (Domain) { 1679 OS.indent(16) << getScheduleStr() << ";\n"; 1680 } else 1681 OS.indent(16) << "n/a\n"; 1682 1683 for (MemoryAccess *Access : MemAccs) 1684 Access->print(OS); 1685 } 1686 1687 void ScopStmt::dump() const { print(dbgs()); } 1688 1689 void ScopStmt::removeMemoryAccess(MemoryAccess *MA) { 1690 // Remove the memory accesses from this statement 1691 // together with all scalar accesses that were caused by it. 1692 // MK_Value READs have no access instruction, hence would not be removed by 1693 // this function. However, it is only used for invariant LoadInst accesses, 1694 // its arguments are always affine, hence synthesizable, and therefore there 1695 // are no MK_Value READ accesses to be removed. 1696 auto Predicate = [&](MemoryAccess *Acc) { 1697 return Acc->getAccessInstruction() == MA->getAccessInstruction(); 1698 }; 1699 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate), 1700 MemAccs.end()); 1701 InstructionToAccess.erase(MA->getAccessInstruction()); 1702 } 1703 1704 //===----------------------------------------------------------------------===// 1705 /// Scop class implement 1706 1707 void Scop::setContext(__isl_take isl_set *NewContext) { 1708 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context)); 1709 isl_set_free(Context); 1710 Context = NewContext; 1711 } 1712 1713 /// Remap parameter values but keep AddRecs valid wrt. invariant loads. 1714 struct SCEVSensitiveParameterRewriter 1715 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> { 1716 ValueToValueMap &VMap; 1717 ScalarEvolution &SE; 1718 1719 public: 1720 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE) 1721 : VMap(VMap), SE(SE) {} 1722 1723 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE, 1724 ValueToValueMap &VMap) { 1725 SCEVSensitiveParameterRewriter SSPR(VMap, SE); 1726 return SSPR.visit(E); 1727 } 1728 1729 const SCEV *visit(const SCEV *E) { 1730 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E); 1731 } 1732 1733 const SCEV *visitConstant(const SCEVConstant *E) { return E; } 1734 1735 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) { 1736 return SE.getTruncateExpr(visit(E->getOperand()), E->getType()); 1737 } 1738 1739 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) { 1740 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType()); 1741 } 1742 1743 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) { 1744 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType()); 1745 } 1746 1747 const SCEV *visitAddExpr(const SCEVAddExpr *E) { 1748 SmallVector<const SCEV *, 4> Operands; 1749 for (int i = 0, e = E->getNumOperands(); i < e; ++i) 1750 Operands.push_back(visit(E->getOperand(i))); 1751 return SE.getAddExpr(Operands); 1752 } 1753 1754 const SCEV *visitMulExpr(const SCEVMulExpr *E) { 1755 SmallVector<const SCEV *, 4> Operands; 1756 for (int i = 0, e = E->getNumOperands(); i < e; ++i) 1757 Operands.push_back(visit(E->getOperand(i))); 1758 return SE.getMulExpr(Operands); 1759 } 1760 1761 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) { 1762 SmallVector<const SCEV *, 4> Operands; 1763 for (int i = 0, e = E->getNumOperands(); i < e; ++i) 1764 Operands.push_back(visit(E->getOperand(i))); 1765 return SE.getSMaxExpr(Operands); 1766 } 1767 1768 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) { 1769 SmallVector<const SCEV *, 4> Operands; 1770 for (int i = 0, e = E->getNumOperands(); i < e; ++i) 1771 Operands.push_back(visit(E->getOperand(i))); 1772 return SE.getUMaxExpr(Operands); 1773 } 1774 1775 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) { 1776 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS())); 1777 } 1778 1779 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) { 1780 auto *Start = visit(E->getStart()); 1781 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0), 1782 visit(E->getStepRecurrence(SE)), 1783 E->getLoop(), SCEV::FlagAnyWrap); 1784 return SE.getAddExpr(Start, AddRec); 1785 } 1786 1787 const SCEV *visitUnknown(const SCEVUnknown *E) { 1788 if (auto *NewValue = VMap.lookup(E->getValue())) 1789 return SE.getUnknown(NewValue); 1790 return E; 1791 } 1792 }; 1793 1794 const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) { 1795 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap); 1796 } 1797 1798 void Scop::createParameterId(const SCEV *Parameter) { 1799 assert(Parameters.count(Parameter)); 1800 assert(!ParameterIds.count(Parameter)); 1801 1802 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1); 1803 1804 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) { 1805 Value *Val = ValueParameter->getValue(); 1806 1807 // If this parameter references a specific Value and this value has a name 1808 // we use this name as it is likely to be unique and more useful than just 1809 // a number. 1810 if (Val->hasName()) 1811 ParameterName = Val->getName(); 1812 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) { 1813 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets(); 1814 if (LoadOrigin->hasName()) { 1815 ParameterName += "_loaded_from_"; 1816 ParameterName += 1817 LI->getPointerOperand()->stripInBoundsOffsets()->getName(); 1818 } 1819 } 1820 } 1821 1822 ParameterName = getIslCompatibleName("", ParameterName, ""); 1823 1824 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(), 1825 const_cast<void *>((const void *)Parameter)); 1826 ParameterIds[Parameter] = Id; 1827 } 1828 1829 void Scop::addParams(const ParameterSetTy &NewParameters) { 1830 for (const SCEV *Parameter : NewParameters) { 1831 // Normalize the SCEV to get the representing element for an invariant load. 1832 Parameter = extractConstantFactor(Parameter, *SE).second; 1833 Parameter = getRepresentingInvariantLoadSCEV(Parameter); 1834 1835 if (Parameters.insert(Parameter)) 1836 createParameterId(Parameter); 1837 } 1838 } 1839 1840 __isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) { 1841 // Normalize the SCEV to get the representing element for an invariant load. 1842 Parameter = getRepresentingInvariantLoadSCEV(Parameter); 1843 return isl_id_copy(ParameterIds.lookup(Parameter)); 1844 } 1845 1846 __isl_give isl_set * 1847 Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const { 1848 isl_set *DomainContext = isl_union_set_params(getDomains()); 1849 return isl_set_intersect_params(C, DomainContext); 1850 } 1851 1852 bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const { 1853 return DT.dominates(BB, getEntry()); 1854 } 1855 1856 void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT, 1857 LoopInfo &LI) { 1858 auto &F = getFunction(); 1859 for (auto &Assumption : AC.assumptions()) { 1860 auto *CI = dyn_cast_or_null<CallInst>(Assumption); 1861 if (!CI || CI->getNumArgOperands() != 1) 1862 continue; 1863 1864 bool InScop = contains(CI); 1865 if (!InScop && !isDominatedBy(DT, CI->getParent())) 1866 continue; 1867 1868 auto *L = LI.getLoopFor(CI->getParent()); 1869 auto *Val = CI->getArgOperand(0); 1870 ParameterSetTy DetectedParams; 1871 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) { 1872 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, 1873 CI->getDebugLoc(), 1874 "Non-affine user assumption ignored."); 1875 continue; 1876 } 1877 1878 // Collect all newly introduced parameters. 1879 ParameterSetTy NewParams; 1880 for (auto *Param : DetectedParams) { 1881 Param = extractConstantFactor(Param, *SE).second; 1882 Param = getRepresentingInvariantLoadSCEV(Param); 1883 if (Parameters.count(Param)) 1884 continue; 1885 NewParams.insert(Param); 1886 } 1887 1888 SmallVector<isl_set *, 2> ConditionSets; 1889 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr; 1890 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin(); 1891 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context); 1892 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets); 1893 isl_set_free(Dom); 1894 1895 if (!Valid) 1896 continue; 1897 1898 isl_set *AssumptionCtx = nullptr; 1899 if (InScop) { 1900 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1])); 1901 isl_set_free(ConditionSets[0]); 1902 } else { 1903 AssumptionCtx = isl_set_complement(ConditionSets[1]); 1904 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]); 1905 } 1906 1907 // Project out newly introduced parameters as they are not otherwise useful. 1908 if (!NewParams.empty()) { 1909 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) { 1910 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u); 1911 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id)); 1912 isl_id_free(Id); 1913 1914 if (!NewParams.count(Param)) 1915 continue; 1916 1917 AssumptionCtx = 1918 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1); 1919 } 1920 } 1921 1922 emitOptimizationRemarkAnalysis( 1923 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(), 1924 "Use user assumption: " + stringFromIslObj(AssumptionCtx)); 1925 Context = isl_set_intersect(Context, AssumptionCtx); 1926 } 1927 } 1928 1929 void Scop::addUserContext() { 1930 if (UserContextStr.empty()) 1931 return; 1932 1933 isl_set *UserContext = 1934 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str()); 1935 isl_space *Space = getParamSpace(); 1936 if (isl_space_dim(Space, isl_dim_param) != 1937 isl_set_dim(UserContext, isl_dim_param)) { 1938 auto SpaceStr = isl_space_to_str(Space); 1939 errs() << "Error: the context provided in -polly-context has not the same " 1940 << "number of dimensions than the computed context. Due to this " 1941 << "mismatch, the -polly-context option is ignored. Please provide " 1942 << "the context in the parameter space: " << SpaceStr << ".\n"; 1943 free(SpaceStr); 1944 isl_set_free(UserContext); 1945 isl_space_free(Space); 1946 return; 1947 } 1948 1949 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) { 1950 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i); 1951 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i); 1952 1953 if (strcmp(NameContext, NameUserContext) != 0) { 1954 auto SpaceStr = isl_space_to_str(Space); 1955 errs() << "Error: the name of dimension " << i 1956 << " provided in -polly-context " 1957 << "is '" << NameUserContext << "', but the name in the computed " 1958 << "context is '" << NameContext 1959 << "'. Due to this name mismatch, " 1960 << "the -polly-context option is ignored. Please provide " 1961 << "the context in the parameter space: " << SpaceStr << ".\n"; 1962 free(SpaceStr); 1963 isl_set_free(UserContext); 1964 isl_space_free(Space); 1965 return; 1966 } 1967 1968 UserContext = 1969 isl_set_set_dim_id(UserContext, isl_dim_param, i, 1970 isl_space_get_dim_id(Space, isl_dim_param, i)); 1971 } 1972 1973 Context = isl_set_intersect(Context, UserContext); 1974 isl_space_free(Space); 1975 } 1976 1977 void Scop::buildInvariantEquivalenceClasses() { 1978 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses; 1979 1980 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads(); 1981 for (LoadInst *LInst : RIL) { 1982 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand()); 1983 1984 Type *Ty = LInst->getType(); 1985 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)]; 1986 if (ClassRep) { 1987 InvEquivClassVMap[LInst] = ClassRep; 1988 continue; 1989 } 1990 1991 ClassRep = LInst; 1992 InvariantEquivClasses.emplace_back( 1993 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty}); 1994 } 1995 } 1996 1997 void Scop::buildContext() { 1998 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0); 1999 Context = isl_set_universe(isl_space_copy(Space)); 2000 InvalidContext = isl_set_empty(isl_space_copy(Space)); 2001 AssumedContext = isl_set_universe(Space); 2002 } 2003 2004 void Scop::addParameterBounds() { 2005 unsigned PDim = 0; 2006 for (auto *Parameter : Parameters) { 2007 ConstantRange SRange = SE->getSignedRange(Parameter); 2008 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param); 2009 } 2010 } 2011 2012 void Scop::realignParams() { 2013 // Add all parameters into a common model. 2014 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size()); 2015 2016 unsigned PDim = 0; 2017 for (const auto *Parameter : Parameters) { 2018 isl_id *id = getIdForParam(Parameter); 2019 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id); 2020 } 2021 2022 // Align the parameters of all data structures to the model. 2023 Context = isl_set_align_params(Context, Space); 2024 2025 // As all parameters are known add bounds to them. 2026 addParameterBounds(); 2027 2028 for (ScopStmt &Stmt : *this) 2029 Stmt.realignParams(); 2030 2031 // Simplify the schedule according to the context too. 2032 Schedule = isl_schedule_gist_domain_params(Schedule, getContext()); 2033 } 2034 2035 static __isl_give isl_set * 2036 simplifyAssumptionContext(__isl_take isl_set *AssumptionContext, 2037 const Scop &S) { 2038 // If we modelt all blocks in the SCoP that have side effects we can simplify 2039 // the context with the constraints that are needed for anything to be 2040 // executed at all. However, if we have error blocks in the SCoP we already 2041 // assumed some parameter combinations cannot occure and removed them from the 2042 // domains, thus we cannot use the remaining domain to simplify the 2043 // assumptions. 2044 if (!S.hasErrorBlock()) { 2045 isl_set *DomainParameters = isl_union_set_params(S.getDomains()); 2046 AssumptionContext = 2047 isl_set_gist_params(AssumptionContext, DomainParameters); 2048 } 2049 2050 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext()); 2051 return AssumptionContext; 2052 } 2053 2054 void Scop::simplifyContexts() { 2055 // The parameter constraints of the iteration domains give us a set of 2056 // constraints that need to hold for all cases where at least a single 2057 // statement iteration is executed in the whole scop. We now simplify the 2058 // assumed context under the assumption that such constraints hold and at 2059 // least a single statement iteration is executed. For cases where no 2060 // statement instances are executed, the assumptions we have taken about 2061 // the executed code do not matter and can be changed. 2062 // 2063 // WARNING: This only holds if the assumptions we have taken do not reduce 2064 // the set of statement instances that are executed. Otherwise we 2065 // may run into a case where the iteration domains suggest that 2066 // for a certain set of parameter constraints no code is executed, 2067 // but in the original program some computation would have been 2068 // performed. In such a case, modifying the run-time conditions and 2069 // possibly influencing the run-time check may cause certain scops 2070 // to not be executed. 2071 // 2072 // Example: 2073 // 2074 // When delinearizing the following code: 2075 // 2076 // for (long i = 0; i < 100; i++) 2077 // for (long j = 0; j < m; j++) 2078 // A[i+p][j] = 1.0; 2079 // 2080 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as 2081 // otherwise we would access out of bound data. Now, knowing that code is 2082 // only executed for the case m >= 0, it is sufficient to assume p >= 0. 2083 AssumedContext = simplifyAssumptionContext(AssumedContext, *this); 2084 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace()); 2085 } 2086 2087 /// Add the minimal/maximal access in @p Set to @p User. 2088 static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) { 2089 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User; 2090 isl_pw_multi_aff *MinPMA, *MaxPMA; 2091 isl_pw_aff *LastDimAff; 2092 isl_aff *OneAff; 2093 unsigned Pos; 2094 2095 Set = isl_set_remove_divs(Set); 2096 2097 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) { 2098 isl_set_free(Set); 2099 return isl_stat_error; 2100 } 2101 2102 // Restrict the number of parameters involved in the access as the lexmin/ 2103 // lexmax computation will take too long if this number is high. 2104 // 2105 // Experiments with a simple test case using an i7 4800MQ: 2106 // 2107 // #Parameters involved | Time (in sec) 2108 // 6 | 0.01 2109 // 7 | 0.04 2110 // 8 | 0.12 2111 // 9 | 0.40 2112 // 10 | 1.54 2113 // 11 | 6.78 2114 // 12 | 30.38 2115 // 2116 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) { 2117 unsigned InvolvedParams = 0; 2118 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++) 2119 if (isl_set_involves_dims(Set, isl_dim_param, u, 1)) 2120 InvolvedParams++; 2121 2122 if (InvolvedParams > RunTimeChecksMaxParameters) { 2123 isl_set_free(Set); 2124 return isl_stat_error; 2125 } 2126 } 2127 2128 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set)); 2129 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set)); 2130 2131 MinPMA = isl_pw_multi_aff_coalesce(MinPMA); 2132 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA); 2133 2134 // Adjust the last dimension of the maximal access by one as we want to 2135 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer 2136 // we test during code generation might now point after the end of the 2137 // allocated array but we will never dereference it anyway. 2138 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) && 2139 "Assumed at least one output dimension"); 2140 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1; 2141 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos); 2142 OneAff = isl_aff_zero_on_domain( 2143 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff))); 2144 OneAff = isl_aff_add_constant_si(OneAff, 1); 2145 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff)); 2146 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff); 2147 2148 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA)); 2149 2150 isl_set_free(Set); 2151 return isl_stat_ok; 2152 } 2153 2154 static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) { 2155 isl_set *Domain = MA->getStatement()->getDomain(); 2156 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain)); 2157 return isl_set_reset_tuple_id(Domain); 2158 } 2159 2160 /// Wrapper function to calculate minimal/maximal accesses to each array. 2161 static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses, 2162 __isl_take isl_union_set *Domains, 2163 Scop::MinMaxVectorTy &MinMaxAccesses) { 2164 2165 Accesses = isl_union_map_intersect_domain(Accesses, Domains); 2166 isl_union_set *Locations = isl_union_map_range(Accesses); 2167 Locations = isl_union_set_coalesce(Locations); 2168 Locations = isl_union_set_detect_equalities(Locations); 2169 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess, 2170 &MinMaxAccesses)); 2171 isl_union_set_free(Locations); 2172 return Valid; 2173 } 2174 2175 /// Helper to treat non-affine regions and basic blocks the same. 2176 /// 2177 ///{ 2178 2179 /// Return the block that is the representing block for @p RN. 2180 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) { 2181 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry() 2182 : RN->getNodeAs<BasicBlock>(); 2183 } 2184 2185 /// Return the @p idx'th block that is executed after @p RN. 2186 static inline BasicBlock * 2187 getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) { 2188 if (RN->isSubRegion()) { 2189 assert(idx == 0); 2190 return RN->getNodeAs<Region>()->getExit(); 2191 } 2192 return TI->getSuccessor(idx); 2193 } 2194 2195 /// Return the smallest loop surrounding @p RN. 2196 static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) { 2197 if (!RN->isSubRegion()) 2198 return LI.getLoopFor(RN->getNodeAs<BasicBlock>()); 2199 2200 Region *NonAffineSubRegion = RN->getNodeAs<Region>(); 2201 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry()); 2202 while (L && NonAffineSubRegion->contains(L)) 2203 L = L->getParentLoop(); 2204 return L; 2205 } 2206 2207 static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) { 2208 if (!RN->isSubRegion()) 2209 return 1; 2210 2211 Region *R = RN->getNodeAs<Region>(); 2212 return std::distance(R->block_begin(), R->block_end()); 2213 } 2214 2215 static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI, 2216 const DominatorTree &DT) { 2217 if (!RN->isSubRegion()) 2218 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT); 2219 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks()) 2220 if (isErrorBlock(*BB, R, LI, DT)) 2221 return true; 2222 return false; 2223 } 2224 2225 ///} 2226 2227 static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain, 2228 unsigned Dim, Loop *L) { 2229 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1); 2230 isl_id *DimId = 2231 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L)); 2232 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId); 2233 } 2234 2235 __isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const { 2236 return getDomainConditions(Stmt->getEntryBlock()); 2237 } 2238 2239 __isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const { 2240 auto DIt = DomainMap.find(BB); 2241 if (DIt != DomainMap.end()) 2242 return isl_set_copy(DIt->getSecond()); 2243 2244 auto &RI = *R.getRegionInfo(); 2245 auto *BBR = RI.getRegionFor(BB); 2246 while (BBR->getEntry() == BB) 2247 BBR = BBR->getParent(); 2248 return getDomainConditions(BBR->getEntry()); 2249 } 2250 2251 bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) { 2252 2253 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R); 2254 auto *EntryBB = R->getEntry(); 2255 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB); 2256 int LD = getRelativeLoopDepth(L); 2257 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1)); 2258 2259 while (LD-- >= 0) { 2260 S = addDomainDimId(S, LD + 1, L); 2261 L = L->getParentLoop(); 2262 } 2263 2264 // Initialize the invalid domain. 2265 auto *EntryStmt = getStmtFor(EntryBB); 2266 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S))); 2267 2268 DomainMap[EntryBB] = S; 2269 2270 if (IsOnlyNonAffineRegion) 2271 return !containsErrorBlock(R->getNode(), *R, LI, DT); 2272 2273 if (!buildDomainsWithBranchConstraints(R, DT, LI)) 2274 return false; 2275 2276 if (!propagateDomainConstraints(R, DT, LI)) 2277 return false; 2278 2279 // Error blocks and blocks dominated by them have been assumed to never be 2280 // executed. Representing them in the Scop does not add any value. In fact, 2281 // it is likely to cause issues during construction of the ScopStmts. The 2282 // contents of error blocks have not been verified to be expressible and 2283 // will cause problems when building up a ScopStmt for them. 2284 // Furthermore, basic blocks dominated by error blocks may reference 2285 // instructions in the error block which, if the error block is not modeled, 2286 // can themselves not be constructed properly. To this end we will replace 2287 // the domains of error blocks and those only reachable via error blocks 2288 // with an empty set. Additionally, we will record for each block under which 2289 // parameter combination it would be reached via an error block in its 2290 // InvalidDomain. This information is needed during load hoisting. 2291 if (!propagateInvalidStmtDomains(R, DT, LI)) 2292 return false; 2293 2294 return true; 2295 } 2296 2297 // If the loop is nonaffine/boxed, return the first non-boxed surrounding loop 2298 // for Polly. If the loop is affine, return the loop itself. Do not call 2299 // `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need 2300 // to analyze the memory accesses of the nonaffine/boxed loops. 2301 static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI, 2302 const BoxedLoopsSetTy &BoxedLoops) { 2303 auto *L = LI.getLoopFor(BB); 2304 while (BoxedLoops.count(L)) 2305 L = L->getParentLoop(); 2306 return L; 2307 } 2308 2309 /// Adjust the dimensions of @p Dom that was constructed for @p OldL 2310 /// to be compatible to domains constructed for loop @p NewL. 2311 /// 2312 /// This function assumes @p NewL and @p OldL are equal or there is a CFG 2313 /// edge from @p OldL to @p NewL. 2314 static __isl_give isl_set *adjustDomainDimensions(Scop &S, 2315 __isl_take isl_set *Dom, 2316 Loop *OldL, Loop *NewL) { 2317 2318 // If the loops are the same there is nothing to do. 2319 if (NewL == OldL) 2320 return Dom; 2321 2322 int OldDepth = S.getRelativeLoopDepth(OldL); 2323 int NewDepth = S.getRelativeLoopDepth(NewL); 2324 // If both loops are non-affine loops there is nothing to do. 2325 if (OldDepth == -1 && NewDepth == -1) 2326 return Dom; 2327 2328 // Distinguish three cases: 2329 // 1) The depth is the same but the loops are not. 2330 // => One loop was left one was entered. 2331 // 2) The depth increased from OldL to NewL. 2332 // => One loop was entered, none was left. 2333 // 3) The depth decreased from OldL to NewL. 2334 // => Loops were left were difference of the depths defines how many. 2335 if (OldDepth == NewDepth) { 2336 assert(OldL->getParentLoop() == NewL->getParentLoop()); 2337 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1); 2338 Dom = isl_set_add_dims(Dom, isl_dim_set, 1); 2339 Dom = addDomainDimId(Dom, NewDepth, NewL); 2340 } else if (OldDepth < NewDepth) { 2341 assert(OldDepth + 1 == NewDepth); 2342 auto &R = S.getRegion(); 2343 (void)R; 2344 assert(NewL->getParentLoop() == OldL || 2345 ((!OldL || !R.contains(OldL)) && R.contains(NewL))); 2346 Dom = isl_set_add_dims(Dom, isl_dim_set, 1); 2347 Dom = addDomainDimId(Dom, NewDepth, NewL); 2348 } else { 2349 assert(OldDepth > NewDepth); 2350 int Diff = OldDepth - NewDepth; 2351 int NumDim = isl_set_n_dim(Dom); 2352 assert(NumDim >= Diff); 2353 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff); 2354 } 2355 2356 return Dom; 2357 } 2358 2359 bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT, 2360 LoopInfo &LI) { 2361 auto &BoxedLoops = getBoxedLoops(); 2362 2363 ReversePostOrderTraversal<Region *> RTraversal(R); 2364 for (auto *RN : RTraversal) { 2365 2366 // Recurse for affine subregions but go on for basic blocks and non-affine 2367 // subregions. 2368 if (RN->isSubRegion()) { 2369 Region *SubRegion = RN->getNodeAs<Region>(); 2370 if (!isNonAffineSubRegion(SubRegion)) { 2371 propagateInvalidStmtDomains(SubRegion, DT, LI); 2372 continue; 2373 } 2374 } 2375 2376 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT); 2377 BasicBlock *BB = getRegionNodeBasicBlock(RN); 2378 ScopStmt *Stmt = getStmtFor(BB); 2379 isl_set *&Domain = DomainMap[BB]; 2380 assert(Domain && "Cannot propagate a nullptr"); 2381 2382 auto *InvalidDomain = Stmt->getInvalidDomain(); 2383 bool IsInvalidBlock = 2384 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain); 2385 2386 if (!IsInvalidBlock) { 2387 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain)); 2388 } else { 2389 isl_set_free(InvalidDomain); 2390 InvalidDomain = Domain; 2391 isl_set *DomPar = isl_set_params(isl_set_copy(Domain)); 2392 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(), 2393 AS_RESTRICTION); 2394 Domain = nullptr; 2395 } 2396 2397 if (isl_set_is_empty(InvalidDomain)) { 2398 Stmt->setInvalidDomain(InvalidDomain); 2399 continue; 2400 } 2401 2402 auto *BBLoop = getRegionNodeLoop(RN, LI); 2403 auto *TI = BB->getTerminator(); 2404 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors(); 2405 for (unsigned u = 0; u < NumSuccs; u++) { 2406 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u); 2407 auto *SuccStmt = getStmtFor(SuccBB); 2408 2409 // Skip successors outside the SCoP. 2410 if (!SuccStmt) 2411 continue; 2412 2413 // Skip backedges. 2414 if (DT.dominates(SuccBB, BB)) 2415 continue; 2416 2417 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops); 2418 auto *AdjustedInvalidDomain = adjustDomainDimensions( 2419 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop); 2420 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain(); 2421 SuccInvalidDomain = 2422 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain); 2423 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain); 2424 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain); 2425 SuccStmt->setInvalidDomain(SuccInvalidDomain); 2426 2427 // Check if the maximal number of domain disjunctions was reached. 2428 // In case this happens we will bail. 2429 if (NumConjucts < MaxDisjunctionsInDomain) 2430 continue; 2431 2432 isl_set_free(InvalidDomain); 2433 invalidate(COMPLEXITY, TI->getDebugLoc()); 2434 return false; 2435 } 2436 2437 Stmt->setInvalidDomain(InvalidDomain); 2438 } 2439 2440 return true; 2441 } 2442 2443 void Scop::propagateDomainConstraintsToRegionExit( 2444 BasicBlock *BB, Loop *BBLoop, 2445 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) { 2446 2447 // Check if the block @p BB is the entry of a region. If so we propagate it's 2448 // domain to the exit block of the region. Otherwise we are done. 2449 auto *RI = R.getRegionInfo(); 2450 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr; 2451 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr; 2452 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB)) 2453 return; 2454 2455 auto &BoxedLoops = getBoxedLoops(); 2456 // Do not propagate the domain if there is a loop backedge inside the region 2457 // that would prevent the exit block from beeing executed. 2458 auto *L = BBLoop; 2459 while (L && contains(L)) { 2460 SmallVector<BasicBlock *, 4> LatchBBs; 2461 BBLoop->getLoopLatches(LatchBBs); 2462 for (auto *LatchBB : LatchBBs) 2463 if (BB != LatchBB && BBReg->contains(LatchBB)) 2464 return; 2465 L = L->getParentLoop(); 2466 } 2467 2468 auto *Domain = DomainMap[BB]; 2469 assert(Domain && "Cannot propagate a nullptr"); 2470 2471 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops); 2472 2473 // Since the dimensions of @p BB and @p ExitBB might be different we have to 2474 // adjust the domain before we can propagate it. 2475 auto *AdjustedDomain = 2476 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop); 2477 auto *&ExitDomain = DomainMap[ExitBB]; 2478 2479 // If the exit domain is not yet created we set it otherwise we "add" the 2480 // current domain. 2481 ExitDomain = 2482 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain; 2483 2484 // Initialize the invalid domain. 2485 auto *ExitStmt = getStmtFor(ExitBB); 2486 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain))); 2487 2488 FinishedExitBlocks.insert(ExitBB); 2489 } 2490 2491 bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT, 2492 LoopInfo &LI) { 2493 // To create the domain for each block in R we iterate over all blocks and 2494 // subregions in R and propagate the conditions under which the current region 2495 // element is executed. To this end we iterate in reverse post order over R as 2496 // it ensures that we first visit all predecessors of a region node (either a 2497 // basic block or a subregion) before we visit the region node itself. 2498 // Initially, only the domain for the SCoP region entry block is set and from 2499 // there we propagate the current domain to all successors, however we add the 2500 // condition that the successor is actually executed next. 2501 // As we are only interested in non-loop carried constraints here we can 2502 // simply skip loop back edges. 2503 2504 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks; 2505 ReversePostOrderTraversal<Region *> RTraversal(R); 2506 for (auto *RN : RTraversal) { 2507 2508 // Recurse for affine subregions but go on for basic blocks and non-affine 2509 // subregions. 2510 if (RN->isSubRegion()) { 2511 Region *SubRegion = RN->getNodeAs<Region>(); 2512 if (!isNonAffineSubRegion(SubRegion)) { 2513 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI)) 2514 return false; 2515 continue; 2516 } 2517 } 2518 2519 if (containsErrorBlock(RN, getRegion(), LI, DT)) 2520 HasErrorBlock = true; 2521 2522 BasicBlock *BB = getRegionNodeBasicBlock(RN); 2523 TerminatorInst *TI = BB->getTerminator(); 2524 2525 if (isa<UnreachableInst>(TI)) 2526 continue; 2527 2528 isl_set *Domain = DomainMap.lookup(BB); 2529 if (!Domain) 2530 continue; 2531 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain)); 2532 2533 auto *BBLoop = getRegionNodeLoop(RN, LI); 2534 // Propagate the domain from BB directly to blocks that have a superset 2535 // domain, at the moment only region exit nodes of regions that start in BB. 2536 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI); 2537 2538 // If all successors of BB have been set a domain through the propagation 2539 // above we do not need to build condition sets but can just skip this 2540 // block. However, it is important to note that this is a local property 2541 // with regards to the region @p R. To this end FinishedExitBlocks is a 2542 // local variable. 2543 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) { 2544 return FinishedExitBlocks.count(SuccBB); 2545 }; 2546 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit)) 2547 continue; 2548 2549 // Build the condition sets for the successor nodes of the current region 2550 // node. If it is a non-affine subregion we will always execute the single 2551 // exit node, hence the single entry node domain is the condition set. For 2552 // basic blocks we use the helper function buildConditionSets. 2553 SmallVector<isl_set *, 8> ConditionSets; 2554 if (RN->isSubRegion()) 2555 ConditionSets.push_back(isl_set_copy(Domain)); 2556 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain, 2557 ConditionSets)) 2558 return false; 2559 2560 // Now iterate over the successors and set their initial domain based on 2561 // their condition set. We skip back edges here and have to be careful when 2562 // we leave a loop not to keep constraints over a dimension that doesn't 2563 // exist anymore. 2564 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size()); 2565 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) { 2566 isl_set *CondSet = ConditionSets[u]; 2567 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u); 2568 2569 auto *SuccStmt = getStmtFor(SuccBB); 2570 // Skip blocks outside the region. 2571 if (!SuccStmt) { 2572 isl_set_free(CondSet); 2573 continue; 2574 } 2575 2576 // If we propagate the domain of some block to "SuccBB" we do not have to 2577 // adjust the domain. 2578 if (FinishedExitBlocks.count(SuccBB)) { 2579 isl_set_free(CondSet); 2580 continue; 2581 } 2582 2583 // Skip back edges. 2584 if (DT.dominates(SuccBB, BB)) { 2585 isl_set_free(CondSet); 2586 continue; 2587 } 2588 2589 auto &BoxedLoops = getBoxedLoops(); 2590 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops); 2591 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop); 2592 2593 // Set the domain for the successor or merge it with an existing domain in 2594 // case there are multiple paths (without loop back edges) to the 2595 // successor block. 2596 isl_set *&SuccDomain = DomainMap[SuccBB]; 2597 2598 if (SuccDomain) { 2599 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet)); 2600 } else { 2601 // Initialize the invalid domain. 2602 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet))); 2603 SuccDomain = CondSet; 2604 } 2605 2606 // Check if the maximal number of domain disjunctions was reached. 2607 // In case this happens we will clean up and bail. 2608 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain) 2609 continue; 2610 2611 invalidate(COMPLEXITY, DebugLoc()); 2612 while (++u < ConditionSets.size()) 2613 isl_set_free(ConditionSets[u]); 2614 return false; 2615 } 2616 } 2617 2618 return true; 2619 } 2620 2621 __isl_give isl_set * 2622 Scop::getPredecessorDomainConstraints(BasicBlock *BB, 2623 __isl_keep isl_set *Domain, 2624 DominatorTree &DT, LoopInfo &LI) { 2625 // If @p BB is the ScopEntry we are done 2626 if (R.getEntry() == BB) 2627 return isl_set_universe(isl_set_get_space(Domain)); 2628 2629 // The set of boxed loops (loops in non-affine subregions) for this SCoP. 2630 auto &BoxedLoops = getBoxedLoops(); 2631 2632 // The region info of this function. 2633 auto &RI = *R.getRegionInfo(); 2634 2635 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops); 2636 2637 // A domain to collect all predecessor domains, thus all conditions under 2638 // which the block is executed. To this end we start with the empty domain. 2639 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain)); 2640 2641 // Set of regions of which the entry block domain has been propagated to BB. 2642 // all predecessors inside any of the regions can be skipped. 2643 SmallSet<Region *, 8> PropagatedRegions; 2644 2645 for (auto *PredBB : predecessors(BB)) { 2646 // Skip backedges. 2647 if (DT.dominates(BB, PredBB)) 2648 continue; 2649 2650 // If the predecessor is in a region we used for propagation we can skip it. 2651 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); }; 2652 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(), 2653 PredBBInRegion)) { 2654 continue; 2655 } 2656 2657 // Check if there is a valid region we can use for propagation, thus look 2658 // for a region that contains the predecessor and has @p BB as exit block. 2659 auto *PredR = RI.getRegionFor(PredBB); 2660 while (PredR->getExit() != BB && !PredR->contains(BB)) 2661 PredR->getParent(); 2662 2663 // If a valid region for propagation was found use the entry of that region 2664 // for propagation, otherwise the PredBB directly. 2665 if (PredR->getExit() == BB) { 2666 PredBB = PredR->getEntry(); 2667 PropagatedRegions.insert(PredR); 2668 } 2669 2670 auto *PredBBDom = getDomainConditions(PredBB); 2671 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops); 2672 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop); 2673 2674 PredDom = isl_set_union(PredDom, PredBBDom); 2675 } 2676 2677 return PredDom; 2678 } 2679 2680 bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT, 2681 LoopInfo &LI) { 2682 // Iterate over the region R and propagate the domain constrains from the 2683 // predecessors to the current node. In contrast to the 2684 // buildDomainsWithBranchConstraints function, this one will pull the domain 2685 // information from the predecessors instead of pushing it to the successors. 2686 // Additionally, we assume the domains to be already present in the domain 2687 // map here. However, we iterate again in reverse post order so we know all 2688 // predecessors have been visited before a block or non-affine subregion is 2689 // visited. 2690 2691 ReversePostOrderTraversal<Region *> RTraversal(R); 2692 for (auto *RN : RTraversal) { 2693 2694 // Recurse for affine subregions but go on for basic blocks and non-affine 2695 // subregions. 2696 if (RN->isSubRegion()) { 2697 Region *SubRegion = RN->getNodeAs<Region>(); 2698 if (!isNonAffineSubRegion(SubRegion)) { 2699 if (!propagateDomainConstraints(SubRegion, DT, LI)) 2700 return false; 2701 continue; 2702 } 2703 } 2704 2705 BasicBlock *BB = getRegionNodeBasicBlock(RN); 2706 isl_set *&Domain = DomainMap[BB]; 2707 assert(Domain); 2708 2709 // Under the union of all predecessor conditions we can reach this block. 2710 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI); 2711 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom)); 2712 Domain = isl_set_align_params(Domain, getParamSpace()); 2713 2714 Loop *BBLoop = getRegionNodeLoop(RN, LI); 2715 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop)) 2716 if (!addLoopBoundsToHeaderDomain(BBLoop, LI)) 2717 return false; 2718 } 2719 2720 return true; 2721 } 2722 2723 /// Create a map to map from a given iteration to a subsequent iteration. 2724 /// 2725 /// This map maps from SetSpace -> SetSpace where the dimensions @p Dim 2726 /// is incremented by one and all other dimensions are equal, e.g., 2727 /// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3] 2728 /// 2729 /// if @p Dim is 2 and @p SetSpace has 4 dimensions. 2730 static __isl_give isl_map * 2731 createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) { 2732 auto *MapSpace = isl_space_map_from_set(SetSpace); 2733 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace)); 2734 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++) 2735 if (u != Dim) 2736 NextIterationMap = 2737 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u); 2738 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace)); 2739 C = isl_constraint_set_constant_si(C, 1); 2740 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1); 2741 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1); 2742 NextIterationMap = isl_map_add_constraint(NextIterationMap, C); 2743 return NextIterationMap; 2744 } 2745 2746 bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) { 2747 int LoopDepth = getRelativeLoopDepth(L); 2748 assert(LoopDepth >= 0 && "Loop in region should have at least depth one"); 2749 2750 BasicBlock *HeaderBB = L->getHeader(); 2751 assert(DomainMap.count(HeaderBB)); 2752 isl_set *&HeaderBBDom = DomainMap[HeaderBB]; 2753 2754 isl_map *NextIterationMap = 2755 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth); 2756 2757 isl_set *UnionBackedgeCondition = 2758 isl_set_empty(isl_set_get_space(HeaderBBDom)); 2759 2760 SmallVector<llvm::BasicBlock *, 4> LatchBlocks; 2761 L->getLoopLatches(LatchBlocks); 2762 2763 for (BasicBlock *LatchBB : LatchBlocks) { 2764 2765 // If the latch is only reachable via error statements we skip it. 2766 isl_set *LatchBBDom = DomainMap.lookup(LatchBB); 2767 if (!LatchBBDom) 2768 continue; 2769 2770 isl_set *BackedgeCondition = nullptr; 2771 2772 TerminatorInst *TI = LatchBB->getTerminator(); 2773 BranchInst *BI = dyn_cast<BranchInst>(TI); 2774 if (BI && BI->isUnconditional()) 2775 BackedgeCondition = isl_set_copy(LatchBBDom); 2776 else { 2777 SmallVector<isl_set *, 8> ConditionSets; 2778 int idx = BI->getSuccessor(0) != HeaderBB; 2779 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom, 2780 ConditionSets)) 2781 return false; 2782 2783 // Free the non back edge condition set as we do not need it. 2784 isl_set_free(ConditionSets[1 - idx]); 2785 2786 BackedgeCondition = ConditionSets[idx]; 2787 } 2788 2789 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB)); 2790 assert(LatchLoopDepth >= LoopDepth); 2791 BackedgeCondition = 2792 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1, 2793 LatchLoopDepth - LoopDepth); 2794 UnionBackedgeCondition = 2795 isl_set_union(UnionBackedgeCondition, BackedgeCondition); 2796 } 2797 2798 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom)); 2799 for (int i = 0; i < LoopDepth; i++) 2800 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i); 2801 2802 isl_set *UnionBackedgeConditionComplement = 2803 isl_set_complement(UnionBackedgeCondition); 2804 UnionBackedgeConditionComplement = isl_set_lower_bound_si( 2805 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0); 2806 UnionBackedgeConditionComplement = 2807 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap); 2808 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement); 2809 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap); 2810 2811 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth); 2812 HeaderBBDom = Parts.second; 2813 2814 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add 2815 // the bounded assumptions to the context as they are already implied by the 2816 // <nsw> tag. 2817 if (Affinator.hasNSWAddRecForLoop(L)) { 2818 isl_set_free(Parts.first); 2819 return true; 2820 } 2821 2822 isl_set *UnboundedCtx = isl_set_params(Parts.first); 2823 recordAssumption(INFINITELOOP, UnboundedCtx, 2824 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION); 2825 return true; 2826 } 2827 2828 MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) { 2829 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr()); 2830 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr)); 2831 if (!PointerBase) 2832 return nullptr; 2833 2834 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue()); 2835 if (!PointerBaseInst) 2836 return nullptr; 2837 2838 auto *BasePtrStmt = getStmtFor(PointerBaseInst); 2839 if (!BasePtrStmt) 2840 return nullptr; 2841 2842 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst); 2843 } 2844 2845 bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA, 2846 __isl_keep isl_union_map *Writes) { 2847 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) { 2848 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes); 2849 bool Hoistable = NHCtx != nullptr; 2850 isl_set_free(NHCtx); 2851 return !Hoistable; 2852 } 2853 2854 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr()); 2855 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr)); 2856 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue())) 2857 if (!isa<LoadInst>(BasePtrInst)) 2858 return contains(BasePtrInst); 2859 2860 return false; 2861 } 2862 2863 bool Scop::buildAliasChecks(AliasAnalysis &AA) { 2864 if (!PollyUseRuntimeAliasChecks) 2865 return true; 2866 2867 if (buildAliasGroups(AA)) 2868 return true; 2869 2870 // If a problem occurs while building the alias groups we need to delete 2871 // this SCoP and pretend it wasn't valid in the first place. To this end 2872 // we make the assumed context infeasible. 2873 invalidate(ALIASING, DebugLoc()); 2874 2875 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr() 2876 << " could not be created as the number of parameters involved " 2877 "is too high. The SCoP will be " 2878 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust " 2879 "the maximal number of parameters but be advised that the " 2880 "compile time might increase exponentially.\n\n"); 2881 return false; 2882 } 2883 2884 bool Scop::buildAliasGroups(AliasAnalysis &AA) { 2885 // To create sound alias checks we perform the following steps: 2886 // o) Use the alias analysis and an alias set tracker to build alias sets 2887 // for all memory accesses inside the SCoP. 2888 // o) For each alias set we then map the aliasing pointers back to the 2889 // memory accesses we know, thus obtain groups of memory accesses which 2890 // might alias. 2891 // o) We divide each group based on the domains of the minimal/maximal 2892 // accesses. That means two minimal/maximal accesses are only in a group 2893 // if their access domains intersect, otherwise they are in different 2894 // ones. 2895 // o) We partition each group into read only and non read only accesses. 2896 // o) For each group with more than one base pointer we then compute minimal 2897 // and maximal accesses to each array of a group in read only and non 2898 // read only partitions separately. 2899 using AliasGroupTy = SmallVector<MemoryAccess *, 4>; 2900 2901 AliasSetTracker AST(AA); 2902 2903 DenseMap<Value *, MemoryAccess *> PtrToAcc; 2904 DenseSet<Value *> HasWriteAccess; 2905 for (ScopStmt &Stmt : *this) { 2906 2907 // Skip statements with an empty domain as they will never be executed. 2908 isl_set *StmtDomain = Stmt.getDomain(); 2909 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain); 2910 isl_set_free(StmtDomain); 2911 if (StmtDomainEmpty) 2912 continue; 2913 2914 for (MemoryAccess *MA : Stmt) { 2915 if (MA->isScalarKind()) 2916 continue; 2917 if (!MA->isRead()) 2918 HasWriteAccess.insert(MA->getBaseAddr()); 2919 MemAccInst Acc(MA->getAccessInstruction()); 2920 if (MA->isRead() && isa<MemTransferInst>(Acc)) 2921 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA; 2922 else 2923 PtrToAcc[Acc.getPointerOperand()] = MA; 2924 AST.add(Acc); 2925 } 2926 } 2927 2928 SmallVector<AliasGroupTy, 4> AliasGroups; 2929 for (AliasSet &AS : AST) { 2930 if (AS.isMustAlias() || AS.isForwardingAliasSet()) 2931 continue; 2932 AliasGroupTy AG; 2933 for (auto &PR : AS) 2934 AG.push_back(PtrToAcc[PR.getValue()]); 2935 if (AG.size() < 2) 2936 continue; 2937 AliasGroups.push_back(std::move(AG)); 2938 } 2939 2940 // Split the alias groups based on their domain. 2941 for (unsigned u = 0; u < AliasGroups.size(); u++) { 2942 AliasGroupTy NewAG; 2943 AliasGroupTy &AG = AliasGroups[u]; 2944 AliasGroupTy::iterator AGI = AG.begin(); 2945 isl_set *AGDomain = getAccessDomain(*AGI); 2946 while (AGI != AG.end()) { 2947 MemoryAccess *MA = *AGI; 2948 isl_set *MADomain = getAccessDomain(MA); 2949 if (isl_set_is_disjoint(AGDomain, MADomain)) { 2950 NewAG.push_back(MA); 2951 AGI = AG.erase(AGI); 2952 isl_set_free(MADomain); 2953 } else { 2954 AGDomain = isl_set_union(AGDomain, MADomain); 2955 AGI++; 2956 } 2957 } 2958 if (NewAG.size() > 1) 2959 AliasGroups.push_back(std::move(NewAG)); 2960 isl_set_free(AGDomain); 2961 } 2962 2963 auto &F = getFunction(); 2964 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs; 2965 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues; 2966 for (AliasGroupTy &AG : AliasGroups) { 2967 NonReadOnlyBaseValues.clear(); 2968 ReadOnlyPairs.clear(); 2969 2970 if (AG.size() < 2) { 2971 AG.clear(); 2972 continue; 2973 } 2974 2975 for (auto II = AG.begin(); II != AG.end();) { 2976 emitOptimizationRemarkAnalysis( 2977 F.getContext(), DEBUG_TYPE, F, 2978 (*II)->getAccessInstruction()->getDebugLoc(), 2979 "Possibly aliasing pointer, use restrict keyword."); 2980 2981 Value *BaseAddr = (*II)->getBaseAddr(); 2982 if (HasWriteAccess.count(BaseAddr)) { 2983 NonReadOnlyBaseValues.insert(BaseAddr); 2984 II++; 2985 } else { 2986 ReadOnlyPairs[BaseAddr].insert(*II); 2987 II = AG.erase(II); 2988 } 2989 } 2990 2991 // If we don't have read only pointers check if there are at least two 2992 // non read only pointers, otherwise clear the alias group. 2993 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) { 2994 AG.clear(); 2995 continue; 2996 } 2997 2998 // If we don't have non read only pointers clear the alias group. 2999 if (NonReadOnlyBaseValues.empty()) { 3000 AG.clear(); 3001 continue; 3002 } 3003 3004 // Check if we have non-affine accesses left, if so bail out as we cannot 3005 // generate a good access range yet. 3006 for (auto *MA : AG) { 3007 if (!MA->isAffine()) { 3008 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc()); 3009 return false; 3010 } 3011 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) 3012 addRequiredInvariantLoad( 3013 cast<LoadInst>(BasePtrMA->getAccessInstruction())); 3014 } 3015 for (auto &ReadOnlyPair : ReadOnlyPairs) 3016 for (auto *MA : ReadOnlyPair.second) { 3017 if (!MA->isAffine()) { 3018 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc()); 3019 return false; 3020 } 3021 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) 3022 addRequiredInvariantLoad( 3023 cast<LoadInst>(BasePtrMA->getAccessInstruction())); 3024 } 3025 3026 // Calculate minimal and maximal accesses for non read only accesses. 3027 MinMaxAliasGroups.emplace_back(); 3028 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back(); 3029 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first; 3030 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second; 3031 MinMaxAccessesNonReadOnly.reserve(AG.size()); 3032 3033 isl_union_map *Accesses = isl_union_map_empty(getParamSpace()); 3034 3035 // AG contains only non read only accesses. 3036 for (MemoryAccess *MA : AG) 3037 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation()); 3038 3039 bool Valid = calculateMinMaxAccess(Accesses, getDomains(), 3040 MinMaxAccessesNonReadOnly); 3041 3042 // Bail out if the number of values we need to compare is too large. 3043 // This is important as the number of comparisions grows quadratically with 3044 // the number of values we need to compare. 3045 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() > 3046 RunTimeChecksMaxArraysPerGroup)) 3047 return false; 3048 3049 // Calculate minimal and maximal accesses for read only accesses. 3050 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size()); 3051 Accesses = isl_union_map_empty(getParamSpace()); 3052 3053 for (const auto &ReadOnlyPair : ReadOnlyPairs) 3054 for (MemoryAccess *MA : ReadOnlyPair.second) 3055 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation()); 3056 3057 Valid = 3058 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly); 3059 3060 if (!Valid) 3061 return false; 3062 } 3063 3064 return true; 3065 } 3066 3067 /// Get the smallest loop that contains @p S but is not in @p S. 3068 static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) { 3069 // Start with the smallest loop containing the entry and expand that 3070 // loop until it contains all blocks in the region. If there is a loop 3071 // containing all blocks in the region check if it is itself contained 3072 // and if so take the parent loop as it will be the smallest containing 3073 // the region but not contained by it. 3074 Loop *L = LI.getLoopFor(S.getEntry()); 3075 while (L) { 3076 bool AllContained = true; 3077 for (auto *BB : S.blocks()) 3078 AllContained &= L->contains(BB); 3079 if (AllContained) 3080 break; 3081 L = L->getParentLoop(); 3082 } 3083 3084 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr; 3085 } 3086 3087 Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI, 3088 ScopDetection::DetectionContext &DC) 3089 : SE(&ScalarEvolution), R(R), IsOptimized(false), 3090 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false), 3091 MaxLoopDepth(0), CopyStmtsNum(0), DC(DC), 3092 IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr), 3093 Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr), 3094 Schedule(nullptr) { 3095 if (IslOnErrorAbort) 3096 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT); 3097 buildContext(); 3098 } 3099 3100 void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT, 3101 LoopInfo &LI) { 3102 buildInvariantEquivalenceClasses(); 3103 3104 if (!buildDomains(&R, DT, LI)) 3105 return; 3106 3107 addUserAssumptions(AC, DT, LI); 3108 3109 // Remove empty statements. 3110 // Exit early in case there are no executable statements left in this scop. 3111 simplifySCoP(false); 3112 if (Stmts.empty()) 3113 return; 3114 3115 // The ScopStmts now have enough information to initialize themselves. 3116 for (ScopStmt &Stmt : Stmts) 3117 Stmt.init(LI); 3118 3119 // Check early for profitability. Afterwards it cannot change anymore, 3120 // only the runtime context could become infeasible. 3121 if (!isProfitable()) { 3122 invalidate(PROFITABLE, DebugLoc()); 3123 return; 3124 } 3125 3126 buildSchedule(LI); 3127 3128 updateAccessDimensionality(); 3129 realignParams(); 3130 addUserContext(); 3131 3132 // After the context was fully constructed, thus all our knowledge about 3133 // the parameters is in there, we add all recorded assumptions to the 3134 // assumed/invalid context. 3135 addRecordedAssumptions(); 3136 3137 simplifyContexts(); 3138 if (!buildAliasChecks(AA)) 3139 return; 3140 3141 hoistInvariantLoads(); 3142 verifyInvariantLoads(); 3143 simplifySCoP(true); 3144 3145 // Check late for a feasible runtime context because profitability did not 3146 // change. 3147 if (!hasFeasibleRuntimeContext()) { 3148 invalidate(PROFITABLE, DebugLoc()); 3149 return; 3150 } 3151 } 3152 3153 Scop::~Scop() { 3154 isl_set_free(Context); 3155 isl_set_free(AssumedContext); 3156 isl_set_free(InvalidContext); 3157 isl_schedule_free(Schedule); 3158 3159 for (auto &It : ParameterIds) 3160 isl_id_free(It.second); 3161 3162 for (auto It : DomainMap) 3163 isl_set_free(It.second); 3164 3165 for (auto &AS : RecordedAssumptions) 3166 isl_set_free(AS.Set); 3167 3168 // Free the alias groups 3169 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) { 3170 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) { 3171 isl_pw_multi_aff_free(MMA.first); 3172 isl_pw_multi_aff_free(MMA.second); 3173 } 3174 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) { 3175 isl_pw_multi_aff_free(MMA.first); 3176 isl_pw_multi_aff_free(MMA.second); 3177 } 3178 } 3179 3180 for (const auto &IAClass : InvariantEquivClasses) 3181 isl_set_free(IAClass.ExecutionContext); 3182 3183 // Explicitly release all Scop objects and the underlying isl objects before 3184 // we relase the isl context. 3185 Stmts.clear(); 3186 ScopArrayInfoSet.clear(); 3187 ScopArrayInfoMap.clear(); 3188 ScopArrayNameMap.clear(); 3189 AccessFunctions.clear(); 3190 } 3191 3192 void Scop::updateAccessDimensionality() { 3193 // Check all array accesses for each base pointer and find a (virtual) element 3194 // size for the base pointer that divides all access functions. 3195 for (auto &Stmt : *this) 3196 for (auto *Access : Stmt) { 3197 if (!Access->isArrayKind()) 3198 continue; 3199 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(), 3200 ScopArrayInfo::MK_Array)]; 3201 if (SAI->getNumberOfDimensions() != 1) 3202 continue; 3203 unsigned DivisibleSize = SAI->getElemSizeInBytes(); 3204 auto *Subscript = Access->getSubscript(0); 3205 while (!isDivisible(Subscript, DivisibleSize, *SE)) 3206 DivisibleSize /= 2; 3207 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8); 3208 SAI->updateElementType(Ty); 3209 } 3210 3211 for (auto &Stmt : *this) 3212 for (auto &Access : Stmt) 3213 Access->updateDimensionality(); 3214 } 3215 3216 void Scop::simplifySCoP(bool AfterHoisting) { 3217 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) { 3218 ScopStmt &Stmt = *StmtIt; 3219 3220 bool RemoveStmt = Stmt.isEmpty(); 3221 if (!RemoveStmt) 3222 RemoveStmt = !DomainMap[Stmt.getEntryBlock()]; 3223 3224 // Remove read only statements only after invariant loop hoisting. 3225 if (!RemoveStmt && AfterHoisting) { 3226 bool OnlyRead = true; 3227 for (MemoryAccess *MA : Stmt) { 3228 if (MA->isRead()) 3229 continue; 3230 3231 OnlyRead = false; 3232 break; 3233 } 3234 3235 RemoveStmt = OnlyRead; 3236 } 3237 3238 if (!RemoveStmt) { 3239 StmtIt++; 3240 continue; 3241 } 3242 3243 // Remove the statement because it is unnecessary. 3244 if (Stmt.isRegionStmt()) 3245 for (BasicBlock *BB : Stmt.getRegion()->blocks()) 3246 StmtMap.erase(BB); 3247 else 3248 StmtMap.erase(Stmt.getBasicBlock()); 3249 3250 StmtIt = Stmts.erase(StmtIt); 3251 } 3252 } 3253 3254 InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) { 3255 LoadInst *LInst = dyn_cast<LoadInst>(Val); 3256 if (!LInst) 3257 return nullptr; 3258 3259 if (Value *Rep = InvEquivClassVMap.lookup(LInst)) 3260 LInst = cast<LoadInst>(Rep); 3261 3262 Type *Ty = LInst->getType(); 3263 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand()); 3264 for (auto &IAClass : InvariantEquivClasses) { 3265 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType) 3266 continue; 3267 3268 auto &MAs = IAClass.InvariantAccesses; 3269 for (auto *MA : MAs) 3270 if (MA->getAccessInstruction() == Val) 3271 return &IAClass; 3272 } 3273 3274 return nullptr; 3275 } 3276 3277 /// Check if @p MA can always be hoisted without execution context. 3278 static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty, 3279 bool MAInvalidCtxIsEmpty, 3280 bool NonHoistableCtxIsEmpty) { 3281 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction()); 3282 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout(); 3283 // TODO: We can provide more information for better but more expensive 3284 // results. 3285 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(), 3286 LInst->getAlignment(), DL)) 3287 return false; 3288 3289 // If the location might be overwritten we do not hoist it unconditionally. 3290 // 3291 // TODO: This is probably to conservative. 3292 if (!NonHoistableCtxIsEmpty) 3293 return false; 3294 3295 // If a dereferencable load is in a statement that is modeled precisely we can 3296 // hoist it. 3297 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty) 3298 return true; 3299 3300 // Even if the statement is not modeled precisely we can hoist the load if it 3301 // does not involve any parameters that might have been specilized by the 3302 // statement domain. 3303 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++) 3304 if (!isa<SCEVConstant>(MA->getSubscript(u))) 3305 return false; 3306 return true; 3307 } 3308 3309 void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) { 3310 3311 if (InvMAs.empty()) 3312 return; 3313 3314 auto *StmtInvalidCtx = Stmt.getInvalidContext(); 3315 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx); 3316 3317 // Get the context under which the statement is executed but remove the error 3318 // context under which this statement is reached. 3319 isl_set *DomainCtx = isl_set_params(Stmt.getDomain()); 3320 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx); 3321 3322 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) { 3323 auto *AccInst = InvMAs.front().MA->getAccessInstruction(); 3324 invalidate(COMPLEXITY, AccInst->getDebugLoc()); 3325 isl_set_free(DomainCtx); 3326 for (auto &InvMA : InvMAs) 3327 isl_set_free(InvMA.NonHoistableCtx); 3328 return; 3329 } 3330 3331 // Project out all parameters that relate to loads in the statement. Otherwise 3332 // we could have cyclic dependences on the constraints under which the 3333 // hoisted loads are executed and we could not determine an order in which to 3334 // pre-load them. This happens because not only lower bounds are part of the 3335 // domain but also upper bounds. 3336 for (auto &InvMA : InvMAs) { 3337 auto *MA = InvMA.MA; 3338 Instruction *AccInst = MA->getAccessInstruction(); 3339 if (SE->isSCEVable(AccInst->getType())) { 3340 SetVector<Value *> Values; 3341 for (const SCEV *Parameter : Parameters) { 3342 Values.clear(); 3343 findValues(Parameter, *SE, Values); 3344 if (!Values.count(AccInst)) 3345 continue; 3346 3347 if (isl_id *ParamId = getIdForParam(Parameter)) { 3348 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId); 3349 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1); 3350 isl_id_free(ParamId); 3351 } 3352 } 3353 } 3354 } 3355 3356 for (auto &InvMA : InvMAs) { 3357 auto *MA = InvMA.MA; 3358 auto *NHCtx = InvMA.NonHoistableCtx; 3359 3360 // Check for another invariant access that accesses the same location as 3361 // MA and if found consolidate them. Otherwise create a new equivalence 3362 // class at the end of InvariantEquivClasses. 3363 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction()); 3364 Type *Ty = LInst->getType(); 3365 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand()); 3366 3367 auto *MAInvalidCtx = MA->getInvalidContext(); 3368 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx); 3369 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx); 3370 3371 isl_set *MACtx; 3372 // Check if we know that this pointer can be speculatively accessed. 3373 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty, 3374 NonHoistableCtxIsEmpty)) { 3375 MACtx = isl_set_universe(isl_set_get_space(DomainCtx)); 3376 isl_set_free(MAInvalidCtx); 3377 isl_set_free(NHCtx); 3378 } else { 3379 MACtx = isl_set_copy(DomainCtx); 3380 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx)); 3381 MACtx = isl_set_gist_params(MACtx, getContext()); 3382 } 3383 3384 bool Consolidated = false; 3385 for (auto &IAClass : InvariantEquivClasses) { 3386 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType) 3387 continue; 3388 3389 // If the pointer and the type is equal check if the access function wrt. 3390 // to the domain is equal too. It can happen that the domain fixes 3391 // parameter values and these can be different for distinct part of the 3392 // SCoP. If this happens we cannot consolidate the loads but need to 3393 // create a new invariant load equivalence class. 3394 auto &MAs = IAClass.InvariantAccesses; 3395 if (!MAs.empty()) { 3396 auto *LastMA = MAs.front(); 3397 3398 auto *AR = isl_map_range(MA->getAccessRelation()); 3399 auto *LastAR = isl_map_range(LastMA->getAccessRelation()); 3400 bool SameAR = isl_set_is_equal(AR, LastAR); 3401 isl_set_free(AR); 3402 isl_set_free(LastAR); 3403 3404 if (!SameAR) 3405 continue; 3406 } 3407 3408 // Add MA to the list of accesses that are in this class. 3409 MAs.push_front(MA); 3410 3411 Consolidated = true; 3412 3413 // Unify the execution context of the class and this statement. 3414 isl_set *&IAClassDomainCtx = IAClass.ExecutionContext; 3415 if (IAClassDomainCtx) 3416 IAClassDomainCtx = 3417 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx)); 3418 else 3419 IAClassDomainCtx = MACtx; 3420 break; 3421 } 3422 3423 if (Consolidated) 3424 continue; 3425 3426 // If we did not consolidate MA, thus did not find an equivalence class 3427 // for it, we create a new one. 3428 InvariantEquivClasses.emplace_back( 3429 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty}); 3430 } 3431 3432 isl_set_free(DomainCtx); 3433 } 3434 3435 __isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access, 3436 __isl_keep isl_union_map *Writes) { 3437 // TODO: Loads that are not loop carried, hence are in a statement with 3438 // zero iterators, are by construction invariant, though we 3439 // currently "hoist" them anyway. This is necessary because we allow 3440 // them to be treated as parameters (e.g., in conditions) and our code 3441 // generation would otherwise use the old value. 3442 3443 auto &Stmt = *Access->getStatement(); 3444 BasicBlock *BB = Stmt.getEntryBlock(); 3445 3446 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine()) 3447 return nullptr; 3448 3449 // Skip accesses that have an invariant base pointer which is defined but 3450 // not loaded inside the SCoP. This can happened e.g., if a readnone call 3451 // returns a pointer that is used as a base address. However, as we want 3452 // to hoist indirect pointers, we allow the base pointer to be defined in 3453 // the region if it is also a memory access. Each ScopArrayInfo object 3454 // that has a base pointer origin has a base pointer that is loaded and 3455 // that it is invariant, thus it will be hoisted too. However, if there is 3456 // no base pointer origin we check that the base pointer is defined 3457 // outside the region. 3458 auto *LI = cast<LoadInst>(Access->getAccessInstruction()); 3459 if (hasNonHoistableBasePtrInScop(Access, Writes)) 3460 return nullptr; 3461 3462 // Skip accesses in non-affine subregions as they might not be executed 3463 // under the same condition as the entry of the non-affine subregion. 3464 if (BB != LI->getParent()) 3465 return nullptr; 3466 3467 isl_map *AccessRelation = Access->getAccessRelation(); 3468 assert(!isl_map_is_empty(AccessRelation)); 3469 3470 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0, 3471 Stmt.getNumIterators())) { 3472 isl_map_free(AccessRelation); 3473 return nullptr; 3474 } 3475 3476 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain()); 3477 isl_set *AccessRange = isl_map_range(AccessRelation); 3478 3479 isl_union_map *Written = isl_union_map_intersect_range( 3480 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange)); 3481 auto *WrittenCtx = isl_union_map_params(Written); 3482 bool IsWritten = !isl_set_is_empty(WrittenCtx); 3483 3484 if (!IsWritten) 3485 return WrittenCtx; 3486 3487 WrittenCtx = isl_set_remove_divs(WrittenCtx); 3488 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain; 3489 if (TooComplex || !isRequiredInvariantLoad(LI)) { 3490 isl_set_free(WrittenCtx); 3491 return nullptr; 3492 } 3493 3494 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(), 3495 AS_RESTRICTION); 3496 return WrittenCtx; 3497 } 3498 3499 void Scop::verifyInvariantLoads() { 3500 auto &RIL = getRequiredInvariantLoads(); 3501 for (LoadInst *LI : RIL) { 3502 assert(LI && contains(LI)); 3503 ScopStmt *Stmt = getStmtFor(LI); 3504 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) { 3505 invalidate(INVARIANTLOAD, LI->getDebugLoc()); 3506 return; 3507 } 3508 } 3509 } 3510 3511 void Scop::hoistInvariantLoads() { 3512 if (!PollyInvariantLoadHoisting) 3513 return; 3514 3515 isl_union_map *Writes = getWrites(); 3516 for (ScopStmt &Stmt : *this) { 3517 InvariantAccessesTy InvariantAccesses; 3518 3519 for (MemoryAccess *Access : Stmt) 3520 if (auto *NHCtx = getNonHoistableCtx(Access, Writes)) 3521 InvariantAccesses.push_back({Access, NHCtx}); 3522 3523 // Transfer the memory access from the statement to the SCoP. 3524 for (auto InvMA : InvariantAccesses) 3525 Stmt.removeMemoryAccess(InvMA.MA); 3526 addInvariantLoads(Stmt, InvariantAccesses); 3527 } 3528 isl_union_map_free(Writes); 3529 } 3530 3531 const ScopArrayInfo *Scop::getOrCreateScopArrayInfo( 3532 Value *BasePtr, Type *ElementType, ArrayRef<const SCEV *> Sizes, 3533 ScopArrayInfo::MemoryKind Kind, const char *BaseName) { 3534 assert((BasePtr || BaseName) && 3535 "BasePtr and BaseName can not be nullptr at the same time."); 3536 assert(!(BasePtr && BaseName) && "BaseName is redundant."); 3537 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)] 3538 : ScopArrayNameMap[BaseName]; 3539 if (!SAI) { 3540 auto &DL = getFunction().getParent()->getDataLayout(); 3541 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind, 3542 DL, this, BaseName)); 3543 ScopArrayInfoSet.insert(SAI.get()); 3544 } else { 3545 SAI->updateElementType(ElementType); 3546 // In case of mismatching array sizes, we bail out by setting the run-time 3547 // context to false. 3548 if (!SAI->updateSizes(Sizes)) 3549 invalidate(DELINEARIZATION, DebugLoc()); 3550 } 3551 return SAI.get(); 3552 } 3553 3554 const ScopArrayInfo * 3555 Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName, 3556 const std::vector<unsigned> &Sizes) { 3557 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext()); 3558 std::vector<const SCEV *> SCEVSizes; 3559 3560 for (auto size : Sizes) 3561 if (size) 3562 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false)); 3563 else 3564 SCEVSizes.push_back(nullptr); 3565 3566 auto *SAI = 3567 getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes, 3568 ScopArrayInfo::MK_Array, BaseName.c_str()); 3569 return SAI; 3570 } 3571 3572 const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, 3573 ScopArrayInfo::MemoryKind Kind) { 3574 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get(); 3575 assert(SAI && "No ScopArrayInfo available for this base pointer"); 3576 return SAI; 3577 } 3578 3579 std::string Scop::getContextStr() const { return stringFromIslObj(Context); } 3580 3581 std::string Scop::getAssumedContextStr() const { 3582 assert(AssumedContext && "Assumed context not yet built"); 3583 return stringFromIslObj(AssumedContext); 3584 } 3585 3586 std::string Scop::getInvalidContextStr() const { 3587 return stringFromIslObj(InvalidContext); 3588 } 3589 3590 std::string Scop::getNameStr() const { 3591 std::string ExitName, EntryName; 3592 raw_string_ostream ExitStr(ExitName); 3593 raw_string_ostream EntryStr(EntryName); 3594 3595 R.getEntry()->printAsOperand(EntryStr, false); 3596 EntryStr.str(); 3597 3598 if (R.getExit()) { 3599 R.getExit()->printAsOperand(ExitStr, false); 3600 ExitStr.str(); 3601 } else 3602 ExitName = "FunctionExit"; 3603 3604 return EntryName + "---" + ExitName; 3605 } 3606 3607 __isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); } 3608 __isl_give isl_space *Scop::getParamSpace() const { 3609 return isl_set_get_space(Context); 3610 } 3611 3612 __isl_give isl_set *Scop::getAssumedContext() const { 3613 assert(AssumedContext && "Assumed context not yet built"); 3614 return isl_set_copy(AssumedContext); 3615 } 3616 3617 bool Scop::isProfitable() const { 3618 if (PollyProcessUnprofitable) 3619 return true; 3620 3621 if (!hasFeasibleRuntimeContext()) 3622 return false; 3623 3624 if (isEmpty()) 3625 return false; 3626 3627 unsigned OptimizableStmtsOrLoops = 0; 3628 for (auto &Stmt : *this) { 3629 if (Stmt.getNumIterators() == 0) 3630 continue; 3631 3632 bool ContainsArrayAccs = false; 3633 bool ContainsScalarAccs = false; 3634 for (auto *MA : Stmt) { 3635 if (MA->isRead()) 3636 continue; 3637 ContainsArrayAccs |= MA->isArrayKind(); 3638 ContainsScalarAccs |= MA->isScalarKind(); 3639 } 3640 3641 if (ContainsArrayAccs && !ContainsScalarAccs) 3642 OptimizableStmtsOrLoops += Stmt.getNumIterators(); 3643 } 3644 3645 return OptimizableStmtsOrLoops > 1; 3646 } 3647 3648 bool Scop::hasFeasibleRuntimeContext() const { 3649 auto *PositiveContext = getAssumedContext(); 3650 auto *NegativeContext = getInvalidContext(); 3651 PositiveContext = addNonEmptyDomainConstraints(PositiveContext); 3652 bool IsFeasible = !(isl_set_is_empty(PositiveContext) || 3653 isl_set_is_subset(PositiveContext, NegativeContext)); 3654 isl_set_free(PositiveContext); 3655 if (!IsFeasible) { 3656 isl_set_free(NegativeContext); 3657 return false; 3658 } 3659 3660 auto *DomainContext = isl_union_set_params(getDomains()); 3661 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext); 3662 IsFeasible &= !isl_set_is_subset(Context, NegativeContext); 3663 isl_set_free(NegativeContext); 3664 isl_set_free(DomainContext); 3665 3666 return IsFeasible; 3667 } 3668 3669 static std::string toString(AssumptionKind Kind) { 3670 switch (Kind) { 3671 case ALIASING: 3672 return "No-aliasing"; 3673 case INBOUNDS: 3674 return "Inbounds"; 3675 case WRAPPING: 3676 return "No-overflows"; 3677 case UNSIGNED: 3678 return "Signed-unsigned"; 3679 case COMPLEXITY: 3680 return "Low complexity"; 3681 case PROFITABLE: 3682 return "Profitable"; 3683 case ERRORBLOCK: 3684 return "No-error"; 3685 case INFINITELOOP: 3686 return "Finite loop"; 3687 case INVARIANTLOAD: 3688 return "Invariant load"; 3689 case DELINEARIZATION: 3690 return "Delinearization"; 3691 } 3692 llvm_unreachable("Unknown AssumptionKind!"); 3693 } 3694 3695 bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) { 3696 if (Sign == AS_ASSUMPTION) { 3697 if (isl_set_is_subset(Context, Set)) 3698 return false; 3699 3700 if (isl_set_is_subset(AssumedContext, Set)) 3701 return false; 3702 } else { 3703 if (isl_set_is_disjoint(Set, Context)) 3704 return false; 3705 3706 if (isl_set_is_subset(Set, InvalidContext)) 3707 return false; 3708 } 3709 return true; 3710 } 3711 3712 bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set, 3713 DebugLoc Loc, AssumptionSign Sign) { 3714 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign)) 3715 return false; 3716 3717 auto &F = getFunction(); 3718 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t"; 3719 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set); 3720 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg); 3721 return true; 3722 } 3723 3724 void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set, 3725 DebugLoc Loc, AssumptionSign Sign) { 3726 // Simplify the assumptions/restrictions first. 3727 Set = isl_set_gist_params(Set, getContext()); 3728 3729 if (!trackAssumption(Kind, Set, Loc, Sign)) { 3730 isl_set_free(Set); 3731 return; 3732 } 3733 3734 if (Sign == AS_ASSUMPTION) { 3735 AssumedContext = isl_set_intersect(AssumedContext, Set); 3736 AssumedContext = isl_set_coalesce(AssumedContext); 3737 } else { 3738 InvalidContext = isl_set_union(InvalidContext, Set); 3739 InvalidContext = isl_set_coalesce(InvalidContext); 3740 } 3741 } 3742 3743 void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set, 3744 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) { 3745 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB}); 3746 } 3747 3748 void Scop::addRecordedAssumptions() { 3749 while (!RecordedAssumptions.empty()) { 3750 const Assumption &AS = RecordedAssumptions.pop_back_val(); 3751 3752 if (!AS.BB) { 3753 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign); 3754 continue; 3755 } 3756 3757 // If the domain was deleted the assumptions are void. 3758 isl_set *Dom = getDomainConditions(AS.BB); 3759 if (!Dom) { 3760 isl_set_free(AS.Set); 3761 continue; 3762 } 3763 3764 // If a basic block was given use its domain to simplify the assumption. 3765 // In case of restrictions we know they only have to hold on the domain, 3766 // thus we can intersect them with the domain of the block. However, for 3767 // assumptions the domain has to imply them, thus: 3768 // _ _____ 3769 // Dom => S <==> A v B <==> A - B 3770 // 3771 // To avoid the complement we will register A - B as a restricton not an 3772 // assumption. 3773 isl_set *S = AS.Set; 3774 if (AS.Sign == AS_RESTRICTION) 3775 S = isl_set_params(isl_set_intersect(S, Dom)); 3776 else /* (AS.Sign == AS_ASSUMPTION) */ 3777 S = isl_set_params(isl_set_subtract(Dom, S)); 3778 3779 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION); 3780 } 3781 } 3782 3783 void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) { 3784 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION); 3785 } 3786 3787 __isl_give isl_set *Scop::getInvalidContext() const { 3788 return isl_set_copy(InvalidContext); 3789 } 3790 3791 void Scop::printContext(raw_ostream &OS) const { 3792 OS << "Context:\n"; 3793 OS.indent(4) << Context << "\n"; 3794 3795 OS.indent(4) << "Assumed Context:\n"; 3796 OS.indent(4) << AssumedContext << "\n"; 3797 3798 OS.indent(4) << "Invalid Context:\n"; 3799 OS.indent(4) << InvalidContext << "\n"; 3800 3801 unsigned Dim = 0; 3802 for (const SCEV *Parameter : Parameters) 3803 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n"; 3804 } 3805 3806 void Scop::printAliasAssumptions(raw_ostream &OS) const { 3807 int noOfGroups = 0; 3808 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) { 3809 if (Pair.second.size() == 0) 3810 noOfGroups += 1; 3811 else 3812 noOfGroups += Pair.second.size(); 3813 } 3814 3815 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n"; 3816 if (MinMaxAliasGroups.empty()) { 3817 OS.indent(8) << "n/a\n"; 3818 return; 3819 } 3820 3821 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) { 3822 3823 // If the group has no read only accesses print the write accesses. 3824 if (Pair.second.empty()) { 3825 OS.indent(8) << "[["; 3826 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) { 3827 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second 3828 << ">"; 3829 } 3830 OS << " ]]\n"; 3831 } 3832 3833 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) { 3834 OS.indent(8) << "[["; 3835 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">"; 3836 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) { 3837 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second 3838 << ">"; 3839 } 3840 OS << " ]]\n"; 3841 } 3842 } 3843 } 3844 3845 void Scop::printStatements(raw_ostream &OS) const { 3846 OS << "Statements {\n"; 3847 3848 for (const ScopStmt &Stmt : *this) 3849 OS.indent(4) << Stmt; 3850 3851 OS.indent(4) << "}\n"; 3852 } 3853 3854 void Scop::printArrayInfo(raw_ostream &OS) const { 3855 OS << "Arrays {\n"; 3856 3857 for (auto &Array : arrays()) 3858 Array->print(OS); 3859 3860 OS.indent(4) << "}\n"; 3861 3862 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n"; 3863 3864 for (auto &Array : arrays()) 3865 Array->print(OS, /* SizeAsPwAff */ true); 3866 3867 OS.indent(4) << "}\n"; 3868 } 3869 3870 void Scop::print(raw_ostream &OS) const { 3871 OS.indent(4) << "Function: " << getFunction().getName() << "\n"; 3872 OS.indent(4) << "Region: " << getNameStr() << "\n"; 3873 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n"; 3874 OS.indent(4) << "Invariant Accesses: {\n"; 3875 for (const auto &IAClass : InvariantEquivClasses) { 3876 const auto &MAs = IAClass.InvariantAccesses; 3877 if (MAs.empty()) { 3878 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n"; 3879 } else { 3880 MAs.front()->print(OS); 3881 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext 3882 << "\n"; 3883 } 3884 } 3885 OS.indent(4) << "}\n"; 3886 printContext(OS.indent(4)); 3887 printArrayInfo(OS.indent(4)); 3888 printAliasAssumptions(OS); 3889 printStatements(OS.indent(4)); 3890 } 3891 3892 void Scop::dump() const { print(dbgs()); } 3893 3894 isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); } 3895 3896 __isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB, 3897 bool NonNegative) { 3898 // First try to use the SCEVAffinator to generate a piecewise defined 3899 // affine function from @p E in the context of @p BB. If that tasks becomes to 3900 // complex the affinator might return a nullptr. In such a case we invalidate 3901 // the SCoP and return a dummy value. This way we do not need to add error 3902 // handling cdoe to all users of this function. 3903 auto PWAC = Affinator.getPwAff(E, BB); 3904 if (PWAC.first) { 3905 // TODO: We could use a heuristic and either use: 3906 // SCEVAffinator::takeNonNegativeAssumption 3907 // or 3908 // SCEVAffinator::interpretAsUnsigned 3909 // to deal with unsigned or "NonNegative" SCEVs. 3910 if (NonNegative) 3911 Affinator.takeNonNegativeAssumption(PWAC); 3912 return PWAC; 3913 } 3914 3915 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc(); 3916 invalidate(COMPLEXITY, DL); 3917 return Affinator.getPwAff(SE->getZero(E->getType()), BB); 3918 } 3919 3920 __isl_give isl_union_set *Scop::getDomains() const { 3921 isl_union_set *Domain = isl_union_set_empty(getParamSpace()); 3922 3923 for (const ScopStmt &Stmt : *this) 3924 Domain = isl_union_set_add_set(Domain, Stmt.getDomain()); 3925 3926 return Domain; 3927 } 3928 3929 __isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) { 3930 PWACtx PWAC = getPwAff(E, BB); 3931 isl_set_free(PWAC.second); 3932 return PWAC.first; 3933 } 3934 3935 __isl_give isl_union_map * 3936 Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) { 3937 isl_union_map *Accesses = isl_union_map_empty(getParamSpace()); 3938 3939 for (ScopStmt &Stmt : *this) { 3940 for (MemoryAccess *MA : Stmt) { 3941 if (!Predicate(*MA)) 3942 continue; 3943 3944 isl_set *Domain = Stmt.getDomain(); 3945 isl_map *AccessDomain = MA->getAccessRelation(); 3946 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain); 3947 Accesses = isl_union_map_add_map(Accesses, AccessDomain); 3948 } 3949 } 3950 return isl_union_map_coalesce(Accesses); 3951 } 3952 3953 __isl_give isl_union_map *Scop::getMustWrites() { 3954 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); }); 3955 } 3956 3957 __isl_give isl_union_map *Scop::getMayWrites() { 3958 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); }); 3959 } 3960 3961 __isl_give isl_union_map *Scop::getWrites() { 3962 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); }); 3963 } 3964 3965 __isl_give isl_union_map *Scop::getReads() { 3966 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); }); 3967 } 3968 3969 __isl_give isl_union_map *Scop::getAccesses() { 3970 return getAccessesOfType([](MemoryAccess &MA) { return true; }); 3971 } 3972 3973 // Check whether @p Node is an extension node. 3974 // 3975 // @return true if @p Node is an extension node. 3976 isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) { 3977 if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension) 3978 return isl_bool_error; 3979 else 3980 return isl_bool_true; 3981 } 3982 3983 bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) { 3984 return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode, 3985 nullptr) == isl_stat_error; 3986 } 3987 3988 __isl_give isl_union_map *Scop::getSchedule() const { 3989 auto *Tree = getScheduleTree(); 3990 if (containsExtensionNode(Tree)) { 3991 isl_schedule_free(Tree); 3992 return nullptr; 3993 } 3994 auto *S = isl_schedule_get_map(Tree); 3995 isl_schedule_free(Tree); 3996 return S; 3997 } 3998 3999 __isl_give isl_schedule *Scop::getScheduleTree() const { 4000 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule), 4001 getDomains()); 4002 } 4003 4004 void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) { 4005 auto *S = isl_schedule_from_domain(getDomains()); 4006 S = isl_schedule_insert_partial_schedule( 4007 S, isl_multi_union_pw_aff_from_union_map(NewSchedule)); 4008 isl_schedule_free(Schedule); 4009 Schedule = S; 4010 } 4011 4012 void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) { 4013 isl_schedule_free(Schedule); 4014 Schedule = NewSchedule; 4015 } 4016 4017 bool Scop::restrictDomains(__isl_take isl_union_set *Domain) { 4018 bool Changed = false; 4019 for (ScopStmt &Stmt : *this) { 4020 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain()); 4021 isl_union_set *NewStmtDomain = isl_union_set_intersect( 4022 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain)); 4023 4024 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) { 4025 isl_union_set_free(StmtDomain); 4026 isl_union_set_free(NewStmtDomain); 4027 continue; 4028 } 4029 4030 Changed = true; 4031 4032 isl_union_set_free(StmtDomain); 4033 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain); 4034 4035 if (isl_union_set_is_empty(NewStmtDomain)) { 4036 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace())); 4037 isl_union_set_free(NewStmtDomain); 4038 } else 4039 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain)); 4040 } 4041 isl_union_set_free(Domain); 4042 return Changed; 4043 } 4044 4045 ScalarEvolution *Scop::getSE() const { return SE; } 4046 4047 struct MapToDimensionDataTy { 4048 int N; 4049 isl_union_pw_multi_aff *Res; 4050 }; 4051 4052 // Create a function that maps the elements of 'Set' to its N-th dimension and 4053 // add it to User->Res. 4054 // 4055 // @param Set The input set. 4056 // @param User->N The dimension to map to. 4057 // @param User->Res The isl_union_pw_multi_aff to which to add the result. 4058 // 4059 // @returns isl_stat_ok if no error occured, othewise isl_stat_error. 4060 static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) { 4061 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User; 4062 int Dim; 4063 isl_space *Space; 4064 isl_pw_multi_aff *PMA; 4065 4066 Dim = isl_set_dim(Set, isl_dim_set); 4067 Space = isl_set_get_space(Set); 4068 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N, 4069 Dim - Data->N); 4070 if (Data->N > 1) 4071 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1); 4072 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA); 4073 4074 isl_set_free(Set); 4075 4076 return isl_stat_ok; 4077 } 4078 4079 // Create an isl_multi_union_aff that defines an identity mapping from the 4080 // elements of USet to their N-th dimension. 4081 // 4082 // # Example: 4083 // 4084 // Domain: { A[i,j]; B[i,j,k] } 4085 // N: 1 4086 // 4087 // Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] } 4088 // 4089 // @param USet A union set describing the elements for which to generate a 4090 // mapping. 4091 // @param N The dimension to map to. 4092 // @returns A mapping from USet to its N-th dimension. 4093 static __isl_give isl_multi_union_pw_aff * 4094 mapToDimension(__isl_take isl_union_set *USet, int N) { 4095 assert(N >= 0); 4096 assert(USet); 4097 assert(!isl_union_set_is_empty(USet)); 4098 4099 struct MapToDimensionDataTy Data; 4100 4101 auto *Space = isl_union_set_get_space(USet); 4102 auto *PwAff = isl_union_pw_multi_aff_empty(Space); 4103 4104 Data = {N, PwAff}; 4105 4106 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data); 4107 (void)Res; 4108 4109 assert(Res == isl_stat_ok); 4110 4111 isl_union_set_free(USet); 4112 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res); 4113 } 4114 4115 void Scop::addScopStmt(BasicBlock *BB, Region *R) { 4116 if (BB) { 4117 Stmts.emplace_back(*this, *BB); 4118 auto *Stmt = &Stmts.back(); 4119 StmtMap[BB] = Stmt; 4120 } else { 4121 assert(R && "Either basic block or a region expected."); 4122 Stmts.emplace_back(*this, *R); 4123 auto *Stmt = &Stmts.back(); 4124 for (BasicBlock *BB : R->blocks()) 4125 StmtMap[BB] = Stmt; 4126 } 4127 } 4128 4129 ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel, 4130 __isl_take isl_map *TargetRel, 4131 __isl_take isl_set *Domain) { 4132 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain); 4133 CopyStmtsNum++; 4134 return &(Stmts.back()); 4135 } 4136 4137 void Scop::buildSchedule(LoopInfo &LI) { 4138 Loop *L = getLoopSurroundingScop(*this, LI); 4139 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)}); 4140 buildSchedule(getRegion().getNode(), LoopStack, LI); 4141 assert(LoopStack.size() == 1 && LoopStack.back().L == L); 4142 Schedule = LoopStack[0].Schedule; 4143 } 4144 4145 /// To generate a schedule for the elements in a Region we traverse the Region 4146 /// in reverse-post-order and add the contained RegionNodes in traversal order 4147 /// to the schedule of the loop that is currently at the top of the LoopStack. 4148 /// For loop-free codes, this results in a correct sequential ordering. 4149 /// 4150 /// Example: 4151 /// bb1(0) 4152 /// / \. 4153 /// bb2(1) bb3(2) 4154 /// \ / \. 4155 /// bb4(3) bb5(4) 4156 /// \ / 4157 /// bb6(5) 4158 /// 4159 /// Including loops requires additional processing. Whenever a loop header is 4160 /// encountered, the corresponding loop is added to the @p LoopStack. Starting 4161 /// from an empty schedule, we first process all RegionNodes that are within 4162 /// this loop and complete the sequential schedule at this loop-level before 4163 /// processing about any other nodes. To implement this 4164 /// loop-nodes-first-processing, the reverse post-order traversal is 4165 /// insufficient. Hence, we additionally check if the traversal yields 4166 /// sub-regions or blocks that are outside the last loop on the @p LoopStack. 4167 /// These region-nodes are then queue and only traverse after the all nodes 4168 /// within the current loop have been processed. 4169 void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) { 4170 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI); 4171 4172 ReversePostOrderTraversal<Region *> RTraversal(R); 4173 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end()); 4174 std::deque<RegionNode *> DelayList; 4175 bool LastRNWaiting = false; 4176 4177 // Iterate over the region @p R in reverse post-order but queue 4178 // sub-regions/blocks iff they are not part of the last encountered but not 4179 // completely traversed loop. The variable LastRNWaiting is a flag to indicate 4180 // that we queued the last sub-region/block from the reverse post-order 4181 // iterator. If it is set we have to explore the next sub-region/block from 4182 // the iterator (if any) to guarantee progress. If it is not set we first try 4183 // the next queued sub-region/blocks. 4184 while (!WorkList.empty() || !DelayList.empty()) { 4185 RegionNode *RN; 4186 4187 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) { 4188 RN = WorkList.front(); 4189 WorkList.pop_front(); 4190 LastRNWaiting = false; 4191 } else { 4192 RN = DelayList.front(); 4193 DelayList.pop_front(); 4194 } 4195 4196 Loop *L = getRegionNodeLoop(RN, LI); 4197 if (!contains(L)) 4198 L = OuterScopLoop; 4199 4200 Loop *LastLoop = LoopStack.back().L; 4201 if (LastLoop != L) { 4202 if (LastLoop && !LastLoop->contains(L)) { 4203 LastRNWaiting = true; 4204 DelayList.push_back(RN); 4205 continue; 4206 } 4207 LoopStack.push_back({L, nullptr, 0}); 4208 } 4209 buildSchedule(RN, LoopStack, LI); 4210 } 4211 4212 return; 4213 } 4214 4215 void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) { 4216 4217 if (RN->isSubRegion()) { 4218 auto *LocalRegion = RN->getNodeAs<Region>(); 4219 if (!isNonAffineSubRegion(LocalRegion)) { 4220 buildSchedule(LocalRegion, LoopStack, LI); 4221 return; 4222 } 4223 } 4224 4225 auto &LoopData = LoopStack.back(); 4226 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN); 4227 4228 if (auto *Stmt = getStmtFor(RN)) { 4229 auto *UDomain = isl_union_set_from_set(Stmt->getDomain()); 4230 auto *StmtSchedule = isl_schedule_from_domain(UDomain); 4231 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule); 4232 } 4233 4234 // Check if we just processed the last node in this loop. If we did, finalize 4235 // the loop by: 4236 // 4237 // - adding new schedule dimensions 4238 // - folding the resulting schedule into the parent loop schedule 4239 // - dropping the loop schedule from the LoopStack. 4240 // 4241 // Then continue to check surrounding loops, which might also have been 4242 // completed by this node. 4243 while (LoopData.L && 4244 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) { 4245 auto *Schedule = LoopData.Schedule; 4246 auto NumBlocksProcessed = LoopData.NumBlocksProcessed; 4247 4248 LoopStack.pop_back(); 4249 auto &NextLoopData = LoopStack.back(); 4250 4251 if (Schedule) { 4252 auto *Domain = isl_schedule_get_domain(Schedule); 4253 auto *MUPA = mapToDimension(Domain, LoopStack.size()); 4254 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA); 4255 NextLoopData.Schedule = 4256 combineInSequence(NextLoopData.Schedule, Schedule); 4257 } 4258 4259 NextLoopData.NumBlocksProcessed += NumBlocksProcessed; 4260 LoopData = NextLoopData; 4261 } 4262 } 4263 4264 ScopStmt *Scop::getStmtFor(BasicBlock *BB) const { 4265 auto StmtMapIt = StmtMap.find(BB); 4266 if (StmtMapIt == StmtMap.end()) 4267 return nullptr; 4268 return StmtMapIt->second; 4269 } 4270 4271 ScopStmt *Scop::getStmtFor(RegionNode *RN) const { 4272 if (RN->isSubRegion()) 4273 return getStmtFor(RN->getNodeAs<Region>()); 4274 return getStmtFor(RN->getNodeAs<BasicBlock>()); 4275 } 4276 4277 ScopStmt *Scop::getStmtFor(Region *R) const { 4278 ScopStmt *Stmt = getStmtFor(R->getEntry()); 4279 assert(!Stmt || Stmt->getRegion() == R); 4280 return Stmt; 4281 } 4282 4283 int Scop::getRelativeLoopDepth(const Loop *L) const { 4284 Loop *OuterLoop = 4285 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr; 4286 if (!OuterLoop) 4287 return -1; 4288 return L->getLoopDepth() - OuterLoop->getLoopDepth(); 4289 } 4290 4291 ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) { 4292 for (auto &SAI : arrays()) { 4293 if (SAI->getName() == BaseName) 4294 return SAI; 4295 } 4296 return nullptr; 4297 } 4298 4299 //===----------------------------------------------------------------------===// 4300 void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const { 4301 AU.addRequired<LoopInfoWrapperPass>(); 4302 AU.addRequired<RegionInfoPass>(); 4303 AU.addRequired<DominatorTreeWrapperPass>(); 4304 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>(); 4305 AU.addRequiredTransitive<ScopDetection>(); 4306 AU.addRequired<AAResultsWrapperPass>(); 4307 AU.addRequired<AssumptionCacheTracker>(); 4308 AU.setPreservesAll(); 4309 } 4310 4311 bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) { 4312 auto &SD = getAnalysis<ScopDetection>(); 4313 4314 if (!SD.isMaxRegionInScop(*R)) 4315 return false; 4316 4317 Function *F = R->getEntry()->getParent(); 4318 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 4319 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 4320 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 4321 auto const &DL = F->getParent()->getDataLayout(); 4322 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 4323 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F); 4324 4325 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE); 4326 S = SB.getScop(); // take ownership of scop object 4327 return false; 4328 } 4329 4330 void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const { 4331 if (S) 4332 S->print(OS); 4333 else 4334 OS << "Invalid Scop!\n"; 4335 } 4336 4337 char ScopInfoRegionPass::ID = 0; 4338 4339 Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); } 4340 4341 INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops", 4342 "Polly - Create polyhedral description of Scops", false, 4343 false); 4344 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass); 4345 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker); 4346 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 4347 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 4348 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 4349 INITIALIZE_PASS_DEPENDENCY(ScopDetection); 4350 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 4351 INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops", 4352 "Polly - Create polyhedral description of Scops", false, 4353 false) 4354 4355 //===----------------------------------------------------------------------===// 4356 void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 4357 AU.addRequired<LoopInfoWrapperPass>(); 4358 AU.addRequired<RegionInfoPass>(); 4359 AU.addRequired<DominatorTreeWrapperPass>(); 4360 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>(); 4361 AU.addRequiredTransitive<ScopDetection>(); 4362 AU.addRequired<AAResultsWrapperPass>(); 4363 AU.addRequired<AssumptionCacheTracker>(); 4364 AU.setPreservesAll(); 4365 } 4366 4367 bool ScopInfoWrapperPass::runOnFunction(Function &F) { 4368 auto &SD = getAnalysis<ScopDetection>(); 4369 4370 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 4371 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 4372 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 4373 auto const &DL = F.getParent()->getDataLayout(); 4374 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 4375 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 4376 4377 /// Create polyhedral descripton of scops for all the valid regions of a 4378 /// function. 4379 for (auto &It : SD) { 4380 Region *R = const_cast<Region *>(It); 4381 if (!SD.isMaxRegionInScop(*R)) 4382 continue; 4383 4384 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE); 4385 std::unique_ptr<Scop> S = SB.getScop(); 4386 if (!S) 4387 continue; 4388 bool Inserted = 4389 RegionToScopMap.insert(std::make_pair(R, std::move(S))).second; 4390 assert(Inserted && "Building Scop for the same region twice!"); 4391 (void)Inserted; 4392 } 4393 return false; 4394 } 4395 4396 void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const { 4397 for (auto &It : RegionToScopMap) { 4398 if (It.second) 4399 It.second->print(OS); 4400 else 4401 OS << "Invalid Scop!\n"; 4402 } 4403 } 4404 4405 char ScopInfoWrapperPass::ID = 0; 4406 4407 Pass *polly::createScopInfoWrapperPassPass() { 4408 return new ScopInfoWrapperPass(); 4409 } 4410 4411 INITIALIZE_PASS_BEGIN( 4412 ScopInfoWrapperPass, "polly-function-scops", 4413 "Polly - Create polyhedral description of all Scops of a function", false, 4414 false); 4415 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass); 4416 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker); 4417 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass); 4418 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass); 4419 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass); 4420 INITIALIZE_PASS_DEPENDENCY(ScopDetection); 4421 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass); 4422 INITIALIZE_PASS_END( 4423 ScopInfoWrapperPass, "polly-function-scops", 4424 "Polly - Create polyhedral description of all Scops of a function", false, 4425 false) 4426