1 //===------ DeLICM.cpp -----------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Undo the effect of Loop Invariant Code Motion (LICM) and 11 // GVN Partial Redundancy Elimination (PRE) on SCoP-level. 12 // 13 // Namely, remove register/scalar dependencies by mapping them back to array 14 // elements. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "polly/DeLICM.h" 19 #include "polly/Options.h" 20 #include "polly/ScopInfo.h" 21 #include "polly/ScopPass.h" 22 #include "polly/Support/ISLOStream.h" 23 #include "polly/Support/ISLTools.h" 24 #include "polly/ZoneAlgo.h" 25 #include "llvm/ADT/Statistic.h" 26 #define DEBUG_TYPE "polly-delicm" 27 28 using namespace polly; 29 using namespace llvm; 30 31 namespace { 32 33 cl::opt<int> 34 DelicmMaxOps("polly-delicm-max-ops", 35 cl::desc("Maximum number of isl operations to invest for " 36 "lifetime analysis; 0=no limit"), 37 cl::init(1000000), cl::cat(PollyCategory)); 38 39 cl::opt<bool> DelicmOverapproximateWrites( 40 "polly-delicm-overapproximate-writes", 41 cl::desc( 42 "Do more PHI writes than necessary in order to avoid partial accesses"), 43 cl::init(false), cl::Hidden, cl::cat(PollyCategory)); 44 45 cl::opt<bool> DelicmPartialWrites("polly-delicm-partial-writes", 46 cl::desc("Allow partial writes"), 47 cl::init(true), cl::Hidden, 48 cl::cat(PollyCategory)); 49 50 cl::opt<bool> 51 DelicmComputeKnown("polly-delicm-compute-known", 52 cl::desc("Compute known content of array elements"), 53 cl::init(true), cl::Hidden, cl::cat(PollyCategory)); 54 55 STATISTIC(DeLICMAnalyzed, "Number of successfully analyzed SCoPs"); 56 STATISTIC(DeLICMOutOfQuota, 57 "Analyses aborted because max_operations was reached"); 58 STATISTIC(MappedValueScalars, "Number of mapped Value scalars"); 59 STATISTIC(MappedPHIScalars, "Number of mapped PHI scalars"); 60 STATISTIC(TargetsMapped, "Number of stores used for at least one mapping"); 61 STATISTIC(DeLICMScopsModified, "Number of SCoPs optimized"); 62 63 STATISTIC(NumValueWrites, "Number of scalar value writes after DeLICM"); 64 STATISTIC(NumValueWritesInLoops, 65 "Number of scalar value writes nested in affine loops after DeLICM"); 66 STATISTIC(NumPHIWrites, "Number of scalar phi writes after DeLICM"); 67 STATISTIC(NumPHIWritesInLoops, 68 "Number of scalar phi writes nested in affine loops after DeLICM"); 69 STATISTIC(NumSingletonWrites, "Number of singleton writes after DeLICM"); 70 STATISTIC(NumSingletonWritesInLoops, 71 "Number of singleton writes nested in affine loops after DeLICM"); 72 73 isl::union_map computeReachingOverwrite(isl::union_map Schedule, 74 isl::union_map Writes, 75 bool InclPrevWrite, 76 bool InclOverwrite) { 77 return computeReachingWrite(Schedule, Writes, true, InclPrevWrite, 78 InclOverwrite); 79 } 80 81 /// Compute the next overwrite for a scalar. 82 /// 83 /// @param Schedule { DomainWrite[] -> Scatter[] } 84 /// Schedule of (at least) all writes. Instances not in @p 85 /// Writes are ignored. 86 /// @param Writes { DomainWrite[] } 87 /// The element instances that write to the scalar. 88 /// @param InclPrevWrite Whether to extend the timepoints to include 89 /// the timepoint where the previous write happens. 90 /// @param InclOverwrite Whether the reaching overwrite includes the timepoint 91 /// of the overwrite itself. 92 /// 93 /// @return { Scatter[] -> DomainDef[] } 94 isl::union_map computeScalarReachingOverwrite(isl::union_map Schedule, 95 isl::union_set Writes, 96 bool InclPrevWrite, 97 bool InclOverwrite) { 98 99 // { DomainWrite[] } 100 auto WritesMap = give(isl_union_map_from_domain(Writes.take())); 101 102 // { [Element[] -> Scatter[]] -> DomainWrite[] } 103 auto Result = computeReachingOverwrite( 104 std::move(Schedule), std::move(WritesMap), InclPrevWrite, InclOverwrite); 105 106 return give(isl_union_map_domain_factor_range(Result.take())); 107 } 108 109 /// Overload of computeScalarReachingOverwrite, with only one writing statement. 110 /// Consequently, the result consists of only one map space. 111 /// 112 /// @param Schedule { DomainWrite[] -> Scatter[] } 113 /// @param Writes { DomainWrite[] } 114 /// @param InclPrevWrite Include the previous write to result. 115 /// @param InclOverwrite Include the overwrite to the result. 116 /// 117 /// @return { Scatter[] -> DomainWrite[] } 118 isl::map computeScalarReachingOverwrite(isl::union_map Schedule, 119 isl::set Writes, bool InclPrevWrite, 120 bool InclOverwrite) { 121 isl::space ScatterSpace = getScatterSpace(Schedule); 122 isl::space DomSpace = Writes.get_space(); 123 124 isl::union_map ReachOverwrite = computeScalarReachingOverwrite( 125 Schedule, isl::union_set(Writes), InclPrevWrite, InclOverwrite); 126 127 isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomSpace); 128 return singleton(std::move(ReachOverwrite), ResultSpace); 129 } 130 131 /// Try to find a 'natural' extension of a mapped to elements outside its 132 /// domain. 133 /// 134 /// @param Relevant The map with mapping that may not be modified. 135 /// @param Universe The domain to which @p Relevant needs to be extended. 136 /// 137 /// @return A map with that associates the domain elements of @p Relevant to the 138 /// same elements and in addition the elements of @p Universe to some 139 /// undefined elements. The function prefers to return simple maps. 140 isl::union_map expandMapping(isl::union_map Relevant, isl::union_set Universe) { 141 Relevant = Relevant.coalesce(); 142 isl::union_set RelevantDomain = Relevant.domain(); 143 isl::union_map Simplified = Relevant.gist_domain(RelevantDomain); 144 Simplified = Simplified.coalesce(); 145 return Simplified.intersect_domain(Universe); 146 } 147 148 /// Represent the knowledge of the contents of any array elements in any zone or 149 /// the knowledge we would add when mapping a scalar to an array element. 150 /// 151 /// Every array element at every zone unit has one of two states: 152 /// 153 /// - Unused: Not occupied by any value so a transformation can change it to 154 /// other values. 155 /// 156 /// - Occupied: The element contains a value that is still needed. 157 /// 158 /// The union of Unused and Unknown zones forms the universe, the set of all 159 /// elements at every timepoint. The universe can easily be derived from the 160 /// array elements that are accessed someway. Arrays that are never accessed 161 /// also never play a role in any computation and can hence be ignored. With a 162 /// given universe, only one of the sets needs to stored implicitly. Computing 163 /// the complement is also an expensive operation, hence this class has been 164 /// designed that only one of sets is needed while the other is assumed to be 165 /// implicit. It can still be given, but is mostly ignored. 166 /// 167 /// There are two use cases for the Knowledge class: 168 /// 169 /// 1) To represent the knowledge of the current state of ScopInfo. The unused 170 /// state means that an element is currently unused: there is no read of it 171 /// before the next overwrite. Also called 'Existing'. 172 /// 173 /// 2) To represent the requirements for mapping a scalar to array elements. The 174 /// unused state means that there is no change/requirement. Also called 175 /// 'Proposed'. 176 /// 177 /// In addition to these states at unit zones, Knowledge needs to know when 178 /// values are written. This is because written values may have no lifetime (one 179 /// reason is that the value is never read). Such writes would therefore never 180 /// conflict, but overwrite values that might still be required. Another source 181 /// of problems are multiple writes to the same element at the same timepoint, 182 /// because their order is undefined. 183 class Knowledge { 184 private: 185 /// { [Element[] -> Zone[]] } 186 /// Set of array elements and when they are alive. 187 /// Can contain a nullptr; in this case the set is implicitly defined as the 188 /// complement of #Unused. 189 /// 190 /// The set of alive array elements is represented as zone, as the set of live 191 /// values can differ depending on how the elements are interpreted. 192 /// Assuming a value X is written at timestep [0] and read at timestep [1] 193 /// without being used at any later point, then the value is alive in the 194 /// interval ]0,1[. This interval cannot be represented by an integer set, as 195 /// it does not contain any integer point. Zones allow us to represent this 196 /// interval and can be converted to sets of timepoints when needed (e.g., in 197 /// isConflicting when comparing to the write sets). 198 /// @see convertZoneToTimepoints and this file's comment for more details. 199 isl::union_set Occupied; 200 201 /// { [Element[] -> Zone[]] } 202 /// Set of array elements when they are not alive, i.e. their memory can be 203 /// used for other purposed. Can contain a nullptr; in this case the set is 204 /// implicitly defined as the complement of #Occupied. 205 isl::union_set Unused; 206 207 /// { [Element[] -> Zone[]] -> ValInst[] } 208 /// Maps to the known content for each array element at any interval. 209 /// 210 /// Any element/interval can map to multiple known elements. This is due to 211 /// multiple llvm::Value referring to the same content. Examples are 212 /// 213 /// - A value stored and loaded again. The LoadInst represents the same value 214 /// as the StoreInst's value operand. 215 /// 216 /// - A PHINode is equal to any one of the incoming values. In case of 217 /// LCSSA-form, it is always equal to its single incoming value. 218 /// 219 /// Two Knowledges are considered not conflicting if at least one of the known 220 /// values match. Not known values are not stored as an unnamed tuple (as 221 /// #Written does), but maps to nothing. 222 /// 223 /// Known values are usually just defined for #Occupied elements. Knowing 224 /// #Unused contents has no advantage as it can be overwritten. 225 isl::union_map Known; 226 227 /// { [Element[] -> Scatter[]] -> ValInst[] } 228 /// The write actions currently in the scop or that would be added when 229 /// mapping a scalar. Maps to the value that is written. 230 /// 231 /// Written values that cannot be identified are represented by an unknown 232 /// ValInst[] (an unnamed tuple of 0 dimension). It conflicts with itself. 233 isl::union_map Written; 234 235 /// Check whether this Knowledge object is well-formed. 236 void checkConsistency() const { 237 #ifndef NDEBUG 238 // Default-initialized object 239 if (!Occupied && !Unused && !Known && !Written) 240 return; 241 242 assert(Occupied || Unused); 243 assert(Known); 244 assert(Written); 245 246 // If not all fields are defined, we cannot derived the universe. 247 if (!Occupied || !Unused) 248 return; 249 250 assert(isl_union_set_is_disjoint(Occupied.keep(), Unused.keep()) == 251 isl_bool_true); 252 auto Universe = give(isl_union_set_union(Occupied.copy(), Unused.copy())); 253 254 assert(!Known.domain().is_subset(Universe).is_false()); 255 assert(!Written.domain().is_subset(Universe).is_false()); 256 #endif 257 } 258 259 public: 260 /// Initialize a nullptr-Knowledge. This is only provided for convenience; do 261 /// not use such an object. 262 Knowledge() {} 263 264 /// Create a new object with the given members. 265 Knowledge(isl::union_set Occupied, isl::union_set Unused, 266 isl::union_map Known, isl::union_map Written) 267 : Occupied(std::move(Occupied)), Unused(std::move(Unused)), 268 Known(std::move(Known)), Written(std::move(Written)) { 269 checkConsistency(); 270 } 271 272 /// Return whether this object was not default-constructed. 273 bool isUsable() const { return (Occupied || Unused) && Known && Written; } 274 275 /// Print the content of this object to @p OS. 276 void print(llvm::raw_ostream &OS, unsigned Indent = 0) const { 277 if (isUsable()) { 278 if (Occupied) 279 OS.indent(Indent) << "Occupied: " << Occupied << "\n"; 280 else 281 OS.indent(Indent) << "Occupied: <Everything else not in Unused>\n"; 282 if (Unused) 283 OS.indent(Indent) << "Unused: " << Unused << "\n"; 284 else 285 OS.indent(Indent) << "Unused: <Everything else not in Occupied>\n"; 286 OS.indent(Indent) << "Known: " << Known << "\n"; 287 OS.indent(Indent) << "Written : " << Written << '\n'; 288 } else { 289 OS.indent(Indent) << "Invalid knowledge\n"; 290 } 291 } 292 293 /// Combine two knowledges, this and @p That. 294 void learnFrom(Knowledge That) { 295 assert(!isConflicting(*this, That)); 296 assert(Unused && That.Occupied); 297 assert( 298 !That.Unused && 299 "This function is only prepared to learn occupied elements from That"); 300 assert(!Occupied && "This function does not implement " 301 "`this->Occupied = " 302 "give(isl_union_set_union(this->Occupied.take(), " 303 "That.Occupied.copy()));`"); 304 305 Unused = give(isl_union_set_subtract(Unused.take(), That.Occupied.copy())); 306 Known = give(isl_union_map_union(Known.take(), That.Known.copy())); 307 Written = give(isl_union_map_union(Written.take(), That.Written.take())); 308 309 checkConsistency(); 310 } 311 312 /// Determine whether two Knowledges conflict with each other. 313 /// 314 /// In theory @p Existing and @p Proposed are symmetric, but the 315 /// implementation is constrained by the implicit interpretation. That is, @p 316 /// Existing must have #Unused defined (use case 1) and @p Proposed must have 317 /// #Occupied defined (use case 1). 318 /// 319 /// A conflict is defined as non-preserved semantics when they are merged. For 320 /// instance, when for the same array and zone they assume different 321 /// llvm::Values. 322 /// 323 /// @param Existing One of the knowledges with #Unused defined. 324 /// @param Proposed One of the knowledges with #Occupied defined. 325 /// @param OS Dump the conflict reason to this output stream; use 326 /// nullptr to not output anything. 327 /// @param Indent Indention for the conflict reason. 328 /// 329 /// @return True, iff the two knowledges are conflicting. 330 static bool isConflicting(const Knowledge &Existing, 331 const Knowledge &Proposed, 332 llvm::raw_ostream *OS = nullptr, 333 unsigned Indent = 0) { 334 assert(Existing.Unused); 335 assert(Proposed.Occupied); 336 337 #ifndef NDEBUG 338 if (Existing.Occupied && Proposed.Unused) { 339 auto ExistingUniverse = give(isl_union_set_union(Existing.Occupied.copy(), 340 Existing.Unused.copy())); 341 auto ProposedUniverse = give(isl_union_set_union(Proposed.Occupied.copy(), 342 Proposed.Unused.copy())); 343 assert(isl_union_set_is_equal(ExistingUniverse.keep(), 344 ProposedUniverse.keep()) == isl_bool_true && 345 "Both inputs' Knowledges must be over the same universe"); 346 } 347 #endif 348 349 // Do the Existing and Proposed lifetimes conflict? 350 // 351 // Lifetimes are described as the cross-product of array elements and zone 352 // intervals in which they are alive (the space { [Element[] -> Zone[]] }). 353 // In the following we call this "element/lifetime interval". 354 // 355 // In order to not conflict, one of the following conditions must apply for 356 // each element/lifetime interval: 357 // 358 // 1. If occupied in one of the knowledges, it is unused in the other. 359 // 360 // - or - 361 // 362 // 2. Both contain the same value. 363 // 364 // Instead of partitioning the element/lifetime intervals into a part that 365 // both Knowledges occupy (which requires an expensive subtraction) and for 366 // these to check whether they are known to be the same value, we check only 367 // the second condition and ensure that it also applies when then first 368 // condition is true. This is done by adding a wildcard value to 369 // Proposed.Known and Existing.Unused such that they match as a common known 370 // value. We use the "unknown ValInst" for this purpose. Every 371 // Existing.Unused may match with an unknown Proposed.Occupied because these 372 // never are in conflict with each other. 373 auto ProposedOccupiedAnyVal = makeUnknownForDomain(Proposed.Occupied); 374 auto ProposedValues = Proposed.Known.unite(ProposedOccupiedAnyVal); 375 376 auto ExistingUnusedAnyVal = makeUnknownForDomain(Existing.Unused); 377 auto ExistingValues = Existing.Known.unite(ExistingUnusedAnyVal); 378 379 auto MatchingVals = ExistingValues.intersect(ProposedValues); 380 auto Matches = MatchingVals.domain(); 381 382 // Any Proposed.Occupied must either have a match between the known values 383 // of Existing and Occupied, or be in Existing.Unused. In the latter case, 384 // the previously added "AnyVal" will match each other. 385 if (!Proposed.Occupied.is_subset(Matches)) { 386 if (OS) { 387 auto Conflicting = Proposed.Occupied.subtract(Matches); 388 auto ExistingConflictingKnown = 389 Existing.Known.intersect_domain(Conflicting); 390 auto ProposedConflictingKnown = 391 Proposed.Known.intersect_domain(Conflicting); 392 393 OS->indent(Indent) << "Proposed lifetime conflicting with Existing's\n"; 394 OS->indent(Indent) << "Conflicting occupied: " << Conflicting << "\n"; 395 if (!ExistingConflictingKnown.is_empty()) 396 OS->indent(Indent) 397 << "Existing Known: " << ExistingConflictingKnown << "\n"; 398 if (!ProposedConflictingKnown.is_empty()) 399 OS->indent(Indent) 400 << "Proposed Known: " << ProposedConflictingKnown << "\n"; 401 } 402 return true; 403 } 404 405 // Do the writes in Existing conflict with occupied values in Proposed? 406 // 407 // In order to not conflict, it must either write to unused lifetime or 408 // write the same value. To check, we remove the writes that write into 409 // Proposed.Unused (they never conflict) and then see whether the written 410 // value is already in Proposed.Known. If there are multiple known values 411 // and a written value is known under different names, it is enough when one 412 // of the written values (assuming that they are the same value under 413 // different names, e.g. a PHINode and one of the incoming values) matches 414 // one of the known names. 415 // 416 // We convert here the set of lifetimes to actual timepoints. A lifetime is 417 // in conflict with a set of write timepoints, if either a live timepoint is 418 // clearly within the lifetime or if a write happens at the beginning of the 419 // lifetime (where it would conflict with the value that actually writes the 420 // value alive). There is no conflict at the end of a lifetime, as the alive 421 // value will always be read, before it is overwritten again. The last 422 // property holds in Polly for all scalar values and we expect all users of 423 // Knowledge to check this property also for accesses to MemoryKind::Array. 424 auto ProposedFixedDefs = 425 convertZoneToTimepoints(Proposed.Occupied, true, false); 426 auto ProposedFixedKnown = 427 convertZoneToTimepoints(Proposed.Known, isl::dim::in, true, false); 428 429 auto ExistingConflictingWrites = 430 Existing.Written.intersect_domain(ProposedFixedDefs); 431 auto ExistingConflictingWritesDomain = ExistingConflictingWrites.domain(); 432 433 auto CommonWrittenVal = 434 ProposedFixedKnown.intersect(ExistingConflictingWrites); 435 auto CommonWrittenValDomain = CommonWrittenVal.domain(); 436 437 if (!ExistingConflictingWritesDomain.is_subset(CommonWrittenValDomain)) { 438 if (OS) { 439 auto ExistingConflictingWritten = 440 ExistingConflictingWrites.subtract_domain(CommonWrittenValDomain); 441 auto ProposedConflictingKnown = ProposedFixedKnown.subtract_domain( 442 ExistingConflictingWritten.domain()); 443 444 OS->indent(Indent) 445 << "Proposed a lifetime where there is an Existing write into it\n"; 446 OS->indent(Indent) << "Existing conflicting writes: " 447 << ExistingConflictingWritten << "\n"; 448 if (!ProposedConflictingKnown.is_empty()) 449 OS->indent(Indent) 450 << "Proposed conflicting known: " << ProposedConflictingKnown 451 << "\n"; 452 } 453 return true; 454 } 455 456 // Do the writes in Proposed conflict with occupied values in Existing? 457 auto ExistingAvailableDefs = 458 convertZoneToTimepoints(Existing.Unused, true, false); 459 auto ExistingKnownDefs = 460 convertZoneToTimepoints(Existing.Known, isl::dim::in, true, false); 461 462 auto ProposedWrittenDomain = Proposed.Written.domain(); 463 auto KnownIdentical = ExistingKnownDefs.intersect(Proposed.Written); 464 auto IdenticalOrUnused = 465 ExistingAvailableDefs.unite(KnownIdentical.domain()); 466 if (!ProposedWrittenDomain.is_subset(IdenticalOrUnused)) { 467 if (OS) { 468 auto Conflicting = ProposedWrittenDomain.subtract(IdenticalOrUnused); 469 auto ExistingConflictingKnown = 470 ExistingKnownDefs.intersect_domain(Conflicting); 471 auto ProposedConflictingWritten = 472 Proposed.Written.intersect_domain(Conflicting); 473 474 OS->indent(Indent) << "Proposed writes into range used by Existing\n"; 475 OS->indent(Indent) << "Proposed conflicting writes: " 476 << ProposedConflictingWritten << "\n"; 477 if (!ExistingConflictingKnown.is_empty()) 478 OS->indent(Indent) 479 << "Existing conflicting known: " << ExistingConflictingKnown 480 << "\n"; 481 } 482 return true; 483 } 484 485 // Does Proposed write at the same time as Existing already does (order of 486 // writes is undefined)? Writing the same value is permitted. 487 auto ExistingWrittenDomain = 488 isl::manage(isl_union_map_domain(Existing.Written.copy())); 489 auto BothWritten = 490 Existing.Written.domain().intersect(Proposed.Written.domain()); 491 auto ExistingKnownWritten = filterKnownValInst(Existing.Written); 492 auto ProposedKnownWritten = filterKnownValInst(Proposed.Written); 493 auto CommonWritten = 494 ExistingKnownWritten.intersect(ProposedKnownWritten).domain(); 495 496 if (!BothWritten.is_subset(CommonWritten)) { 497 if (OS) { 498 auto Conflicting = BothWritten.subtract(CommonWritten); 499 auto ExistingConflictingWritten = 500 Existing.Written.intersect_domain(Conflicting); 501 auto ProposedConflictingWritten = 502 Proposed.Written.intersect_domain(Conflicting); 503 504 OS->indent(Indent) << "Proposed writes at the same time as an already " 505 "Existing write\n"; 506 OS->indent(Indent) << "Conflicting writes: " << Conflicting << "\n"; 507 if (!ExistingConflictingWritten.is_empty()) 508 OS->indent(Indent) 509 << "Exiting write: " << ExistingConflictingWritten << "\n"; 510 if (!ProposedConflictingWritten.is_empty()) 511 OS->indent(Indent) 512 << "Proposed write: " << ProposedConflictingWritten << "\n"; 513 } 514 return true; 515 } 516 517 return false; 518 } 519 }; 520 521 /// Implementation of the DeLICM/DePRE transformation. 522 class DeLICMImpl : public ZoneAlgorithm { 523 private: 524 /// Knowledge before any transformation took place. 525 Knowledge OriginalZone; 526 527 /// Current knowledge of the SCoP including all already applied 528 /// transformations. 529 Knowledge Zone; 530 531 /// Number of StoreInsts something can be mapped to. 532 int NumberOfCompatibleTargets = 0; 533 534 /// The number of StoreInsts to which at least one value or PHI has been 535 /// mapped to. 536 int NumberOfTargetsMapped = 0; 537 538 /// The number of llvm::Value mapped to some array element. 539 int NumberOfMappedValueScalars = 0; 540 541 /// The number of PHIs mapped to some array element. 542 int NumberOfMappedPHIScalars = 0; 543 544 /// Determine whether two knowledges are conflicting with each other. 545 /// 546 /// @see Knowledge::isConflicting 547 bool isConflicting(const Knowledge &Proposed) { 548 raw_ostream *OS = nullptr; 549 DEBUG(OS = &llvm::dbgs()); 550 return Knowledge::isConflicting(Zone, Proposed, OS, 4); 551 } 552 553 /// Determine whether @p SAI is a scalar that can be mapped to an array 554 /// element. 555 bool isMappable(const ScopArrayInfo *SAI) { 556 assert(SAI); 557 558 if (SAI->isValueKind()) { 559 auto *MA = S->getValueDef(SAI); 560 if (!MA) { 561 DEBUG(dbgs() 562 << " Reject because value is read-only within the scop\n"); 563 return false; 564 } 565 566 // Mapping if value is used after scop is not supported. The code 567 // generator would need to reload the scalar after the scop, but it 568 // does not have the information to where it is mapped to. Only the 569 // MemoryAccesses have that information, not the ScopArrayInfo. 570 auto Inst = MA->getAccessInstruction(); 571 for (auto User : Inst->users()) { 572 if (!isa<Instruction>(User)) 573 return false; 574 auto UserInst = cast<Instruction>(User); 575 576 if (!S->contains(UserInst)) { 577 DEBUG(dbgs() << " Reject because value is escaping\n"); 578 return false; 579 } 580 } 581 582 return true; 583 } 584 585 if (SAI->isPHIKind()) { 586 auto *MA = S->getPHIRead(SAI); 587 assert(MA); 588 589 // Mapping of an incoming block from before the SCoP is not supported by 590 // the code generator. 591 auto PHI = cast<PHINode>(MA->getAccessInstruction()); 592 for (auto Incoming : PHI->blocks()) { 593 if (!S->contains(Incoming)) { 594 DEBUG(dbgs() << " Reject because at least one incoming block is " 595 "not in the scop region\n"); 596 return false; 597 } 598 } 599 600 return true; 601 } 602 603 DEBUG(dbgs() << " Reject ExitPHI or other non-value\n"); 604 return false; 605 } 606 607 /// Compute the uses of a MemoryKind::Value and its lifetime (from its 608 /// definition to the last use). 609 /// 610 /// @param SAI The ScopArrayInfo representing the value's storage. 611 /// 612 /// @return { DomainDef[] -> DomainUse[] }, { DomainDef[] -> Zone[] } 613 /// First element is the set of uses for each definition. 614 /// The second is the lifetime of each definition. 615 std::tuple<isl::union_map, isl::map> 616 computeValueUses(const ScopArrayInfo *SAI) { 617 assert(SAI->isValueKind()); 618 619 // { DomainRead[] } 620 auto Reads = makeEmptyUnionSet(); 621 622 // Find all uses. 623 for (auto *MA : S->getValueUses(SAI)) 624 Reads = 625 give(isl_union_set_add_set(Reads.take(), getDomainFor(MA).take())); 626 627 // { DomainRead[] -> Scatter[] } 628 auto ReadSchedule = getScatterFor(Reads); 629 630 auto *DefMA = S->getValueDef(SAI); 631 assert(DefMA); 632 633 // { DomainDef[] } 634 auto Writes = getDomainFor(DefMA); 635 636 // { DomainDef[] -> Scatter[] } 637 auto WriteScatter = getScatterFor(Writes); 638 639 // { Scatter[] -> DomainDef[] } 640 auto ReachDef = getScalarReachingDefinition(DefMA->getStatement()); 641 642 // { [DomainDef[] -> Scatter[]] -> DomainUse[] } 643 auto Uses = give( 644 isl_union_map_apply_range(isl_union_map_from_map(isl_map_range_map( 645 isl_map_reverse(ReachDef.take()))), 646 isl_union_map_reverse(ReadSchedule.take()))); 647 648 // { DomainDef[] -> Scatter[] } 649 auto UseScatter = 650 singleton(give(isl_union_set_unwrap(isl_union_map_domain(Uses.copy()))), 651 give(isl_space_map_from_domain_and_range( 652 isl_set_get_space(Writes.keep()), ScatterSpace.copy()))); 653 654 // { DomainDef[] -> Zone[] } 655 auto Lifetime = betweenScatter(WriteScatter, UseScatter, false, true); 656 657 // { DomainDef[] -> DomainRead[] } 658 auto DefUses = give(isl_union_map_domain_factor_domain(Uses.take())); 659 660 return std::make_pair(DefUses, Lifetime); 661 } 662 663 /// For each 'execution' of a PHINode, get the incoming block that was 664 /// executed before. 665 /// 666 /// For each PHI instance we can directly determine which was the incoming 667 /// block, and hence derive which value the PHI has. 668 /// 669 /// @param SAI The ScopArrayInfo representing the PHI's storage. 670 /// 671 /// @return { DomainPHIRead[] -> DomainPHIWrite[] } 672 isl::union_map computePerPHI(const ScopArrayInfo *SAI) { 673 assert(SAI->isPHIKind()); 674 675 // { DomainPHIWrite[] -> Scatter[] } 676 auto PHIWriteScatter = makeEmptyUnionMap(); 677 678 // Collect all incoming block timepoint. 679 for (auto *MA : S->getPHIIncomings(SAI)) { 680 auto Scatter = getScatterFor(MA); 681 PHIWriteScatter = 682 give(isl_union_map_add_map(PHIWriteScatter.take(), Scatter.take())); 683 } 684 685 // { DomainPHIRead[] -> Scatter[] } 686 auto PHIReadScatter = getScatterFor(S->getPHIRead(SAI)); 687 688 // { DomainPHIRead[] -> Scatter[] } 689 auto BeforeRead = beforeScatter(PHIReadScatter, true); 690 691 // { Scatter[] } 692 auto WriteTimes = singleton( 693 give(isl_union_map_range(PHIWriteScatter.copy())), ScatterSpace); 694 695 // { DomainPHIRead[] -> Scatter[] } 696 auto PHIWriteTimes = 697 give(isl_map_intersect_range(BeforeRead.take(), WriteTimes.take())); 698 auto LastPerPHIWrites = give(isl_map_lexmax(PHIWriteTimes.take())); 699 700 // { DomainPHIRead[] -> DomainPHIWrite[] } 701 auto Result = give(isl_union_map_apply_range( 702 isl_union_map_from_map(LastPerPHIWrites.take()), 703 isl_union_map_reverse(PHIWriteScatter.take()))); 704 assert(isl_union_map_is_single_valued(Result.keep()) == isl_bool_true); 705 assert(isl_union_map_is_injective(Result.keep()) == isl_bool_true); 706 return Result; 707 } 708 709 /// Try to map a MemoryKind::Value to a given array element. 710 /// 711 /// @param SAI Representation of the scalar's memory to map. 712 /// @param TargetElt { Scatter[] -> Element[] } 713 /// Suggestion where to map a scalar to when at a timepoint. 714 /// 715 /// @return true if the scalar was successfully mapped. 716 bool tryMapValue(const ScopArrayInfo *SAI, isl::map TargetElt) { 717 assert(SAI->isValueKind()); 718 719 auto *DefMA = S->getValueDef(SAI); 720 assert(DefMA->isValueKind()); 721 assert(DefMA->isMustWrite()); 722 auto *V = DefMA->getAccessValue(); 723 auto *DefInst = DefMA->getAccessInstruction(); 724 725 // Stop if the scalar has already been mapped. 726 if (!DefMA->getLatestScopArrayInfo()->isValueKind()) 727 return false; 728 729 // { DomainDef[] -> Scatter[] } 730 auto DefSched = getScatterFor(DefMA); 731 732 // Where each write is mapped to, according to the suggestion. 733 // { DomainDef[] -> Element[] } 734 auto DefTarget = give(isl_map_apply_domain( 735 TargetElt.copy(), isl_map_reverse(DefSched.copy()))); 736 simplify(DefTarget); 737 DEBUG(dbgs() << " Def Mapping: " << DefTarget << '\n'); 738 739 auto OrigDomain = getDomainFor(DefMA); 740 auto MappedDomain = give(isl_map_domain(DefTarget.copy())); 741 if (!isl_set_is_subset(OrigDomain.keep(), MappedDomain.keep())) { 742 DEBUG(dbgs() 743 << " Reject because mapping does not encompass all instances\n"); 744 return false; 745 } 746 747 // { DomainDef[] -> Zone[] } 748 isl::map Lifetime; 749 750 // { DomainDef[] -> DomainUse[] } 751 isl::union_map DefUses; 752 753 std::tie(DefUses, Lifetime) = computeValueUses(SAI); 754 DEBUG(dbgs() << " Lifetime: " << Lifetime << '\n'); 755 756 /// { [Element[] -> Zone[]] } 757 auto EltZone = give( 758 isl_map_wrap(isl_map_apply_domain(Lifetime.copy(), DefTarget.copy()))); 759 simplify(EltZone); 760 761 // When known knowledge is disabled, just return the unknown value. It will 762 // either get filtered out or conflict with itself. 763 // { DomainDef[] -> ValInst[] } 764 isl::map ValInst; 765 if (DelicmComputeKnown) 766 ValInst = makeValInst(V, DefMA->getStatement(), 767 LI->getLoopFor(DefInst->getParent())); 768 else 769 ValInst = makeUnknownForDomain(DefMA->getStatement()); 770 771 // { DomainDef[] -> [Element[] -> Zone[]] } 772 auto EltKnownTranslator = 773 give(isl_map_range_product(DefTarget.copy(), Lifetime.copy())); 774 775 // { [Element[] -> Zone[]] -> ValInst[] } 776 auto EltKnown = 777 give(isl_map_apply_domain(ValInst.copy(), EltKnownTranslator.take())); 778 simplify(EltKnown); 779 780 // { DomainDef[] -> [Element[] -> Scatter[]] } 781 auto WrittenTranslator = 782 give(isl_map_range_product(DefTarget.copy(), DefSched.take())); 783 784 // { [Element[] -> Scatter[]] -> ValInst[] } 785 auto DefEltSched = 786 give(isl_map_apply_domain(ValInst.copy(), WrittenTranslator.take())); 787 simplify(DefEltSched); 788 789 Knowledge Proposed(EltZone, nullptr, filterKnownValInst(EltKnown), 790 DefEltSched); 791 if (isConflicting(Proposed)) 792 return false; 793 794 // { DomainUse[] -> Element[] } 795 auto UseTarget = give( 796 isl_union_map_apply_range(isl_union_map_reverse(DefUses.take()), 797 isl_union_map_from_map(DefTarget.copy()))); 798 799 mapValue(SAI, std::move(DefTarget), std::move(UseTarget), 800 std::move(Lifetime), std::move(Proposed)); 801 return true; 802 } 803 804 /// After a scalar has been mapped, update the global knowledge. 805 void applyLifetime(Knowledge Proposed) { 806 Zone.learnFrom(std::move(Proposed)); 807 } 808 809 /// Map a MemoryKind::Value scalar to an array element. 810 /// 811 /// Callers must have ensured that the mapping is valid and not conflicting. 812 /// 813 /// @param SAI The ScopArrayInfo representing the scalar's memory to 814 /// map. 815 /// @param DefTarget { DomainDef[] -> Element[] } 816 /// The array element to map the scalar to. 817 /// @param UseTarget { DomainUse[] -> Element[] } 818 /// The array elements the uses are mapped to. 819 /// @param Lifetime { DomainDef[] -> Zone[] } 820 /// The lifetime of each llvm::Value definition for 821 /// reporting. 822 /// @param Proposed Mapping constraints for reporting. 823 void mapValue(const ScopArrayInfo *SAI, isl::map DefTarget, 824 isl::union_map UseTarget, isl::map Lifetime, 825 Knowledge Proposed) { 826 // Redirect the read accesses. 827 for (auto *MA : S->getValueUses(SAI)) { 828 // { DomainUse[] } 829 auto Domain = getDomainFor(MA); 830 831 // { DomainUse[] -> Element[] } 832 auto NewAccRel = give(isl_union_map_intersect_domain( 833 UseTarget.copy(), isl_union_set_from_set(Domain.take()))); 834 simplify(NewAccRel); 835 836 assert(isl_union_map_n_map(NewAccRel.keep()) == 1); 837 MA->setNewAccessRelation(isl::map::from_union_map(NewAccRel)); 838 } 839 840 auto *WA = S->getValueDef(SAI); 841 WA->setNewAccessRelation(DefTarget); 842 applyLifetime(Proposed); 843 844 MappedValueScalars++; 845 NumberOfMappedValueScalars += 1; 846 } 847 848 isl::map makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope, 849 bool IsCertain = true) { 850 // When known knowledge is disabled, just return the unknown value. It will 851 // either get filtered out or conflict with itself. 852 if (!DelicmComputeKnown) 853 return makeUnknownForDomain(UserStmt); 854 return ZoneAlgorithm::makeValInst(Val, UserStmt, Scope, IsCertain); 855 } 856 857 /// Express the incoming values of a PHI for each incoming statement in an 858 /// isl::union_map. 859 /// 860 /// @param SAI The PHI scalar represented by a ScopArrayInfo. 861 /// 862 /// @return { PHIWriteDomain[] -> ValInst[] } 863 isl::union_map determinePHIWrittenValues(const ScopArrayInfo *SAI) { 864 auto Result = makeEmptyUnionMap(); 865 866 // Collect the incoming values. 867 for (auto *MA : S->getPHIIncomings(SAI)) { 868 // { DomainWrite[] -> ValInst[] } 869 isl::union_map ValInst; 870 auto *WriteStmt = MA->getStatement(); 871 872 auto Incoming = MA->getIncoming(); 873 assert(!Incoming.empty()); 874 if (Incoming.size() == 1) { 875 ValInst = makeValInst(Incoming[0].second, WriteStmt, 876 LI->getLoopFor(Incoming[0].first)); 877 } else { 878 // If the PHI is in a subregion's exit node it can have multiple 879 // incoming values (+ maybe another incoming edge from an unrelated 880 // block). We cannot directly represent it as a single llvm::Value. 881 // We currently model it as unknown value, but modeling as the PHIInst 882 // itself could be OK, too. 883 ValInst = makeUnknownForDomain(WriteStmt); 884 } 885 886 Result = give(isl_union_map_union(Result.take(), ValInst.take())); 887 } 888 889 assert(isl_union_map_is_single_valued(Result.keep()) == isl_bool_true && 890 "Cannot have multiple incoming values for same incoming statement"); 891 return Result; 892 } 893 894 /// Try to map a MemoryKind::PHI scalar to a given array element. 895 /// 896 /// @param SAI Representation of the scalar's memory to map. 897 /// @param TargetElt { Scatter[] -> Element[] } 898 /// Suggestion where to map the scalar to when at a 899 /// timepoint. 900 /// 901 /// @return true if the PHI scalar has been mapped. 902 bool tryMapPHI(const ScopArrayInfo *SAI, isl::map TargetElt) { 903 auto *PHIRead = S->getPHIRead(SAI); 904 assert(PHIRead->isPHIKind()); 905 assert(PHIRead->isRead()); 906 907 // Skip if already been mapped. 908 if (!PHIRead->getLatestScopArrayInfo()->isPHIKind()) 909 return false; 910 911 // { DomainRead[] -> Scatter[] } 912 auto PHISched = getScatterFor(PHIRead); 913 914 // { DomainRead[] -> Element[] } 915 auto PHITarget = 916 give(isl_map_apply_range(PHISched.copy(), TargetElt.copy())); 917 simplify(PHITarget); 918 DEBUG(dbgs() << " Mapping: " << PHITarget << '\n'); 919 920 auto OrigDomain = getDomainFor(PHIRead); 921 auto MappedDomain = give(isl_map_domain(PHITarget.copy())); 922 if (!isl_set_is_subset(OrigDomain.keep(), MappedDomain.keep())) { 923 DEBUG(dbgs() 924 << " Reject because mapping does not encompass all instances\n"); 925 return false; 926 } 927 928 // { DomainRead[] -> DomainWrite[] } 929 auto PerPHIWrites = computePerPHI(SAI); 930 931 // { DomainWrite[] -> Element[] } 932 auto WritesTarget = give(isl_union_map_reverse(isl_union_map_apply_domain( 933 PerPHIWrites.copy(), isl_union_map_from_map(PHITarget.copy())))); 934 simplify(WritesTarget); 935 936 // { DomainWrite[] } 937 auto UniverseWritesDom = give(isl_union_set_empty(ParamSpace.copy())); 938 939 for (auto *MA : S->getPHIIncomings(SAI)) 940 UniverseWritesDom = give(isl_union_set_add_set(UniverseWritesDom.take(), 941 getDomainFor(MA).take())); 942 943 auto RelevantWritesTarget = WritesTarget; 944 if (DelicmOverapproximateWrites) 945 WritesTarget = expandMapping(WritesTarget, UniverseWritesDom); 946 947 auto ExpandedWritesDom = give(isl_union_map_domain(WritesTarget.copy())); 948 if (!DelicmPartialWrites && 949 !isl_union_set_is_subset(UniverseWritesDom.keep(), 950 ExpandedWritesDom.keep())) { 951 DEBUG(dbgs() << " Reject because did not find PHI write mapping for " 952 "all instances\n"); 953 if (DelicmOverapproximateWrites) 954 DEBUG(dbgs() << " Relevant Mapping: " << RelevantWritesTarget 955 << '\n'); 956 DEBUG(dbgs() << " Deduced Mapping: " << WritesTarget << '\n'); 957 DEBUG(dbgs() << " Missing instances: " 958 << give(isl_union_set_subtract(UniverseWritesDom.copy(), 959 ExpandedWritesDom.copy())) 960 << '\n'); 961 return false; 962 } 963 964 // { DomainRead[] -> Scatter[] } 965 auto PerPHIWriteScatter = give(isl_map_from_union_map( 966 isl_union_map_apply_range(PerPHIWrites.copy(), Schedule.copy()))); 967 968 // { DomainRead[] -> Zone[] } 969 auto Lifetime = betweenScatter(PerPHIWriteScatter, PHISched, false, true); 970 simplify(Lifetime); 971 DEBUG(dbgs() << " Lifetime: " << Lifetime << "\n"); 972 973 // { DomainWrite[] -> Zone[] } 974 auto WriteLifetime = give(isl_union_map_apply_domain( 975 isl_union_map_from_map(Lifetime.copy()), PerPHIWrites.copy())); 976 977 // { DomainWrite[] -> ValInst[] } 978 auto WrittenValue = determinePHIWrittenValues(SAI); 979 980 // { DomainWrite[] -> [Element[] -> Scatter[]] } 981 auto WrittenTranslator = 982 give(isl_union_map_range_product(WritesTarget.copy(), Schedule.copy())); 983 984 // { [Element[] -> Scatter[]] -> ValInst[] } 985 auto Written = give(isl_union_map_apply_domain(WrittenValue.copy(), 986 WrittenTranslator.copy())); 987 simplify(Written); 988 989 // { DomainWrite[] -> [Element[] -> Zone[]] } 990 auto LifetimeTranslator = give( 991 isl_union_map_range_product(WritesTarget.copy(), WriteLifetime.copy())); 992 993 // { DomainWrite[] -> ValInst[] } 994 auto WrittenKnownValue = filterKnownValInst(WrittenValue); 995 996 // { [Element[] -> Zone[]] -> ValInst[] } 997 auto EltLifetimeInst = give(isl_union_map_apply_domain( 998 WrittenKnownValue.copy(), LifetimeTranslator.copy())); 999 simplify(EltLifetimeInst); 1000 1001 // { [Element[] -> Zone[] } 1002 auto Occupied = give(isl_union_map_range(LifetimeTranslator.copy())); 1003 simplify(Occupied); 1004 1005 Knowledge Proposed(Occupied, nullptr, EltLifetimeInst, Written); 1006 if (isConflicting(Proposed)) 1007 return false; 1008 1009 mapPHI(SAI, std::move(PHITarget), std::move(WritesTarget), 1010 std::move(Lifetime), std::move(Proposed)); 1011 return true; 1012 } 1013 1014 /// Map a MemoryKind::PHI scalar to an array element. 1015 /// 1016 /// Callers must have ensured that the mapping is valid and not conflicting 1017 /// with the common knowledge. 1018 /// 1019 /// @param SAI The ScopArrayInfo representing the scalar's memory to 1020 /// map. 1021 /// @param ReadTarget { DomainRead[] -> Element[] } 1022 /// The array element to map the scalar to. 1023 /// @param WriteTarget { DomainWrite[] -> Element[] } 1024 /// New access target for each PHI incoming write. 1025 /// @param Lifetime { DomainRead[] -> Zone[] } 1026 /// The lifetime of each PHI for reporting. 1027 /// @param Proposed Mapping constraints for reporting. 1028 void mapPHI(const ScopArrayInfo *SAI, isl::map ReadTarget, 1029 isl::union_map WriteTarget, isl::map Lifetime, 1030 Knowledge Proposed) { 1031 // { Element[] } 1032 isl::space ElementSpace = ReadTarget.get_space().range(); 1033 1034 // Redirect the PHI incoming writes. 1035 for (auto *MA : S->getPHIIncomings(SAI)) { 1036 // { DomainWrite[] } 1037 auto Domain = getDomainFor(MA); 1038 1039 // { DomainWrite[] -> Element[] } 1040 auto NewAccRel = give(isl_union_map_intersect_domain( 1041 WriteTarget.copy(), isl_union_set_from_set(Domain.copy()))); 1042 simplify(NewAccRel); 1043 1044 isl::space NewAccRelSpace = 1045 Domain.get_space().map_from_domain_and_range(ElementSpace); 1046 isl::map NewAccRelMap = singleton(NewAccRel, NewAccRelSpace); 1047 MA->setNewAccessRelation(NewAccRelMap); 1048 } 1049 1050 // Redirect the PHI read. 1051 auto *PHIRead = S->getPHIRead(SAI); 1052 PHIRead->setNewAccessRelation(ReadTarget); 1053 applyLifetime(Proposed); 1054 1055 MappedPHIScalars++; 1056 NumberOfMappedPHIScalars++; 1057 } 1058 1059 /// Search and map scalars to memory overwritten by @p TargetStoreMA. 1060 /// 1061 /// Start trying to map scalars that are used in the same statement as the 1062 /// store. For every successful mapping, try to also map scalars of the 1063 /// statements where those are written. Repeat, until no more mapping 1064 /// opportunity is found. 1065 /// 1066 /// There is currently no preference in which order scalars are tried. 1067 /// Ideally, we would direct it towards a load instruction of the same array 1068 /// element. 1069 bool collapseScalarsToStore(MemoryAccess *TargetStoreMA) { 1070 assert(TargetStoreMA->isLatestArrayKind()); 1071 assert(TargetStoreMA->isMustWrite()); 1072 1073 auto TargetStmt = TargetStoreMA->getStatement(); 1074 1075 // { DomTarget[] } 1076 auto TargetDom = getDomainFor(TargetStmt); 1077 1078 // { DomTarget[] -> Element[] } 1079 auto TargetAccRel = getAccessRelationFor(TargetStoreMA); 1080 1081 // { Zone[] -> DomTarget[] } 1082 // For each point in time, find the next target store instance. 1083 auto Target = 1084 computeScalarReachingOverwrite(Schedule, TargetDom, false, true); 1085 1086 // { Zone[] -> Element[] } 1087 // Use the target store's write location as a suggestion to map scalars to. 1088 auto EltTarget = 1089 give(isl_map_apply_range(Target.take(), TargetAccRel.take())); 1090 simplify(EltTarget); 1091 DEBUG(dbgs() << " Target mapping is " << EltTarget << '\n'); 1092 1093 // Stack of elements not yet processed. 1094 SmallVector<MemoryAccess *, 16> Worklist; 1095 1096 // Set of scalars already tested. 1097 SmallPtrSet<const ScopArrayInfo *, 16> Closed; 1098 1099 // Lambda to add all scalar reads to the work list. 1100 auto ProcessAllIncoming = [&](ScopStmt *Stmt) { 1101 for (auto *MA : *Stmt) { 1102 if (!MA->isLatestScalarKind()) 1103 continue; 1104 if (!MA->isRead()) 1105 continue; 1106 1107 Worklist.push_back(MA); 1108 } 1109 }; 1110 1111 auto *WrittenVal = TargetStoreMA->getAccessInstruction()->getOperand(0); 1112 if (auto *WrittenValInputMA = TargetStmt->lookupInputAccessOf(WrittenVal)) 1113 Worklist.push_back(WrittenValInputMA); 1114 else 1115 ProcessAllIncoming(TargetStmt); 1116 1117 auto AnyMapped = false; 1118 auto &DL = S->getRegion().getEntry()->getModule()->getDataLayout(); 1119 auto StoreSize = 1120 DL.getTypeAllocSize(TargetStoreMA->getAccessValue()->getType()); 1121 1122 while (!Worklist.empty()) { 1123 auto *MA = Worklist.pop_back_val(); 1124 1125 auto *SAI = MA->getScopArrayInfo(); 1126 if (Closed.count(SAI)) 1127 continue; 1128 Closed.insert(SAI); 1129 DEBUG(dbgs() << "\n Trying to map " << MA << " (SAI: " << SAI 1130 << ")\n"); 1131 1132 // Skip non-mappable scalars. 1133 if (!isMappable(SAI)) 1134 continue; 1135 1136 auto MASize = DL.getTypeAllocSize(MA->getAccessValue()->getType()); 1137 if (MASize > StoreSize) { 1138 DEBUG(dbgs() << " Reject because storage size is insufficient\n"); 1139 continue; 1140 } 1141 1142 // Try to map MemoryKind::Value scalars. 1143 if (SAI->isValueKind()) { 1144 if (!tryMapValue(SAI, EltTarget)) 1145 continue; 1146 1147 auto *DefAcc = S->getValueDef(SAI); 1148 ProcessAllIncoming(DefAcc->getStatement()); 1149 1150 AnyMapped = true; 1151 continue; 1152 } 1153 1154 // Try to map MemoryKind::PHI scalars. 1155 if (SAI->isPHIKind()) { 1156 if (!tryMapPHI(SAI, EltTarget)) 1157 continue; 1158 // Add inputs of all incoming statements to the worklist. Prefer the 1159 // input accesses of the incoming blocks. 1160 for (auto *PHIWrite : S->getPHIIncomings(SAI)) { 1161 auto *PHIWriteStmt = PHIWrite->getStatement(); 1162 bool FoundAny = false; 1163 for (auto Incoming : PHIWrite->getIncoming()) { 1164 auto *IncomingInputMA = 1165 PHIWriteStmt->lookupInputAccessOf(Incoming.second); 1166 if (!IncomingInputMA) 1167 continue; 1168 1169 Worklist.push_back(IncomingInputMA); 1170 FoundAny = true; 1171 } 1172 1173 if (!FoundAny) 1174 ProcessAllIncoming(PHIWrite->getStatement()); 1175 } 1176 1177 AnyMapped = true; 1178 continue; 1179 } 1180 } 1181 1182 if (AnyMapped) { 1183 TargetsMapped++; 1184 NumberOfTargetsMapped++; 1185 } 1186 return AnyMapped; 1187 } 1188 1189 /// Compute when an array element is unused. 1190 /// 1191 /// @return { [Element[] -> Zone[]] } 1192 isl::union_set computeLifetime() const { 1193 // { Element[] -> Zone[] } 1194 auto ArrayUnused = computeArrayUnused(Schedule, AllMustWrites, AllReads, 1195 false, false, true); 1196 1197 auto Result = give(isl_union_map_wrap(ArrayUnused.copy())); 1198 1199 simplify(Result); 1200 return Result; 1201 } 1202 1203 /// Determine when an array element is written to, and which value instance is 1204 /// written. 1205 /// 1206 /// @return { [Element[] -> Scatter[]] -> ValInst[] } 1207 isl::union_map computeWritten() const { 1208 // { [Element[] -> Scatter[]] -> ValInst[] } 1209 auto EltWritten = applyDomainRange(AllWriteValInst, Schedule); 1210 1211 simplify(EltWritten); 1212 return EltWritten; 1213 } 1214 1215 /// Determine whether an access touches at most one element. 1216 /// 1217 /// The accessed element could be a scalar or accessing an array with constant 1218 /// subscript, such that all instances access only that element. 1219 /// 1220 /// @param MA The access to test. 1221 /// 1222 /// @return True, if zero or one elements are accessed; False if at least two 1223 /// different elements are accessed. 1224 bool isScalarAccess(MemoryAccess *MA) { 1225 auto Map = getAccessRelationFor(MA); 1226 auto Set = give(isl_map_range(Map.take())); 1227 return isl_set_is_singleton(Set.keep()) == isl_bool_true; 1228 } 1229 1230 /// Print mapping statistics to @p OS. 1231 void printStatistics(llvm::raw_ostream &OS, int Indent = 0) const { 1232 OS.indent(Indent) << "Statistics {\n"; 1233 OS.indent(Indent + 4) << "Compatible overwrites: " 1234 << NumberOfCompatibleTargets << "\n"; 1235 OS.indent(Indent + 4) << "Overwrites mapped to: " << NumberOfTargetsMapped 1236 << '\n'; 1237 OS.indent(Indent + 4) << "Value scalars mapped: " 1238 << NumberOfMappedValueScalars << '\n'; 1239 OS.indent(Indent + 4) << "PHI scalars mapped: " 1240 << NumberOfMappedPHIScalars << '\n'; 1241 OS.indent(Indent) << "}\n"; 1242 } 1243 1244 /// Return whether at least one transformation been applied. 1245 bool isModified() const { return NumberOfTargetsMapped > 0; } 1246 1247 public: 1248 DeLICMImpl(Scop *S, LoopInfo *LI) : ZoneAlgorithm("polly-delicm", S, LI) {} 1249 1250 /// Calculate the lifetime (definition to last use) of every array element. 1251 /// 1252 /// @return True if the computed lifetimes (#Zone) is usable. 1253 bool computeZone() { 1254 // Check that nothing strange occurs. 1255 collectCompatibleElts(); 1256 1257 isl::union_set EltUnused; 1258 isl::union_map EltKnown, EltWritten; 1259 1260 { 1261 IslMaxOperationsGuard MaxOpGuard(IslCtx.get(), DelicmMaxOps); 1262 1263 computeCommon(); 1264 1265 EltUnused = computeLifetime(); 1266 EltKnown = computeKnown(true, false); 1267 EltWritten = computeWritten(); 1268 } 1269 DeLICMAnalyzed++; 1270 1271 if (!EltUnused || !EltKnown || !EltWritten) { 1272 assert(isl_ctx_last_error(IslCtx.get()) == isl_error_quota && 1273 "The only reason that these things have not been computed should " 1274 "be if the max-operations limit hit"); 1275 DeLICMOutOfQuota++; 1276 DEBUG(dbgs() << "DeLICM analysis exceeded max_operations\n"); 1277 DebugLoc Begin, End; 1278 getDebugLocations(getBBPairForRegion(&S->getRegion()), Begin, End); 1279 OptimizationRemarkAnalysis R(DEBUG_TYPE, "OutOfQuota", Begin, 1280 S->getEntry()); 1281 R << "maximal number of operations exceeded during zone analysis"; 1282 S->getFunction().getContext().diagnose(R); 1283 return false; 1284 } 1285 1286 Zone = OriginalZone = Knowledge(nullptr, EltUnused, EltKnown, EltWritten); 1287 DEBUG(dbgs() << "Computed Zone:\n"; OriginalZone.print(dbgs(), 4)); 1288 1289 assert(Zone.isUsable() && OriginalZone.isUsable()); 1290 return true; 1291 } 1292 1293 /// Try to map as many scalars to unused array elements as possible. 1294 /// 1295 /// Multiple scalars might be mappable to intersecting unused array element 1296 /// zones, but we can only chose one. This is a greedy algorithm, therefore 1297 /// the first processed element claims it. 1298 void greedyCollapse() { 1299 bool Modified = false; 1300 1301 for (auto &Stmt : *S) { 1302 for (auto *MA : Stmt) { 1303 if (!MA->isLatestArrayKind()) 1304 continue; 1305 if (!MA->isWrite()) 1306 continue; 1307 1308 if (MA->isMayWrite()) { 1309 DEBUG(dbgs() << "Access " << MA 1310 << " pruned because it is a MAY_WRITE\n"); 1311 OptimizationRemarkMissed R(DEBUG_TYPE, "TargetMayWrite", 1312 MA->getAccessInstruction()); 1313 R << "Skipped possible mapping target because it is not an " 1314 "unconditional overwrite"; 1315 S->getFunction().getContext().diagnose(R); 1316 continue; 1317 } 1318 1319 if (Stmt.getNumIterators() == 0) { 1320 DEBUG(dbgs() << "Access " << MA 1321 << " pruned because it is not in a loop\n"); 1322 OptimizationRemarkMissed R(DEBUG_TYPE, "WriteNotInLoop", 1323 MA->getAccessInstruction()); 1324 R << "skipped possible mapping target because it is not in a loop"; 1325 S->getFunction().getContext().diagnose(R); 1326 continue; 1327 } 1328 1329 if (isScalarAccess(MA)) { 1330 DEBUG(dbgs() << "Access " << MA 1331 << " pruned because it writes only a single element\n"); 1332 OptimizationRemarkMissed R(DEBUG_TYPE, "ScalarWrite", 1333 MA->getAccessInstruction()); 1334 R << "skipped possible mapping target because the memory location " 1335 "written to does not depend on its outer loop"; 1336 S->getFunction().getContext().diagnose(R); 1337 continue; 1338 } 1339 1340 if (!isa<StoreInst>(MA->getAccessInstruction())) { 1341 DEBUG(dbgs() << "Access " << MA 1342 << " pruned because it is not a StoreInst\n"); 1343 OptimizationRemarkMissed R(DEBUG_TYPE, "NotAStore", 1344 MA->getAccessInstruction()); 1345 R << "skipped possible mapping target because non-store instructions " 1346 "are not supported"; 1347 S->getFunction().getContext().diagnose(R); 1348 continue; 1349 } 1350 1351 // Check for more than one element acces per statement instance. 1352 // Currently we expect write accesses to be functional, eg. disallow 1353 // 1354 // { Stmt[0] -> [i] : 0 <= i < 2 } 1355 // 1356 // This may occur when some accesses to the element write/read only 1357 // parts of the element, eg. a single byte. Polly then divides each 1358 // element into subelements of the smallest access length, normal access 1359 // then touch multiple of such subelements. It is very common when the 1360 // array is accesses with memset, memcpy or memmove which take i8* 1361 // arguments. 1362 isl::union_map AccRel = MA->getLatestAccessRelation(); 1363 if (!AccRel.is_single_valued().is_true()) { 1364 DEBUG(dbgs() << "Access " << MA 1365 << " is incompatible because it writes multiple " 1366 "elements per instance\n"); 1367 OptimizationRemarkMissed R(DEBUG_TYPE, "NonFunctionalAccRel", 1368 MA->getAccessInstruction()); 1369 R << "skipped possible mapping target because it writes more than " 1370 "one element"; 1371 S->getFunction().getContext().diagnose(R); 1372 continue; 1373 } 1374 1375 isl::union_set TouchedElts = AccRel.range(); 1376 if (!TouchedElts.is_subset(CompatibleElts)) { 1377 DEBUG( 1378 dbgs() 1379 << "Access " << MA 1380 << " is incompatible because it touches incompatible elements\n"); 1381 OptimizationRemarkMissed R(DEBUG_TYPE, "IncompatibleElts", 1382 MA->getAccessInstruction()); 1383 R << "skipped possible mapping target because a target location " 1384 "cannot be reliably analyzed"; 1385 S->getFunction().getContext().diagnose(R); 1386 continue; 1387 } 1388 1389 assert(isCompatibleAccess(MA)); 1390 NumberOfCompatibleTargets++; 1391 DEBUG(dbgs() << "Analyzing target access " << MA << "\n"); 1392 if (collapseScalarsToStore(MA)) 1393 Modified = true; 1394 } 1395 } 1396 1397 if (Modified) 1398 DeLICMScopsModified++; 1399 } 1400 1401 /// Dump the internal information about a performed DeLICM to @p OS. 1402 void print(llvm::raw_ostream &OS, int Indent = 0) { 1403 if (!Zone.isUsable()) { 1404 OS.indent(Indent) << "Zone not computed\n"; 1405 return; 1406 } 1407 1408 printStatistics(OS, Indent); 1409 if (!isModified()) { 1410 OS.indent(Indent) << "No modification has been made\n"; 1411 return; 1412 } 1413 printAccesses(OS, Indent); 1414 } 1415 }; 1416 1417 class DeLICM : public ScopPass { 1418 private: 1419 DeLICM(const DeLICM &) = delete; 1420 const DeLICM &operator=(const DeLICM &) = delete; 1421 1422 /// The pass implementation, also holding per-scop data. 1423 std::unique_ptr<DeLICMImpl> Impl; 1424 1425 void collapseToUnused(Scop &S) { 1426 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1427 Impl = make_unique<DeLICMImpl>(&S, &LI); 1428 1429 if (!Impl->computeZone()) { 1430 DEBUG(dbgs() << "Abort because cannot reliably compute lifetimes\n"); 1431 return; 1432 } 1433 1434 DEBUG(dbgs() << "Collapsing scalars to unused array elements...\n"); 1435 Impl->greedyCollapse(); 1436 1437 DEBUG(dbgs() << "\nFinal Scop:\n"); 1438 DEBUG(dbgs() << S); 1439 } 1440 1441 public: 1442 static char ID; 1443 explicit DeLICM() : ScopPass(ID) {} 1444 1445 virtual void getAnalysisUsage(AnalysisUsage &AU) const override { 1446 AU.addRequiredTransitive<ScopInfoRegionPass>(); 1447 AU.addRequired<LoopInfoWrapperPass>(); 1448 AU.setPreservesAll(); 1449 } 1450 1451 virtual bool runOnScop(Scop &S) override { 1452 // Free resources for previous scop's computation, if not yet done. 1453 releaseMemory(); 1454 1455 collapseToUnused(S); 1456 1457 auto ScopStats = S.getStatistics(); 1458 NumValueWrites += ScopStats.NumValueWrites; 1459 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops; 1460 NumPHIWrites += ScopStats.NumPHIWrites; 1461 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops; 1462 NumSingletonWrites += ScopStats.NumSingletonWrites; 1463 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops; 1464 1465 return false; 1466 } 1467 1468 virtual void printScop(raw_ostream &OS, Scop &S) const override { 1469 if (!Impl) 1470 return; 1471 assert(Impl->getScop() == &S); 1472 1473 OS << "DeLICM result:\n"; 1474 Impl->print(OS); 1475 } 1476 1477 virtual void releaseMemory() override { Impl.reset(); } 1478 }; 1479 1480 char DeLICM::ID; 1481 } // anonymous namespace 1482 1483 Pass *polly::createDeLICMPass() { return new DeLICM(); } 1484 1485 INITIALIZE_PASS_BEGIN(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false, 1486 false) 1487 INITIALIZE_PASS_DEPENDENCY(ScopInfoWrapperPass) 1488 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 1489 INITIALIZE_PASS_END(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false, 1490 false) 1491 1492 bool polly::isConflicting( 1493 isl::union_set ExistingOccupied, isl::union_set ExistingUnused, 1494 isl::union_map ExistingKnown, isl::union_map ExistingWrites, 1495 isl::union_set ProposedOccupied, isl::union_set ProposedUnused, 1496 isl::union_map ProposedKnown, isl::union_map ProposedWrites, 1497 llvm::raw_ostream *OS, unsigned Indent) { 1498 Knowledge Existing(std::move(ExistingOccupied), std::move(ExistingUnused), 1499 std::move(ExistingKnown), std::move(ExistingWrites)); 1500 Knowledge Proposed(std::move(ProposedOccupied), std::move(ProposedUnused), 1501 std::move(ProposedKnown), std::move(ProposedWrites)); 1502 1503 return Knowledge::isConflicting(Existing, Proposed, OS, Indent); 1504 } 1505