1 //===- ScopBuilder.cpp ----------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Create a polyhedral description for a static control flow region. 10 // 11 // The pass creates a polyhedral description of the Scops detected by the SCoP 12 // detection derived from their LLVM-IR code. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "polly/ScopBuilder.h" 17 #include "polly/Options.h" 18 #include "polly/ScopDetection.h" 19 #include "polly/ScopInfo.h" 20 #include "polly/Support/GICHelper.h" 21 #include "polly/Support/ISLTools.h" 22 #include "polly/Support/SCEVValidator.h" 23 #include "polly/Support/ScopHelper.h" 24 #include "polly/Support/VirtualInstruction.h" 25 #include "llvm/ADT/ArrayRef.h" 26 #include "llvm/ADT/EquivalenceClasses.h" 27 #include "llvm/ADT/PostOrderIterator.h" 28 #include "llvm/ADT/Sequence.h" 29 #include "llvm/ADT/SmallSet.h" 30 #include "llvm/ADT/Statistic.h" 31 #include "llvm/Analysis/AliasAnalysis.h" 32 #include "llvm/Analysis/AssumptionCache.h" 33 #include "llvm/Analysis/Loads.h" 34 #include "llvm/Analysis/LoopInfo.h" 35 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 36 #include "llvm/Analysis/RegionInfo.h" 37 #include "llvm/Analysis/RegionIterator.h" 38 #include "llvm/Analysis/ScalarEvolution.h" 39 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 40 #include "llvm/IR/BasicBlock.h" 41 #include "llvm/IR/DataLayout.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/IR/DerivedTypes.h" 44 #include "llvm/IR/Dominators.h" 45 #include "llvm/IR/Function.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/Type.h" 50 #include "llvm/IR/Use.h" 51 #include "llvm/IR/Value.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/Support/Compiler.h" 54 #include "llvm/Support/Debug.h" 55 #include "llvm/Support/ErrorHandling.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include <cassert> 58 59 using namespace llvm; 60 using namespace polly; 61 62 #define DEBUG_TYPE "polly-scops" 63 64 STATISTIC(ScopFound, "Number of valid Scops"); 65 STATISTIC(RichScopFound, "Number of Scops containing a loop"); 66 STATISTIC(InfeasibleScops, 67 "Number of SCoPs with statically infeasible context."); 68 69 bool polly::ModelReadOnlyScalars; 70 71 // The maximal number of dimensions we allow during invariant load construction. 72 // More complex access ranges will result in very high compile time and are also 73 // unlikely to result in good code. This value is very high and should only 74 // trigger for corner cases (e.g., the "dct_luma" function in h264, SPEC2006). 75 static int const MaxDimensionsInAccessRange = 9; 76 77 static cl::opt<bool, true> XModelReadOnlyScalars( 78 "polly-analyze-read-only-scalars", 79 cl::desc("Model read-only scalar values in the scop description"), 80 cl::location(ModelReadOnlyScalars), cl::Hidden, cl::ZeroOrMore, 81 cl::init(true), cl::cat(PollyCategory)); 82 83 static cl::opt<int> 84 OptComputeOut("polly-analysis-computeout", 85 cl::desc("Bound the scop analysis by a maximal amount of " 86 "computational steps (0 means no bound)"), 87 cl::Hidden, cl::init(800000), cl::ZeroOrMore, 88 cl::cat(PollyCategory)); 89 90 static cl::opt<bool> PollyAllowDereferenceOfAllFunctionParams( 91 "polly-allow-dereference-of-all-function-parameters", 92 cl::desc( 93 "Treat all parameters to functions that are pointers as dereferencible." 94 " This is useful for invariant load hoisting, since we can generate" 95 " less runtime checks. This is only valid if all pointers to functions" 96 " are always initialized, so that Polly can choose to hoist" 97 " their loads. "), 98 cl::Hidden, cl::init(false), cl::cat(PollyCategory)); 99 100 static cl::opt<bool> 101 PollyIgnoreInbounds("polly-ignore-inbounds", 102 cl::desc("Do not take inbounds assumptions at all"), 103 cl::Hidden, cl::init(false), cl::cat(PollyCategory)); 104 105 static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup( 106 "polly-rtc-max-arrays-per-group", 107 cl::desc("The maximal number of arrays to compare in each alias group."), 108 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory)); 109 110 static cl::opt<int> RunTimeChecksMaxAccessDisjuncts( 111 "polly-rtc-max-array-disjuncts", 112 cl::desc("The maximal number of disjunts allowed in memory accesses to " 113 "to build RTCs."), 114 cl::Hidden, cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory)); 115 116 static cl::opt<unsigned> RunTimeChecksMaxParameters( 117 "polly-rtc-max-parameters", 118 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden, 119 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory)); 120 121 static cl::opt<bool> UnprofitableScalarAccs( 122 "polly-unprofitable-scalar-accs", 123 cl::desc("Count statements with scalar accesses as not optimizable"), 124 cl::Hidden, cl::init(false), cl::cat(PollyCategory)); 125 126 static cl::opt<std::string> UserContextStr( 127 "polly-context", cl::value_desc("isl parameter set"), 128 cl::desc("Provide additional constraints on the context parameters"), 129 cl::init(""), cl::cat(PollyCategory)); 130 131 static cl::opt<bool> DetectFortranArrays( 132 "polly-detect-fortran-arrays", 133 cl::desc("Detect Fortran arrays and use this for code generation"), 134 cl::Hidden, cl::init(false), cl::cat(PollyCategory)); 135 136 static cl::opt<bool> DetectReductions("polly-detect-reductions", 137 cl::desc("Detect and exploit reductions"), 138 cl::Hidden, cl::ZeroOrMore, 139 cl::init(true), cl::cat(PollyCategory)); 140 141 // Multiplicative reductions can be disabled separately as these kind of 142 // operations can overflow easily. Additive reductions and bit operations 143 // are in contrast pretty stable. 144 static cl::opt<bool> DisableMultiplicativeReductions( 145 "polly-disable-multiplicative-reductions", 146 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore, 147 cl::init(false), cl::cat(PollyCategory)); 148 149 enum class GranularityChoice { BasicBlocks, ScalarIndependence, Stores }; 150 151 static cl::opt<GranularityChoice> StmtGranularity( 152 "polly-stmt-granularity", 153 cl::desc( 154 "Algorithm to use for splitting basic blocks into multiple statements"), 155 cl::values(clEnumValN(GranularityChoice::BasicBlocks, "bb", 156 "One statement per basic block"), 157 clEnumValN(GranularityChoice::ScalarIndependence, "scalar-indep", 158 "Scalar independence heuristic"), 159 clEnumValN(GranularityChoice::Stores, "store", 160 "Store-level granularity")), 161 cl::init(GranularityChoice::ScalarIndependence), cl::cat(PollyCategory)); 162 163 /// Helper to treat non-affine regions and basic blocks the same. 164 /// 165 ///{ 166 167 /// Return the block that is the representing block for @p RN. 168 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) { 169 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry() 170 : RN->getNodeAs<BasicBlock>(); 171 } 172 173 /// Return the @p idx'th block that is executed after @p RN. 174 static inline BasicBlock * 175 getRegionNodeSuccessor(RegionNode *RN, Instruction *TI, unsigned idx) { 176 if (RN->isSubRegion()) { 177 assert(idx == 0); 178 return RN->getNodeAs<Region>()->getExit(); 179 } 180 return TI->getSuccessor(idx); 181 } 182 183 static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI, 184 const DominatorTree &DT) { 185 if (!RN->isSubRegion()) 186 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT); 187 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks()) 188 if (isErrorBlock(*BB, R, LI, DT)) 189 return true; 190 return false; 191 } 192 193 ///} 194 195 /// Create a map to map from a given iteration to a subsequent iteration. 196 /// 197 /// This map maps from SetSpace -> SetSpace where the dimensions @p Dim 198 /// is incremented by one and all other dimensions are equal, e.g., 199 /// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3] 200 /// 201 /// if @p Dim is 2 and @p SetSpace has 4 dimensions. 202 static isl::map createNextIterationMap(isl::space SetSpace, unsigned Dim) { 203 isl::space MapSpace = SetSpace.map_from_set(); 204 isl::map NextIterationMap = isl::map::universe(MapSpace); 205 for (auto u : seq<isl_size>(0, NextIterationMap.dim(isl::dim::in))) 206 if (u != (isl_size)Dim) 207 NextIterationMap = 208 NextIterationMap.equate(isl::dim::in, u, isl::dim::out, u); 209 isl::constraint C = 210 isl::constraint::alloc_equality(isl::local_space(MapSpace)); 211 C = C.set_constant_si(1); 212 C = C.set_coefficient_si(isl::dim::in, Dim, 1); 213 C = C.set_coefficient_si(isl::dim::out, Dim, -1); 214 NextIterationMap = NextIterationMap.add_constraint(C); 215 return NextIterationMap; 216 } 217 218 /// Add @p BSet to set @p BoundedParts if @p BSet is bounded. 219 static isl::set collectBoundedParts(isl::set S) { 220 isl::set BoundedParts = isl::set::empty(S.get_space()); 221 for (isl::basic_set BSet : S.get_basic_set_list()) 222 if (BSet.is_bounded()) 223 BoundedParts = BoundedParts.unite(isl::set(BSet)); 224 return BoundedParts; 225 } 226 227 /// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim. 228 /// 229 /// @returns A separation of @p S into first an unbounded then a bounded subset, 230 /// both with regards to the dimension @p Dim. 231 static std::pair<isl::set, isl::set> partitionSetParts(isl::set S, 232 unsigned Dim) { 233 for (unsigned u = 0, e = S.n_dim(); u < e; u++) 234 S = S.lower_bound_si(isl::dim::set, u, 0); 235 236 unsigned NumDimsS = S.n_dim(); 237 isl::set OnlyDimS = S; 238 239 // Remove dimensions that are greater than Dim as they are not interesting. 240 assert(NumDimsS >= Dim + 1); 241 OnlyDimS = OnlyDimS.project_out(isl::dim::set, Dim + 1, NumDimsS - Dim - 1); 242 243 // Create artificial parametric upper bounds for dimensions smaller than Dim 244 // as we are not interested in them. 245 OnlyDimS = OnlyDimS.insert_dims(isl::dim::param, 0, Dim); 246 247 for (unsigned u = 0; u < Dim; u++) { 248 isl::constraint C = isl::constraint::alloc_inequality( 249 isl::local_space(OnlyDimS.get_space())); 250 C = C.set_coefficient_si(isl::dim::param, u, 1); 251 C = C.set_coefficient_si(isl::dim::set, u, -1); 252 OnlyDimS = OnlyDimS.add_constraint(C); 253 } 254 255 // Collect all bounded parts of OnlyDimS. 256 isl::set BoundedParts = collectBoundedParts(OnlyDimS); 257 258 // Create the dimensions greater than Dim again. 259 BoundedParts = 260 BoundedParts.insert_dims(isl::dim::set, Dim + 1, NumDimsS - Dim - 1); 261 262 // Remove the artificial upper bound parameters again. 263 BoundedParts = BoundedParts.remove_dims(isl::dim::param, 0, Dim); 264 265 isl::set UnboundedParts = S.subtract(BoundedParts); 266 return std::make_pair(UnboundedParts, BoundedParts); 267 } 268 269 /// Create the conditions under which @p L @p Pred @p R is true. 270 static isl::set buildConditionSet(ICmpInst::Predicate Pred, isl::pw_aff L, 271 isl::pw_aff R) { 272 switch (Pred) { 273 case ICmpInst::ICMP_EQ: 274 return L.eq_set(R); 275 case ICmpInst::ICMP_NE: 276 return L.ne_set(R); 277 case ICmpInst::ICMP_SLT: 278 return L.lt_set(R); 279 case ICmpInst::ICMP_SLE: 280 return L.le_set(R); 281 case ICmpInst::ICMP_SGT: 282 return L.gt_set(R); 283 case ICmpInst::ICMP_SGE: 284 return L.ge_set(R); 285 case ICmpInst::ICMP_ULT: 286 return L.lt_set(R); 287 case ICmpInst::ICMP_UGT: 288 return L.gt_set(R); 289 case ICmpInst::ICMP_ULE: 290 return L.le_set(R); 291 case ICmpInst::ICMP_UGE: 292 return L.ge_set(R); 293 default: 294 llvm_unreachable("Non integer predicate not supported"); 295 } 296 } 297 298 isl::set ScopBuilder::adjustDomainDimensions(isl::set Dom, Loop *OldL, 299 Loop *NewL) { 300 // If the loops are the same there is nothing to do. 301 if (NewL == OldL) 302 return Dom; 303 304 int OldDepth = scop->getRelativeLoopDepth(OldL); 305 int NewDepth = scop->getRelativeLoopDepth(NewL); 306 // If both loops are non-affine loops there is nothing to do. 307 if (OldDepth == -1 && NewDepth == -1) 308 return Dom; 309 310 // Distinguish three cases: 311 // 1) The depth is the same but the loops are not. 312 // => One loop was left one was entered. 313 // 2) The depth increased from OldL to NewL. 314 // => One loop was entered, none was left. 315 // 3) The depth decreased from OldL to NewL. 316 // => Loops were left were difference of the depths defines how many. 317 if (OldDepth == NewDepth) { 318 assert(OldL->getParentLoop() == NewL->getParentLoop()); 319 Dom = Dom.project_out(isl::dim::set, NewDepth, 1); 320 Dom = Dom.add_dims(isl::dim::set, 1); 321 } else if (OldDepth < NewDepth) { 322 assert(OldDepth + 1 == NewDepth); 323 auto &R = scop->getRegion(); 324 (void)R; 325 assert(NewL->getParentLoop() == OldL || 326 ((!OldL || !R.contains(OldL)) && R.contains(NewL))); 327 Dom = Dom.add_dims(isl::dim::set, 1); 328 } else { 329 assert(OldDepth > NewDepth); 330 int Diff = OldDepth - NewDepth; 331 int NumDim = Dom.n_dim(); 332 assert(NumDim >= Diff); 333 Dom = Dom.project_out(isl::dim::set, NumDim - Diff, Diff); 334 } 335 336 return Dom; 337 } 338 339 /// Compute the isl representation for the SCEV @p E in this BB. 340 /// 341 /// @param BB The BB for which isl representation is to be 342 /// computed. 343 /// @param InvalidDomainMap A map of BB to their invalid domains. 344 /// @param E The SCEV that should be translated. 345 /// @param NonNegative Flag to indicate the @p E has to be non-negative. 346 /// 347 /// Note that this function will also adjust the invalid context accordingly. 348 349 __isl_give isl_pw_aff * 350 ScopBuilder::getPwAff(BasicBlock *BB, 351 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 352 const SCEV *E, bool NonNegative) { 353 PWACtx PWAC = scop->getPwAff(E, BB, NonNegative, &RecordedAssumptions); 354 InvalidDomainMap[BB] = InvalidDomainMap[BB].unite(PWAC.second); 355 return PWAC.first.release(); 356 } 357 358 /// Build condition sets for unsigned ICmpInst(s). 359 /// Special handling is required for unsigned operands to ensure that if 360 /// MSB (aka the Sign bit) is set for an operands in an unsigned ICmpInst 361 /// it should wrap around. 362 /// 363 /// @param IsStrictUpperBound holds information on the predicate relation 364 /// between TestVal and UpperBound, i.e, 365 /// TestVal < UpperBound OR TestVal <= UpperBound 366 __isl_give isl_set *ScopBuilder::buildUnsignedConditionSets( 367 BasicBlock *BB, Value *Condition, __isl_keep isl_set *Domain, 368 const SCEV *SCEV_TestVal, const SCEV *SCEV_UpperBound, 369 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 370 bool IsStrictUpperBound) { 371 // Do not take NonNeg assumption on TestVal 372 // as it might have MSB (Sign bit) set. 373 isl_pw_aff *TestVal = getPwAff(BB, InvalidDomainMap, SCEV_TestVal, false); 374 // Take NonNeg assumption on UpperBound. 375 isl_pw_aff *UpperBound = 376 getPwAff(BB, InvalidDomainMap, SCEV_UpperBound, true); 377 378 // 0 <= TestVal 379 isl_set *First = 380 isl_pw_aff_le_set(isl_pw_aff_zero_on_domain(isl_local_space_from_space( 381 isl_pw_aff_get_domain_space(TestVal))), 382 isl_pw_aff_copy(TestVal)); 383 384 isl_set *Second; 385 if (IsStrictUpperBound) 386 // TestVal < UpperBound 387 Second = isl_pw_aff_lt_set(TestVal, UpperBound); 388 else 389 // TestVal <= UpperBound 390 Second = isl_pw_aff_le_set(TestVal, UpperBound); 391 392 isl_set *ConsequenceCondSet = isl_set_intersect(First, Second); 393 return ConsequenceCondSet; 394 } 395 396 bool ScopBuilder::buildConditionSets( 397 BasicBlock *BB, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain, 398 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 399 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 400 Value *Condition = getConditionFromTerminator(SI); 401 assert(Condition && "No condition for switch"); 402 403 isl_pw_aff *LHS, *RHS; 404 LHS = getPwAff(BB, InvalidDomainMap, SE.getSCEVAtScope(Condition, L)); 405 406 unsigned NumSuccessors = SI->getNumSuccessors(); 407 ConditionSets.resize(NumSuccessors); 408 for (auto &Case : SI->cases()) { 409 unsigned Idx = Case.getSuccessorIndex(); 410 ConstantInt *CaseValue = Case.getCaseValue(); 411 412 RHS = getPwAff(BB, InvalidDomainMap, SE.getSCEV(CaseValue)); 413 isl_set *CaseConditionSet = 414 buildConditionSet(ICmpInst::ICMP_EQ, isl::manage_copy(LHS), 415 isl::manage(RHS)) 416 .release(); 417 ConditionSets[Idx] = isl_set_coalesce( 418 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain))); 419 } 420 421 assert(ConditionSets[0] == nullptr && "Default condition set was set"); 422 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]); 423 for (unsigned u = 2; u < NumSuccessors; u++) 424 ConditionSetUnion = 425 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u])); 426 ConditionSets[0] = isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion); 427 428 isl_pw_aff_free(LHS); 429 430 return true; 431 } 432 433 bool ScopBuilder::buildConditionSets( 434 BasicBlock *BB, Value *Condition, Instruction *TI, Loop *L, 435 __isl_keep isl_set *Domain, 436 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 437 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 438 isl_set *ConsequenceCondSet = nullptr; 439 440 if (auto Load = dyn_cast<LoadInst>(Condition)) { 441 const SCEV *LHSSCEV = SE.getSCEVAtScope(Load, L); 442 const SCEV *RHSSCEV = SE.getZero(LHSSCEV->getType()); 443 bool NonNeg = false; 444 isl_pw_aff *LHS = getPwAff(BB, InvalidDomainMap, LHSSCEV, NonNeg); 445 isl_pw_aff *RHS = getPwAff(BB, InvalidDomainMap, RHSSCEV, NonNeg); 446 ConsequenceCondSet = buildConditionSet(ICmpInst::ICMP_SLE, isl::manage(LHS), 447 isl::manage(RHS)) 448 .release(); 449 } else if (auto *PHI = dyn_cast<PHINode>(Condition)) { 450 auto *Unique = dyn_cast<ConstantInt>( 451 getUniqueNonErrorValue(PHI, &scop->getRegion(), LI, DT)); 452 453 if (Unique->isZero()) 454 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain)); 455 else 456 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain)); 457 } else if (auto *CCond = dyn_cast<ConstantInt>(Condition)) { 458 if (CCond->isZero()) 459 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain)); 460 else 461 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain)); 462 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) { 463 auto Opcode = BinOp->getOpcode(); 464 assert(Opcode == Instruction::And || Opcode == Instruction::Or); 465 466 bool Valid = buildConditionSets(BB, BinOp->getOperand(0), TI, L, Domain, 467 InvalidDomainMap, ConditionSets) && 468 buildConditionSets(BB, BinOp->getOperand(1), TI, L, Domain, 469 InvalidDomainMap, ConditionSets); 470 if (!Valid) { 471 while (!ConditionSets.empty()) 472 isl_set_free(ConditionSets.pop_back_val()); 473 return false; 474 } 475 476 isl_set_free(ConditionSets.pop_back_val()); 477 isl_set *ConsCondPart0 = ConditionSets.pop_back_val(); 478 isl_set_free(ConditionSets.pop_back_val()); 479 isl_set *ConsCondPart1 = ConditionSets.pop_back_val(); 480 481 if (Opcode == Instruction::And) 482 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1); 483 else 484 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1); 485 } else { 486 auto *ICond = dyn_cast<ICmpInst>(Condition); 487 assert(ICond && 488 "Condition of exiting branch was neither constant nor ICmp!"); 489 490 Region &R = scop->getRegion(); 491 492 isl_pw_aff *LHS, *RHS; 493 // For unsigned comparisons we assumed the signed bit of neither operand 494 // to be set. The comparison is equal to a signed comparison under this 495 // assumption. 496 bool NonNeg = ICond->isUnsigned(); 497 const SCEV *LeftOperand = SE.getSCEVAtScope(ICond->getOperand(0), L), 498 *RightOperand = SE.getSCEVAtScope(ICond->getOperand(1), L); 499 500 LeftOperand = tryForwardThroughPHI(LeftOperand, R, SE, LI, DT); 501 RightOperand = tryForwardThroughPHI(RightOperand, R, SE, LI, DT); 502 503 switch (ICond->getPredicate()) { 504 case ICmpInst::ICMP_ULT: 505 ConsequenceCondSet = 506 buildUnsignedConditionSets(BB, Condition, Domain, LeftOperand, 507 RightOperand, InvalidDomainMap, true); 508 break; 509 case ICmpInst::ICMP_ULE: 510 ConsequenceCondSet = 511 buildUnsignedConditionSets(BB, Condition, Domain, LeftOperand, 512 RightOperand, InvalidDomainMap, false); 513 break; 514 case ICmpInst::ICMP_UGT: 515 ConsequenceCondSet = 516 buildUnsignedConditionSets(BB, Condition, Domain, RightOperand, 517 LeftOperand, InvalidDomainMap, true); 518 break; 519 case ICmpInst::ICMP_UGE: 520 ConsequenceCondSet = 521 buildUnsignedConditionSets(BB, Condition, Domain, RightOperand, 522 LeftOperand, InvalidDomainMap, false); 523 break; 524 default: 525 LHS = getPwAff(BB, InvalidDomainMap, LeftOperand, NonNeg); 526 RHS = getPwAff(BB, InvalidDomainMap, RightOperand, NonNeg); 527 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), 528 isl::manage(LHS), isl::manage(RHS)) 529 .release(); 530 break; 531 } 532 } 533 534 // If no terminator was given we are only looking for parameter constraints 535 // under which @p Condition is true/false. 536 if (!TI) 537 ConsequenceCondSet = isl_set_params(ConsequenceCondSet); 538 assert(ConsequenceCondSet); 539 ConsequenceCondSet = isl_set_coalesce( 540 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))); 541 542 isl_set *AlternativeCondSet = nullptr; 543 bool TooComplex = 544 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain; 545 546 if (!TooComplex) { 547 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain), 548 isl_set_copy(ConsequenceCondSet)); 549 TooComplex = 550 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain; 551 } 552 553 if (TooComplex) { 554 scop->invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc(), 555 TI ? TI->getParent() : nullptr /* BasicBlock */); 556 isl_set_free(AlternativeCondSet); 557 isl_set_free(ConsequenceCondSet); 558 return false; 559 } 560 561 ConditionSets.push_back(ConsequenceCondSet); 562 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet)); 563 564 return true; 565 } 566 567 bool ScopBuilder::buildConditionSets( 568 BasicBlock *BB, Instruction *TI, Loop *L, __isl_keep isl_set *Domain, 569 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap, 570 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) { 571 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) 572 return buildConditionSets(BB, SI, L, Domain, InvalidDomainMap, 573 ConditionSets); 574 575 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch."); 576 577 if (TI->getNumSuccessors() == 1) { 578 ConditionSets.push_back(isl_set_copy(Domain)); 579 return true; 580 } 581 582 Value *Condition = getConditionFromTerminator(TI); 583 assert(Condition && "No condition for Terminator"); 584 585 return buildConditionSets(BB, Condition, TI, L, Domain, InvalidDomainMap, 586 ConditionSets); 587 } 588 589 bool ScopBuilder::propagateDomainConstraints( 590 Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 591 // Iterate over the region R and propagate the domain constrains from the 592 // predecessors to the current node. In contrast to the 593 // buildDomainsWithBranchConstraints function, this one will pull the domain 594 // information from the predecessors instead of pushing it to the successors. 595 // Additionally, we assume the domains to be already present in the domain 596 // map here. However, we iterate again in reverse post order so we know all 597 // predecessors have been visited before a block or non-affine subregion is 598 // visited. 599 600 ReversePostOrderTraversal<Region *> RTraversal(R); 601 for (auto *RN : RTraversal) { 602 // Recurse for affine subregions but go on for basic blocks and non-affine 603 // subregions. 604 if (RN->isSubRegion()) { 605 Region *SubRegion = RN->getNodeAs<Region>(); 606 if (!scop->isNonAffineSubRegion(SubRegion)) { 607 if (!propagateDomainConstraints(SubRegion, InvalidDomainMap)) 608 return false; 609 continue; 610 } 611 } 612 613 BasicBlock *BB = getRegionNodeBasicBlock(RN); 614 isl::set &Domain = scop->getOrInitEmptyDomain(BB); 615 assert(!Domain.is_null()); 616 617 // Under the union of all predecessor conditions we can reach this block. 618 isl::set PredDom = getPredecessorDomainConstraints(BB, Domain); 619 Domain = Domain.intersect(PredDom).coalesce(); 620 Domain = Domain.align_params(scop->getParamSpace()); 621 622 Loop *BBLoop = getRegionNodeLoop(RN, LI); 623 if (BBLoop && BBLoop->getHeader() == BB && scop->contains(BBLoop)) 624 if (!addLoopBoundsToHeaderDomain(BBLoop, InvalidDomainMap)) 625 return false; 626 } 627 628 return true; 629 } 630 631 void ScopBuilder::propagateDomainConstraintsToRegionExit( 632 BasicBlock *BB, Loop *BBLoop, 633 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, 634 DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 635 // Check if the block @p BB is the entry of a region. If so we propagate it's 636 // domain to the exit block of the region. Otherwise we are done. 637 auto *RI = scop->getRegion().getRegionInfo(); 638 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr; 639 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr; 640 if (!BBReg || BBReg->getEntry() != BB || !scop->contains(ExitBB)) 641 return; 642 643 // Do not propagate the domain if there is a loop backedge inside the region 644 // that would prevent the exit block from being executed. 645 auto *L = BBLoop; 646 while (L && scop->contains(L)) { 647 SmallVector<BasicBlock *, 4> LatchBBs; 648 BBLoop->getLoopLatches(LatchBBs); 649 for (auto *LatchBB : LatchBBs) 650 if (BB != LatchBB && BBReg->contains(LatchBB)) 651 return; 652 L = L->getParentLoop(); 653 } 654 655 isl::set Domain = scop->getOrInitEmptyDomain(BB); 656 assert(!Domain.is_null() && "Cannot propagate a nullptr"); 657 658 Loop *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, scop->getBoxedLoops()); 659 660 // Since the dimensions of @p BB and @p ExitBB might be different we have to 661 // adjust the domain before we can propagate it. 662 isl::set AdjustedDomain = adjustDomainDimensions(Domain, BBLoop, ExitBBLoop); 663 isl::set &ExitDomain = scop->getOrInitEmptyDomain(ExitBB); 664 665 // If the exit domain is not yet created we set it otherwise we "add" the 666 // current domain. 667 ExitDomain = 668 !ExitDomain.is_null() ? AdjustedDomain.unite(ExitDomain) : AdjustedDomain; 669 670 // Initialize the invalid domain. 671 InvalidDomainMap[ExitBB] = ExitDomain.empty(ExitDomain.get_space()); 672 673 FinishedExitBlocks.insert(ExitBB); 674 } 675 676 isl::set ScopBuilder::getPredecessorDomainConstraints(BasicBlock *BB, 677 isl::set Domain) { 678 // If @p BB is the ScopEntry we are done 679 if (scop->getRegion().getEntry() == BB) 680 return isl::set::universe(Domain.get_space()); 681 682 // The region info of this function. 683 auto &RI = *scop->getRegion().getRegionInfo(); 684 685 Loop *BBLoop = getFirstNonBoxedLoopFor(BB, LI, scop->getBoxedLoops()); 686 687 // A domain to collect all predecessor domains, thus all conditions under 688 // which the block is executed. To this end we start with the empty domain. 689 isl::set PredDom = isl::set::empty(Domain.get_space()); 690 691 // Set of regions of which the entry block domain has been propagated to BB. 692 // all predecessors inside any of the regions can be skipped. 693 SmallSet<Region *, 8> PropagatedRegions; 694 695 for (auto *PredBB : predecessors(BB)) { 696 // Skip backedges. 697 if (DT.dominates(BB, PredBB)) 698 continue; 699 700 // If the predecessor is in a region we used for propagation we can skip it. 701 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); }; 702 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(), 703 PredBBInRegion)) { 704 continue; 705 } 706 707 // Check if there is a valid region we can use for propagation, thus look 708 // for a region that contains the predecessor and has @p BB as exit block. 709 auto *PredR = RI.getRegionFor(PredBB); 710 while (PredR->getExit() != BB && !PredR->contains(BB)) 711 PredR->getParent(); 712 713 // If a valid region for propagation was found use the entry of that region 714 // for propagation, otherwise the PredBB directly. 715 if (PredR->getExit() == BB) { 716 PredBB = PredR->getEntry(); 717 PropagatedRegions.insert(PredR); 718 } 719 720 isl::set PredBBDom = scop->getDomainConditions(PredBB); 721 Loop *PredBBLoop = 722 getFirstNonBoxedLoopFor(PredBB, LI, scop->getBoxedLoops()); 723 PredBBDom = adjustDomainDimensions(PredBBDom, PredBBLoop, BBLoop); 724 PredDom = PredDom.unite(PredBBDom); 725 } 726 727 return PredDom; 728 } 729 730 bool ScopBuilder::addLoopBoundsToHeaderDomain( 731 Loop *L, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 732 int LoopDepth = scop->getRelativeLoopDepth(L); 733 assert(LoopDepth >= 0 && "Loop in region should have at least depth one"); 734 735 BasicBlock *HeaderBB = L->getHeader(); 736 assert(scop->isDomainDefined(HeaderBB)); 737 isl::set &HeaderBBDom = scop->getOrInitEmptyDomain(HeaderBB); 738 739 isl::map NextIterationMap = 740 createNextIterationMap(HeaderBBDom.get_space(), LoopDepth); 741 742 isl::set UnionBackedgeCondition = HeaderBBDom.empty(HeaderBBDom.get_space()); 743 744 SmallVector<BasicBlock *, 4> LatchBlocks; 745 L->getLoopLatches(LatchBlocks); 746 747 for (BasicBlock *LatchBB : LatchBlocks) { 748 // If the latch is only reachable via error statements we skip it. 749 if (!scop->isDomainDefined(LatchBB)) 750 continue; 751 752 isl::set LatchBBDom = scop->getDomainConditions(LatchBB); 753 754 isl::set BackedgeCondition; 755 756 Instruction *TI = LatchBB->getTerminator(); 757 BranchInst *BI = dyn_cast<BranchInst>(TI); 758 assert(BI && "Only branch instructions allowed in loop latches"); 759 760 if (BI->isUnconditional()) 761 BackedgeCondition = LatchBBDom; 762 else { 763 SmallVector<isl_set *, 8> ConditionSets; 764 int idx = BI->getSuccessor(0) != HeaderBB; 765 if (!buildConditionSets(LatchBB, TI, L, LatchBBDom.get(), 766 InvalidDomainMap, ConditionSets)) 767 return false; 768 769 // Free the non back edge condition set as we do not need it. 770 isl_set_free(ConditionSets[1 - idx]); 771 772 BackedgeCondition = isl::manage(ConditionSets[idx]); 773 } 774 775 int LatchLoopDepth = scop->getRelativeLoopDepth(LI.getLoopFor(LatchBB)); 776 assert(LatchLoopDepth >= LoopDepth); 777 BackedgeCondition = BackedgeCondition.project_out( 778 isl::dim::set, LoopDepth + 1, LatchLoopDepth - LoopDepth); 779 UnionBackedgeCondition = UnionBackedgeCondition.unite(BackedgeCondition); 780 } 781 782 isl::map ForwardMap = ForwardMap.lex_le(HeaderBBDom.get_space()); 783 for (int i = 0; i < LoopDepth; i++) 784 ForwardMap = ForwardMap.equate(isl::dim::in, i, isl::dim::out, i); 785 786 isl::set UnionBackedgeConditionComplement = 787 UnionBackedgeCondition.complement(); 788 UnionBackedgeConditionComplement = 789 UnionBackedgeConditionComplement.lower_bound_si(isl::dim::set, LoopDepth, 790 0); 791 UnionBackedgeConditionComplement = 792 UnionBackedgeConditionComplement.apply(ForwardMap); 793 HeaderBBDom = HeaderBBDom.subtract(UnionBackedgeConditionComplement); 794 HeaderBBDom = HeaderBBDom.apply(NextIterationMap); 795 796 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth); 797 HeaderBBDom = Parts.second; 798 799 // Check if there is a <nsw> tagged AddRec for this loop and if so do not 800 // require a runtime check. The assumption is already implied by the <nsw> 801 // tag. 802 bool RequiresRTC = !scop->hasNSWAddRecForLoop(L); 803 804 isl::set UnboundedCtx = Parts.first.params(); 805 recordAssumption(&RecordedAssumptions, INFINITELOOP, UnboundedCtx, 806 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION, 807 nullptr, RequiresRTC); 808 return true; 809 } 810 811 void ScopBuilder::buildInvariantEquivalenceClasses() { 812 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses; 813 814 const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads(); 815 for (LoadInst *LInst : RIL) { 816 const SCEV *PointerSCEV = SE.getSCEV(LInst->getPointerOperand()); 817 818 Type *Ty = LInst->getType(); 819 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)]; 820 if (ClassRep) { 821 scop->addInvariantLoadMapping(LInst, ClassRep); 822 continue; 823 } 824 825 ClassRep = LInst; 826 scop->addInvariantEquivClass( 827 InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), {}, Ty}); 828 } 829 } 830 831 bool ScopBuilder::buildDomains( 832 Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 833 bool IsOnlyNonAffineRegion = scop->isNonAffineSubRegion(R); 834 auto *EntryBB = R->getEntry(); 835 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB); 836 int LD = scop->getRelativeLoopDepth(L); 837 auto *S = 838 isl_set_universe(isl_space_set_alloc(scop->getIslCtx().get(), 0, LD + 1)); 839 840 InvalidDomainMap[EntryBB] = isl::manage(isl_set_empty(isl_set_get_space(S))); 841 isl::noexceptions::set Domain = isl::manage(S); 842 scop->setDomain(EntryBB, Domain); 843 844 if (IsOnlyNonAffineRegion) 845 return !containsErrorBlock(R->getNode(), *R, LI, DT); 846 847 if (!buildDomainsWithBranchConstraints(R, InvalidDomainMap)) 848 return false; 849 850 if (!propagateDomainConstraints(R, InvalidDomainMap)) 851 return false; 852 853 // Error blocks and blocks dominated by them have been assumed to never be 854 // executed. Representing them in the Scop does not add any value. In fact, 855 // it is likely to cause issues during construction of the ScopStmts. The 856 // contents of error blocks have not been verified to be expressible and 857 // will cause problems when building up a ScopStmt for them. 858 // Furthermore, basic blocks dominated by error blocks may reference 859 // instructions in the error block which, if the error block is not modeled, 860 // can themselves not be constructed properly. To this end we will replace 861 // the domains of error blocks and those only reachable via error blocks 862 // with an empty set. Additionally, we will record for each block under which 863 // parameter combination it would be reached via an error block in its 864 // InvalidDomain. This information is needed during load hoisting. 865 if (!propagateInvalidStmtDomains(R, InvalidDomainMap)) 866 return false; 867 868 return true; 869 } 870 871 bool ScopBuilder::buildDomainsWithBranchConstraints( 872 Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 873 // To create the domain for each block in R we iterate over all blocks and 874 // subregions in R and propagate the conditions under which the current region 875 // element is executed. To this end we iterate in reverse post order over R as 876 // it ensures that we first visit all predecessors of a region node (either a 877 // basic block or a subregion) before we visit the region node itself. 878 // Initially, only the domain for the SCoP region entry block is set and from 879 // there we propagate the current domain to all successors, however we add the 880 // condition that the successor is actually executed next. 881 // As we are only interested in non-loop carried constraints here we can 882 // simply skip loop back edges. 883 884 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks; 885 ReversePostOrderTraversal<Region *> RTraversal(R); 886 for (auto *RN : RTraversal) { 887 // Recurse for affine subregions but go on for basic blocks and non-affine 888 // subregions. 889 if (RN->isSubRegion()) { 890 Region *SubRegion = RN->getNodeAs<Region>(); 891 if (!scop->isNonAffineSubRegion(SubRegion)) { 892 if (!buildDomainsWithBranchConstraints(SubRegion, InvalidDomainMap)) 893 return false; 894 continue; 895 } 896 } 897 898 if (containsErrorBlock(RN, scop->getRegion(), LI, DT)) 899 scop->notifyErrorBlock(); 900 ; 901 902 BasicBlock *BB = getRegionNodeBasicBlock(RN); 903 Instruction *TI = BB->getTerminator(); 904 905 if (isa<UnreachableInst>(TI)) 906 continue; 907 908 if (!scop->isDomainDefined(BB)) 909 continue; 910 isl::set Domain = scop->getDomainConditions(BB); 911 912 scop->updateMaxLoopDepth(isl_set_n_dim(Domain.get())); 913 914 auto *BBLoop = getRegionNodeLoop(RN, LI); 915 // Propagate the domain from BB directly to blocks that have a superset 916 // domain, at the moment only region exit nodes of regions that start in BB. 917 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, 918 InvalidDomainMap); 919 920 // If all successors of BB have been set a domain through the propagation 921 // above we do not need to build condition sets but can just skip this 922 // block. However, it is important to note that this is a local property 923 // with regards to the region @p R. To this end FinishedExitBlocks is a 924 // local variable. 925 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) { 926 return FinishedExitBlocks.count(SuccBB); 927 }; 928 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit)) 929 continue; 930 931 // Build the condition sets for the successor nodes of the current region 932 // node. If it is a non-affine subregion we will always execute the single 933 // exit node, hence the single entry node domain is the condition set. For 934 // basic blocks we use the helper function buildConditionSets. 935 SmallVector<isl_set *, 8> ConditionSets; 936 if (RN->isSubRegion()) 937 ConditionSets.push_back(Domain.copy()); 938 else if (!buildConditionSets(BB, TI, BBLoop, Domain.get(), InvalidDomainMap, 939 ConditionSets)) 940 return false; 941 942 // Now iterate over the successors and set their initial domain based on 943 // their condition set. We skip back edges here and have to be careful when 944 // we leave a loop not to keep constraints over a dimension that doesn't 945 // exist anymore. 946 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size()); 947 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) { 948 isl::set CondSet = isl::manage(ConditionSets[u]); 949 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u); 950 951 // Skip blocks outside the region. 952 if (!scop->contains(SuccBB)) 953 continue; 954 955 // If we propagate the domain of some block to "SuccBB" we do not have to 956 // adjust the domain. 957 if (FinishedExitBlocks.count(SuccBB)) 958 continue; 959 960 // Skip back edges. 961 if (DT.dominates(SuccBB, BB)) 962 continue; 963 964 Loop *SuccBBLoop = 965 getFirstNonBoxedLoopFor(SuccBB, LI, scop->getBoxedLoops()); 966 967 CondSet = adjustDomainDimensions(CondSet, BBLoop, SuccBBLoop); 968 969 // Set the domain for the successor or merge it with an existing domain in 970 // case there are multiple paths (without loop back edges) to the 971 // successor block. 972 isl::set &SuccDomain = scop->getOrInitEmptyDomain(SuccBB); 973 974 if (!SuccDomain.is_null()) { 975 SuccDomain = SuccDomain.unite(CondSet).coalesce(); 976 } else { 977 // Initialize the invalid domain. 978 InvalidDomainMap[SuccBB] = CondSet.empty(CondSet.get_space()); 979 SuccDomain = CondSet; 980 } 981 982 SuccDomain = SuccDomain.detect_equalities(); 983 984 // Check if the maximal number of domain disjunctions was reached. 985 // In case this happens we will clean up and bail. 986 if (SuccDomain.n_basic_set() < MaxDisjunctsInDomain) 987 continue; 988 989 scop->invalidate(COMPLEXITY, DebugLoc()); 990 while (++u < ConditionSets.size()) 991 isl_set_free(ConditionSets[u]); 992 return false; 993 } 994 } 995 996 return true; 997 } 998 999 bool ScopBuilder::propagateInvalidStmtDomains( 1000 Region *R, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 1001 ReversePostOrderTraversal<Region *> RTraversal(R); 1002 for (auto *RN : RTraversal) { 1003 1004 // Recurse for affine subregions but go on for basic blocks and non-affine 1005 // subregions. 1006 if (RN->isSubRegion()) { 1007 Region *SubRegion = RN->getNodeAs<Region>(); 1008 if (!scop->isNonAffineSubRegion(SubRegion)) { 1009 propagateInvalidStmtDomains(SubRegion, InvalidDomainMap); 1010 continue; 1011 } 1012 } 1013 1014 bool ContainsErrorBlock = containsErrorBlock(RN, scop->getRegion(), LI, DT); 1015 BasicBlock *BB = getRegionNodeBasicBlock(RN); 1016 isl::set &Domain = scop->getOrInitEmptyDomain(BB); 1017 assert(!Domain.is_null() && "Cannot propagate a nullptr"); 1018 1019 isl::set InvalidDomain = InvalidDomainMap[BB]; 1020 1021 bool IsInvalidBlock = ContainsErrorBlock || Domain.is_subset(InvalidDomain); 1022 1023 if (!IsInvalidBlock) { 1024 InvalidDomain = InvalidDomain.intersect(Domain); 1025 } else { 1026 InvalidDomain = Domain; 1027 isl::set DomPar = Domain.params(); 1028 recordAssumption(&RecordedAssumptions, ERRORBLOCK, DomPar, 1029 BB->getTerminator()->getDebugLoc(), AS_RESTRICTION); 1030 Domain = isl::set::empty(Domain.get_space()); 1031 } 1032 1033 if (InvalidDomain.is_empty()) { 1034 InvalidDomainMap[BB] = InvalidDomain; 1035 continue; 1036 } 1037 1038 auto *BBLoop = getRegionNodeLoop(RN, LI); 1039 auto *TI = BB->getTerminator(); 1040 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors(); 1041 for (unsigned u = 0; u < NumSuccs; u++) { 1042 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u); 1043 1044 // Skip successors outside the SCoP. 1045 if (!scop->contains(SuccBB)) 1046 continue; 1047 1048 // Skip backedges. 1049 if (DT.dominates(SuccBB, BB)) 1050 continue; 1051 1052 Loop *SuccBBLoop = 1053 getFirstNonBoxedLoopFor(SuccBB, LI, scop->getBoxedLoops()); 1054 1055 auto AdjustedInvalidDomain = 1056 adjustDomainDimensions(InvalidDomain, BBLoop, SuccBBLoop); 1057 1058 isl::set SuccInvalidDomain = InvalidDomainMap[SuccBB]; 1059 SuccInvalidDomain = SuccInvalidDomain.unite(AdjustedInvalidDomain); 1060 SuccInvalidDomain = SuccInvalidDomain.coalesce(); 1061 1062 InvalidDomainMap[SuccBB] = SuccInvalidDomain; 1063 1064 // Check if the maximal number of domain disjunctions was reached. 1065 // In case this happens we will bail. 1066 if (SuccInvalidDomain.n_basic_set() < MaxDisjunctsInDomain) 1067 continue; 1068 1069 InvalidDomainMap.erase(BB); 1070 scop->invalidate(COMPLEXITY, TI->getDebugLoc(), TI->getParent()); 1071 return false; 1072 } 1073 1074 InvalidDomainMap[BB] = InvalidDomain; 1075 } 1076 1077 return true; 1078 } 1079 1080 void ScopBuilder::buildPHIAccesses(ScopStmt *PHIStmt, PHINode *PHI, 1081 Region *NonAffineSubRegion, 1082 bool IsExitBlock) { 1083 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is 1084 // true, are not modeled as ordinary PHI nodes as they are not part of the 1085 // region. However, we model the operands in the predecessor blocks that are 1086 // part of the region as regular scalar accesses. 1087 1088 // If we can synthesize a PHI we can skip it, however only if it is in 1089 // the region. If it is not it can only be in the exit block of the region. 1090 // In this case we model the operands but not the PHI itself. 1091 auto *Scope = LI.getLoopFor(PHI->getParent()); 1092 if (!IsExitBlock && canSynthesize(PHI, *scop, &SE, Scope)) 1093 return; 1094 1095 // PHI nodes are modeled as if they had been demoted prior to the SCoP 1096 // detection. Hence, the PHI is a load of a new memory location in which the 1097 // incoming value was written at the end of the incoming basic block. 1098 bool OnlyNonAffineSubRegionOperands = true; 1099 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) { 1100 Value *Op = PHI->getIncomingValue(u); 1101 BasicBlock *OpBB = PHI->getIncomingBlock(u); 1102 ScopStmt *OpStmt = scop->getIncomingStmtFor(PHI->getOperandUse(u)); 1103 1104 // Do not build PHI dependences inside a non-affine subregion, but make 1105 // sure that the necessary scalar values are still made available. 1106 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB)) { 1107 auto *OpInst = dyn_cast<Instruction>(Op); 1108 if (!OpInst || !NonAffineSubRegion->contains(OpInst)) 1109 ensureValueRead(Op, OpStmt); 1110 continue; 1111 } 1112 1113 OnlyNonAffineSubRegionOperands = false; 1114 ensurePHIWrite(PHI, OpStmt, OpBB, Op, IsExitBlock); 1115 } 1116 1117 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) { 1118 addPHIReadAccess(PHIStmt, PHI); 1119 } 1120 } 1121 1122 void ScopBuilder::buildScalarDependences(ScopStmt *UserStmt, 1123 Instruction *Inst) { 1124 assert(!isa<PHINode>(Inst)); 1125 1126 // Pull-in required operands. 1127 for (Use &Op : Inst->operands()) 1128 ensureValueRead(Op.get(), UserStmt); 1129 } 1130 1131 // Create a sequence of two schedules. Either argument may be null and is 1132 // interpreted as the empty schedule. Can also return null if both schedules are 1133 // empty. 1134 static isl::schedule combineInSequence(isl::schedule Prev, isl::schedule Succ) { 1135 if (Prev.is_null()) 1136 return Succ; 1137 if (Succ.is_null()) 1138 return Prev; 1139 1140 return Prev.sequence(Succ); 1141 } 1142 1143 // Create an isl_multi_union_aff that defines an identity mapping from the 1144 // elements of USet to their N-th dimension. 1145 // 1146 // # Example: 1147 // 1148 // Domain: { A[i,j]; B[i,j,k] } 1149 // N: 1 1150 // 1151 // Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] } 1152 // 1153 // @param USet A union set describing the elements for which to generate a 1154 // mapping. 1155 // @param N The dimension to map to. 1156 // @returns A mapping from USet to its N-th dimension. 1157 static isl::multi_union_pw_aff mapToDimension(isl::union_set USet, int N) { 1158 assert(N >= 0); 1159 assert(!USet.is_null()); 1160 assert(!USet.is_empty()); 1161 1162 auto Result = isl::union_pw_multi_aff::empty(USet.get_space()); 1163 1164 for (isl::set S : USet.get_set_list()) { 1165 int Dim = S.dim(isl::dim::set); 1166 auto PMA = isl::pw_multi_aff::project_out_map(S.get_space(), isl::dim::set, 1167 N, Dim - N); 1168 if (N > 1) 1169 PMA = PMA.drop_dims(isl::dim::out, 0, N - 1); 1170 1171 Result = Result.add_pw_multi_aff(PMA); 1172 } 1173 1174 return isl::multi_union_pw_aff(isl::union_pw_multi_aff(Result)); 1175 } 1176 1177 void ScopBuilder::buildSchedule() { 1178 Loop *L = getLoopSurroundingScop(*scop, LI); 1179 LoopStackTy LoopStack({LoopStackElementTy(L, {}, 0)}); 1180 buildSchedule(scop->getRegion().getNode(), LoopStack); 1181 assert(LoopStack.size() == 1 && LoopStack.back().L == L); 1182 scop->setScheduleTree(LoopStack[0].Schedule); 1183 } 1184 1185 /// To generate a schedule for the elements in a Region we traverse the Region 1186 /// in reverse-post-order and add the contained RegionNodes in traversal order 1187 /// to the schedule of the loop that is currently at the top of the LoopStack. 1188 /// For loop-free codes, this results in a correct sequential ordering. 1189 /// 1190 /// Example: 1191 /// bb1(0) 1192 /// / \. 1193 /// bb2(1) bb3(2) 1194 /// \ / \. 1195 /// bb4(3) bb5(4) 1196 /// \ / 1197 /// bb6(5) 1198 /// 1199 /// Including loops requires additional processing. Whenever a loop header is 1200 /// encountered, the corresponding loop is added to the @p LoopStack. Starting 1201 /// from an empty schedule, we first process all RegionNodes that are within 1202 /// this loop and complete the sequential schedule at this loop-level before 1203 /// processing about any other nodes. To implement this 1204 /// loop-nodes-first-processing, the reverse post-order traversal is 1205 /// insufficient. Hence, we additionally check if the traversal yields 1206 /// sub-regions or blocks that are outside the last loop on the @p LoopStack. 1207 /// These region-nodes are then queue and only traverse after the all nodes 1208 /// within the current loop have been processed. 1209 void ScopBuilder::buildSchedule(Region *R, LoopStackTy &LoopStack) { 1210 Loop *OuterScopLoop = getLoopSurroundingScop(*scop, LI); 1211 1212 ReversePostOrderTraversal<Region *> RTraversal(R); 1213 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end()); 1214 std::deque<RegionNode *> DelayList; 1215 bool LastRNWaiting = false; 1216 1217 // Iterate over the region @p R in reverse post-order but queue 1218 // sub-regions/blocks iff they are not part of the last encountered but not 1219 // completely traversed loop. The variable LastRNWaiting is a flag to indicate 1220 // that we queued the last sub-region/block from the reverse post-order 1221 // iterator. If it is set we have to explore the next sub-region/block from 1222 // the iterator (if any) to guarantee progress. If it is not set we first try 1223 // the next queued sub-region/blocks. 1224 while (!WorkList.empty() || !DelayList.empty()) { 1225 RegionNode *RN; 1226 1227 if ((LastRNWaiting && !WorkList.empty()) || DelayList.empty()) { 1228 RN = WorkList.front(); 1229 WorkList.pop_front(); 1230 LastRNWaiting = false; 1231 } else { 1232 RN = DelayList.front(); 1233 DelayList.pop_front(); 1234 } 1235 1236 Loop *L = getRegionNodeLoop(RN, LI); 1237 if (!scop->contains(L)) 1238 L = OuterScopLoop; 1239 1240 Loop *LastLoop = LoopStack.back().L; 1241 if (LastLoop != L) { 1242 if (LastLoop && !LastLoop->contains(L)) { 1243 LastRNWaiting = true; 1244 DelayList.push_back(RN); 1245 continue; 1246 } 1247 LoopStack.push_back({L, {}, 0}); 1248 } 1249 buildSchedule(RN, LoopStack); 1250 } 1251 } 1252 1253 void ScopBuilder::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack) { 1254 if (RN->isSubRegion()) { 1255 auto *LocalRegion = RN->getNodeAs<Region>(); 1256 if (!scop->isNonAffineSubRegion(LocalRegion)) { 1257 buildSchedule(LocalRegion, LoopStack); 1258 return; 1259 } 1260 } 1261 1262 assert(LoopStack.rbegin() != LoopStack.rend()); 1263 auto LoopData = LoopStack.rbegin(); 1264 LoopData->NumBlocksProcessed += getNumBlocksInRegionNode(RN); 1265 1266 for (auto *Stmt : scop->getStmtListFor(RN)) { 1267 isl::union_set UDomain{Stmt->getDomain()}; 1268 auto StmtSchedule = isl::schedule::from_domain(UDomain); 1269 LoopData->Schedule = combineInSequence(LoopData->Schedule, StmtSchedule); 1270 } 1271 1272 // Check if we just processed the last node in this loop. If we did, finalize 1273 // the loop by: 1274 // 1275 // - adding new schedule dimensions 1276 // - folding the resulting schedule into the parent loop schedule 1277 // - dropping the loop schedule from the LoopStack. 1278 // 1279 // Then continue to check surrounding loops, which might also have been 1280 // completed by this node. 1281 size_t Dimension = LoopStack.size(); 1282 while (LoopData->L && 1283 LoopData->NumBlocksProcessed == getNumBlocksInLoop(LoopData->L)) { 1284 isl::schedule Schedule = LoopData->Schedule; 1285 auto NumBlocksProcessed = LoopData->NumBlocksProcessed; 1286 1287 assert(std::next(LoopData) != LoopStack.rend()); 1288 Loop *L = LoopData->L; 1289 ++LoopData; 1290 --Dimension; 1291 1292 if (!Schedule.is_null()) { 1293 isl::union_set Domain = Schedule.get_domain(); 1294 isl::multi_union_pw_aff MUPA = mapToDimension(Domain, Dimension); 1295 Schedule = Schedule.insert_partial_schedule(MUPA); 1296 1297 if (hasDisableAllTransformsHint(L)) { 1298 /// If any of the loops has a disable_nonforced heuristic, mark the 1299 /// entire SCoP as such. The ISL rescheduler can only reschedule the 1300 /// SCoP in its entirety. 1301 /// TODO: ScopDetection could avoid including such loops or warp them as 1302 /// boxed loop. It still needs to pass-through loop with user-defined 1303 /// metadata. 1304 scop->markDisableHeuristics(); 1305 } 1306 1307 // It is easier to insert the marks here that do it retroactively. 1308 isl::id IslLoopId = createIslLoopAttr(scop->getIslCtx(), L); 1309 if (!IslLoopId.is_null()) 1310 Schedule = Schedule.get_root() 1311 .get_child(0) 1312 .insert_mark(IslLoopId) 1313 .get_schedule(); 1314 1315 LoopData->Schedule = combineInSequence(LoopData->Schedule, Schedule); 1316 } 1317 1318 LoopData->NumBlocksProcessed += NumBlocksProcessed; 1319 } 1320 // Now pop all loops processed up there from the LoopStack 1321 LoopStack.erase(LoopStack.begin() + Dimension, LoopStack.end()); 1322 } 1323 1324 void ScopBuilder::buildEscapingDependences(Instruction *Inst) { 1325 // Check for uses of this instruction outside the scop. Because we do not 1326 // iterate over such instructions and therefore did not "ensure" the existence 1327 // of a write, we must determine such use here. 1328 if (scop->isEscaping(Inst)) 1329 ensureValueWrite(Inst); 1330 } 1331 1332 /// Check that a value is a Fortran Array descriptor. 1333 /// 1334 /// We check if V has the following structure: 1335 /// %"struct.array1_real(kind=8)" = type { i8*, i<zz>, i<zz>, 1336 /// [<num> x %struct.descriptor_dimension] } 1337 /// 1338 /// 1339 /// %struct.descriptor_dimension = type { i<zz>, i<zz>, i<zz> } 1340 /// 1341 /// 1. V's type name starts with "struct.array" 1342 /// 2. V's type has layout as shown. 1343 /// 3. Final member of V's type has name "struct.descriptor_dimension", 1344 /// 4. "struct.descriptor_dimension" has layout as shown. 1345 /// 5. Consistent use of i<zz> where <zz> is some fixed integer number. 1346 /// 1347 /// We are interested in such types since this is the code that dragonegg 1348 /// generates for Fortran array descriptors. 1349 /// 1350 /// @param V the Value to be checked. 1351 /// 1352 /// @returns True if V is a Fortran array descriptor, False otherwise. 1353 bool isFortranArrayDescriptor(Value *V) { 1354 PointerType *PTy = dyn_cast<PointerType>(V->getType()); 1355 1356 if (!PTy) 1357 return false; 1358 1359 Type *Ty = PTy->getElementType(); 1360 assert(Ty && "Ty expected to be initialized"); 1361 auto *StructArrTy = dyn_cast<StructType>(Ty); 1362 1363 if (!(StructArrTy && StructArrTy->hasName())) 1364 return false; 1365 1366 if (!StructArrTy->getName().startswith("struct.array")) 1367 return false; 1368 1369 if (StructArrTy->getNumElements() != 4) 1370 return false; 1371 1372 const ArrayRef<Type *> ArrMemberTys = StructArrTy->elements(); 1373 1374 // i8* match 1375 if (ArrMemberTys[0] != Type::getInt8PtrTy(V->getContext())) 1376 return false; 1377 1378 // Get a reference to the int type and check that all the members 1379 // share the same int type 1380 Type *IntTy = ArrMemberTys[1]; 1381 if (ArrMemberTys[2] != IntTy) 1382 return false; 1383 1384 // type: [<num> x %struct.descriptor_dimension] 1385 ArrayType *DescriptorDimArrayTy = dyn_cast<ArrayType>(ArrMemberTys[3]); 1386 if (!DescriptorDimArrayTy) 1387 return false; 1388 1389 // type: %struct.descriptor_dimension := type { ixx, ixx, ixx } 1390 StructType *DescriptorDimTy = 1391 dyn_cast<StructType>(DescriptorDimArrayTy->getElementType()); 1392 1393 if (!(DescriptorDimTy && DescriptorDimTy->hasName())) 1394 return false; 1395 1396 if (DescriptorDimTy->getName() != "struct.descriptor_dimension") 1397 return false; 1398 1399 if (DescriptorDimTy->getNumElements() != 3) 1400 return false; 1401 1402 for (auto MemberTy : DescriptorDimTy->elements()) { 1403 if (MemberTy != IntTy) 1404 return false; 1405 } 1406 1407 return true; 1408 } 1409 1410 Value *ScopBuilder::findFADAllocationVisible(MemAccInst Inst) { 1411 // match: 4.1 & 4.2 store/load 1412 if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst)) 1413 return nullptr; 1414 1415 // match: 4 1416 if (Inst.getAlignment() != 8) 1417 return nullptr; 1418 1419 Value *Address = Inst.getPointerOperand(); 1420 1421 const BitCastInst *Bitcast = nullptr; 1422 // [match: 3] 1423 if (auto *Slot = dyn_cast<GetElementPtrInst>(Address)) { 1424 Value *TypedMem = Slot->getPointerOperand(); 1425 // match: 2 1426 Bitcast = dyn_cast<BitCastInst>(TypedMem); 1427 } else { 1428 // match: 2 1429 Bitcast = dyn_cast<BitCastInst>(Address); 1430 } 1431 1432 if (!Bitcast) 1433 return nullptr; 1434 1435 auto *MallocMem = Bitcast->getOperand(0); 1436 1437 // match: 1 1438 auto *MallocCall = dyn_cast<CallInst>(MallocMem); 1439 if (!MallocCall) 1440 return nullptr; 1441 1442 Function *MallocFn = MallocCall->getCalledFunction(); 1443 if (!(MallocFn && MallocFn->hasName() && MallocFn->getName() == "malloc")) 1444 return nullptr; 1445 1446 // Find all uses the malloc'd memory. 1447 // We are looking for a "store" into a struct with the type being the Fortran 1448 // descriptor type 1449 for (auto user : MallocMem->users()) { 1450 /// match: 5 1451 auto *MallocStore = dyn_cast<StoreInst>(user); 1452 if (!MallocStore) 1453 continue; 1454 1455 auto *DescriptorGEP = 1456 dyn_cast<GEPOperator>(MallocStore->getPointerOperand()); 1457 if (!DescriptorGEP) 1458 continue; 1459 1460 // match: 5 1461 auto DescriptorType = 1462 dyn_cast<StructType>(DescriptorGEP->getSourceElementType()); 1463 if (!(DescriptorType && DescriptorType->hasName())) 1464 continue; 1465 1466 Value *Descriptor = dyn_cast<Value>(DescriptorGEP->getPointerOperand()); 1467 1468 if (!Descriptor) 1469 continue; 1470 1471 if (!isFortranArrayDescriptor(Descriptor)) 1472 continue; 1473 1474 return Descriptor; 1475 } 1476 1477 return nullptr; 1478 } 1479 1480 Value *ScopBuilder::findFADAllocationInvisible(MemAccInst Inst) { 1481 // match: 3 1482 if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst)) 1483 return nullptr; 1484 1485 Value *Slot = Inst.getPointerOperand(); 1486 1487 LoadInst *MemLoad = nullptr; 1488 // [match: 2] 1489 if (auto *SlotGEP = dyn_cast<GetElementPtrInst>(Slot)) { 1490 // match: 1 1491 MemLoad = dyn_cast<LoadInst>(SlotGEP->getPointerOperand()); 1492 } else { 1493 // match: 1 1494 MemLoad = dyn_cast<LoadInst>(Slot); 1495 } 1496 1497 if (!MemLoad) 1498 return nullptr; 1499 1500 auto *BitcastOperator = 1501 dyn_cast<BitCastOperator>(MemLoad->getPointerOperand()); 1502 if (!BitcastOperator) 1503 return nullptr; 1504 1505 Value *Descriptor = dyn_cast<Value>(BitcastOperator->getOperand(0)); 1506 if (!Descriptor) 1507 return nullptr; 1508 1509 if (!isFortranArrayDescriptor(Descriptor)) 1510 return nullptr; 1511 1512 return Descriptor; 1513 } 1514 1515 void ScopBuilder::addRecordedAssumptions() { 1516 for (auto &AS : llvm::reverse(RecordedAssumptions)) { 1517 1518 if (!AS.BB) { 1519 scop->addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign, 1520 nullptr /* BasicBlock */, AS.RequiresRTC); 1521 continue; 1522 } 1523 1524 // If the domain was deleted the assumptions are void. 1525 isl_set *Dom = scop->getDomainConditions(AS.BB).release(); 1526 if (!Dom) 1527 continue; 1528 1529 // If a basic block was given use its domain to simplify the assumption. 1530 // In case of restrictions we know they only have to hold on the domain, 1531 // thus we can intersect them with the domain of the block. However, for 1532 // assumptions the domain has to imply them, thus: 1533 // _ _____ 1534 // Dom => S <==> A v B <==> A - B 1535 // 1536 // To avoid the complement we will register A - B as a restriction not an 1537 // assumption. 1538 isl_set *S = AS.Set.copy(); 1539 if (AS.Sign == AS_RESTRICTION) 1540 S = isl_set_params(isl_set_intersect(S, Dom)); 1541 else /* (AS.Sign == AS_ASSUMPTION) */ 1542 S = isl_set_params(isl_set_subtract(Dom, S)); 1543 1544 scop->addAssumption(AS.Kind, isl::manage(S), AS.Loc, AS_RESTRICTION, AS.BB, 1545 AS.RequiresRTC); 1546 } 1547 } 1548 1549 void ScopBuilder::addUserAssumptions( 1550 AssumptionCache &AC, DenseMap<BasicBlock *, isl::set> &InvalidDomainMap) { 1551 for (auto &Assumption : AC.assumptions()) { 1552 auto *CI = dyn_cast_or_null<CallInst>(Assumption); 1553 if (!CI || CI->getNumArgOperands() != 1) 1554 continue; 1555 1556 bool InScop = scop->contains(CI); 1557 if (!InScop && !scop->isDominatedBy(DT, CI->getParent())) 1558 continue; 1559 1560 auto *L = LI.getLoopFor(CI->getParent()); 1561 auto *Val = CI->getArgOperand(0); 1562 ParameterSetTy DetectedParams; 1563 auto &R = scop->getRegion(); 1564 if (!isAffineConstraint(Val, &R, L, SE, DetectedParams)) { 1565 ORE.emit( 1566 OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreUserAssumption", CI) 1567 << "Non-affine user assumption ignored."); 1568 continue; 1569 } 1570 1571 // Collect all newly introduced parameters. 1572 ParameterSetTy NewParams; 1573 for (auto *Param : DetectedParams) { 1574 Param = extractConstantFactor(Param, SE).second; 1575 Param = scop->getRepresentingInvariantLoadSCEV(Param); 1576 if (scop->isParam(Param)) 1577 continue; 1578 NewParams.insert(Param); 1579 } 1580 1581 SmallVector<isl_set *, 2> ConditionSets; 1582 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr; 1583 BasicBlock *BB = InScop ? CI->getParent() : R.getEntry(); 1584 auto *Dom = InScop ? isl_set_copy(scop->getDomainConditions(BB).get()) 1585 : isl_set_copy(scop->getContext().get()); 1586 assert(Dom && "Cannot propagate a nullptr."); 1587 bool Valid = buildConditionSets(BB, Val, TI, L, Dom, InvalidDomainMap, 1588 ConditionSets); 1589 isl_set_free(Dom); 1590 1591 if (!Valid) 1592 continue; 1593 1594 isl_set *AssumptionCtx = nullptr; 1595 if (InScop) { 1596 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1])); 1597 isl_set_free(ConditionSets[0]); 1598 } else { 1599 AssumptionCtx = isl_set_complement(ConditionSets[1]); 1600 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]); 1601 } 1602 1603 // Project out newly introduced parameters as they are not otherwise useful. 1604 if (!NewParams.empty()) { 1605 for (isl_size u = 0; u < isl_set_n_param(AssumptionCtx); u++) { 1606 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u); 1607 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id)); 1608 isl_id_free(Id); 1609 1610 if (!NewParams.count(Param)) 1611 continue; 1612 1613 AssumptionCtx = 1614 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1); 1615 } 1616 } 1617 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "UserAssumption", CI) 1618 << "Use user assumption: " << stringFromIslObj(AssumptionCtx)); 1619 isl::set newContext = 1620 scop->getContext().intersect(isl::manage(AssumptionCtx)); 1621 scop->setContext(newContext); 1622 } 1623 } 1624 1625 bool ScopBuilder::buildAccessMultiDimFixed(MemAccInst Inst, ScopStmt *Stmt) { 1626 Value *Val = Inst.getValueOperand(); 1627 Type *ElementType = Val->getType(); 1628 Value *Address = Inst.getPointerOperand(); 1629 const SCEV *AccessFunction = 1630 SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent())); 1631 const SCEVUnknown *BasePointer = 1632 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 1633 enum MemoryAccess::AccessType AccType = 1634 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 1635 1636 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) { 1637 auto *Src = BitCast->getOperand(0); 1638 auto *SrcTy = Src->getType(); 1639 auto *DstTy = BitCast->getType(); 1640 // Do not try to delinearize non-sized (opaque) pointers. 1641 if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) || 1642 (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) { 1643 return false; 1644 } 1645 if (SrcTy->isPointerTy() && DstTy->isPointerTy() && 1646 DL.getTypeAllocSize(SrcTy->getPointerElementType()) == 1647 DL.getTypeAllocSize(DstTy->getPointerElementType())) 1648 Address = Src; 1649 } 1650 1651 auto *GEP = dyn_cast<GetElementPtrInst>(Address); 1652 if (!GEP) 1653 return false; 1654 1655 SmallVector<const SCEV *, 4> Subscripts; 1656 SmallVector<int, 4> Sizes; 1657 SE.getIndexExpressionsFromGEP(GEP, Subscripts, Sizes); 1658 auto *BasePtr = GEP->getOperand(0); 1659 1660 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr)) 1661 BasePtr = BasePtrCast->getOperand(0); 1662 1663 // Check for identical base pointers to ensure that we do not miss index 1664 // offsets that have been added before this GEP is applied. 1665 if (BasePtr != BasePointer->getValue()) 1666 return false; 1667 1668 std::vector<const SCEV *> SizesSCEV; 1669 1670 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 1671 1672 Loop *SurroundingLoop = Stmt->getSurroundingLoop(); 1673 for (auto *Subscript : Subscripts) { 1674 InvariantLoadsSetTy AccessILS; 1675 if (!isAffineExpr(&scop->getRegion(), SurroundingLoop, Subscript, SE, 1676 &AccessILS)) 1677 return false; 1678 1679 for (LoadInst *LInst : AccessILS) 1680 if (!ScopRIL.count(LInst)) 1681 return false; 1682 } 1683 1684 if (Sizes.empty()) 1685 return false; 1686 1687 SizesSCEV.push_back(nullptr); 1688 1689 for (auto V : Sizes) 1690 SizesSCEV.push_back(SE.getSCEV( 1691 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V))); 1692 1693 addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType, 1694 true, Subscripts, SizesSCEV, Val); 1695 return true; 1696 } 1697 1698 bool ScopBuilder::buildAccessMultiDimParam(MemAccInst Inst, ScopStmt *Stmt) { 1699 if (!PollyDelinearize) 1700 return false; 1701 1702 Value *Address = Inst.getPointerOperand(); 1703 Value *Val = Inst.getValueOperand(); 1704 Type *ElementType = Val->getType(); 1705 unsigned ElementSize = DL.getTypeAllocSize(ElementType); 1706 enum MemoryAccess::AccessType AccType = 1707 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 1708 1709 const SCEV *AccessFunction = 1710 SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent())); 1711 const SCEVUnknown *BasePointer = 1712 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 1713 1714 assert(BasePointer && "Could not find base pointer"); 1715 1716 auto &InsnToMemAcc = scop->getInsnToMemAccMap(); 1717 auto AccItr = InsnToMemAcc.find(Inst); 1718 if (AccItr == InsnToMemAcc.end()) 1719 return false; 1720 1721 std::vector<const SCEV *> Sizes = {nullptr}; 1722 1723 Sizes.insert(Sizes.end(), AccItr->second.Shape->DelinearizedSizes.begin(), 1724 AccItr->second.Shape->DelinearizedSizes.end()); 1725 1726 // In case only the element size is contained in the 'Sizes' array, the 1727 // access does not access a real multi-dimensional array. Hence, we allow 1728 // the normal single-dimensional access construction to handle this. 1729 if (Sizes.size() == 1) 1730 return false; 1731 1732 // Remove the element size. This information is already provided by the 1733 // ElementSize parameter. In case the element size of this access and the 1734 // element size used for delinearization differs the delinearization is 1735 // incorrect. Hence, we invalidate the scop. 1736 // 1737 // TODO: Handle delinearization with differing element sizes. 1738 auto DelinearizedSize = 1739 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue(); 1740 Sizes.pop_back(); 1741 if (ElementSize != DelinearizedSize) 1742 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc(), Inst->getParent()); 1743 1744 addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType, 1745 true, AccItr->second.DelinearizedSubscripts, Sizes, Val); 1746 return true; 1747 } 1748 1749 bool ScopBuilder::buildAccessMemIntrinsic(MemAccInst Inst, ScopStmt *Stmt) { 1750 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst); 1751 1752 if (MemIntr == nullptr) 1753 return false; 1754 1755 auto *L = LI.getLoopFor(Inst->getParent()); 1756 auto *LengthVal = SE.getSCEVAtScope(MemIntr->getLength(), L); 1757 assert(LengthVal); 1758 1759 // Check if the length val is actually affine or if we overapproximate it 1760 InvariantLoadsSetTy AccessILS; 1761 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 1762 1763 Loop *SurroundingLoop = Stmt->getSurroundingLoop(); 1764 bool LengthIsAffine = isAffineExpr(&scop->getRegion(), SurroundingLoop, 1765 LengthVal, SE, &AccessILS); 1766 for (LoadInst *LInst : AccessILS) 1767 if (!ScopRIL.count(LInst)) 1768 LengthIsAffine = false; 1769 if (!LengthIsAffine) 1770 LengthVal = nullptr; 1771 1772 auto *DestPtrVal = MemIntr->getDest(); 1773 assert(DestPtrVal); 1774 1775 auto *DestAccFunc = SE.getSCEVAtScope(DestPtrVal, L); 1776 assert(DestAccFunc); 1777 // Ignore accesses to "NULL". 1778 // TODO: We could use this to optimize the region further, e.g., intersect 1779 // the context with 1780 // isl_set_complement(isl_set_params(getDomain())) 1781 // as we know it would be undefined to execute this instruction anyway. 1782 if (DestAccFunc->isZero()) 1783 return true; 1784 1785 if (auto *U = dyn_cast<SCEVUnknown>(DestAccFunc)) { 1786 if (isa<ConstantPointerNull>(U->getValue())) 1787 return true; 1788 } 1789 1790 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(DestAccFunc)); 1791 assert(DestPtrSCEV); 1792 DestAccFunc = SE.getMinusSCEV(DestAccFunc, DestPtrSCEV); 1793 addArrayAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(), 1794 IntegerType::getInt8Ty(DestPtrVal->getContext()), 1795 LengthIsAffine, {DestAccFunc, LengthVal}, {nullptr}, 1796 Inst.getValueOperand()); 1797 1798 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr); 1799 if (!MemTrans) 1800 return true; 1801 1802 auto *SrcPtrVal = MemTrans->getSource(); 1803 assert(SrcPtrVal); 1804 1805 auto *SrcAccFunc = SE.getSCEVAtScope(SrcPtrVal, L); 1806 assert(SrcAccFunc); 1807 // Ignore accesses to "NULL". 1808 // TODO: See above TODO 1809 if (SrcAccFunc->isZero()) 1810 return true; 1811 1812 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(SrcAccFunc)); 1813 assert(SrcPtrSCEV); 1814 SrcAccFunc = SE.getMinusSCEV(SrcAccFunc, SrcPtrSCEV); 1815 addArrayAccess(Stmt, Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(), 1816 IntegerType::getInt8Ty(SrcPtrVal->getContext()), 1817 LengthIsAffine, {SrcAccFunc, LengthVal}, {nullptr}, 1818 Inst.getValueOperand()); 1819 1820 return true; 1821 } 1822 1823 bool ScopBuilder::buildAccessCallInst(MemAccInst Inst, ScopStmt *Stmt) { 1824 auto *CI = dyn_cast_or_null<CallInst>(Inst); 1825 1826 if (CI == nullptr) 1827 return false; 1828 1829 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI) || isDebugCall(CI)) 1830 return true; 1831 1832 bool ReadOnly = false; 1833 auto *AF = SE.getConstant(IntegerType::getInt64Ty(CI->getContext()), 0); 1834 auto *CalledFunction = CI->getCalledFunction(); 1835 switch (AA.getModRefBehavior(CalledFunction)) { 1836 case FMRB_UnknownModRefBehavior: 1837 llvm_unreachable("Unknown mod ref behaviour cannot be represented."); 1838 case FMRB_DoesNotAccessMemory: 1839 return true; 1840 case FMRB_OnlyWritesMemory: 1841 case FMRB_OnlyWritesInaccessibleMem: 1842 case FMRB_OnlyWritesInaccessibleOrArgMem: 1843 case FMRB_OnlyAccessesInaccessibleMem: 1844 case FMRB_OnlyAccessesInaccessibleOrArgMem: 1845 return false; 1846 case FMRB_OnlyReadsMemory: 1847 case FMRB_OnlyReadsInaccessibleMem: 1848 case FMRB_OnlyReadsInaccessibleOrArgMem: 1849 GlobalReads.emplace_back(Stmt, CI); 1850 return true; 1851 case FMRB_OnlyReadsArgumentPointees: 1852 ReadOnly = true; 1853 LLVM_FALLTHROUGH; 1854 case FMRB_OnlyWritesArgumentPointees: 1855 case FMRB_OnlyAccessesArgumentPointees: { 1856 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE; 1857 Loop *L = LI.getLoopFor(Inst->getParent()); 1858 for (const auto &Arg : CI->arg_operands()) { 1859 if (!Arg->getType()->isPointerTy()) 1860 continue; 1861 1862 auto *ArgSCEV = SE.getSCEVAtScope(Arg, L); 1863 if (ArgSCEV->isZero()) 1864 continue; 1865 1866 if (auto *U = dyn_cast<SCEVUnknown>(ArgSCEV)) { 1867 if (isa<ConstantPointerNull>(U->getValue())) 1868 return true; 1869 } 1870 1871 auto *ArgBasePtr = cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV)); 1872 addArrayAccess(Stmt, Inst, AccType, ArgBasePtr->getValue(), 1873 ArgBasePtr->getType(), false, {AF}, {nullptr}, CI); 1874 } 1875 return true; 1876 } 1877 } 1878 1879 return true; 1880 } 1881 1882 void ScopBuilder::buildAccessSingleDim(MemAccInst Inst, ScopStmt *Stmt) { 1883 Value *Address = Inst.getPointerOperand(); 1884 Value *Val = Inst.getValueOperand(); 1885 Type *ElementType = Val->getType(); 1886 enum MemoryAccess::AccessType AccType = 1887 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE; 1888 1889 const SCEV *AccessFunction = 1890 SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent())); 1891 const SCEVUnknown *BasePointer = 1892 dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction)); 1893 1894 assert(BasePointer && "Could not find base pointer"); 1895 AccessFunction = SE.getMinusSCEV(AccessFunction, BasePointer); 1896 1897 // Check if the access depends on a loop contained in a non-affine subregion. 1898 bool isVariantInNonAffineLoop = false; 1899 SetVector<const Loop *> Loops; 1900 findLoops(AccessFunction, Loops); 1901 for (const Loop *L : Loops) 1902 if (Stmt->contains(L)) { 1903 isVariantInNonAffineLoop = true; 1904 break; 1905 } 1906 1907 InvariantLoadsSetTy AccessILS; 1908 1909 Loop *SurroundingLoop = Stmt->getSurroundingLoop(); 1910 bool IsAffine = !isVariantInNonAffineLoop && 1911 isAffineExpr(&scop->getRegion(), SurroundingLoop, 1912 AccessFunction, SE, &AccessILS); 1913 1914 const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads(); 1915 for (LoadInst *LInst : AccessILS) 1916 if (!ScopRIL.count(LInst)) 1917 IsAffine = false; 1918 1919 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE) 1920 AccType = MemoryAccess::MAY_WRITE; 1921 1922 addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType, 1923 IsAffine, {AccessFunction}, {nullptr}, Val); 1924 } 1925 1926 void ScopBuilder::buildMemoryAccess(MemAccInst Inst, ScopStmt *Stmt) { 1927 if (buildAccessMemIntrinsic(Inst, Stmt)) 1928 return; 1929 1930 if (buildAccessCallInst(Inst, Stmt)) 1931 return; 1932 1933 if (buildAccessMultiDimFixed(Inst, Stmt)) 1934 return; 1935 1936 if (buildAccessMultiDimParam(Inst, Stmt)) 1937 return; 1938 1939 buildAccessSingleDim(Inst, Stmt); 1940 } 1941 1942 void ScopBuilder::buildAccessFunctions() { 1943 for (auto &Stmt : *scop) { 1944 if (Stmt.isBlockStmt()) { 1945 buildAccessFunctions(&Stmt, *Stmt.getBasicBlock()); 1946 continue; 1947 } 1948 1949 Region *R = Stmt.getRegion(); 1950 for (BasicBlock *BB : R->blocks()) 1951 buildAccessFunctions(&Stmt, *BB, R); 1952 } 1953 1954 // Build write accesses for values that are used after the SCoP. 1955 // The instructions defining them might be synthesizable and therefore not 1956 // contained in any statement, hence we iterate over the original instructions 1957 // to identify all escaping values. 1958 for (BasicBlock *BB : scop->getRegion().blocks()) { 1959 for (Instruction &Inst : *BB) 1960 buildEscapingDependences(&Inst); 1961 } 1962 } 1963 1964 bool ScopBuilder::shouldModelInst(Instruction *Inst, Loop *L) { 1965 return !Inst->isTerminator() && !isIgnoredIntrinsic(Inst) && 1966 !canSynthesize(Inst, *scop, &SE, L); 1967 } 1968 1969 /// Generate a name for a statement. 1970 /// 1971 /// @param BB The basic block the statement will represent. 1972 /// @param BBIdx The index of the @p BB relative to other BBs/regions. 1973 /// @param Count The index of the created statement in @p BB. 1974 /// @param IsMain Whether this is the main of all statement for @p BB. If true, 1975 /// no suffix will be added. 1976 /// @param IsLast Uses a special indicator for the last statement of a BB. 1977 static std::string makeStmtName(BasicBlock *BB, long BBIdx, int Count, 1978 bool IsMain, bool IsLast = false) { 1979 std::string Suffix; 1980 if (!IsMain) { 1981 if (UseInstructionNames) 1982 Suffix = '_'; 1983 if (IsLast) 1984 Suffix += "last"; 1985 else if (Count < 26) 1986 Suffix += 'a' + Count; 1987 else 1988 Suffix += std::to_string(Count); 1989 } 1990 return getIslCompatibleName("Stmt", BB, BBIdx, Suffix, UseInstructionNames); 1991 } 1992 1993 /// Generate a name for a statement that represents a non-affine subregion. 1994 /// 1995 /// @param R The region the statement will represent. 1996 /// @param RIdx The index of the @p R relative to other BBs/regions. 1997 static std::string makeStmtName(Region *R, long RIdx) { 1998 return getIslCompatibleName("Stmt", R->getNameStr(), RIdx, "", 1999 UseInstructionNames); 2000 } 2001 2002 void ScopBuilder::buildSequentialBlockStmts(BasicBlock *BB, bool SplitOnStore) { 2003 Loop *SurroundingLoop = LI.getLoopFor(BB); 2004 2005 int Count = 0; 2006 long BBIdx = scop->getNextStmtIdx(); 2007 std::vector<Instruction *> Instructions; 2008 for (Instruction &Inst : *BB) { 2009 if (shouldModelInst(&Inst, SurroundingLoop)) 2010 Instructions.push_back(&Inst); 2011 if (Inst.getMetadata("polly_split_after") || 2012 (SplitOnStore && isa<StoreInst>(Inst))) { 2013 std::string Name = makeStmtName(BB, BBIdx, Count, Count == 0); 2014 scop->addScopStmt(BB, Name, SurroundingLoop, Instructions); 2015 Count++; 2016 Instructions.clear(); 2017 } 2018 } 2019 2020 std::string Name = makeStmtName(BB, BBIdx, Count, Count == 0); 2021 scop->addScopStmt(BB, Name, SurroundingLoop, Instructions); 2022 } 2023 2024 /// Is @p Inst an ordered instruction? 2025 /// 2026 /// An unordered instruction is an instruction, such that a sequence of 2027 /// unordered instructions can be permuted without changing semantics. Any 2028 /// instruction for which this is not always the case is ordered. 2029 static bool isOrderedInstruction(Instruction *Inst) { 2030 return Inst->mayHaveSideEffects() || Inst->mayReadOrWriteMemory(); 2031 } 2032 2033 /// Join instructions to the same statement if one uses the scalar result of the 2034 /// other. 2035 static void joinOperandTree(EquivalenceClasses<Instruction *> &UnionFind, 2036 ArrayRef<Instruction *> ModeledInsts) { 2037 for (Instruction *Inst : ModeledInsts) { 2038 if (isa<PHINode>(Inst)) 2039 continue; 2040 2041 for (Use &Op : Inst->operands()) { 2042 Instruction *OpInst = dyn_cast<Instruction>(Op.get()); 2043 if (!OpInst) 2044 continue; 2045 2046 // Check if OpInst is in the BB and is a modeled instruction. 2047 auto OpVal = UnionFind.findValue(OpInst); 2048 if (OpVal == UnionFind.end()) 2049 continue; 2050 2051 UnionFind.unionSets(Inst, OpInst); 2052 } 2053 } 2054 } 2055 2056 /// Ensure that the order of ordered instructions does not change. 2057 /// 2058 /// If we encounter an ordered instruction enclosed in instructions belonging to 2059 /// a different statement (which might as well contain ordered instructions, but 2060 /// this is not tested here), join them. 2061 static void 2062 joinOrderedInstructions(EquivalenceClasses<Instruction *> &UnionFind, 2063 ArrayRef<Instruction *> ModeledInsts) { 2064 SetVector<Instruction *> SeenLeaders; 2065 for (Instruction *Inst : ModeledInsts) { 2066 if (!isOrderedInstruction(Inst)) 2067 continue; 2068 2069 Instruction *Leader = UnionFind.getLeaderValue(Inst); 2070 // Since previous iterations might have merged sets, some items in 2071 // SeenLeaders are not leaders anymore. However, The new leader of 2072 // previously merged instructions must be one of the former leaders of 2073 // these merged instructions. 2074 bool Inserted = SeenLeaders.insert(Leader); 2075 if (Inserted) 2076 continue; 2077 2078 // Merge statements to close holes. Say, we have already seen statements A 2079 // and B, in this order. Then we see an instruction of A again and we would 2080 // see the pattern "A B A". This function joins all statements until the 2081 // only seen occurrence of A. 2082 for (Instruction *Prev : reverse(SeenLeaders)) { 2083 // We are backtracking from the last element until we see Inst's leader 2084 // in SeenLeaders and merge all into one set. Although leaders of 2085 // instructions change during the execution of this loop, it's irrelevant 2086 // as we are just searching for the element that we already confirmed is 2087 // in the list. 2088 if (Prev == Leader) 2089 break; 2090 UnionFind.unionSets(Prev, Leader); 2091 } 2092 } 2093 } 2094 2095 /// If the BasicBlock has an edge from itself, ensure that the PHI WRITEs for 2096 /// the incoming values from this block are executed after the PHI READ. 2097 /// 2098 /// Otherwise it could overwrite the incoming value from before the BB with the 2099 /// value for the next execution. This can happen if the PHI WRITE is added to 2100 /// the statement with the instruction that defines the incoming value (instead 2101 /// of the last statement of the same BB). To ensure that the PHI READ and WRITE 2102 /// are in order, we put both into the statement. PHI WRITEs are always executed 2103 /// after PHI READs when they are in the same statement. 2104 /// 2105 /// TODO: This is an overpessimization. We only have to ensure that the PHI 2106 /// WRITE is not put into a statement containing the PHI itself. That could also 2107 /// be done by 2108 /// - having all (strongly connected) PHIs in a single statement, 2109 /// - unite only the PHIs in the operand tree of the PHI WRITE (because it only 2110 /// has a chance of being lifted before a PHI by being in a statement with a 2111 /// PHI that comes before in the basic block), or 2112 /// - when uniting statements, ensure that no (relevant) PHIs are overtaken. 2113 static void joinOrderedPHIs(EquivalenceClasses<Instruction *> &UnionFind, 2114 ArrayRef<Instruction *> ModeledInsts) { 2115 for (Instruction *Inst : ModeledInsts) { 2116 PHINode *PHI = dyn_cast<PHINode>(Inst); 2117 if (!PHI) 2118 continue; 2119 2120 int Idx = PHI->getBasicBlockIndex(PHI->getParent()); 2121 if (Idx < 0) 2122 continue; 2123 2124 Instruction *IncomingVal = 2125 dyn_cast<Instruction>(PHI->getIncomingValue(Idx)); 2126 if (!IncomingVal) 2127 continue; 2128 2129 UnionFind.unionSets(PHI, IncomingVal); 2130 } 2131 } 2132 2133 void ScopBuilder::buildEqivClassBlockStmts(BasicBlock *BB) { 2134 Loop *L = LI.getLoopFor(BB); 2135 2136 // Extracting out modeled instructions saves us from checking 2137 // shouldModelInst() repeatedly. 2138 SmallVector<Instruction *, 32> ModeledInsts; 2139 EquivalenceClasses<Instruction *> UnionFind; 2140 Instruction *MainInst = nullptr, *MainLeader = nullptr; 2141 for (Instruction &Inst : *BB) { 2142 if (!shouldModelInst(&Inst, L)) 2143 continue; 2144 ModeledInsts.push_back(&Inst); 2145 UnionFind.insert(&Inst); 2146 2147 // When a BB is split into multiple statements, the main statement is the 2148 // one containing the 'main' instruction. We select the first instruction 2149 // that is unlikely to be removed (because it has side-effects) as the main 2150 // one. It is used to ensure that at least one statement from the bb has the 2151 // same name as with -polly-stmt-granularity=bb. 2152 if (!MainInst && (isa<StoreInst>(Inst) || 2153 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))) 2154 MainInst = &Inst; 2155 } 2156 2157 joinOperandTree(UnionFind, ModeledInsts); 2158 joinOrderedInstructions(UnionFind, ModeledInsts); 2159 joinOrderedPHIs(UnionFind, ModeledInsts); 2160 2161 // The list of instructions for statement (statement represented by the leader 2162 // instruction). 2163 MapVector<Instruction *, std::vector<Instruction *>> LeaderToInstList; 2164 2165 // The order of statements must be preserved w.r.t. their ordered 2166 // instructions. Without this explicit scan, we would also use non-ordered 2167 // instructions (whose order is arbitrary) to determine statement order. 2168 for (Instruction *Inst : ModeledInsts) { 2169 if (!isOrderedInstruction(Inst)) 2170 continue; 2171 2172 auto LeaderIt = UnionFind.findLeader(Inst); 2173 if (LeaderIt == UnionFind.member_end()) 2174 continue; 2175 2176 // Insert element for the leader instruction. 2177 (void)LeaderToInstList[*LeaderIt]; 2178 } 2179 2180 // Collect the instructions of all leaders. UnionFind's member iterator 2181 // unfortunately are not in any specific order. 2182 for (Instruction *Inst : ModeledInsts) { 2183 auto LeaderIt = UnionFind.findLeader(Inst); 2184 if (LeaderIt == UnionFind.member_end()) 2185 continue; 2186 2187 if (Inst == MainInst) 2188 MainLeader = *LeaderIt; 2189 std::vector<Instruction *> &InstList = LeaderToInstList[*LeaderIt]; 2190 InstList.push_back(Inst); 2191 } 2192 2193 // Finally build the statements. 2194 int Count = 0; 2195 long BBIdx = scop->getNextStmtIdx(); 2196 for (auto &Instructions : LeaderToInstList) { 2197 std::vector<Instruction *> &InstList = Instructions.second; 2198 2199 // If there is no main instruction, make the first statement the main. 2200 bool IsMain = (MainInst ? MainLeader == Instructions.first : Count == 0); 2201 2202 std::string Name = makeStmtName(BB, BBIdx, Count, IsMain); 2203 scop->addScopStmt(BB, Name, L, std::move(InstList)); 2204 Count += 1; 2205 } 2206 2207 // Unconditionally add an epilogue (last statement). It contains no 2208 // instructions, but holds the PHI write accesses for successor basic blocks, 2209 // if the incoming value is not defined in another statement if the same BB. 2210 // The epilogue becomes the main statement only if there is no other 2211 // statement that could become main. 2212 // The epilogue will be removed if no PHIWrite is added to it. 2213 std::string EpilogueName = makeStmtName(BB, BBIdx, Count, Count == 0, true); 2214 scop->addScopStmt(BB, EpilogueName, L, {}); 2215 } 2216 2217 void ScopBuilder::buildStmts(Region &SR) { 2218 if (scop->isNonAffineSubRegion(&SR)) { 2219 std::vector<Instruction *> Instructions; 2220 Loop *SurroundingLoop = 2221 getFirstNonBoxedLoopFor(SR.getEntry(), LI, scop->getBoxedLoops()); 2222 for (Instruction &Inst : *SR.getEntry()) 2223 if (shouldModelInst(&Inst, SurroundingLoop)) 2224 Instructions.push_back(&Inst); 2225 long RIdx = scop->getNextStmtIdx(); 2226 std::string Name = makeStmtName(&SR, RIdx); 2227 scop->addScopStmt(&SR, Name, SurroundingLoop, Instructions); 2228 return; 2229 } 2230 2231 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I) 2232 if (I->isSubRegion()) 2233 buildStmts(*I->getNodeAs<Region>()); 2234 else { 2235 BasicBlock *BB = I->getNodeAs<BasicBlock>(); 2236 switch (StmtGranularity) { 2237 case GranularityChoice::BasicBlocks: 2238 buildSequentialBlockStmts(BB); 2239 break; 2240 case GranularityChoice::ScalarIndependence: 2241 buildEqivClassBlockStmts(BB); 2242 break; 2243 case GranularityChoice::Stores: 2244 buildSequentialBlockStmts(BB, true); 2245 break; 2246 } 2247 } 2248 } 2249 2250 void ScopBuilder::buildAccessFunctions(ScopStmt *Stmt, BasicBlock &BB, 2251 Region *NonAffineSubRegion) { 2252 assert( 2253 Stmt && 2254 "The exit BB is the only one that cannot be represented by a statement"); 2255 assert(Stmt->represents(&BB)); 2256 2257 // We do not build access functions for error blocks, as they may contain 2258 // instructions we can not model. 2259 if (isErrorBlock(BB, scop->getRegion(), LI, DT)) 2260 return; 2261 2262 auto BuildAccessesForInst = [this, Stmt, 2263 NonAffineSubRegion](Instruction *Inst) { 2264 PHINode *PHI = dyn_cast<PHINode>(Inst); 2265 if (PHI) 2266 buildPHIAccesses(Stmt, PHI, NonAffineSubRegion, false); 2267 2268 if (auto MemInst = MemAccInst::dyn_cast(*Inst)) { 2269 assert(Stmt && "Cannot build access function in non-existing statement"); 2270 buildMemoryAccess(MemInst, Stmt); 2271 } 2272 2273 // PHI nodes have already been modeled above and terminators that are 2274 // not part of a non-affine subregion are fully modeled and regenerated 2275 // from the polyhedral domains. Hence, they do not need to be modeled as 2276 // explicit data dependences. 2277 if (!PHI) 2278 buildScalarDependences(Stmt, Inst); 2279 }; 2280 2281 const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads(); 2282 bool IsEntryBlock = (Stmt->getEntryBlock() == &BB); 2283 if (IsEntryBlock) { 2284 for (Instruction *Inst : Stmt->getInstructions()) 2285 BuildAccessesForInst(Inst); 2286 if (Stmt->isRegionStmt()) 2287 BuildAccessesForInst(BB.getTerminator()); 2288 } else { 2289 for (Instruction &Inst : BB) { 2290 if (isIgnoredIntrinsic(&Inst)) 2291 continue; 2292 2293 // Invariant loads already have been processed. 2294 if (isa<LoadInst>(Inst) && RIL.count(cast<LoadInst>(&Inst))) 2295 continue; 2296 2297 BuildAccessesForInst(&Inst); 2298 } 2299 } 2300 } 2301 2302 MemoryAccess *ScopBuilder::addMemoryAccess( 2303 ScopStmt *Stmt, Instruction *Inst, MemoryAccess::AccessType AccType, 2304 Value *BaseAddress, Type *ElementType, bool Affine, Value *AccessValue, 2305 ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes, 2306 MemoryKind Kind) { 2307 bool isKnownMustAccess = false; 2308 2309 // Accesses in single-basic block statements are always executed. 2310 if (Stmt->isBlockStmt()) 2311 isKnownMustAccess = true; 2312 2313 if (Stmt->isRegionStmt()) { 2314 // Accesses that dominate the exit block of a non-affine region are always 2315 // executed. In non-affine regions there may exist MemoryKind::Values that 2316 // do not dominate the exit. MemoryKind::Values will always dominate the 2317 // exit and MemoryKind::PHIs only if there is at most one PHI_WRITE in the 2318 // non-affine region. 2319 if (Inst && DT.dominates(Inst->getParent(), Stmt->getRegion()->getExit())) 2320 isKnownMustAccess = true; 2321 } 2322 2323 // Non-affine PHI writes do not "happen" at a particular instruction, but 2324 // after exiting the statement. Therefore they are guaranteed to execute and 2325 // overwrite the old value. 2326 if (Kind == MemoryKind::PHI || Kind == MemoryKind::ExitPHI) 2327 isKnownMustAccess = true; 2328 2329 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE) 2330 AccType = MemoryAccess::MAY_WRITE; 2331 2332 auto *Access = new MemoryAccess(Stmt, Inst, AccType, BaseAddress, ElementType, 2333 Affine, Subscripts, Sizes, AccessValue, Kind); 2334 2335 scop->addAccessFunction(Access); 2336 Stmt->addAccess(Access); 2337 return Access; 2338 } 2339 2340 void ScopBuilder::addArrayAccess(ScopStmt *Stmt, MemAccInst MemAccInst, 2341 MemoryAccess::AccessType AccType, 2342 Value *BaseAddress, Type *ElementType, 2343 bool IsAffine, 2344 ArrayRef<const SCEV *> Subscripts, 2345 ArrayRef<const SCEV *> Sizes, 2346 Value *AccessValue) { 2347 ArrayBasePointers.insert(BaseAddress); 2348 auto *MemAccess = addMemoryAccess(Stmt, MemAccInst, AccType, BaseAddress, 2349 ElementType, IsAffine, AccessValue, 2350 Subscripts, Sizes, MemoryKind::Array); 2351 2352 if (!DetectFortranArrays) 2353 return; 2354 2355 if (Value *FAD = findFADAllocationInvisible(MemAccInst)) 2356 MemAccess->setFortranArrayDescriptor(FAD); 2357 else if (Value *FAD = findFADAllocationVisible(MemAccInst)) 2358 MemAccess->setFortranArrayDescriptor(FAD); 2359 } 2360 2361 /// Check if @p Expr is divisible by @p Size. 2362 static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) { 2363 assert(Size != 0); 2364 if (Size == 1) 2365 return true; 2366 2367 // Only one factor needs to be divisible. 2368 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) { 2369 for (auto *FactorExpr : MulExpr->operands()) 2370 if (isDivisible(FactorExpr, Size, SE)) 2371 return true; 2372 return false; 2373 } 2374 2375 // For other n-ary expressions (Add, AddRec, Max,...) all operands need 2376 // to be divisible. 2377 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) { 2378 for (auto *OpExpr : NAryExpr->operands()) 2379 if (!isDivisible(OpExpr, Size, SE)) 2380 return false; 2381 return true; 2382 } 2383 2384 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size); 2385 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV); 2386 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV); 2387 return MulSCEV == Expr; 2388 } 2389 2390 void ScopBuilder::foldSizeConstantsToRight() { 2391 isl::union_set Accessed = scop->getAccesses().range(); 2392 2393 for (auto Array : scop->arrays()) { 2394 if (Array->getNumberOfDimensions() <= 1) 2395 continue; 2396 2397 isl::space Space = Array->getSpace(); 2398 Space = Space.align_params(Accessed.get_space()); 2399 2400 if (!Accessed.contains(Space)) 2401 continue; 2402 2403 isl::set Elements = Accessed.extract_set(Space); 2404 isl::map Transform = isl::map::universe(Array->getSpace().map_from_set()); 2405 2406 std::vector<int> Int; 2407 int Dims = Elements.dim(isl::dim::set); 2408 for (int i = 0; i < Dims; i++) { 2409 isl::set DimOnly = isl::set(Elements).project_out(isl::dim::set, 0, i); 2410 DimOnly = DimOnly.project_out(isl::dim::set, 1, Dims - i - 1); 2411 DimOnly = DimOnly.lower_bound_si(isl::dim::set, 0, 0); 2412 2413 isl::basic_set DimHull = DimOnly.affine_hull(); 2414 2415 if (i == Dims - 1) { 2416 Int.push_back(1); 2417 Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i); 2418 continue; 2419 } 2420 2421 if (DimHull.dim(isl::dim::div) == 1) { 2422 isl::aff Diff = DimHull.get_div(0); 2423 isl::val Val = Diff.get_denominator_val(); 2424 2425 int ValInt = 1; 2426 if (Val.is_int()) { 2427 auto ValAPInt = APIntFromVal(Val); 2428 if (ValAPInt.isSignedIntN(32)) 2429 ValInt = ValAPInt.getSExtValue(); 2430 } else { 2431 } 2432 2433 Int.push_back(ValInt); 2434 isl::constraint C = isl::constraint::alloc_equality( 2435 isl::local_space(Transform.get_space())); 2436 C = C.set_coefficient_si(isl::dim::out, i, ValInt); 2437 C = C.set_coefficient_si(isl::dim::in, i, -1); 2438 Transform = Transform.add_constraint(C); 2439 continue; 2440 } 2441 2442 isl::basic_set ZeroSet = isl::basic_set(DimHull); 2443 ZeroSet = ZeroSet.fix_si(isl::dim::set, 0, 0); 2444 2445 int ValInt = 1; 2446 if (ZeroSet.is_equal(DimHull)) { 2447 ValInt = 0; 2448 } 2449 2450 Int.push_back(ValInt); 2451 Transform = Transform.equate(isl::dim::in, i, isl::dim::out, i); 2452 } 2453 2454 isl::set MappedElements = isl::map(Transform).domain(); 2455 if (!Elements.is_subset(MappedElements)) 2456 continue; 2457 2458 bool CanFold = true; 2459 if (Int[0] <= 1) 2460 CanFold = false; 2461 2462 unsigned NumDims = Array->getNumberOfDimensions(); 2463 for (unsigned i = 1; i < NumDims - 1; i++) 2464 if (Int[0] != Int[i] && Int[i]) 2465 CanFold = false; 2466 2467 if (!CanFold) 2468 continue; 2469 2470 for (auto &Access : scop->access_functions()) 2471 if (Access->getScopArrayInfo() == Array) 2472 Access->setAccessRelation( 2473 Access->getAccessRelation().apply_range(Transform)); 2474 2475 std::vector<const SCEV *> Sizes; 2476 for (unsigned i = 0; i < NumDims; i++) { 2477 auto Size = Array->getDimensionSize(i); 2478 2479 if (i == NumDims - 1) 2480 Size = SE.getMulExpr(Size, SE.getConstant(Size->getType(), Int[0])); 2481 Sizes.push_back(Size); 2482 } 2483 2484 Array->updateSizes(Sizes, false /* CheckConsistency */); 2485 } 2486 } 2487 2488 void ScopBuilder::markFortranArrays() { 2489 for (ScopStmt &Stmt : *scop) { 2490 for (MemoryAccess *MemAcc : Stmt) { 2491 Value *FAD = MemAcc->getFortranArrayDescriptor(); 2492 if (!FAD) 2493 continue; 2494 2495 // TODO: const_cast-ing to edit 2496 ScopArrayInfo *SAI = 2497 const_cast<ScopArrayInfo *>(MemAcc->getLatestScopArrayInfo()); 2498 assert(SAI && "memory access into a Fortran array does not " 2499 "have an associated ScopArrayInfo"); 2500 SAI->applyAndSetFAD(FAD); 2501 } 2502 } 2503 } 2504 2505 void ScopBuilder::finalizeAccesses() { 2506 updateAccessDimensionality(); 2507 foldSizeConstantsToRight(); 2508 foldAccessRelations(); 2509 assumeNoOutOfBounds(); 2510 markFortranArrays(); 2511 } 2512 2513 void ScopBuilder::updateAccessDimensionality() { 2514 // Check all array accesses for each base pointer and find a (virtual) element 2515 // size for the base pointer that divides all access functions. 2516 for (ScopStmt &Stmt : *scop) 2517 for (MemoryAccess *Access : Stmt) { 2518 if (!Access->isArrayKind()) 2519 continue; 2520 ScopArrayInfo *Array = 2521 const_cast<ScopArrayInfo *>(Access->getScopArrayInfo()); 2522 2523 if (Array->getNumberOfDimensions() != 1) 2524 continue; 2525 unsigned DivisibleSize = Array->getElemSizeInBytes(); 2526 const SCEV *Subscript = Access->getSubscript(0); 2527 while (!isDivisible(Subscript, DivisibleSize, SE)) 2528 DivisibleSize /= 2; 2529 auto *Ty = IntegerType::get(SE.getContext(), DivisibleSize * 8); 2530 Array->updateElementType(Ty); 2531 } 2532 2533 for (auto &Stmt : *scop) 2534 for (auto &Access : Stmt) 2535 Access->updateDimensionality(); 2536 } 2537 2538 void ScopBuilder::foldAccessRelations() { 2539 for (auto &Stmt : *scop) 2540 for (auto &Access : Stmt) 2541 Access->foldAccessRelation(); 2542 } 2543 2544 void ScopBuilder::assumeNoOutOfBounds() { 2545 if (PollyIgnoreInbounds) 2546 return; 2547 for (auto &Stmt : *scop) 2548 for (auto &Access : Stmt) { 2549 isl::set Outside = Access->assumeNoOutOfBound(); 2550 const auto &Loc = Access->getAccessInstruction() 2551 ? Access->getAccessInstruction()->getDebugLoc() 2552 : DebugLoc(); 2553 recordAssumption(&RecordedAssumptions, INBOUNDS, Outside, Loc, 2554 AS_ASSUMPTION); 2555 } 2556 } 2557 2558 void ScopBuilder::ensureValueWrite(Instruction *Inst) { 2559 // Find the statement that defines the value of Inst. That statement has to 2560 // write the value to make it available to those statements that read it. 2561 ScopStmt *Stmt = scop->getStmtFor(Inst); 2562 2563 // It is possible that the value is synthesizable within a loop (such that it 2564 // is not part of any statement), but not after the loop (where you need the 2565 // number of loop round-trips to synthesize it). In LCSSA-form a PHI node will 2566 // avoid this. In case the IR has no such PHI, use the last statement (where 2567 // the value is synthesizable) to write the value. 2568 if (!Stmt) 2569 Stmt = scop->getLastStmtFor(Inst->getParent()); 2570 2571 // Inst not defined within this SCoP. 2572 if (!Stmt) 2573 return; 2574 2575 // Do not process further if the instruction is already written. 2576 if (Stmt->lookupValueWriteOf(Inst)) 2577 return; 2578 2579 addMemoryAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, Inst, Inst->getType(), 2580 true, Inst, ArrayRef<const SCEV *>(), 2581 ArrayRef<const SCEV *>(), MemoryKind::Value); 2582 } 2583 2584 void ScopBuilder::ensureValueRead(Value *V, ScopStmt *UserStmt) { 2585 // TODO: Make ScopStmt::ensureValueRead(Value*) offer the same functionality 2586 // to be able to replace this one. Currently, there is a split responsibility. 2587 // In a first step, the MemoryAccess is created, but without the 2588 // AccessRelation. In the second step by ScopStmt::buildAccessRelations(), the 2589 // AccessRelation is created. At least for scalar accesses, there is no new 2590 // information available at ScopStmt::buildAccessRelations(), so we could 2591 // create the AccessRelation right away. This is what 2592 // ScopStmt::ensureValueRead(Value*) does. 2593 2594 auto *Scope = UserStmt->getSurroundingLoop(); 2595 auto VUse = VirtualUse::create(scop.get(), UserStmt, Scope, V, false); 2596 switch (VUse.getKind()) { 2597 case VirtualUse::Constant: 2598 case VirtualUse::Block: 2599 case VirtualUse::Synthesizable: 2600 case VirtualUse::Hoisted: 2601 case VirtualUse::Intra: 2602 // Uses of these kinds do not need a MemoryAccess. 2603 break; 2604 2605 case VirtualUse::ReadOnly: 2606 // Add MemoryAccess for invariant values only if requested. 2607 if (!ModelReadOnlyScalars) 2608 break; 2609 2610 LLVM_FALLTHROUGH; 2611 case VirtualUse::Inter: 2612 2613 // Do not create another MemoryAccess for reloading the value if one already 2614 // exists. 2615 if (UserStmt->lookupValueReadOf(V)) 2616 break; 2617 2618 addMemoryAccess(UserStmt, nullptr, MemoryAccess::READ, V, V->getType(), 2619 true, V, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), 2620 MemoryKind::Value); 2621 2622 // Inter-statement uses need to write the value in their defining statement. 2623 if (VUse.isInter()) 2624 ensureValueWrite(cast<Instruction>(V)); 2625 break; 2626 } 2627 } 2628 2629 void ScopBuilder::ensurePHIWrite(PHINode *PHI, ScopStmt *IncomingStmt, 2630 BasicBlock *IncomingBlock, 2631 Value *IncomingValue, bool IsExitBlock) { 2632 // As the incoming block might turn out to be an error statement ensure we 2633 // will create an exit PHI SAI object. It is needed during code generation 2634 // and would be created later anyway. 2635 if (IsExitBlock) 2636 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {}, 2637 MemoryKind::ExitPHI); 2638 2639 // This is possible if PHI is in the SCoP's entry block. The incoming blocks 2640 // from outside the SCoP's region have no statement representation. 2641 if (!IncomingStmt) 2642 return; 2643 2644 // Take care for the incoming value being available in the incoming block. 2645 // This must be done before the check for multiple PHI writes because multiple 2646 // exiting edges from subregion each can be the effective written value of the 2647 // subregion. As such, all of them must be made available in the subregion 2648 // statement. 2649 ensureValueRead(IncomingValue, IncomingStmt); 2650 2651 // Do not add more than one MemoryAccess per PHINode and ScopStmt. 2652 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) { 2653 assert(Acc->getAccessInstruction() == PHI); 2654 Acc->addIncoming(IncomingBlock, IncomingValue); 2655 return; 2656 } 2657 2658 MemoryAccess *Acc = addMemoryAccess( 2659 IncomingStmt, PHI, MemoryAccess::MUST_WRITE, PHI, PHI->getType(), true, 2660 PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), 2661 IsExitBlock ? MemoryKind::ExitPHI : MemoryKind::PHI); 2662 assert(Acc); 2663 Acc->addIncoming(IncomingBlock, IncomingValue); 2664 } 2665 2666 void ScopBuilder::addPHIReadAccess(ScopStmt *PHIStmt, PHINode *PHI) { 2667 addMemoryAccess(PHIStmt, PHI, MemoryAccess::READ, PHI, PHI->getType(), true, 2668 PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), 2669 MemoryKind::PHI); 2670 } 2671 2672 void ScopBuilder::buildDomain(ScopStmt &Stmt) { 2673 isl::id Id = isl::id::alloc(scop->getIslCtx(), Stmt.getBaseName(), &Stmt); 2674 2675 Stmt.Domain = scop->getDomainConditions(&Stmt); 2676 Stmt.Domain = Stmt.Domain.set_tuple_id(Id); 2677 } 2678 2679 void ScopBuilder::collectSurroundingLoops(ScopStmt &Stmt) { 2680 isl::set Domain = Stmt.getDomain(); 2681 BasicBlock *BB = Stmt.getEntryBlock(); 2682 2683 Loop *L = LI.getLoopFor(BB); 2684 2685 while (L && Stmt.isRegionStmt() && Stmt.getRegion()->contains(L)) 2686 L = L->getParentLoop(); 2687 2688 SmallVector<llvm::Loop *, 8> Loops; 2689 2690 while (L && Stmt.getParent()->getRegion().contains(L)) { 2691 Loops.push_back(L); 2692 L = L->getParentLoop(); 2693 } 2694 2695 Stmt.NestLoops.insert(Stmt.NestLoops.begin(), Loops.rbegin(), Loops.rend()); 2696 } 2697 2698 /// Return the reduction type for a given binary operator. 2699 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp, 2700 const Instruction *Load) { 2701 if (!BinOp) 2702 return MemoryAccess::RT_NONE; 2703 switch (BinOp->getOpcode()) { 2704 case Instruction::FAdd: 2705 if (!BinOp->isFast()) 2706 return MemoryAccess::RT_NONE; 2707 LLVM_FALLTHROUGH; 2708 case Instruction::Add: 2709 return MemoryAccess::RT_ADD; 2710 case Instruction::Or: 2711 return MemoryAccess::RT_BOR; 2712 case Instruction::Xor: 2713 return MemoryAccess::RT_BXOR; 2714 case Instruction::And: 2715 return MemoryAccess::RT_BAND; 2716 case Instruction::FMul: 2717 if (!BinOp->isFast()) 2718 return MemoryAccess::RT_NONE; 2719 LLVM_FALLTHROUGH; 2720 case Instruction::Mul: 2721 if (DisableMultiplicativeReductions) 2722 return MemoryAccess::RT_NONE; 2723 return MemoryAccess::RT_MUL; 2724 default: 2725 return MemoryAccess::RT_NONE; 2726 } 2727 } 2728 2729 void ScopBuilder::checkForReductions(ScopStmt &Stmt) { 2730 SmallVector<MemoryAccess *, 2> Loads; 2731 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates; 2732 2733 // First collect candidate load-store reduction chains by iterating over all 2734 // stores and collecting possible reduction loads. 2735 for (MemoryAccess *StoreMA : Stmt) { 2736 if (StoreMA->isRead()) 2737 continue; 2738 2739 Loads.clear(); 2740 collectCandidateReductionLoads(StoreMA, Loads); 2741 for (MemoryAccess *LoadMA : Loads) 2742 Candidates.push_back(std::make_pair(LoadMA, StoreMA)); 2743 } 2744 2745 // Then check each possible candidate pair. 2746 for (const auto &CandidatePair : Candidates) { 2747 bool Valid = true; 2748 isl::map LoadAccs = CandidatePair.first->getAccessRelation(); 2749 isl::map StoreAccs = CandidatePair.second->getAccessRelation(); 2750 2751 // Skip those with obviously unequal base addresses. 2752 if (!LoadAccs.has_equal_space(StoreAccs)) { 2753 continue; 2754 } 2755 2756 // And check if the remaining for overlap with other memory accesses. 2757 isl::map AllAccsRel = LoadAccs.unite(StoreAccs); 2758 AllAccsRel = AllAccsRel.intersect_domain(Stmt.getDomain()); 2759 isl::set AllAccs = AllAccsRel.range(); 2760 2761 for (MemoryAccess *MA : Stmt) { 2762 if (MA == CandidatePair.first || MA == CandidatePair.second) 2763 continue; 2764 2765 isl::map AccRel = 2766 MA->getAccessRelation().intersect_domain(Stmt.getDomain()); 2767 isl::set Accs = AccRel.range(); 2768 2769 if (AllAccs.has_equal_space(Accs)) { 2770 isl::set OverlapAccs = Accs.intersect(AllAccs); 2771 Valid = Valid && OverlapAccs.is_empty(); 2772 } 2773 } 2774 2775 if (!Valid) 2776 continue; 2777 2778 const LoadInst *Load = 2779 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction()); 2780 MemoryAccess::ReductionType RT = 2781 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load); 2782 2783 // If no overlapping access was found we mark the load and store as 2784 // reduction like. 2785 CandidatePair.first->markAsReductionLike(RT); 2786 CandidatePair.second->markAsReductionLike(RT); 2787 } 2788 } 2789 2790 void ScopBuilder::verifyInvariantLoads() { 2791 auto &RIL = scop->getRequiredInvariantLoads(); 2792 for (LoadInst *LI : RIL) { 2793 assert(LI && scop->contains(LI)); 2794 // If there exists a statement in the scop which has a memory access for 2795 // @p LI, then mark this scop as infeasible for optimization. 2796 for (ScopStmt &Stmt : *scop) 2797 if (Stmt.getArrayAccessOrNULLFor(LI)) { 2798 scop->invalidate(INVARIANTLOAD, LI->getDebugLoc(), LI->getParent()); 2799 return; 2800 } 2801 } 2802 } 2803 2804 void ScopBuilder::hoistInvariantLoads() { 2805 if (!PollyInvariantLoadHoisting) 2806 return; 2807 2808 isl::union_map Writes = scop->getWrites(); 2809 for (ScopStmt &Stmt : *scop) { 2810 InvariantAccessesTy InvariantAccesses; 2811 2812 for (MemoryAccess *Access : Stmt) { 2813 isl::set NHCtx = getNonHoistableCtx(Access, Writes); 2814 if (!NHCtx.is_null()) 2815 InvariantAccesses.push_back({Access, NHCtx}); 2816 } 2817 2818 // Transfer the memory access from the statement to the SCoP. 2819 for (auto InvMA : InvariantAccesses) 2820 Stmt.removeMemoryAccess(InvMA.MA); 2821 addInvariantLoads(Stmt, InvariantAccesses); 2822 } 2823 } 2824 2825 /// Check if an access range is too complex. 2826 /// 2827 /// An access range is too complex, if it contains either many disjuncts or 2828 /// very complex expressions. As a simple heuristic, we assume if a set to 2829 /// be too complex if the sum of existentially quantified dimensions and 2830 /// set dimensions is larger than a threshold. This reliably detects both 2831 /// sets with many disjuncts as well as sets with many divisions as they 2832 /// arise in h264. 2833 /// 2834 /// @param AccessRange The range to check for complexity. 2835 /// 2836 /// @returns True if the access range is too complex. 2837 static bool isAccessRangeTooComplex(isl::set AccessRange) { 2838 int NumTotalDims = 0; 2839 2840 for (isl::basic_set BSet : AccessRange.get_basic_set_list()) { 2841 NumTotalDims += BSet.dim(isl::dim::div); 2842 NumTotalDims += BSet.dim(isl::dim::set); 2843 } 2844 2845 if (NumTotalDims > MaxDimensionsInAccessRange) 2846 return true; 2847 2848 return false; 2849 } 2850 2851 bool ScopBuilder::hasNonHoistableBasePtrInScop(MemoryAccess *MA, 2852 isl::union_map Writes) { 2853 if (auto *BasePtrMA = scop->lookupBasePtrAccess(MA)) { 2854 return getNonHoistableCtx(BasePtrMA, Writes).is_null(); 2855 } 2856 2857 Value *BaseAddr = MA->getOriginalBaseAddr(); 2858 if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr)) 2859 if (!isa<LoadInst>(BasePtrInst)) 2860 return scop->contains(BasePtrInst); 2861 2862 return false; 2863 } 2864 2865 void ScopBuilder::addUserContext() { 2866 if (UserContextStr.empty()) 2867 return; 2868 2869 isl::set UserContext = isl::set(scop->getIslCtx(), UserContextStr.c_str()); 2870 isl::space Space = scop->getParamSpace(); 2871 if (Space.dim(isl::dim::param) != UserContext.dim(isl::dim::param)) { 2872 std::string SpaceStr = Space.to_str(); 2873 errs() << "Error: the context provided in -polly-context has not the same " 2874 << "number of dimensions than the computed context. Due to this " 2875 << "mismatch, the -polly-context option is ignored. Please provide " 2876 << "the context in the parameter space: " << SpaceStr << ".\n"; 2877 return; 2878 } 2879 2880 for (auto i : seq<isl_size>(0, Space.dim(isl::dim::param))) { 2881 std::string NameContext = 2882 scop->getContext().get_dim_name(isl::dim::param, i); 2883 std::string NameUserContext = UserContext.get_dim_name(isl::dim::param, i); 2884 2885 if (NameContext != NameUserContext) { 2886 std::string SpaceStr = Space.to_str(); 2887 errs() << "Error: the name of dimension " << i 2888 << " provided in -polly-context " 2889 << "is '" << NameUserContext << "', but the name in the computed " 2890 << "context is '" << NameContext 2891 << "'. Due to this name mismatch, " 2892 << "the -polly-context option is ignored. Please provide " 2893 << "the context in the parameter space: " << SpaceStr << ".\n"; 2894 return; 2895 } 2896 2897 UserContext = UserContext.set_dim_id(isl::dim::param, i, 2898 Space.get_dim_id(isl::dim::param, i)); 2899 } 2900 isl::set newContext = scop->getContext().intersect(UserContext); 2901 scop->setContext(newContext); 2902 } 2903 2904 isl::set ScopBuilder::getNonHoistableCtx(MemoryAccess *Access, 2905 isl::union_map Writes) { 2906 // TODO: Loads that are not loop carried, hence are in a statement with 2907 // zero iterators, are by construction invariant, though we 2908 // currently "hoist" them anyway. This is necessary because we allow 2909 // them to be treated as parameters (e.g., in conditions) and our code 2910 // generation would otherwise use the old value. 2911 2912 auto &Stmt = *Access->getStatement(); 2913 BasicBlock *BB = Stmt.getEntryBlock(); 2914 2915 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() || 2916 Access->isMemoryIntrinsic()) 2917 return {}; 2918 2919 // Skip accesses that have an invariant base pointer which is defined but 2920 // not loaded inside the SCoP. This can happened e.g., if a readnone call 2921 // returns a pointer that is used as a base address. However, as we want 2922 // to hoist indirect pointers, we allow the base pointer to be defined in 2923 // the region if it is also a memory access. Each ScopArrayInfo object 2924 // that has a base pointer origin has a base pointer that is loaded and 2925 // that it is invariant, thus it will be hoisted too. However, if there is 2926 // no base pointer origin we check that the base pointer is defined 2927 // outside the region. 2928 auto *LI = cast<LoadInst>(Access->getAccessInstruction()); 2929 if (hasNonHoistableBasePtrInScop(Access, Writes)) 2930 return {}; 2931 2932 isl::map AccessRelation = Access->getAccessRelation(); 2933 assert(!AccessRelation.is_empty()); 2934 2935 if (AccessRelation.involves_dims(isl::dim::in, 0, Stmt.getNumIterators())) 2936 return {}; 2937 2938 AccessRelation = AccessRelation.intersect_domain(Stmt.getDomain()); 2939 isl::set SafeToLoad; 2940 2941 auto &DL = scop->getFunction().getParent()->getDataLayout(); 2942 if (isSafeToLoadUnconditionally(LI->getPointerOperand(), LI->getType(), 2943 LI->getAlign(), DL)) { 2944 SafeToLoad = isl::set::universe(AccessRelation.get_space().range()); 2945 } else if (BB != LI->getParent()) { 2946 // Skip accesses in non-affine subregions as they might not be executed 2947 // under the same condition as the entry of the non-affine subregion. 2948 return {}; 2949 } else { 2950 SafeToLoad = AccessRelation.range(); 2951 } 2952 2953 if (isAccessRangeTooComplex(AccessRelation.range())) 2954 return {}; 2955 2956 isl::union_map Written = Writes.intersect_range(SafeToLoad); 2957 isl::set WrittenCtx = Written.params(); 2958 bool IsWritten = !WrittenCtx.is_empty(); 2959 2960 if (!IsWritten) 2961 return WrittenCtx; 2962 2963 WrittenCtx = WrittenCtx.remove_divs(); 2964 bool TooComplex = WrittenCtx.n_basic_set() >= MaxDisjunctsInDomain; 2965 if (TooComplex || !isRequiredInvariantLoad(LI)) 2966 return {}; 2967 2968 scop->addAssumption(INVARIANTLOAD, WrittenCtx, LI->getDebugLoc(), 2969 AS_RESTRICTION, LI->getParent()); 2970 return WrittenCtx; 2971 } 2972 2973 static bool isAParameter(llvm::Value *maybeParam, const Function &F) { 2974 for (const llvm::Argument &Arg : F.args()) 2975 if (&Arg == maybeParam) 2976 return true; 2977 2978 return false; 2979 } 2980 2981 bool ScopBuilder::canAlwaysBeHoisted(MemoryAccess *MA, 2982 bool StmtInvalidCtxIsEmpty, 2983 bool MAInvalidCtxIsEmpty, 2984 bool NonHoistableCtxIsEmpty) { 2985 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction()); 2986 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout(); 2987 if (PollyAllowDereferenceOfAllFunctionParams && 2988 isAParameter(LInst->getPointerOperand(), scop->getFunction())) 2989 return true; 2990 2991 // TODO: We can provide more information for better but more expensive 2992 // results. 2993 if (!isDereferenceableAndAlignedPointer( 2994 LInst->getPointerOperand(), LInst->getType(), LInst->getAlign(), DL)) 2995 return false; 2996 2997 // If the location might be overwritten we do not hoist it unconditionally. 2998 // 2999 // TODO: This is probably too conservative. 3000 if (!NonHoistableCtxIsEmpty) 3001 return false; 3002 3003 // If a dereferenceable load is in a statement that is modeled precisely we 3004 // can hoist it. 3005 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty) 3006 return true; 3007 3008 // Even if the statement is not modeled precisely we can hoist the load if it 3009 // does not involve any parameters that might have been specialized by the 3010 // statement domain. 3011 for (const SCEV *Subscript : MA->subscripts()) 3012 if (!isa<SCEVConstant>(Subscript)) 3013 return false; 3014 return true; 3015 } 3016 3017 void ScopBuilder::addInvariantLoads(ScopStmt &Stmt, 3018 InvariantAccessesTy &InvMAs) { 3019 if (InvMAs.empty()) 3020 return; 3021 3022 isl::set StmtInvalidCtx = Stmt.getInvalidContext(); 3023 bool StmtInvalidCtxIsEmpty = StmtInvalidCtx.is_empty(); 3024 3025 // Get the context under which the statement is executed but remove the error 3026 // context under which this statement is reached. 3027 isl::set DomainCtx = Stmt.getDomain().params(); 3028 DomainCtx = DomainCtx.subtract(StmtInvalidCtx); 3029 3030 if (DomainCtx.n_basic_set() >= MaxDisjunctsInDomain) { 3031 auto *AccInst = InvMAs.front().MA->getAccessInstruction(); 3032 scop->invalidate(COMPLEXITY, AccInst->getDebugLoc(), AccInst->getParent()); 3033 return; 3034 } 3035 3036 // Project out all parameters that relate to loads in the statement. Otherwise 3037 // we could have cyclic dependences on the constraints under which the 3038 // hoisted loads are executed and we could not determine an order in which to 3039 // pre-load them. This happens because not only lower bounds are part of the 3040 // domain but also upper bounds. 3041 for (auto &InvMA : InvMAs) { 3042 auto *MA = InvMA.MA; 3043 Instruction *AccInst = MA->getAccessInstruction(); 3044 if (SE.isSCEVable(AccInst->getType())) { 3045 SetVector<Value *> Values; 3046 for (const SCEV *Parameter : scop->parameters()) { 3047 Values.clear(); 3048 findValues(Parameter, SE, Values); 3049 if (!Values.count(AccInst)) 3050 continue; 3051 3052 isl::id ParamId = scop->getIdForParam(Parameter); 3053 if (!ParamId.is_null()) { 3054 int Dim = DomainCtx.find_dim_by_id(isl::dim::param, ParamId); 3055 if (Dim >= 0) 3056 DomainCtx = DomainCtx.eliminate(isl::dim::param, Dim, 1); 3057 } 3058 } 3059 } 3060 } 3061 3062 for (auto &InvMA : InvMAs) { 3063 auto *MA = InvMA.MA; 3064 isl::set NHCtx = InvMA.NonHoistableCtx; 3065 3066 // Check for another invariant access that accesses the same location as 3067 // MA and if found consolidate them. Otherwise create a new equivalence 3068 // class at the end of InvariantEquivClasses. 3069 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction()); 3070 Type *Ty = LInst->getType(); 3071 const SCEV *PointerSCEV = SE.getSCEV(LInst->getPointerOperand()); 3072 3073 isl::set MAInvalidCtx = MA->getInvalidContext(); 3074 bool NonHoistableCtxIsEmpty = NHCtx.is_empty(); 3075 bool MAInvalidCtxIsEmpty = MAInvalidCtx.is_empty(); 3076 3077 isl::set MACtx; 3078 // Check if we know that this pointer can be speculatively accessed. 3079 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty, 3080 NonHoistableCtxIsEmpty)) { 3081 MACtx = isl::set::universe(DomainCtx.get_space()); 3082 } else { 3083 MACtx = DomainCtx; 3084 MACtx = MACtx.subtract(MAInvalidCtx.unite(NHCtx)); 3085 MACtx = MACtx.gist_params(scop->getContext()); 3086 } 3087 3088 bool Consolidated = false; 3089 for (auto &IAClass : scop->invariantEquivClasses()) { 3090 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType) 3091 continue; 3092 3093 // If the pointer and the type is equal check if the access function wrt. 3094 // to the domain is equal too. It can happen that the domain fixes 3095 // parameter values and these can be different for distinct part of the 3096 // SCoP. If this happens we cannot consolidate the loads but need to 3097 // create a new invariant load equivalence class. 3098 auto &MAs = IAClass.InvariantAccesses; 3099 if (!MAs.empty()) { 3100 auto *LastMA = MAs.front(); 3101 3102 isl::set AR = MA->getAccessRelation().range(); 3103 isl::set LastAR = LastMA->getAccessRelation().range(); 3104 bool SameAR = AR.is_equal(LastAR); 3105 3106 if (!SameAR) 3107 continue; 3108 } 3109 3110 // Add MA to the list of accesses that are in this class. 3111 MAs.push_front(MA); 3112 3113 Consolidated = true; 3114 3115 // Unify the execution context of the class and this statement. 3116 isl::set IAClassDomainCtx = IAClass.ExecutionContext; 3117 if (!IAClassDomainCtx.is_null()) 3118 IAClassDomainCtx = IAClassDomainCtx.unite(MACtx).coalesce(); 3119 else 3120 IAClassDomainCtx = MACtx; 3121 IAClass.ExecutionContext = IAClassDomainCtx; 3122 break; 3123 } 3124 3125 if (Consolidated) 3126 continue; 3127 3128 MACtx = MACtx.coalesce(); 3129 3130 // If we did not consolidate MA, thus did not find an equivalence class 3131 // for it, we create a new one. 3132 scop->addInvariantEquivClass( 3133 InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty}); 3134 } 3135 } 3136 3137 void ScopBuilder::collectCandidateReductionLoads( 3138 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) { 3139 ScopStmt *Stmt = StoreMA->getStatement(); 3140 3141 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction()); 3142 if (!Store) 3143 return; 3144 3145 // Skip if there is not one binary operator between the load and the store 3146 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand()); 3147 if (!BinOp) 3148 return; 3149 3150 // Skip if the binary operators has multiple uses 3151 if (BinOp->getNumUses() != 1) 3152 return; 3153 3154 // Skip if the opcode of the binary operator is not commutative/associative 3155 if (!BinOp->isCommutative() || !BinOp->isAssociative()) 3156 return; 3157 3158 // Skip if the binary operator is outside the current SCoP 3159 if (BinOp->getParent() != Store->getParent()) 3160 return; 3161 3162 // Skip if it is a multiplicative reduction and we disabled them 3163 if (DisableMultiplicativeReductions && 3164 (BinOp->getOpcode() == Instruction::Mul || 3165 BinOp->getOpcode() == Instruction::FMul)) 3166 return; 3167 3168 // Check the binary operator operands for a candidate load 3169 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0)); 3170 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1)); 3171 if (!PossibleLoad0 && !PossibleLoad1) 3172 return; 3173 3174 // A load is only a candidate if it cannot escape (thus has only this use) 3175 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1) 3176 if (PossibleLoad0->getParent() == Store->getParent()) 3177 Loads.push_back(&Stmt->getArrayAccessFor(PossibleLoad0)); 3178 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1) 3179 if (PossibleLoad1->getParent() == Store->getParent()) 3180 Loads.push_back(&Stmt->getArrayAccessFor(PossibleLoad1)); 3181 } 3182 3183 /// Find the canonical scop array info object for a set of invariant load 3184 /// hoisted loads. The canonical array is the one that corresponds to the 3185 /// first load in the list of accesses which is used as base pointer of a 3186 /// scop array. 3187 static const ScopArrayInfo *findCanonicalArray(Scop &S, 3188 MemoryAccessList &Accesses) { 3189 for (MemoryAccess *Access : Accesses) { 3190 const ScopArrayInfo *CanonicalArray = S.getScopArrayInfoOrNull( 3191 Access->getAccessInstruction(), MemoryKind::Array); 3192 if (CanonicalArray) 3193 return CanonicalArray; 3194 } 3195 return nullptr; 3196 } 3197 3198 /// Check if @p Array severs as base array in an invariant load. 3199 static bool isUsedForIndirectHoistedLoad(Scop &S, const ScopArrayInfo *Array) { 3200 for (InvariantEquivClassTy &EqClass2 : S.getInvariantAccesses()) 3201 for (MemoryAccess *Access2 : EqClass2.InvariantAccesses) 3202 if (Access2->getScopArrayInfo() == Array) 3203 return true; 3204 return false; 3205 } 3206 3207 /// Replace the base pointer arrays in all memory accesses referencing @p Old, 3208 /// with a reference to @p New. 3209 static void replaceBasePtrArrays(Scop &S, const ScopArrayInfo *Old, 3210 const ScopArrayInfo *New) { 3211 for (ScopStmt &Stmt : S) 3212 for (MemoryAccess *Access : Stmt) { 3213 if (Access->getLatestScopArrayInfo() != Old) 3214 continue; 3215 3216 isl::id Id = New->getBasePtrId(); 3217 isl::map Map = Access->getAccessRelation(); 3218 Map = Map.set_tuple_id(isl::dim::out, Id); 3219 Access->setAccessRelation(Map); 3220 } 3221 } 3222 3223 void ScopBuilder::canonicalizeDynamicBasePtrs() { 3224 for (InvariantEquivClassTy &EqClass : scop->InvariantEquivClasses) { 3225 MemoryAccessList &BasePtrAccesses = EqClass.InvariantAccesses; 3226 3227 const ScopArrayInfo *CanonicalBasePtrSAI = 3228 findCanonicalArray(*scop, BasePtrAccesses); 3229 3230 if (!CanonicalBasePtrSAI) 3231 continue; 3232 3233 for (MemoryAccess *BasePtrAccess : BasePtrAccesses) { 3234 const ScopArrayInfo *BasePtrSAI = scop->getScopArrayInfoOrNull( 3235 BasePtrAccess->getAccessInstruction(), MemoryKind::Array); 3236 if (!BasePtrSAI || BasePtrSAI == CanonicalBasePtrSAI || 3237 !BasePtrSAI->isCompatibleWith(CanonicalBasePtrSAI)) 3238 continue; 3239 3240 // we currently do not canonicalize arrays where some accesses are 3241 // hoisted as invariant loads. If we would, we need to update the access 3242 // function of the invariant loads as well. However, as this is not a 3243 // very common situation, we leave this for now to avoid further 3244 // complexity increases. 3245 if (isUsedForIndirectHoistedLoad(*scop, BasePtrSAI)) 3246 continue; 3247 3248 replaceBasePtrArrays(*scop, BasePtrSAI, CanonicalBasePtrSAI); 3249 } 3250 } 3251 } 3252 3253 void ScopBuilder::buildAccessRelations(ScopStmt &Stmt) { 3254 for (MemoryAccess *Access : Stmt.MemAccs) { 3255 Type *ElementType = Access->getElementType(); 3256 3257 MemoryKind Ty; 3258 if (Access->isPHIKind()) 3259 Ty = MemoryKind::PHI; 3260 else if (Access->isExitPHIKind()) 3261 Ty = MemoryKind::ExitPHI; 3262 else if (Access->isValueKind()) 3263 Ty = MemoryKind::Value; 3264 else 3265 Ty = MemoryKind::Array; 3266 3267 // Create isl::pw_aff for SCEVs which describe sizes. Collect all 3268 // assumptions which are taken. isl::pw_aff objects are cached internally 3269 // and they are used later by scop. 3270 for (const SCEV *Size : Access->Sizes) { 3271 if (!Size) 3272 continue; 3273 scop->getPwAff(Size, nullptr, false, &RecordedAssumptions); 3274 } 3275 auto *SAI = scop->getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(), 3276 ElementType, Access->Sizes, Ty); 3277 3278 // Create isl::pw_aff for SCEVs which describe subscripts. Collect all 3279 // assumptions which are taken. isl::pw_aff objects are cached internally 3280 // and they are used later by scop. 3281 for (const SCEV *Subscript : Access->subscripts()) { 3282 if (!Access->isAffine() || !Subscript) 3283 continue; 3284 scop->getPwAff(Subscript, Stmt.getEntryBlock(), false, 3285 &RecordedAssumptions); 3286 } 3287 Access->buildAccessRelation(SAI); 3288 scop->addAccessData(Access); 3289 } 3290 } 3291 3292 /// Add the minimal/maximal access in @p Set to @p User. 3293 /// 3294 /// @return True if more accesses should be added, false if we reached the 3295 /// maximal number of run-time checks to be generated. 3296 static bool buildMinMaxAccess(isl::set Set, 3297 Scop::MinMaxVectorTy &MinMaxAccesses, Scop &S) { 3298 isl::pw_multi_aff MinPMA, MaxPMA; 3299 isl::pw_aff LastDimAff; 3300 isl::aff OneAff; 3301 unsigned Pos; 3302 3303 Set = Set.remove_divs(); 3304 polly::simplify(Set); 3305 3306 if (Set.n_basic_set() > RunTimeChecksMaxAccessDisjuncts) 3307 Set = Set.simple_hull(); 3308 3309 // Restrict the number of parameters involved in the access as the lexmin/ 3310 // lexmax computation will take too long if this number is high. 3311 // 3312 // Experiments with a simple test case using an i7 4800MQ: 3313 // 3314 // #Parameters involved | Time (in sec) 3315 // 6 | 0.01 3316 // 7 | 0.04 3317 // 8 | 0.12 3318 // 9 | 0.40 3319 // 10 | 1.54 3320 // 11 | 6.78 3321 // 12 | 30.38 3322 // 3323 if (isl_set_n_param(Set.get()) > 3324 static_cast<isl_size>(RunTimeChecksMaxParameters)) { 3325 unsigned InvolvedParams = 0; 3326 for (unsigned u = 0, e = isl_set_n_param(Set.get()); u < e; u++) 3327 if (Set.involves_dims(isl::dim::param, u, 1)) 3328 InvolvedParams++; 3329 3330 if (InvolvedParams > RunTimeChecksMaxParameters) 3331 return false; 3332 } 3333 3334 MinPMA = Set.lexmin_pw_multi_aff(); 3335 MaxPMA = Set.lexmax_pw_multi_aff(); 3336 3337 MinPMA = MinPMA.coalesce(); 3338 MaxPMA = MaxPMA.coalesce(); 3339 3340 // Adjust the last dimension of the maximal access by one as we want to 3341 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer 3342 // we test during code generation might now point after the end of the 3343 // allocated array but we will never dereference it anyway. 3344 assert((MaxPMA.is_null() || MaxPMA.dim(isl::dim::out)) && 3345 "Assumed at least one output dimension"); 3346 3347 Pos = MaxPMA.dim(isl::dim::out) - 1; 3348 LastDimAff = MaxPMA.get_pw_aff(Pos); 3349 OneAff = isl::aff(isl::local_space(LastDimAff.get_domain_space())); 3350 OneAff = OneAff.add_constant_si(1); 3351 LastDimAff = LastDimAff.add(OneAff); 3352 MaxPMA = MaxPMA.set_pw_aff(Pos, LastDimAff); 3353 3354 if (MinPMA.is_null() || MaxPMA.is_null()) 3355 return false; 3356 3357 MinMaxAccesses.push_back(std::make_pair(MinPMA, MaxPMA)); 3358 3359 return true; 3360 } 3361 3362 /// Wrapper function to calculate minimal/maximal accesses to each array. 3363 bool ScopBuilder::calculateMinMaxAccess(AliasGroupTy AliasGroup, 3364 Scop::MinMaxVectorTy &MinMaxAccesses) { 3365 MinMaxAccesses.reserve(AliasGroup.size()); 3366 3367 isl::union_set Domains = scop->getDomains(); 3368 isl::union_map Accesses = isl::union_map::empty(scop->getParamSpace()); 3369 3370 for (MemoryAccess *MA : AliasGroup) 3371 Accesses = Accesses.add_map(MA->getAccessRelation()); 3372 3373 Accesses = Accesses.intersect_domain(Domains); 3374 isl::union_set Locations = Accesses.range(); 3375 3376 bool LimitReached = false; 3377 for (isl::set Set : Locations.get_set_list()) { 3378 LimitReached |= !buildMinMaxAccess(Set, MinMaxAccesses, *scop); 3379 if (LimitReached) 3380 break; 3381 } 3382 3383 return !LimitReached; 3384 } 3385 3386 static isl::set getAccessDomain(MemoryAccess *MA) { 3387 isl::set Domain = MA->getStatement()->getDomain(); 3388 Domain = Domain.project_out(isl::dim::set, 0, Domain.n_dim()); 3389 return Domain.reset_tuple_id(); 3390 } 3391 3392 bool ScopBuilder::buildAliasChecks() { 3393 if (!PollyUseRuntimeAliasChecks) 3394 return true; 3395 3396 if (buildAliasGroups()) { 3397 // Aliasing assumptions do not go through addAssumption but we still want to 3398 // collect statistics so we do it here explicitly. 3399 if (scop->getAliasGroups().size()) 3400 Scop::incrementNumberOfAliasingAssumptions(1); 3401 return true; 3402 } 3403 3404 // If a problem occurs while building the alias groups we need to delete 3405 // this SCoP and pretend it wasn't valid in the first place. To this end 3406 // we make the assumed context infeasible. 3407 scop->invalidate(ALIASING, DebugLoc()); 3408 3409 LLVM_DEBUG( 3410 dbgs() << "\n\nNOTE: Run time checks for " << scop->getNameStr() 3411 << " could not be created as the number of parameters involved " 3412 "is too high. The SCoP will be " 3413 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust " 3414 "the maximal number of parameters but be advised that the " 3415 "compile time might increase exponentially.\n\n"); 3416 return false; 3417 } 3418 3419 std::tuple<ScopBuilder::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>> 3420 ScopBuilder::buildAliasGroupsForAccesses() { 3421 AliasSetTracker AST(AA); 3422 3423 DenseMap<Value *, MemoryAccess *> PtrToAcc; 3424 DenseSet<const ScopArrayInfo *> HasWriteAccess; 3425 for (ScopStmt &Stmt : *scop) { 3426 3427 isl::set StmtDomain = Stmt.getDomain(); 3428 bool StmtDomainEmpty = StmtDomain.is_empty(); 3429 3430 // Statements with an empty domain will never be executed. 3431 if (StmtDomainEmpty) 3432 continue; 3433 3434 for (MemoryAccess *MA : Stmt) { 3435 if (MA->isScalarKind()) 3436 continue; 3437 if (!MA->isRead()) 3438 HasWriteAccess.insert(MA->getScopArrayInfo()); 3439 MemAccInst Acc(MA->getAccessInstruction()); 3440 if (MA->isRead() && isa<MemTransferInst>(Acc)) 3441 PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA; 3442 else 3443 PtrToAcc[Acc.getPointerOperand()] = MA; 3444 AST.add(Acc); 3445 } 3446 } 3447 3448 AliasGroupVectorTy AliasGroups; 3449 for (AliasSet &AS : AST) { 3450 if (AS.isMustAlias() || AS.isForwardingAliasSet()) 3451 continue; 3452 AliasGroupTy AG; 3453 for (auto &PR : AS) 3454 AG.push_back(PtrToAcc[PR.getValue()]); 3455 if (AG.size() < 2) 3456 continue; 3457 AliasGroups.push_back(std::move(AG)); 3458 } 3459 3460 return std::make_tuple(AliasGroups, HasWriteAccess); 3461 } 3462 3463 bool ScopBuilder::buildAliasGroups() { 3464 // To create sound alias checks we perform the following steps: 3465 // o) We partition each group into read only and non read only accesses. 3466 // o) For each group with more than one base pointer we then compute minimal 3467 // and maximal accesses to each array of a group in read only and non 3468 // read only partitions separately. 3469 AliasGroupVectorTy AliasGroups; 3470 DenseSet<const ScopArrayInfo *> HasWriteAccess; 3471 3472 std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(); 3473 3474 splitAliasGroupsByDomain(AliasGroups); 3475 3476 for (AliasGroupTy &AG : AliasGroups) { 3477 if (!scop->hasFeasibleRuntimeContext()) 3478 return false; 3479 3480 { 3481 IslMaxOperationsGuard MaxOpGuard(scop->getIslCtx().get(), OptComputeOut); 3482 bool Valid = buildAliasGroup(AG, HasWriteAccess); 3483 if (!Valid) 3484 return false; 3485 } 3486 if (isl_ctx_last_error(scop->getIslCtx().get()) == isl_error_quota) { 3487 scop->invalidate(COMPLEXITY, DebugLoc()); 3488 return false; 3489 } 3490 } 3491 3492 return true; 3493 } 3494 3495 bool ScopBuilder::buildAliasGroup( 3496 AliasGroupTy &AliasGroup, DenseSet<const ScopArrayInfo *> HasWriteAccess) { 3497 AliasGroupTy ReadOnlyAccesses; 3498 AliasGroupTy ReadWriteAccesses; 3499 SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays; 3500 SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays; 3501 3502 if (AliasGroup.size() < 2) 3503 return true; 3504 3505 for (MemoryAccess *Access : AliasGroup) { 3506 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "PossibleAlias", 3507 Access->getAccessInstruction()) 3508 << "Possibly aliasing pointer, use restrict keyword."); 3509 const ScopArrayInfo *Array = Access->getScopArrayInfo(); 3510 if (HasWriteAccess.count(Array)) { 3511 ReadWriteArrays.insert(Array); 3512 ReadWriteAccesses.push_back(Access); 3513 } else { 3514 ReadOnlyArrays.insert(Array); 3515 ReadOnlyAccesses.push_back(Access); 3516 } 3517 } 3518 3519 // If there are no read-only pointers, and less than two read-write pointers, 3520 // no alias check is needed. 3521 if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1) 3522 return true; 3523 3524 // If there is no read-write pointer, no alias check is needed. 3525 if (ReadWriteArrays.empty()) 3526 return true; 3527 3528 // For non-affine accesses, no alias check can be generated as we cannot 3529 // compute a sufficiently tight lower and upper bound: bail out. 3530 for (MemoryAccess *MA : AliasGroup) { 3531 if (!MA->isAffine()) { 3532 scop->invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc(), 3533 MA->getAccessInstruction()->getParent()); 3534 return false; 3535 } 3536 } 3537 3538 // Ensure that for all memory accesses for which we generate alias checks, 3539 // their base pointers are available. 3540 for (MemoryAccess *MA : AliasGroup) { 3541 if (MemoryAccess *BasePtrMA = scop->lookupBasePtrAccess(MA)) 3542 scop->addRequiredInvariantLoad( 3543 cast<LoadInst>(BasePtrMA->getAccessInstruction())); 3544 } 3545 3546 // scop->getAliasGroups().emplace_back(); 3547 // Scop::MinMaxVectorPairTy &pair = scop->getAliasGroups().back(); 3548 Scop::MinMaxVectorTy MinMaxAccessesReadWrite; 3549 Scop::MinMaxVectorTy MinMaxAccessesReadOnly; 3550 3551 bool Valid; 3552 3553 Valid = calculateMinMaxAccess(ReadWriteAccesses, MinMaxAccessesReadWrite); 3554 3555 if (!Valid) 3556 return false; 3557 3558 // Bail out if the number of values we need to compare is too large. 3559 // This is important as the number of comparisons grows quadratically with 3560 // the number of values we need to compare. 3561 if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() > 3562 RunTimeChecksMaxArraysPerGroup) 3563 return false; 3564 3565 Valid = calculateMinMaxAccess(ReadOnlyAccesses, MinMaxAccessesReadOnly); 3566 3567 scop->addAliasGroup(MinMaxAccessesReadWrite, MinMaxAccessesReadOnly); 3568 if (!Valid) 3569 return false; 3570 3571 return true; 3572 } 3573 3574 void ScopBuilder::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) { 3575 for (unsigned u = 0; u < AliasGroups.size(); u++) { 3576 AliasGroupTy NewAG; 3577 AliasGroupTy &AG = AliasGroups[u]; 3578 AliasGroupTy::iterator AGI = AG.begin(); 3579 isl::set AGDomain = getAccessDomain(*AGI); 3580 while (AGI != AG.end()) { 3581 MemoryAccess *MA = *AGI; 3582 isl::set MADomain = getAccessDomain(MA); 3583 if (AGDomain.is_disjoint(MADomain)) { 3584 NewAG.push_back(MA); 3585 AGI = AG.erase(AGI); 3586 } else { 3587 AGDomain = AGDomain.unite(MADomain); 3588 AGI++; 3589 } 3590 } 3591 if (NewAG.size() > 1) 3592 AliasGroups.push_back(std::move(NewAG)); 3593 } 3594 } 3595 3596 #ifndef NDEBUG 3597 static void verifyUse(Scop *S, Use &Op, LoopInfo &LI) { 3598 auto PhysUse = VirtualUse::create(S, Op, &LI, false); 3599 auto VirtUse = VirtualUse::create(S, Op, &LI, true); 3600 assert(PhysUse.getKind() == VirtUse.getKind()); 3601 } 3602 3603 /// Check the consistency of every statement's MemoryAccesses. 3604 /// 3605 /// The check is carried out by expecting the "physical" kind of use (derived 3606 /// from the BasicBlocks instructions resides in) to be same as the "virtual" 3607 /// kind of use (derived from a statement's MemoryAccess). 3608 /// 3609 /// The "physical" uses are taken by ensureValueRead to determine whether to 3610 /// create MemoryAccesses. When done, the kind of scalar access should be the 3611 /// same no matter which way it was derived. 3612 /// 3613 /// The MemoryAccesses might be changed by later SCoP-modifying passes and hence 3614 /// can intentionally influence on the kind of uses (not corresponding to the 3615 /// "physical" anymore, hence called "virtual"). The CodeGenerator therefore has 3616 /// to pick up the virtual uses. But here in the code generator, this has not 3617 /// happened yet, such that virtual and physical uses are equivalent. 3618 static void verifyUses(Scop *S, LoopInfo &LI, DominatorTree &DT) { 3619 for (auto *BB : S->getRegion().blocks()) { 3620 for (auto &Inst : *BB) { 3621 auto *Stmt = S->getStmtFor(&Inst); 3622 if (!Stmt) 3623 continue; 3624 3625 if (isIgnoredIntrinsic(&Inst)) 3626 continue; 3627 3628 // Branch conditions are encoded in the statement domains. 3629 if (Inst.isTerminator() && Stmt->isBlockStmt()) 3630 continue; 3631 3632 // Verify all uses. 3633 for (auto &Op : Inst.operands()) 3634 verifyUse(S, Op, LI); 3635 3636 // Stores do not produce values used by other statements. 3637 if (isa<StoreInst>(Inst)) 3638 continue; 3639 3640 // For every value defined in the block, also check that a use of that 3641 // value in the same statement would not be an inter-statement use. It can 3642 // still be synthesizable or load-hoisted, but these kind of instructions 3643 // are not directly copied in code-generation. 3644 auto VirtDef = 3645 VirtualUse::create(S, Stmt, Stmt->getSurroundingLoop(), &Inst, true); 3646 assert(VirtDef.getKind() == VirtualUse::Synthesizable || 3647 VirtDef.getKind() == VirtualUse::Intra || 3648 VirtDef.getKind() == VirtualUse::Hoisted); 3649 } 3650 } 3651 3652 if (S->hasSingleExitEdge()) 3653 return; 3654 3655 // PHINodes in the SCoP region's exit block are also uses to be checked. 3656 if (!S->getRegion().isTopLevelRegion()) { 3657 for (auto &Inst : *S->getRegion().getExit()) { 3658 if (!isa<PHINode>(Inst)) 3659 break; 3660 3661 for (auto &Op : Inst.operands()) 3662 verifyUse(S, Op, LI); 3663 } 3664 } 3665 } 3666 #endif 3667 3668 void ScopBuilder::buildScop(Region &R, AssumptionCache &AC) { 3669 scop.reset(new Scop(R, SE, LI, DT, *SD.getDetectionContext(&R), ORE, 3670 SD.getNextID())); 3671 3672 buildStmts(R); 3673 3674 // Create all invariant load instructions first. These are categorized as 3675 // 'synthesizable', therefore are not part of any ScopStmt but need to be 3676 // created somewhere. 3677 const InvariantLoadsSetTy &RIL = scop->getRequiredInvariantLoads(); 3678 for (BasicBlock *BB : scop->getRegion().blocks()) { 3679 if (isErrorBlock(*BB, scop->getRegion(), LI, DT)) 3680 continue; 3681 3682 for (Instruction &Inst : *BB) { 3683 LoadInst *Load = dyn_cast<LoadInst>(&Inst); 3684 if (!Load) 3685 continue; 3686 3687 if (!RIL.count(Load)) 3688 continue; 3689 3690 // Invariant loads require a MemoryAccess to be created in some statement. 3691 // It is not important to which statement the MemoryAccess is added 3692 // because it will later be removed from the ScopStmt again. We chose the 3693 // first statement of the basic block the LoadInst is in. 3694 ArrayRef<ScopStmt *> List = scop->getStmtListFor(BB); 3695 assert(!List.empty()); 3696 ScopStmt *RILStmt = List.front(); 3697 buildMemoryAccess(Load, RILStmt); 3698 } 3699 } 3700 buildAccessFunctions(); 3701 3702 // In case the region does not have an exiting block we will later (during 3703 // code generation) split the exit block. This will move potential PHI nodes 3704 // from the current exit block into the new region exiting block. Hence, PHI 3705 // nodes that are at this point not part of the region will be. 3706 // To handle these PHI nodes later we will now model their operands as scalar 3707 // accesses. Note that we do not model anything in the exit block if we have 3708 // an exiting block in the region, as there will not be any splitting later. 3709 if (!R.isTopLevelRegion() && !scop->hasSingleExitEdge()) { 3710 for (Instruction &Inst : *R.getExit()) { 3711 PHINode *PHI = dyn_cast<PHINode>(&Inst); 3712 if (!PHI) 3713 break; 3714 3715 buildPHIAccesses(nullptr, PHI, nullptr, true); 3716 } 3717 } 3718 3719 // Create memory accesses for global reads since all arrays are now known. 3720 auto *AF = SE.getConstant(IntegerType::getInt64Ty(SE.getContext()), 0); 3721 for (auto GlobalReadPair : GlobalReads) { 3722 ScopStmt *GlobalReadStmt = GlobalReadPair.first; 3723 Instruction *GlobalRead = GlobalReadPair.second; 3724 for (auto *BP : ArrayBasePointers) 3725 addArrayAccess(GlobalReadStmt, MemAccInst(GlobalRead), MemoryAccess::READ, 3726 BP, BP->getType(), false, {AF}, {nullptr}, GlobalRead); 3727 } 3728 3729 buildInvariantEquivalenceClasses(); 3730 3731 /// A map from basic blocks to their invalid domains. 3732 DenseMap<BasicBlock *, isl::set> InvalidDomainMap; 3733 3734 if (!buildDomains(&R, InvalidDomainMap)) { 3735 LLVM_DEBUG( 3736 dbgs() << "Bailing-out because buildDomains encountered problems\n"); 3737 return; 3738 } 3739 3740 addUserAssumptions(AC, InvalidDomainMap); 3741 3742 // Initialize the invalid domain. 3743 for (ScopStmt &Stmt : scop->Stmts) 3744 if (Stmt.isBlockStmt()) 3745 Stmt.setInvalidDomain(InvalidDomainMap[Stmt.getEntryBlock()]); 3746 else 3747 Stmt.setInvalidDomain(InvalidDomainMap[getRegionNodeBasicBlock( 3748 Stmt.getRegion()->getNode())]); 3749 3750 // Remove empty statements. 3751 // Exit early in case there are no executable statements left in this scop. 3752 scop->removeStmtNotInDomainMap(); 3753 scop->simplifySCoP(false); 3754 if (scop->isEmpty()) { 3755 LLVM_DEBUG(dbgs() << "Bailing-out because SCoP is empty\n"); 3756 return; 3757 } 3758 3759 // The ScopStmts now have enough information to initialize themselves. 3760 for (ScopStmt &Stmt : *scop) { 3761 collectSurroundingLoops(Stmt); 3762 3763 buildDomain(Stmt); 3764 buildAccessRelations(Stmt); 3765 3766 if (DetectReductions) 3767 checkForReductions(Stmt); 3768 } 3769 3770 // Check early for a feasible runtime context. 3771 if (!scop->hasFeasibleRuntimeContext()) { 3772 LLVM_DEBUG(dbgs() << "Bailing-out because of unfeasible context (early)\n"); 3773 return; 3774 } 3775 3776 // Check early for profitability. Afterwards it cannot change anymore, 3777 // only the runtime context could become infeasible. 3778 if (!scop->isProfitable(UnprofitableScalarAccs)) { 3779 scop->invalidate(PROFITABLE, DebugLoc()); 3780 LLVM_DEBUG( 3781 dbgs() << "Bailing-out because SCoP is not considered profitable\n"); 3782 return; 3783 } 3784 3785 buildSchedule(); 3786 3787 finalizeAccesses(); 3788 3789 scop->realignParams(); 3790 addUserContext(); 3791 3792 // After the context was fully constructed, thus all our knowledge about 3793 // the parameters is in there, we add all recorded assumptions to the 3794 // assumed/invalid context. 3795 addRecordedAssumptions(); 3796 3797 scop->simplifyContexts(); 3798 if (!buildAliasChecks()) { 3799 LLVM_DEBUG(dbgs() << "Bailing-out because could not build alias checks\n"); 3800 return; 3801 } 3802 3803 hoistInvariantLoads(); 3804 canonicalizeDynamicBasePtrs(); 3805 verifyInvariantLoads(); 3806 scop->simplifySCoP(true); 3807 3808 // Check late for a feasible runtime context because profitability did not 3809 // change. 3810 if (!scop->hasFeasibleRuntimeContext()) { 3811 LLVM_DEBUG(dbgs() << "Bailing-out because of unfeasible context (late)\n"); 3812 return; 3813 } 3814 3815 #ifndef NDEBUG 3816 verifyUses(scop.get(), LI, DT); 3817 #endif 3818 } 3819 3820 ScopBuilder::ScopBuilder(Region *R, AssumptionCache &AC, AliasAnalysis &AA, 3821 const DataLayout &DL, DominatorTree &DT, LoopInfo &LI, 3822 ScopDetection &SD, ScalarEvolution &SE, 3823 OptimizationRemarkEmitter &ORE) 3824 : AA(AA), DL(DL), DT(DT), LI(LI), SD(SD), SE(SE), ORE(ORE) { 3825 DebugLoc Beg, End; 3826 auto P = getBBPairForRegion(R); 3827 getDebugLocations(P, Beg, End); 3828 3829 std::string Msg = "SCoP begins here."; 3830 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEntry", Beg, P.first) 3831 << Msg); 3832 3833 buildScop(*R, AC); 3834 3835 LLVM_DEBUG(dbgs() << *scop); 3836 3837 if (!scop->hasFeasibleRuntimeContext()) { 3838 InfeasibleScops++; 3839 Msg = "SCoP ends here but was dismissed."; 3840 LLVM_DEBUG(dbgs() << "SCoP detected but dismissed\n"); 3841 RecordedAssumptions.clear(); 3842 scop.reset(); 3843 } else { 3844 Msg = "SCoP ends here."; 3845 ++ScopFound; 3846 if (scop->getMaxLoopDepth() > 0) 3847 ++RichScopFound; 3848 } 3849 3850 if (R->isTopLevelRegion()) 3851 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.first) 3852 << Msg); 3853 else 3854 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.second) 3855 << Msg); 3856 } 3857