1 //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===// 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 /// \file 9 /// This transformation implements the well known scalar replacement of 10 /// aggregates transformation. It tries to identify promotable elements of an 11 /// aggregate alloca, and promote them to registers. It will also try to 12 /// convert uses of an element (or set of elements) of an alloca into a vector 13 /// or bitfield-style integer scalar if appropriate. 14 /// 15 /// It works to do this with minimal slicing of the alloca so that regions 16 /// which are merely transferred in and out of external memory remain unchanged 17 /// and are not decomposed to scalar code. 18 /// 19 /// Because this also performs alloca promotion, it can be thought of as also 20 /// serving the purpose of SSA formation. The algorithm iterates on the 21 /// function until all opportunities for promotion have been realized. 22 /// 23 //===----------------------------------------------------------------------===// 24 25 #include "llvm/Transforms/Scalar/SROA.h" 26 #include "llvm/ADT/APInt.h" 27 #include "llvm/ADT/ArrayRef.h" 28 #include "llvm/ADT/DenseMap.h" 29 #include "llvm/ADT/PointerIntPair.h" 30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SetVector.h" 32 #include "llvm/ADT/SmallBitVector.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/ADT/iterator.h" 39 #include "llvm/ADT/iterator_range.h" 40 #include "llvm/Analysis/AssumptionCache.h" 41 #include "llvm/Analysis/GlobalsModRef.h" 42 #include "llvm/Analysis/Loads.h" 43 #include "llvm/Analysis/PtrUseVisitor.h" 44 #include "llvm/Config/llvm-config.h" 45 #include "llvm/IR/BasicBlock.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/ConstantFolder.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DIBuilder.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugInfoMetadata.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Dominators.h" 54 #include "llvm/IR/Function.h" 55 #include "llvm/IR/GetElementPtrTypeIterator.h" 56 #include "llvm/IR/GlobalAlias.h" 57 #include "llvm/IR/IRBuilder.h" 58 #include "llvm/IR/InstVisitor.h" 59 #include "llvm/IR/InstrTypes.h" 60 #include "llvm/IR/Instruction.h" 61 #include "llvm/IR/Instructions.h" 62 #include "llvm/IR/IntrinsicInst.h" 63 #include "llvm/IR/Intrinsics.h" 64 #include "llvm/IR/LLVMContext.h" 65 #include "llvm/IR/Metadata.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/IR/Operator.h" 68 #include "llvm/IR/PassManager.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/IR/Use.h" 71 #include "llvm/IR/User.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/InitializePasses.h" 74 #include "llvm/Pass.h" 75 #include "llvm/Support/Casting.h" 76 #include "llvm/Support/CommandLine.h" 77 #include "llvm/Support/Compiler.h" 78 #include "llvm/Support/Debug.h" 79 #include "llvm/Support/ErrorHandling.h" 80 #include "llvm/Support/MathExtras.h" 81 #include "llvm/Support/raw_ostream.h" 82 #include "llvm/Transforms/Scalar.h" 83 #include "llvm/Transforms/Utils/Local.h" 84 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 85 #include <algorithm> 86 #include <cassert> 87 #include <chrono> 88 #include <cstddef> 89 #include <cstdint> 90 #include <cstring> 91 #include <iterator> 92 #include <string> 93 #include <tuple> 94 #include <utility> 95 #include <vector> 96 97 #ifndef NDEBUG 98 // We only use this for a debug check. 99 #include <random> 100 #endif 101 102 using namespace llvm; 103 using namespace llvm::sroa; 104 105 #define DEBUG_TYPE "sroa" 106 107 STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement"); 108 STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed"); 109 STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca"); 110 STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten"); 111 STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition"); 112 STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced"); 113 STATISTIC(NumPromoted, "Number of allocas promoted to SSA values"); 114 STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion"); 115 STATISTIC(NumDeleted, "Number of instructions deleted"); 116 STATISTIC(NumVectorized, "Number of vectorized aggregates"); 117 118 /// Hidden option to enable randomly shuffling the slices to help uncover 119 /// instability in their order. 120 static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices", 121 cl::init(false), cl::Hidden); 122 123 /// Hidden option to experiment with completely strict handling of inbounds 124 /// GEPs. 125 static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false), 126 cl::Hidden); 127 128 namespace { 129 130 /// A custom IRBuilder inserter which prefixes all names, but only in 131 /// Assert builds. 132 class IRBuilderPrefixedInserter final : public IRBuilderDefaultInserter { 133 std::string Prefix; 134 135 const Twine getNameWithPrefix(const Twine &Name) const { 136 return Name.isTriviallyEmpty() ? Name : Prefix + Name; 137 } 138 139 public: 140 void SetNamePrefix(const Twine &P) { Prefix = P.str(); } 141 142 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB, 143 BasicBlock::iterator InsertPt) const override { 144 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB, 145 InsertPt); 146 } 147 }; 148 149 /// Provide a type for IRBuilder that drops names in release builds. 150 using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>; 151 152 /// A used slice of an alloca. 153 /// 154 /// This structure represents a slice of an alloca used by some instruction. It 155 /// stores both the begin and end offsets of this use, a pointer to the use 156 /// itself, and a flag indicating whether we can classify the use as splittable 157 /// or not when forming partitions of the alloca. 158 class Slice { 159 /// The beginning offset of the range. 160 uint64_t BeginOffset = 0; 161 162 /// The ending offset, not included in the range. 163 uint64_t EndOffset = 0; 164 165 /// Storage for both the use of this slice and whether it can be 166 /// split. 167 PointerIntPair<Use *, 1, bool> UseAndIsSplittable; 168 169 public: 170 Slice() = default; 171 172 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable) 173 : BeginOffset(BeginOffset), EndOffset(EndOffset), 174 UseAndIsSplittable(U, IsSplittable) {} 175 176 uint64_t beginOffset() const { return BeginOffset; } 177 uint64_t endOffset() const { return EndOffset; } 178 179 bool isSplittable() const { return UseAndIsSplittable.getInt(); } 180 void makeUnsplittable() { UseAndIsSplittable.setInt(false); } 181 182 Use *getUse() const { return UseAndIsSplittable.getPointer(); } 183 184 bool isDead() const { return getUse() == nullptr; } 185 void kill() { UseAndIsSplittable.setPointer(nullptr); } 186 187 /// Support for ordering ranges. 188 /// 189 /// This provides an ordering over ranges such that start offsets are 190 /// always increasing, and within equal start offsets, the end offsets are 191 /// decreasing. Thus the spanning range comes first in a cluster with the 192 /// same start position. 193 bool operator<(const Slice &RHS) const { 194 if (beginOffset() < RHS.beginOffset()) 195 return true; 196 if (beginOffset() > RHS.beginOffset()) 197 return false; 198 if (isSplittable() != RHS.isSplittable()) 199 return !isSplittable(); 200 if (endOffset() > RHS.endOffset()) 201 return true; 202 return false; 203 } 204 205 /// Support comparison with a single offset to allow binary searches. 206 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS, 207 uint64_t RHSOffset) { 208 return LHS.beginOffset() < RHSOffset; 209 } 210 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset, 211 const Slice &RHS) { 212 return LHSOffset < RHS.beginOffset(); 213 } 214 215 bool operator==(const Slice &RHS) const { 216 return isSplittable() == RHS.isSplittable() && 217 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset(); 218 } 219 bool operator!=(const Slice &RHS) const { return !operator==(RHS); } 220 }; 221 222 } // end anonymous namespace 223 224 /// Representation of the alloca slices. 225 /// 226 /// This class represents the slices of an alloca which are formed by its 227 /// various uses. If a pointer escapes, we can't fully build a representation 228 /// for the slices used and we reflect that in this structure. The uses are 229 /// stored, sorted by increasing beginning offset and with unsplittable slices 230 /// starting at a particular offset before splittable slices. 231 class llvm::sroa::AllocaSlices { 232 public: 233 /// Construct the slices of a particular alloca. 234 AllocaSlices(const DataLayout &DL, AllocaInst &AI); 235 236 /// Test whether a pointer to the allocation escapes our analysis. 237 /// 238 /// If this is true, the slices are never fully built and should be 239 /// ignored. 240 bool isEscaped() const { return PointerEscapingInstr; } 241 242 /// Support for iterating over the slices. 243 /// @{ 244 using iterator = SmallVectorImpl<Slice>::iterator; 245 using range = iterator_range<iterator>; 246 247 iterator begin() { return Slices.begin(); } 248 iterator end() { return Slices.end(); } 249 250 using const_iterator = SmallVectorImpl<Slice>::const_iterator; 251 using const_range = iterator_range<const_iterator>; 252 253 const_iterator begin() const { return Slices.begin(); } 254 const_iterator end() const { return Slices.end(); } 255 /// @} 256 257 /// Erase a range of slices. 258 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); } 259 260 /// Insert new slices for this alloca. 261 /// 262 /// This moves the slices into the alloca's slices collection, and re-sorts 263 /// everything so that the usual ordering properties of the alloca's slices 264 /// hold. 265 void insert(ArrayRef<Slice> NewSlices) { 266 int OldSize = Slices.size(); 267 Slices.append(NewSlices.begin(), NewSlices.end()); 268 auto SliceI = Slices.begin() + OldSize; 269 llvm::sort(SliceI, Slices.end()); 270 std::inplace_merge(Slices.begin(), SliceI, Slices.end()); 271 } 272 273 // Forward declare the iterator and range accessor for walking the 274 // partitions. 275 class partition_iterator; 276 iterator_range<partition_iterator> partitions(); 277 278 /// Access the dead users for this alloca. 279 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; } 280 281 /// Access the dead operands referring to this alloca. 282 /// 283 /// These are operands which have cannot actually be used to refer to the 284 /// alloca as they are outside its range and the user doesn't correct for 285 /// that. These mostly consist of PHI node inputs and the like which we just 286 /// need to replace with undef. 287 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; } 288 289 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 290 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const; 291 void printSlice(raw_ostream &OS, const_iterator I, 292 StringRef Indent = " ") const; 293 void printUse(raw_ostream &OS, const_iterator I, 294 StringRef Indent = " ") const; 295 void print(raw_ostream &OS) const; 296 void dump(const_iterator I) const; 297 void dump() const; 298 #endif 299 300 private: 301 template <typename DerivedT, typename RetT = void> class BuilderBase; 302 class SliceBuilder; 303 304 friend class AllocaSlices::SliceBuilder; 305 306 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 307 /// Handle to alloca instruction to simplify method interfaces. 308 AllocaInst &AI; 309 #endif 310 311 /// The instruction responsible for this alloca not having a known set 312 /// of slices. 313 /// 314 /// When an instruction (potentially) escapes the pointer to the alloca, we 315 /// store a pointer to that here and abort trying to form slices of the 316 /// alloca. This will be null if the alloca slices are analyzed successfully. 317 Instruction *PointerEscapingInstr; 318 319 /// The slices of the alloca. 320 /// 321 /// We store a vector of the slices formed by uses of the alloca here. This 322 /// vector is sorted by increasing begin offset, and then the unsplittable 323 /// slices before the splittable ones. See the Slice inner class for more 324 /// details. 325 SmallVector<Slice, 8> Slices; 326 327 /// Instructions which will become dead if we rewrite the alloca. 328 /// 329 /// Note that these are not separated by slice. This is because we expect an 330 /// alloca to be completely rewritten or not rewritten at all. If rewritten, 331 /// all these instructions can simply be removed and replaced with undef as 332 /// they come from outside of the allocated space. 333 SmallVector<Instruction *, 8> DeadUsers; 334 335 /// Operands which will become dead if we rewrite the alloca. 336 /// 337 /// These are operands that in their particular use can be replaced with 338 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs 339 /// to PHI nodes and the like. They aren't entirely dead (there might be 340 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we 341 /// want to swap this particular input for undef to simplify the use lists of 342 /// the alloca. 343 SmallVector<Use *, 8> DeadOperands; 344 }; 345 346 /// A partition of the slices. 347 /// 348 /// An ephemeral representation for a range of slices which can be viewed as 349 /// a partition of the alloca. This range represents a span of the alloca's 350 /// memory which cannot be split, and provides access to all of the slices 351 /// overlapping some part of the partition. 352 /// 353 /// Objects of this type are produced by traversing the alloca's slices, but 354 /// are only ephemeral and not persistent. 355 class llvm::sroa::Partition { 356 private: 357 friend class AllocaSlices; 358 friend class AllocaSlices::partition_iterator; 359 360 using iterator = AllocaSlices::iterator; 361 362 /// The beginning and ending offsets of the alloca for this 363 /// partition. 364 uint64_t BeginOffset = 0, EndOffset = 0; 365 366 /// The start and end iterators of this partition. 367 iterator SI, SJ; 368 369 /// A collection of split slice tails overlapping the partition. 370 SmallVector<Slice *, 4> SplitTails; 371 372 /// Raw constructor builds an empty partition starting and ending at 373 /// the given iterator. 374 Partition(iterator SI) : SI(SI), SJ(SI) {} 375 376 public: 377 /// The start offset of this partition. 378 /// 379 /// All of the contained slices start at or after this offset. 380 uint64_t beginOffset() const { return BeginOffset; } 381 382 /// The end offset of this partition. 383 /// 384 /// All of the contained slices end at or before this offset. 385 uint64_t endOffset() const { return EndOffset; } 386 387 /// The size of the partition. 388 /// 389 /// Note that this can never be zero. 390 uint64_t size() const { 391 assert(BeginOffset < EndOffset && "Partitions must span some bytes!"); 392 return EndOffset - BeginOffset; 393 } 394 395 /// Test whether this partition contains no slices, and merely spans 396 /// a region occupied by split slices. 397 bool empty() const { return SI == SJ; } 398 399 /// \name Iterate slices that start within the partition. 400 /// These may be splittable or unsplittable. They have a begin offset >= the 401 /// partition begin offset. 402 /// @{ 403 // FIXME: We should probably define a "concat_iterator" helper and use that 404 // to stitch together pointee_iterators over the split tails and the 405 // contiguous iterators of the partition. That would give a much nicer 406 // interface here. We could then additionally expose filtered iterators for 407 // split, unsplit, and unsplittable splices based on the usage patterns. 408 iterator begin() const { return SI; } 409 iterator end() const { return SJ; } 410 /// @} 411 412 /// Get the sequence of split slice tails. 413 /// 414 /// These tails are of slices which start before this partition but are 415 /// split and overlap into the partition. We accumulate these while forming 416 /// partitions. 417 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; } 418 }; 419 420 /// An iterator over partitions of the alloca's slices. 421 /// 422 /// This iterator implements the core algorithm for partitioning the alloca's 423 /// slices. It is a forward iterator as we don't support backtracking for 424 /// efficiency reasons, and re-use a single storage area to maintain the 425 /// current set of split slices. 426 /// 427 /// It is templated on the slice iterator type to use so that it can operate 428 /// with either const or non-const slice iterators. 429 class AllocaSlices::partition_iterator 430 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag, 431 Partition> { 432 friend class AllocaSlices; 433 434 /// Most of the state for walking the partitions is held in a class 435 /// with a nice interface for examining them. 436 Partition P; 437 438 /// We need to keep the end of the slices to know when to stop. 439 AllocaSlices::iterator SE; 440 441 /// We also need to keep track of the maximum split end offset seen. 442 /// FIXME: Do we really? 443 uint64_t MaxSplitSliceEndOffset = 0; 444 445 /// Sets the partition to be empty at given iterator, and sets the 446 /// end iterator. 447 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE) 448 : P(SI), SE(SE) { 449 // If not already at the end, advance our state to form the initial 450 // partition. 451 if (SI != SE) 452 advance(); 453 } 454 455 /// Advance the iterator to the next partition. 456 /// 457 /// Requires that the iterator not be at the end of the slices. 458 void advance() { 459 assert((P.SI != SE || !P.SplitTails.empty()) && 460 "Cannot advance past the end of the slices!"); 461 462 // Clear out any split uses which have ended. 463 if (!P.SplitTails.empty()) { 464 if (P.EndOffset >= MaxSplitSliceEndOffset) { 465 // If we've finished all splits, this is easy. 466 P.SplitTails.clear(); 467 MaxSplitSliceEndOffset = 0; 468 } else { 469 // Remove the uses which have ended in the prior partition. This 470 // cannot change the max split slice end because we just checked that 471 // the prior partition ended prior to that max. 472 P.SplitTails.erase(llvm::remove_if(P.SplitTails, 473 [&](Slice *S) { 474 return S->endOffset() <= 475 P.EndOffset; 476 }), 477 P.SplitTails.end()); 478 assert(llvm::any_of(P.SplitTails, 479 [&](Slice *S) { 480 return S->endOffset() == MaxSplitSliceEndOffset; 481 }) && 482 "Could not find the current max split slice offset!"); 483 assert(llvm::all_of(P.SplitTails, 484 [&](Slice *S) { 485 return S->endOffset() <= MaxSplitSliceEndOffset; 486 }) && 487 "Max split slice end offset is not actually the max!"); 488 } 489 } 490 491 // If P.SI is already at the end, then we've cleared the split tail and 492 // now have an end iterator. 493 if (P.SI == SE) { 494 assert(P.SplitTails.empty() && "Failed to clear the split slices!"); 495 return; 496 } 497 498 // If we had a non-empty partition previously, set up the state for 499 // subsequent partitions. 500 if (P.SI != P.SJ) { 501 // Accumulate all the splittable slices which started in the old 502 // partition into the split list. 503 for (Slice &S : P) 504 if (S.isSplittable() && S.endOffset() > P.EndOffset) { 505 P.SplitTails.push_back(&S); 506 MaxSplitSliceEndOffset = 507 std::max(S.endOffset(), MaxSplitSliceEndOffset); 508 } 509 510 // Start from the end of the previous partition. 511 P.SI = P.SJ; 512 513 // If P.SI is now at the end, we at most have a tail of split slices. 514 if (P.SI == SE) { 515 P.BeginOffset = P.EndOffset; 516 P.EndOffset = MaxSplitSliceEndOffset; 517 return; 518 } 519 520 // If the we have split slices and the next slice is after a gap and is 521 // not splittable immediately form an empty partition for the split 522 // slices up until the next slice begins. 523 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset && 524 !P.SI->isSplittable()) { 525 P.BeginOffset = P.EndOffset; 526 P.EndOffset = P.SI->beginOffset(); 527 return; 528 } 529 } 530 531 // OK, we need to consume new slices. Set the end offset based on the 532 // current slice, and step SJ past it. The beginning offset of the 533 // partition is the beginning offset of the next slice unless we have 534 // pre-existing split slices that are continuing, in which case we begin 535 // at the prior end offset. 536 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset; 537 P.EndOffset = P.SI->endOffset(); 538 ++P.SJ; 539 540 // There are two strategies to form a partition based on whether the 541 // partition starts with an unsplittable slice or a splittable slice. 542 if (!P.SI->isSplittable()) { 543 // When we're forming an unsplittable region, it must always start at 544 // the first slice and will extend through its end. 545 assert(P.BeginOffset == P.SI->beginOffset()); 546 547 // Form a partition including all of the overlapping slices with this 548 // unsplittable slice. 549 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) { 550 if (!P.SJ->isSplittable()) 551 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset()); 552 ++P.SJ; 553 } 554 555 // We have a partition across a set of overlapping unsplittable 556 // partitions. 557 return; 558 } 559 560 // If we're starting with a splittable slice, then we need to form 561 // a synthetic partition spanning it and any other overlapping splittable 562 // splices. 563 assert(P.SI->isSplittable() && "Forming a splittable partition!"); 564 565 // Collect all of the overlapping splittable slices. 566 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset && 567 P.SJ->isSplittable()) { 568 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset()); 569 ++P.SJ; 570 } 571 572 // Back upiP.EndOffset if we ended the span early when encountering an 573 // unsplittable slice. This synthesizes the early end offset of 574 // a partition spanning only splittable slices. 575 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) { 576 assert(!P.SJ->isSplittable()); 577 P.EndOffset = P.SJ->beginOffset(); 578 } 579 } 580 581 public: 582 bool operator==(const partition_iterator &RHS) const { 583 assert(SE == RHS.SE && 584 "End iterators don't match between compared partition iterators!"); 585 586 // The observed positions of partitions is marked by the P.SI iterator and 587 // the emptiness of the split slices. The latter is only relevant when 588 // P.SI == SE, as the end iterator will additionally have an empty split 589 // slices list, but the prior may have the same P.SI and a tail of split 590 // slices. 591 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) { 592 assert(P.SJ == RHS.P.SJ && 593 "Same set of slices formed two different sized partitions!"); 594 assert(P.SplitTails.size() == RHS.P.SplitTails.size() && 595 "Same slice position with differently sized non-empty split " 596 "slice tails!"); 597 return true; 598 } 599 return false; 600 } 601 602 partition_iterator &operator++() { 603 advance(); 604 return *this; 605 } 606 607 Partition &operator*() { return P; } 608 }; 609 610 /// A forward range over the partitions of the alloca's slices. 611 /// 612 /// This accesses an iterator range over the partitions of the alloca's 613 /// slices. It computes these partitions on the fly based on the overlapping 614 /// offsets of the slices and the ability to split them. It will visit "empty" 615 /// partitions to cover regions of the alloca only accessed via split 616 /// slices. 617 iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() { 618 return make_range(partition_iterator(begin(), end()), 619 partition_iterator(end(), end())); 620 } 621 622 static Value *foldSelectInst(SelectInst &SI) { 623 // If the condition being selected on is a constant or the same value is 624 // being selected between, fold the select. Yes this does (rarely) happen 625 // early on. 626 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition())) 627 return SI.getOperand(1 + CI->isZero()); 628 if (SI.getOperand(1) == SI.getOperand(2)) 629 return SI.getOperand(1); 630 631 return nullptr; 632 } 633 634 /// A helper that folds a PHI node or a select. 635 static Value *foldPHINodeOrSelectInst(Instruction &I) { 636 if (PHINode *PN = dyn_cast<PHINode>(&I)) { 637 // If PN merges together the same value, return that value. 638 return PN->hasConstantValue(); 639 } 640 return foldSelectInst(cast<SelectInst>(I)); 641 } 642 643 /// Builder for the alloca slices. 644 /// 645 /// This class builds a set of alloca slices by recursively visiting the uses 646 /// of an alloca and making a slice for each load and store at each offset. 647 class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> { 648 friend class PtrUseVisitor<SliceBuilder>; 649 friend class InstVisitor<SliceBuilder>; 650 651 using Base = PtrUseVisitor<SliceBuilder>; 652 653 const uint64_t AllocSize; 654 AllocaSlices &AS; 655 656 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap; 657 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes; 658 659 /// Set to de-duplicate dead instructions found in the use walk. 660 SmallPtrSet<Instruction *, 4> VisitedDeadInsts; 661 662 public: 663 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS) 664 : PtrUseVisitor<SliceBuilder>(DL), 665 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType()).getFixedSize()), 666 AS(AS) {} 667 668 private: 669 void markAsDead(Instruction &I) { 670 if (VisitedDeadInsts.insert(&I).second) 671 AS.DeadUsers.push_back(&I); 672 } 673 674 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size, 675 bool IsSplittable = false) { 676 // Completely skip uses which have a zero size or start either before or 677 // past the end of the allocation. 678 if (Size == 0 || Offset.uge(AllocSize)) { 679 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" 680 << Offset 681 << " which has zero size or starts outside of the " 682 << AllocSize << " byte alloca:\n" 683 << " alloca: " << AS.AI << "\n" 684 << " use: " << I << "\n"); 685 return markAsDead(I); 686 } 687 688 uint64_t BeginOffset = Offset.getZExtValue(); 689 uint64_t EndOffset = BeginOffset + Size; 690 691 // Clamp the end offset to the end of the allocation. Note that this is 692 // formulated to handle even the case where "BeginOffset + Size" overflows. 693 // This may appear superficially to be something we could ignore entirely, 694 // but that is not so! There may be widened loads or PHI-node uses where 695 // some instructions are dead but not others. We can't completely ignore 696 // them, and so have to record at least the information here. 697 assert(AllocSize >= BeginOffset); // Established above. 698 if (Size > AllocSize - BeginOffset) { 699 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" 700 << Offset << " to remain within the " << AllocSize 701 << " byte alloca:\n" 702 << " alloca: " << AS.AI << "\n" 703 << " use: " << I << "\n"); 704 EndOffset = AllocSize; 705 } 706 707 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable)); 708 } 709 710 void visitBitCastInst(BitCastInst &BC) { 711 if (BC.use_empty()) 712 return markAsDead(BC); 713 714 return Base::visitBitCastInst(BC); 715 } 716 717 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) { 718 if (ASC.use_empty()) 719 return markAsDead(ASC); 720 721 return Base::visitAddrSpaceCastInst(ASC); 722 } 723 724 void visitGetElementPtrInst(GetElementPtrInst &GEPI) { 725 if (GEPI.use_empty()) 726 return markAsDead(GEPI); 727 728 if (SROAStrictInbounds && GEPI.isInBounds()) { 729 // FIXME: This is a manually un-factored variant of the basic code inside 730 // of GEPs with checking of the inbounds invariant specified in the 731 // langref in a very strict sense. If we ever want to enable 732 // SROAStrictInbounds, this code should be factored cleanly into 733 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds 734 // by writing out the code here where we have the underlying allocation 735 // size readily available. 736 APInt GEPOffset = Offset; 737 const DataLayout &DL = GEPI.getModule()->getDataLayout(); 738 for (gep_type_iterator GTI = gep_type_begin(GEPI), 739 GTE = gep_type_end(GEPI); 740 GTI != GTE; ++GTI) { 741 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); 742 if (!OpC) 743 break; 744 745 // Handle a struct index, which adds its field offset to the pointer. 746 if (StructType *STy = GTI.getStructTypeOrNull()) { 747 unsigned ElementIdx = OpC->getZExtValue(); 748 const StructLayout *SL = DL.getStructLayout(STy); 749 GEPOffset += 750 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx)); 751 } else { 752 // For array or vector indices, scale the index by the size of the 753 // type. 754 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth()); 755 GEPOffset += 756 Index * 757 APInt(Offset.getBitWidth(), 758 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize()); 759 } 760 761 // If this index has computed an intermediate pointer which is not 762 // inbounds, then the result of the GEP is a poison value and we can 763 // delete it and all uses. 764 if (GEPOffset.ugt(AllocSize)) 765 return markAsDead(GEPI); 766 } 767 } 768 769 return Base::visitGetElementPtrInst(GEPI); 770 } 771 772 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset, 773 uint64_t Size, bool IsVolatile) { 774 // We allow splitting of non-volatile loads and stores where the type is an 775 // integer type. These may be used to implement 'memcpy' or other "transfer 776 // of bits" patterns. 777 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile; 778 779 insertUse(I, Offset, Size, IsSplittable); 780 } 781 782 void visitLoadInst(LoadInst &LI) { 783 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) && 784 "All simple FCA loads should have been pre-split"); 785 786 if (!IsOffsetKnown) 787 return PI.setAborted(&LI); 788 789 if (LI.isVolatile() && 790 LI.getPointerAddressSpace() != DL.getAllocaAddrSpace()) 791 return PI.setAborted(&LI); 792 793 uint64_t Size = DL.getTypeStoreSize(LI.getType()).getFixedSize(); 794 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile()); 795 } 796 797 void visitStoreInst(StoreInst &SI) { 798 Value *ValOp = SI.getValueOperand(); 799 if (ValOp == *U) 800 return PI.setEscapedAndAborted(&SI); 801 if (!IsOffsetKnown) 802 return PI.setAborted(&SI); 803 804 if (SI.isVolatile() && 805 SI.getPointerAddressSpace() != DL.getAllocaAddrSpace()) 806 return PI.setAborted(&SI); 807 808 uint64_t Size = DL.getTypeStoreSize(ValOp->getType()).getFixedSize(); 809 810 // If this memory access can be shown to *statically* extend outside the 811 // bounds of the allocation, it's behavior is undefined, so simply 812 // ignore it. Note that this is more strict than the generic clamping 813 // behavior of insertUse. We also try to handle cases which might run the 814 // risk of overflow. 815 // FIXME: We should instead consider the pointer to have escaped if this 816 // function is being instrumented for addressing bugs or race conditions. 817 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) { 818 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" 819 << Offset << " which extends past the end of the " 820 << AllocSize << " byte alloca:\n" 821 << " alloca: " << AS.AI << "\n" 822 << " use: " << SI << "\n"); 823 return markAsDead(SI); 824 } 825 826 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) && 827 "All simple FCA stores should have been pre-split"); 828 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile()); 829 } 830 831 void visitMemSetInst(MemSetInst &II) { 832 assert(II.getRawDest() == *U && "Pointer use is not the destination?"); 833 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); 834 if ((Length && Length->getValue() == 0) || 835 (IsOffsetKnown && Offset.uge(AllocSize))) 836 // Zero-length mem transfer intrinsics can be ignored entirely. 837 return markAsDead(II); 838 839 if (!IsOffsetKnown) 840 return PI.setAborted(&II); 841 842 // Don't replace this with a store with a different address space. TODO: 843 // Use a store with the casted new alloca? 844 if (II.isVolatile() && II.getDestAddressSpace() != DL.getAllocaAddrSpace()) 845 return PI.setAborted(&II); 846 847 insertUse(II, Offset, Length ? Length->getLimitedValue() 848 : AllocSize - Offset.getLimitedValue(), 849 (bool)Length); 850 } 851 852 void visitMemTransferInst(MemTransferInst &II) { 853 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); 854 if (Length && Length->getValue() == 0) 855 // Zero-length mem transfer intrinsics can be ignored entirely. 856 return markAsDead(II); 857 858 // Because we can visit these intrinsics twice, also check to see if the 859 // first time marked this instruction as dead. If so, skip it. 860 if (VisitedDeadInsts.count(&II)) 861 return; 862 863 if (!IsOffsetKnown) 864 return PI.setAborted(&II); 865 866 // Don't replace this with a load/store with a different address space. 867 // TODO: Use a store with the casted new alloca? 868 if (II.isVolatile() && 869 (II.getDestAddressSpace() != DL.getAllocaAddrSpace() || 870 II.getSourceAddressSpace() != DL.getAllocaAddrSpace())) 871 return PI.setAborted(&II); 872 873 // This side of the transfer is completely out-of-bounds, and so we can 874 // nuke the entire transfer. However, we also need to nuke the other side 875 // if already added to our partitions. 876 // FIXME: Yet another place we really should bypass this when 877 // instrumenting for ASan. 878 if (Offset.uge(AllocSize)) { 879 SmallDenseMap<Instruction *, unsigned>::iterator MTPI = 880 MemTransferSliceMap.find(&II); 881 if (MTPI != MemTransferSliceMap.end()) 882 AS.Slices[MTPI->second].kill(); 883 return markAsDead(II); 884 } 885 886 uint64_t RawOffset = Offset.getLimitedValue(); 887 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset; 888 889 // Check for the special case where the same exact value is used for both 890 // source and dest. 891 if (*U == II.getRawDest() && *U == II.getRawSource()) { 892 // For non-volatile transfers this is a no-op. 893 if (!II.isVolatile()) 894 return markAsDead(II); 895 896 return insertUse(II, Offset, Size, /*IsSplittable=*/false); 897 } 898 899 // If we have seen both source and destination for a mem transfer, then 900 // they both point to the same alloca. 901 bool Inserted; 902 SmallDenseMap<Instruction *, unsigned>::iterator MTPI; 903 std::tie(MTPI, Inserted) = 904 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size())); 905 unsigned PrevIdx = MTPI->second; 906 if (!Inserted) { 907 Slice &PrevP = AS.Slices[PrevIdx]; 908 909 // Check if the begin offsets match and this is a non-volatile transfer. 910 // In that case, we can completely elide the transfer. 911 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) { 912 PrevP.kill(); 913 return markAsDead(II); 914 } 915 916 // Otherwise we have an offset transfer within the same alloca. We can't 917 // split those. 918 PrevP.makeUnsplittable(); 919 } 920 921 // Insert the use now that we've fixed up the splittable nature. 922 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length); 923 924 // Check that we ended up with a valid index in the map. 925 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II && 926 "Map index doesn't point back to a slice with this user."); 927 } 928 929 // Disable SRoA for any intrinsics except for lifetime invariants. 930 // FIXME: What about debug intrinsics? This matches old behavior, but 931 // doesn't make sense. 932 void visitIntrinsicInst(IntrinsicInst &II) { 933 if (!IsOffsetKnown) 934 return PI.setAborted(&II); 935 936 if (II.isLifetimeStartOrEnd()) { 937 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0)); 938 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(), 939 Length->getLimitedValue()); 940 insertUse(II, Offset, Size, true); 941 return; 942 } 943 944 Base::visitIntrinsicInst(II); 945 } 946 947 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) { 948 // We consider any PHI or select that results in a direct load or store of 949 // the same offset to be a viable use for slicing purposes. These uses 950 // are considered unsplittable and the size is the maximum loaded or stored 951 // size. 952 SmallPtrSet<Instruction *, 4> Visited; 953 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses; 954 Visited.insert(Root); 955 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root)); 956 const DataLayout &DL = Root->getModule()->getDataLayout(); 957 // If there are no loads or stores, the access is dead. We mark that as 958 // a size zero access. 959 Size = 0; 960 do { 961 Instruction *I, *UsedI; 962 std::tie(UsedI, I) = Uses.pop_back_val(); 963 964 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 965 Size = std::max(Size, 966 DL.getTypeStoreSize(LI->getType()).getFixedSize()); 967 continue; 968 } 969 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 970 Value *Op = SI->getOperand(0); 971 if (Op == UsedI) 972 return SI; 973 Size = std::max(Size, 974 DL.getTypeStoreSize(Op->getType()).getFixedSize()); 975 continue; 976 } 977 978 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { 979 if (!GEP->hasAllZeroIndices()) 980 return GEP; 981 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) && 982 !isa<SelectInst>(I) && !isa<AddrSpaceCastInst>(I)) { 983 return I; 984 } 985 986 for (User *U : I->users()) 987 if (Visited.insert(cast<Instruction>(U)).second) 988 Uses.push_back(std::make_pair(I, cast<Instruction>(U))); 989 } while (!Uses.empty()); 990 991 return nullptr; 992 } 993 994 void visitPHINodeOrSelectInst(Instruction &I) { 995 assert(isa<PHINode>(I) || isa<SelectInst>(I)); 996 if (I.use_empty()) 997 return markAsDead(I); 998 999 // TODO: We could use SimplifyInstruction here to fold PHINodes and 1000 // SelectInsts. However, doing so requires to change the current 1001 // dead-operand-tracking mechanism. For instance, suppose neither loading 1002 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not 1003 // trap either. However, if we simply replace %U with undef using the 1004 // current dead-operand-tracking mechanism, "load (select undef, undef, 1005 // %other)" may trap because the select may return the first operand 1006 // "undef". 1007 if (Value *Result = foldPHINodeOrSelectInst(I)) { 1008 if (Result == *U) 1009 // If the result of the constant fold will be the pointer, recurse 1010 // through the PHI/select as if we had RAUW'ed it. 1011 enqueueUsers(I); 1012 else 1013 // Otherwise the operand to the PHI/select is dead, and we can replace 1014 // it with undef. 1015 AS.DeadOperands.push_back(U); 1016 1017 return; 1018 } 1019 1020 if (!IsOffsetKnown) 1021 return PI.setAborted(&I); 1022 1023 // See if we already have computed info on this node. 1024 uint64_t &Size = PHIOrSelectSizes[&I]; 1025 if (!Size) { 1026 // This is a new PHI/Select, check for an unsafe use of it. 1027 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size)) 1028 return PI.setAborted(UnsafeI); 1029 } 1030 1031 // For PHI and select operands outside the alloca, we can't nuke the entire 1032 // phi or select -- the other side might still be relevant, so we special 1033 // case them here and use a separate structure to track the operands 1034 // themselves which should be replaced with undef. 1035 // FIXME: This should instead be escaped in the event we're instrumenting 1036 // for address sanitization. 1037 if (Offset.uge(AllocSize)) { 1038 AS.DeadOperands.push_back(U); 1039 return; 1040 } 1041 1042 insertUse(I, Offset, Size); 1043 } 1044 1045 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); } 1046 1047 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); } 1048 1049 /// Disable SROA entirely if there are unhandled users of the alloca. 1050 void visitInstruction(Instruction &I) { PI.setAborted(&I); } 1051 }; 1052 1053 AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI) 1054 : 1055 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1056 AI(AI), 1057 #endif 1058 PointerEscapingInstr(nullptr) { 1059 SliceBuilder PB(DL, AI, *this); 1060 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI); 1061 if (PtrI.isEscaped() || PtrI.isAborted()) { 1062 // FIXME: We should sink the escape vs. abort info into the caller nicely, 1063 // possibly by just storing the PtrInfo in the AllocaSlices. 1064 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst() 1065 : PtrI.getAbortingInst(); 1066 assert(PointerEscapingInstr && "Did not track a bad instruction"); 1067 return; 1068 } 1069 1070 Slices.erase( 1071 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }), 1072 Slices.end()); 1073 1074 #ifndef NDEBUG 1075 if (SROARandomShuffleSlices) { 1076 std::mt19937 MT(static_cast<unsigned>( 1077 std::chrono::system_clock::now().time_since_epoch().count())); 1078 std::shuffle(Slices.begin(), Slices.end(), MT); 1079 } 1080 #endif 1081 1082 // Sort the uses. This arranges for the offsets to be in ascending order, 1083 // and the sizes to be in descending order. 1084 llvm::sort(Slices); 1085 } 1086 1087 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1088 1089 void AllocaSlices::print(raw_ostream &OS, const_iterator I, 1090 StringRef Indent) const { 1091 printSlice(OS, I, Indent); 1092 OS << "\n"; 1093 printUse(OS, I, Indent); 1094 } 1095 1096 void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I, 1097 StringRef Indent) const { 1098 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")" 1099 << " slice #" << (I - begin()) 1100 << (I->isSplittable() ? " (splittable)" : ""); 1101 } 1102 1103 void AllocaSlices::printUse(raw_ostream &OS, const_iterator I, 1104 StringRef Indent) const { 1105 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n"; 1106 } 1107 1108 void AllocaSlices::print(raw_ostream &OS) const { 1109 if (PointerEscapingInstr) { 1110 OS << "Can't analyze slices for alloca: " << AI << "\n" 1111 << " A pointer to this alloca escaped by:\n" 1112 << " " << *PointerEscapingInstr << "\n"; 1113 return; 1114 } 1115 1116 OS << "Slices of alloca: " << AI << "\n"; 1117 for (const_iterator I = begin(), E = end(); I != E; ++I) 1118 print(OS, I); 1119 } 1120 1121 LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const { 1122 print(dbgs(), I); 1123 } 1124 LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); } 1125 1126 #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1127 1128 /// Walk the range of a partitioning looking for a common type to cover this 1129 /// sequence of slices. 1130 static Type *findCommonType(AllocaSlices::const_iterator B, 1131 AllocaSlices::const_iterator E, 1132 uint64_t EndOffset) { 1133 Type *Ty = nullptr; 1134 bool TyIsCommon = true; 1135 IntegerType *ITy = nullptr; 1136 1137 // Note that we need to look at *every* alloca slice's Use to ensure we 1138 // always get consistent results regardless of the order of slices. 1139 for (AllocaSlices::const_iterator I = B; I != E; ++I) { 1140 Use *U = I->getUse(); 1141 if (isa<IntrinsicInst>(*U->getUser())) 1142 continue; 1143 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset) 1144 continue; 1145 1146 Type *UserTy = nullptr; 1147 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1148 UserTy = LI->getType(); 1149 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 1150 UserTy = SI->getValueOperand()->getType(); 1151 } 1152 1153 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) { 1154 // If the type is larger than the partition, skip it. We only encounter 1155 // this for split integer operations where we want to use the type of the 1156 // entity causing the split. Also skip if the type is not a byte width 1157 // multiple. 1158 if (UserITy->getBitWidth() % 8 != 0 || 1159 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset())) 1160 continue; 1161 1162 // Track the largest bitwidth integer type used in this way in case there 1163 // is no common type. 1164 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth()) 1165 ITy = UserITy; 1166 } 1167 1168 // To avoid depending on the order of slices, Ty and TyIsCommon must not 1169 // depend on types skipped above. 1170 if (!UserTy || (Ty && Ty != UserTy)) 1171 TyIsCommon = false; // Give up on anything but an iN type. 1172 else 1173 Ty = UserTy; 1174 } 1175 1176 return TyIsCommon ? Ty : ITy; 1177 } 1178 1179 /// PHI instructions that use an alloca and are subsequently loaded can be 1180 /// rewritten to load both input pointers in the pred blocks and then PHI the 1181 /// results, allowing the load of the alloca to be promoted. 1182 /// From this: 1183 /// %P2 = phi [i32* %Alloca, i32* %Other] 1184 /// %V = load i32* %P2 1185 /// to: 1186 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1187 /// ... 1188 /// %V2 = load i32* %Other 1189 /// ... 1190 /// %V = phi [i32 %V1, i32 %V2] 1191 /// 1192 /// We can do this to a select if its only uses are loads and if the operands 1193 /// to the select can be loaded unconditionally. 1194 /// 1195 /// FIXME: This should be hoisted into a generic utility, likely in 1196 /// Transforms/Util/Local.h 1197 static bool isSafePHIToSpeculate(PHINode &PN) { 1198 const DataLayout &DL = PN.getModule()->getDataLayout(); 1199 1200 // For now, we can only do this promotion if the load is in the same block 1201 // as the PHI, and if there are no stores between the phi and load. 1202 // TODO: Allow recursive phi users. 1203 // TODO: Allow stores. 1204 BasicBlock *BB = PN.getParent(); 1205 Align MaxAlign; 1206 uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType()); 1207 APInt MaxSize(APWidth, 0); 1208 bool HaveLoad = false; 1209 for (User *U : PN.users()) { 1210 LoadInst *LI = dyn_cast<LoadInst>(U); 1211 if (!LI || !LI->isSimple()) 1212 return false; 1213 1214 // For now we only allow loads in the same block as the PHI. This is 1215 // a common case that happens when instcombine merges two loads through 1216 // a PHI. 1217 if (LI->getParent() != BB) 1218 return false; 1219 1220 // Ensure that there are no instructions between the PHI and the load that 1221 // could store. 1222 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI) 1223 if (BBI->mayWriteToMemory()) 1224 return false; 1225 1226 uint64_t Size = DL.getTypeStoreSize(LI->getType()).getFixedSize(); 1227 MaxAlign = std::max(MaxAlign, LI->getAlign()); 1228 MaxSize = MaxSize.ult(Size) ? APInt(APWidth, Size) : MaxSize; 1229 HaveLoad = true; 1230 } 1231 1232 if (!HaveLoad) 1233 return false; 1234 1235 // We can only transform this if it is safe to push the loads into the 1236 // predecessor blocks. The only thing to watch out for is that we can't put 1237 // a possibly trapping load in the predecessor if it is a critical edge. 1238 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) { 1239 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator(); 1240 Value *InVal = PN.getIncomingValue(Idx); 1241 1242 // If the value is produced by the terminator of the predecessor (an 1243 // invoke) or it has side-effects, there is no valid place to put a load 1244 // in the predecessor. 1245 if (TI == InVal || TI->mayHaveSideEffects()) 1246 return false; 1247 1248 // If the predecessor has a single successor, then the edge isn't 1249 // critical. 1250 if (TI->getNumSuccessors() == 1) 1251 continue; 1252 1253 // If this pointer is always safe to load, or if we can prove that there 1254 // is already a load in the block, then we can move the load to the pred 1255 // block. 1256 if (isSafeToLoadUnconditionally(InVal, MaxAlign, MaxSize, DL, TI)) 1257 continue; 1258 1259 return false; 1260 } 1261 1262 return true; 1263 } 1264 1265 static void speculatePHINodeLoads(PHINode &PN) { 1266 LLVM_DEBUG(dbgs() << " original: " << PN << "\n"); 1267 1268 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back()); 1269 Type *LoadTy = SomeLoad->getType(); 1270 IRBuilderTy PHIBuilder(&PN); 1271 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(), 1272 PN.getName() + ".sroa.speculated"); 1273 1274 // Get the AA tags and alignment to use from one of the loads. It does not 1275 // matter which one we get and if any differ. 1276 AAMDNodes AATags; 1277 SomeLoad->getAAMetadata(AATags); 1278 Align Alignment = SomeLoad->getAlign(); 1279 1280 // Rewrite all loads of the PN to use the new PHI. 1281 while (!PN.use_empty()) { 1282 LoadInst *LI = cast<LoadInst>(PN.user_back()); 1283 LI->replaceAllUsesWith(NewPN); 1284 LI->eraseFromParent(); 1285 } 1286 1287 // Inject loads into all of the pred blocks. 1288 DenseMap<BasicBlock*, Value*> InjectedLoads; 1289 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) { 1290 BasicBlock *Pred = PN.getIncomingBlock(Idx); 1291 Value *InVal = PN.getIncomingValue(Idx); 1292 1293 // A PHI node is allowed to have multiple (duplicated) entries for the same 1294 // basic block, as long as the value is the same. So if we already injected 1295 // a load in the predecessor, then we should reuse the same load for all 1296 // duplicated entries. 1297 if (Value* V = InjectedLoads.lookup(Pred)) { 1298 NewPN->addIncoming(V, Pred); 1299 continue; 1300 } 1301 1302 Instruction *TI = Pred->getTerminator(); 1303 IRBuilderTy PredBuilder(TI); 1304 1305 LoadInst *Load = PredBuilder.CreateAlignedLoad( 1306 LoadTy, InVal, Alignment, 1307 (PN.getName() + ".sroa.speculate.load." + Pred->getName())); 1308 ++NumLoadsSpeculated; 1309 if (AATags) 1310 Load->setAAMetadata(AATags); 1311 NewPN->addIncoming(Load, Pred); 1312 InjectedLoads[Pred] = Load; 1313 } 1314 1315 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n"); 1316 PN.eraseFromParent(); 1317 } 1318 1319 /// Select instructions that use an alloca and are subsequently loaded can be 1320 /// rewritten to load both input pointers and then select between the result, 1321 /// allowing the load of the alloca to be promoted. 1322 /// From this: 1323 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other 1324 /// %V = load i32* %P2 1325 /// to: 1326 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1327 /// %V2 = load i32* %Other 1328 /// %V = select i1 %cond, i32 %V1, i32 %V2 1329 /// 1330 /// We can do this to a select if its only uses are loads and if the operand 1331 /// to the select can be loaded unconditionally. 1332 static bool isSafeSelectToSpeculate(SelectInst &SI) { 1333 Value *TValue = SI.getTrueValue(); 1334 Value *FValue = SI.getFalseValue(); 1335 const DataLayout &DL = SI.getModule()->getDataLayout(); 1336 1337 for (User *U : SI.users()) { 1338 LoadInst *LI = dyn_cast<LoadInst>(U); 1339 if (!LI || !LI->isSimple()) 1340 return false; 1341 1342 // Both operands to the select need to be dereferenceable, either 1343 // absolutely (e.g. allocas) or at this point because we can see other 1344 // accesses to it. 1345 if (!isSafeToLoadUnconditionally(TValue, LI->getType(), 1346 LI->getAlign(), DL, LI)) 1347 return false; 1348 if (!isSafeToLoadUnconditionally(FValue, LI->getType(), 1349 LI->getAlign(), DL, LI)) 1350 return false; 1351 } 1352 1353 return true; 1354 } 1355 1356 static void speculateSelectInstLoads(SelectInst &SI) { 1357 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 1358 1359 IRBuilderTy IRB(&SI); 1360 Value *TV = SI.getTrueValue(); 1361 Value *FV = SI.getFalseValue(); 1362 // Replace the loads of the select with a select of two loads. 1363 while (!SI.use_empty()) { 1364 LoadInst *LI = cast<LoadInst>(SI.user_back()); 1365 assert(LI->isSimple() && "We only speculate simple loads"); 1366 1367 IRB.SetInsertPoint(LI); 1368 LoadInst *TL = IRB.CreateLoad(LI->getType(), TV, 1369 LI->getName() + ".sroa.speculate.load.true"); 1370 LoadInst *FL = IRB.CreateLoad(LI->getType(), FV, 1371 LI->getName() + ".sroa.speculate.load.false"); 1372 NumLoadsSpeculated += 2; 1373 1374 // Transfer alignment and AA info if present. 1375 TL->setAlignment(LI->getAlign()); 1376 FL->setAlignment(LI->getAlign()); 1377 1378 AAMDNodes Tags; 1379 LI->getAAMetadata(Tags); 1380 if (Tags) { 1381 TL->setAAMetadata(Tags); 1382 FL->setAAMetadata(Tags); 1383 } 1384 1385 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL, 1386 LI->getName() + ".sroa.speculated"); 1387 1388 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n"); 1389 LI->replaceAllUsesWith(V); 1390 LI->eraseFromParent(); 1391 } 1392 SI.eraseFromParent(); 1393 } 1394 1395 /// Build a GEP out of a base pointer and indices. 1396 /// 1397 /// This will return the BasePtr if that is valid, or build a new GEP 1398 /// instruction using the IRBuilder if GEP-ing is needed. 1399 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr, 1400 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) { 1401 if (Indices.empty()) 1402 return BasePtr; 1403 1404 // A single zero index is a no-op, so check for this and avoid building a GEP 1405 // in that case. 1406 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero()) 1407 return BasePtr; 1408 1409 return IRB.CreateInBoundsGEP(BasePtr->getType()->getPointerElementType(), 1410 BasePtr, Indices, NamePrefix + "sroa_idx"); 1411 } 1412 1413 /// Get a natural GEP off of the BasePtr walking through Ty toward 1414 /// TargetTy without changing the offset of the pointer. 1415 /// 1416 /// This routine assumes we've already established a properly offset GEP with 1417 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with 1418 /// zero-indices down through type layers until we find one the same as 1419 /// TargetTy. If we can't find one with the same type, we at least try to use 1420 /// one with the same size. If none of that works, we just produce the GEP as 1421 /// indicated by Indices to have the correct offset. 1422 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL, 1423 Value *BasePtr, Type *Ty, Type *TargetTy, 1424 SmallVectorImpl<Value *> &Indices, 1425 Twine NamePrefix) { 1426 if (Ty == TargetTy) 1427 return buildGEP(IRB, BasePtr, Indices, NamePrefix); 1428 1429 // Offset size to use for the indices. 1430 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType()); 1431 1432 // See if we can descend into a struct and locate a field with the correct 1433 // type. 1434 unsigned NumLayers = 0; 1435 Type *ElementTy = Ty; 1436 do { 1437 if (ElementTy->isPointerTy()) 1438 break; 1439 1440 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) { 1441 ElementTy = ArrayTy->getElementType(); 1442 Indices.push_back(IRB.getIntN(OffsetSize, 0)); 1443 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) { 1444 ElementTy = VectorTy->getElementType(); 1445 Indices.push_back(IRB.getInt32(0)); 1446 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) { 1447 if (STy->element_begin() == STy->element_end()) 1448 break; // Nothing left to descend into. 1449 ElementTy = *STy->element_begin(); 1450 Indices.push_back(IRB.getInt32(0)); 1451 } else { 1452 break; 1453 } 1454 ++NumLayers; 1455 } while (ElementTy != TargetTy); 1456 if (ElementTy != TargetTy) 1457 Indices.erase(Indices.end() - NumLayers, Indices.end()); 1458 1459 return buildGEP(IRB, BasePtr, Indices, NamePrefix); 1460 } 1461 1462 /// Recursively compute indices for a natural GEP. 1463 /// 1464 /// This is the recursive step for getNaturalGEPWithOffset that walks down the 1465 /// element types adding appropriate indices for the GEP. 1466 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL, 1467 Value *Ptr, Type *Ty, APInt &Offset, 1468 Type *TargetTy, 1469 SmallVectorImpl<Value *> &Indices, 1470 Twine NamePrefix) { 1471 if (Offset == 0) 1472 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, 1473 NamePrefix); 1474 1475 // We can't recurse through pointer types. 1476 if (Ty->isPointerTy()) 1477 return nullptr; 1478 1479 // We try to analyze GEPs over vectors here, but note that these GEPs are 1480 // extremely poorly defined currently. The long-term goal is to remove GEPing 1481 // over a vector from the IR completely. 1482 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) { 1483 unsigned ElementSizeInBits = 1484 DL.getTypeSizeInBits(VecTy->getScalarType()).getFixedSize(); 1485 if (ElementSizeInBits % 8 != 0) { 1486 // GEPs over non-multiple of 8 size vector elements are invalid. 1487 return nullptr; 1488 } 1489 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8); 1490 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1491 if (NumSkippedElements.ugt(VecTy->getNumElements())) 1492 return nullptr; 1493 Offset -= NumSkippedElements * ElementSize; 1494 Indices.push_back(IRB.getInt(NumSkippedElements)); 1495 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(), 1496 Offset, TargetTy, Indices, NamePrefix); 1497 } 1498 1499 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { 1500 Type *ElementTy = ArrTy->getElementType(); 1501 APInt ElementSize(Offset.getBitWidth(), 1502 DL.getTypeAllocSize(ElementTy).getFixedSize()); 1503 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1504 if (NumSkippedElements.ugt(ArrTy->getNumElements())) 1505 return nullptr; 1506 1507 Offset -= NumSkippedElements * ElementSize; 1508 Indices.push_back(IRB.getInt(NumSkippedElements)); 1509 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1510 Indices, NamePrefix); 1511 } 1512 1513 StructType *STy = dyn_cast<StructType>(Ty); 1514 if (!STy) 1515 return nullptr; 1516 1517 const StructLayout *SL = DL.getStructLayout(STy); 1518 uint64_t StructOffset = Offset.getZExtValue(); 1519 if (StructOffset >= SL->getSizeInBytes()) 1520 return nullptr; 1521 unsigned Index = SL->getElementContainingOffset(StructOffset); 1522 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index)); 1523 Type *ElementTy = STy->getElementType(Index); 1524 if (Offset.uge(DL.getTypeAllocSize(ElementTy).getFixedSize())) 1525 return nullptr; // The offset points into alignment padding. 1526 1527 Indices.push_back(IRB.getInt32(Index)); 1528 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1529 Indices, NamePrefix); 1530 } 1531 1532 /// Get a natural GEP from a base pointer to a particular offset and 1533 /// resulting in a particular type. 1534 /// 1535 /// The goal is to produce a "natural" looking GEP that works with the existing 1536 /// composite types to arrive at the appropriate offset and element type for 1537 /// a pointer. TargetTy is the element type the returned GEP should point-to if 1538 /// possible. We recurse by decreasing Offset, adding the appropriate index to 1539 /// Indices, and setting Ty to the result subtype. 1540 /// 1541 /// If no natural GEP can be constructed, this function returns null. 1542 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL, 1543 Value *Ptr, APInt Offset, Type *TargetTy, 1544 SmallVectorImpl<Value *> &Indices, 1545 Twine NamePrefix) { 1546 PointerType *Ty = cast<PointerType>(Ptr->getType()); 1547 1548 // Don't consider any GEPs through an i8* as natural unless the TargetTy is 1549 // an i8. 1550 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8)) 1551 return nullptr; 1552 1553 Type *ElementTy = Ty->getElementType(); 1554 if (!ElementTy->isSized()) 1555 return nullptr; // We can't GEP through an unsized element. 1556 APInt ElementSize(Offset.getBitWidth(), 1557 DL.getTypeAllocSize(ElementTy).getFixedSize()); 1558 if (ElementSize == 0) 1559 return nullptr; // Zero-length arrays can't help us build a natural GEP. 1560 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1561 1562 Offset -= NumSkippedElements * ElementSize; 1563 Indices.push_back(IRB.getInt(NumSkippedElements)); 1564 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1565 Indices, NamePrefix); 1566 } 1567 1568 /// Compute an adjusted pointer from Ptr by Offset bytes where the 1569 /// resulting pointer has PointerTy. 1570 /// 1571 /// This tries very hard to compute a "natural" GEP which arrives at the offset 1572 /// and produces the pointer type desired. Where it cannot, it will try to use 1573 /// the natural GEP to arrive at the offset and bitcast to the type. Where that 1574 /// fails, it will try to use an existing i8* and GEP to the byte offset and 1575 /// bitcast to the type. 1576 /// 1577 /// The strategy for finding the more natural GEPs is to peel off layers of the 1578 /// pointer, walking back through bit casts and GEPs, searching for a base 1579 /// pointer from which we can compute a natural GEP with the desired 1580 /// properties. The algorithm tries to fold as many constant indices into 1581 /// a single GEP as possible, thus making each GEP more independent of the 1582 /// surrounding code. 1583 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, 1584 APInt Offset, Type *PointerTy, Twine NamePrefix) { 1585 // Even though we don't look through PHI nodes, we could be called on an 1586 // instruction in an unreachable block, which may be on a cycle. 1587 SmallPtrSet<Value *, 4> Visited; 1588 Visited.insert(Ptr); 1589 SmallVector<Value *, 4> Indices; 1590 1591 // We may end up computing an offset pointer that has the wrong type. If we 1592 // never are able to compute one directly that has the correct type, we'll 1593 // fall back to it, so keep it and the base it was computed from around here. 1594 Value *OffsetPtr = nullptr; 1595 Value *OffsetBasePtr; 1596 1597 // Remember any i8 pointer we come across to re-use if we need to do a raw 1598 // byte offset. 1599 Value *Int8Ptr = nullptr; 1600 APInt Int8PtrOffset(Offset.getBitWidth(), 0); 1601 1602 PointerType *TargetPtrTy = cast<PointerType>(PointerTy); 1603 Type *TargetTy = TargetPtrTy->getElementType(); 1604 1605 // As `addrspacecast` is , `Ptr` (the storage pointer) may have different 1606 // address space from the expected `PointerTy` (the pointer to be used). 1607 // Adjust the pointer type based the original storage pointer. 1608 auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace(); 1609 PointerTy = TargetTy->getPointerTo(AS); 1610 1611 do { 1612 // First fold any existing GEPs into the offset. 1613 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) { 1614 APInt GEPOffset(Offset.getBitWidth(), 0); 1615 if (!GEP->accumulateConstantOffset(DL, GEPOffset)) 1616 break; 1617 Offset += GEPOffset; 1618 Ptr = GEP->getPointerOperand(); 1619 if (!Visited.insert(Ptr).second) 1620 break; 1621 } 1622 1623 // See if we can perform a natural GEP here. 1624 Indices.clear(); 1625 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy, 1626 Indices, NamePrefix)) { 1627 // If we have a new natural pointer at the offset, clear out any old 1628 // offset pointer we computed. Unless it is the base pointer or 1629 // a non-instruction, we built a GEP we don't need. Zap it. 1630 if (OffsetPtr && OffsetPtr != OffsetBasePtr) 1631 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) { 1632 assert(I->use_empty() && "Built a GEP with uses some how!"); 1633 I->eraseFromParent(); 1634 } 1635 OffsetPtr = P; 1636 OffsetBasePtr = Ptr; 1637 // If we also found a pointer of the right type, we're done. 1638 if (P->getType() == PointerTy) 1639 break; 1640 } 1641 1642 // Stash this pointer if we've found an i8*. 1643 if (Ptr->getType()->isIntegerTy(8)) { 1644 Int8Ptr = Ptr; 1645 Int8PtrOffset = Offset; 1646 } 1647 1648 // Peel off a layer of the pointer and update the offset appropriately. 1649 if (Operator::getOpcode(Ptr) == Instruction::BitCast) { 1650 Ptr = cast<Operator>(Ptr)->getOperand(0); 1651 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) { 1652 if (GA->isInterposable()) 1653 break; 1654 Ptr = GA->getAliasee(); 1655 } else { 1656 break; 1657 } 1658 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!"); 1659 } while (Visited.insert(Ptr).second); 1660 1661 if (!OffsetPtr) { 1662 if (!Int8Ptr) { 1663 Int8Ptr = IRB.CreateBitCast( 1664 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()), 1665 NamePrefix + "sroa_raw_cast"); 1666 Int8PtrOffset = Offset; 1667 } 1668 1669 OffsetPtr = Int8PtrOffset == 0 1670 ? Int8Ptr 1671 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr, 1672 IRB.getInt(Int8PtrOffset), 1673 NamePrefix + "sroa_raw_idx"); 1674 } 1675 Ptr = OffsetPtr; 1676 1677 // On the off chance we were targeting i8*, guard the bitcast here. 1678 if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) { 1679 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, 1680 TargetPtrTy, 1681 NamePrefix + "sroa_cast"); 1682 } 1683 1684 return Ptr; 1685 } 1686 1687 /// Compute the adjusted alignment for a load or store from an offset. 1688 static Align getAdjustedAlignment(Instruction *I, uint64_t Offset) { 1689 return commonAlignment(getLoadStoreAlignment(I), Offset); 1690 } 1691 1692 /// Test whether we can convert a value from the old to the new type. 1693 /// 1694 /// This predicate should be used to guard calls to convertValue in order to 1695 /// ensure that we only try to convert viable values. The strategy is that we 1696 /// will peel off single element struct and array wrappings to get to an 1697 /// underlying value, and convert that value. 1698 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) { 1699 if (OldTy == NewTy) 1700 return true; 1701 1702 // For integer types, we can't handle any bit-width differences. This would 1703 // break both vector conversions with extension and introduce endianness 1704 // issues when in conjunction with loads and stores. 1705 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) { 1706 assert(cast<IntegerType>(OldTy)->getBitWidth() != 1707 cast<IntegerType>(NewTy)->getBitWidth() && 1708 "We can't have the same bitwidth for different int types"); 1709 return false; 1710 } 1711 1712 if (DL.getTypeSizeInBits(NewTy).getFixedSize() != 1713 DL.getTypeSizeInBits(OldTy).getFixedSize()) 1714 return false; 1715 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType()) 1716 return false; 1717 1718 // We can convert pointers to integers and vice-versa. Same for vectors 1719 // of pointers and integers. 1720 OldTy = OldTy->getScalarType(); 1721 NewTy = NewTy->getScalarType(); 1722 if (NewTy->isPointerTy() || OldTy->isPointerTy()) { 1723 if (NewTy->isPointerTy() && OldTy->isPointerTy()) { 1724 return cast<PointerType>(NewTy)->getPointerAddressSpace() == 1725 cast<PointerType>(OldTy)->getPointerAddressSpace(); 1726 } 1727 1728 // We can convert integers to integral pointers, but not to non-integral 1729 // pointers. 1730 if (OldTy->isIntegerTy()) 1731 return !DL.isNonIntegralPointerType(NewTy); 1732 1733 // We can convert integral pointers to integers, but non-integral pointers 1734 // need to remain pointers. 1735 if (!DL.isNonIntegralPointerType(OldTy)) 1736 return NewTy->isIntegerTy(); 1737 1738 return false; 1739 } 1740 1741 return true; 1742 } 1743 1744 /// Generic routine to convert an SSA value to a value of a different 1745 /// type. 1746 /// 1747 /// This will try various different casting techniques, such as bitcasts, 1748 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test 1749 /// two types for viability with this routine. 1750 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V, 1751 Type *NewTy) { 1752 Type *OldTy = V->getType(); 1753 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type"); 1754 1755 if (OldTy == NewTy) 1756 return V; 1757 1758 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) && 1759 "Integer types must be the exact same to convert."); 1760 1761 // See if we need inttoptr for this type pair. A cast involving both scalars 1762 // and vectors requires and additional bitcast. 1763 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) { 1764 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8* 1765 if (OldTy->isVectorTy() && !NewTy->isVectorTy()) 1766 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)), 1767 NewTy); 1768 1769 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*> 1770 if (!OldTy->isVectorTy() && NewTy->isVectorTy()) 1771 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)), 1772 NewTy); 1773 1774 return IRB.CreateIntToPtr(V, NewTy); 1775 } 1776 1777 // See if we need ptrtoint for this type pair. A cast involving both scalars 1778 // and vectors requires and additional bitcast. 1779 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) { 1780 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128 1781 if (OldTy->isVectorTy() && !NewTy->isVectorTy()) 1782 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)), 1783 NewTy); 1784 1785 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32> 1786 if (!OldTy->isVectorTy() && NewTy->isVectorTy()) 1787 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)), 1788 NewTy); 1789 1790 return IRB.CreatePtrToInt(V, NewTy); 1791 } 1792 1793 return IRB.CreateBitCast(V, NewTy); 1794 } 1795 1796 /// Test whether the given slice use can be promoted to a vector. 1797 /// 1798 /// This function is called to test each entry in a partition which is slated 1799 /// for a single slice. 1800 static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S, 1801 VectorType *Ty, 1802 uint64_t ElementSize, 1803 const DataLayout &DL) { 1804 // First validate the slice offsets. 1805 uint64_t BeginOffset = 1806 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset(); 1807 uint64_t BeginIndex = BeginOffset / ElementSize; 1808 if (BeginIndex * ElementSize != BeginOffset || 1809 BeginIndex >= Ty->getNumElements()) 1810 return false; 1811 uint64_t EndOffset = 1812 std::min(S.endOffset(), P.endOffset()) - P.beginOffset(); 1813 uint64_t EndIndex = EndOffset / ElementSize; 1814 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements()) 1815 return false; 1816 1817 assert(EndIndex > BeginIndex && "Empty vector!"); 1818 uint64_t NumElements = EndIndex - BeginIndex; 1819 Type *SliceTy = (NumElements == 1) 1820 ? Ty->getElementType() 1821 : VectorType::get(Ty->getElementType(), NumElements); 1822 1823 Type *SplitIntTy = 1824 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8); 1825 1826 Use *U = S.getUse(); 1827 1828 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) { 1829 if (MI->isVolatile()) 1830 return false; 1831 if (!S.isSplittable()) 1832 return false; // Skip any unsplittable intrinsics. 1833 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) { 1834 if (!II->isLifetimeStartOrEnd()) 1835 return false; 1836 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) { 1837 // Disable vector promotion when there are loads or stores of an FCA. 1838 return false; 1839 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1840 if (LI->isVolatile()) 1841 return false; 1842 Type *LTy = LI->getType(); 1843 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) { 1844 assert(LTy->isIntegerTy()); 1845 LTy = SplitIntTy; 1846 } 1847 if (!canConvertValue(DL, SliceTy, LTy)) 1848 return false; 1849 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 1850 if (SI->isVolatile()) 1851 return false; 1852 Type *STy = SI->getValueOperand()->getType(); 1853 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) { 1854 assert(STy->isIntegerTy()); 1855 STy = SplitIntTy; 1856 } 1857 if (!canConvertValue(DL, STy, SliceTy)) 1858 return false; 1859 } else { 1860 return false; 1861 } 1862 1863 return true; 1864 } 1865 1866 /// Test whether the given alloca partitioning and range of slices can be 1867 /// promoted to a vector. 1868 /// 1869 /// This is a quick test to check whether we can rewrite a particular alloca 1870 /// partition (and its newly formed alloca) into a vector alloca with only 1871 /// whole-vector loads and stores such that it could be promoted to a vector 1872 /// SSA value. We only can ensure this for a limited set of operations, and we 1873 /// don't want to do the rewrites unless we are confident that the result will 1874 /// be promotable, so we have an early test here. 1875 static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) { 1876 // Collect the candidate types for vector-based promotion. Also track whether 1877 // we have different element types. 1878 SmallVector<VectorType *, 4> CandidateTys; 1879 Type *CommonEltTy = nullptr; 1880 bool HaveCommonEltTy = true; 1881 auto CheckCandidateType = [&](Type *Ty) { 1882 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 1883 // Return if bitcast to vectors is different for total size in bits. 1884 if (!CandidateTys.empty()) { 1885 VectorType *V = CandidateTys[0]; 1886 if (DL.getTypeSizeInBits(VTy).getFixedSize() != 1887 DL.getTypeSizeInBits(V).getFixedSize()) { 1888 CandidateTys.clear(); 1889 return; 1890 } 1891 } 1892 CandidateTys.push_back(VTy); 1893 if (!CommonEltTy) 1894 CommonEltTy = VTy->getElementType(); 1895 else if (CommonEltTy != VTy->getElementType()) 1896 HaveCommonEltTy = false; 1897 } 1898 }; 1899 // Consider any loads or stores that are the exact size of the slice. 1900 for (const Slice &S : P) 1901 if (S.beginOffset() == P.beginOffset() && 1902 S.endOffset() == P.endOffset()) { 1903 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser())) 1904 CheckCandidateType(LI->getType()); 1905 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) 1906 CheckCandidateType(SI->getValueOperand()->getType()); 1907 } 1908 1909 // If we didn't find a vector type, nothing to do here. 1910 if (CandidateTys.empty()) 1911 return nullptr; 1912 1913 // Remove non-integer vector types if we had multiple common element types. 1914 // FIXME: It'd be nice to replace them with integer vector types, but we can't 1915 // do that until all the backends are known to produce good code for all 1916 // integer vector types. 1917 if (!HaveCommonEltTy) { 1918 CandidateTys.erase( 1919 llvm::remove_if(CandidateTys, 1920 [](VectorType *VTy) { 1921 return !VTy->getElementType()->isIntegerTy(); 1922 }), 1923 CandidateTys.end()); 1924 1925 // If there were no integer vector types, give up. 1926 if (CandidateTys.empty()) 1927 return nullptr; 1928 1929 // Rank the remaining candidate vector types. This is easy because we know 1930 // they're all integer vectors. We sort by ascending number of elements. 1931 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) { 1932 (void)DL; 1933 assert(DL.getTypeSizeInBits(RHSTy).getFixedSize() == 1934 DL.getTypeSizeInBits(LHSTy).getFixedSize() && 1935 "Cannot have vector types of different sizes!"); 1936 assert(RHSTy->getElementType()->isIntegerTy() && 1937 "All non-integer types eliminated!"); 1938 assert(LHSTy->getElementType()->isIntegerTy() && 1939 "All non-integer types eliminated!"); 1940 return RHSTy->getNumElements() < LHSTy->getNumElements(); 1941 }; 1942 llvm::sort(CandidateTys, RankVectorTypes); 1943 CandidateTys.erase( 1944 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes), 1945 CandidateTys.end()); 1946 } else { 1947 // The only way to have the same element type in every vector type is to 1948 // have the same vector type. Check that and remove all but one. 1949 #ifndef NDEBUG 1950 for (VectorType *VTy : CandidateTys) { 1951 assert(VTy->getElementType() == CommonEltTy && 1952 "Unaccounted for element type!"); 1953 assert(VTy == CandidateTys[0] && 1954 "Different vector types with the same element type!"); 1955 } 1956 #endif 1957 CandidateTys.resize(1); 1958 } 1959 1960 // Try each vector type, and return the one which works. 1961 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) { 1962 uint64_t ElementSize = 1963 DL.getTypeSizeInBits(VTy->getElementType()).getFixedSize(); 1964 1965 // While the definition of LLVM vectors is bitpacked, we don't support sizes 1966 // that aren't byte sized. 1967 if (ElementSize % 8) 1968 return false; 1969 assert((DL.getTypeSizeInBits(VTy).getFixedSize() % 8) == 0 && 1970 "vector size not a multiple of element size?"); 1971 ElementSize /= 8; 1972 1973 for (const Slice &S : P) 1974 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL)) 1975 return false; 1976 1977 for (const Slice *S : P.splitSliceTails()) 1978 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL)) 1979 return false; 1980 1981 return true; 1982 }; 1983 for (VectorType *VTy : CandidateTys) 1984 if (CheckVectorTypeForPromotion(VTy)) 1985 return VTy; 1986 1987 return nullptr; 1988 } 1989 1990 /// Test whether a slice of an alloca is valid for integer widening. 1991 /// 1992 /// This implements the necessary checking for the \c isIntegerWideningViable 1993 /// test below on a single slice of the alloca. 1994 static bool isIntegerWideningViableForSlice(const Slice &S, 1995 uint64_t AllocBeginOffset, 1996 Type *AllocaTy, 1997 const DataLayout &DL, 1998 bool &WholeAllocaOp) { 1999 uint64_t Size = DL.getTypeStoreSize(AllocaTy).getFixedSize(); 2000 2001 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset; 2002 uint64_t RelEnd = S.endOffset() - AllocBeginOffset; 2003 2004 // We can't reasonably handle cases where the load or store extends past 2005 // the end of the alloca's type and into its padding. 2006 if (RelEnd > Size) 2007 return false; 2008 2009 Use *U = S.getUse(); 2010 2011 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 2012 if (LI->isVolatile()) 2013 return false; 2014 // We can't handle loads that extend past the allocated memory. 2015 if (DL.getTypeStoreSize(LI->getType()).getFixedSize() > Size) 2016 return false; 2017 // So far, AllocaSliceRewriter does not support widening split slice tails 2018 // in rewriteIntegerLoad. 2019 if (S.beginOffset() < AllocBeginOffset) 2020 return false; 2021 // Note that we don't count vector loads or stores as whole-alloca 2022 // operations which enable integer widening because we would prefer to use 2023 // vector widening instead. 2024 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size) 2025 WholeAllocaOp = true; 2026 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) { 2027 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize()) 2028 return false; 2029 } else if (RelBegin != 0 || RelEnd != Size || 2030 !canConvertValue(DL, AllocaTy, LI->getType())) { 2031 // Non-integer loads need to be convertible from the alloca type so that 2032 // they are promotable. 2033 return false; 2034 } 2035 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 2036 Type *ValueTy = SI->getValueOperand()->getType(); 2037 if (SI->isVolatile()) 2038 return false; 2039 // We can't handle stores that extend past the allocated memory. 2040 if (DL.getTypeStoreSize(ValueTy).getFixedSize() > Size) 2041 return false; 2042 // So far, AllocaSliceRewriter does not support widening split slice tails 2043 // in rewriteIntegerStore. 2044 if (S.beginOffset() < AllocBeginOffset) 2045 return false; 2046 // Note that we don't count vector loads or stores as whole-alloca 2047 // operations which enable integer widening because we would prefer to use 2048 // vector widening instead. 2049 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size) 2050 WholeAllocaOp = true; 2051 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) { 2052 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize()) 2053 return false; 2054 } else if (RelBegin != 0 || RelEnd != Size || 2055 !canConvertValue(DL, ValueTy, AllocaTy)) { 2056 // Non-integer stores need to be convertible to the alloca type so that 2057 // they are promotable. 2058 return false; 2059 } 2060 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) { 2061 if (MI->isVolatile() || !isa<Constant>(MI->getLength())) 2062 return false; 2063 if (!S.isSplittable()) 2064 return false; // Skip any unsplittable intrinsics. 2065 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) { 2066 if (!II->isLifetimeStartOrEnd()) 2067 return false; 2068 } else { 2069 return false; 2070 } 2071 2072 return true; 2073 } 2074 2075 /// Test whether the given alloca partition's integer operations can be 2076 /// widened to promotable ones. 2077 /// 2078 /// This is a quick test to check whether we can rewrite the integer loads and 2079 /// stores to a particular alloca into wider loads and stores and be able to 2080 /// promote the resulting alloca. 2081 static bool isIntegerWideningViable(Partition &P, Type *AllocaTy, 2082 const DataLayout &DL) { 2083 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy).getFixedSize(); 2084 // Don't create integer types larger than the maximum bitwidth. 2085 if (SizeInBits > IntegerType::MAX_INT_BITS) 2086 return false; 2087 2088 // Don't try to handle allocas with bit-padding. 2089 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy).getFixedSize()) 2090 return false; 2091 2092 // We need to ensure that an integer type with the appropriate bitwidth can 2093 // be converted to the alloca type, whatever that is. We don't want to force 2094 // the alloca itself to have an integer type if there is a more suitable one. 2095 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits); 2096 if (!canConvertValue(DL, AllocaTy, IntTy) || 2097 !canConvertValue(DL, IntTy, AllocaTy)) 2098 return false; 2099 2100 // While examining uses, we ensure that the alloca has a covering load or 2101 // store. We don't want to widen the integer operations only to fail to 2102 // promote due to some other unsplittable entry (which we may make splittable 2103 // later). However, if there are only splittable uses, go ahead and assume 2104 // that we cover the alloca. 2105 // FIXME: We shouldn't consider split slices that happen to start in the 2106 // partition here... 2107 bool WholeAllocaOp = 2108 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits); 2109 2110 for (const Slice &S : P) 2111 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL, 2112 WholeAllocaOp)) 2113 return false; 2114 2115 for (const Slice *S : P.splitSliceTails()) 2116 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL, 2117 WholeAllocaOp)) 2118 return false; 2119 2120 return WholeAllocaOp; 2121 } 2122 2123 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V, 2124 IntegerType *Ty, uint64_t Offset, 2125 const Twine &Name) { 2126 LLVM_DEBUG(dbgs() << " start: " << *V << "\n"); 2127 IntegerType *IntTy = cast<IntegerType>(V->getType()); 2128 assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= 2129 DL.getTypeStoreSize(IntTy).getFixedSize() && 2130 "Element extends past full value"); 2131 uint64_t ShAmt = 8 * Offset; 2132 if (DL.isBigEndian()) 2133 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() - 2134 DL.getTypeStoreSize(Ty).getFixedSize() - Offset); 2135 if (ShAmt) { 2136 V = IRB.CreateLShr(V, ShAmt, Name + ".shift"); 2137 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n"); 2138 } 2139 assert(Ty->getBitWidth() <= IntTy->getBitWidth() && 2140 "Cannot extract to a larger integer!"); 2141 if (Ty != IntTy) { 2142 V = IRB.CreateTrunc(V, Ty, Name + ".trunc"); 2143 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n"); 2144 } 2145 return V; 2146 } 2147 2148 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, 2149 Value *V, uint64_t Offset, const Twine &Name) { 2150 IntegerType *IntTy = cast<IntegerType>(Old->getType()); 2151 IntegerType *Ty = cast<IntegerType>(V->getType()); 2152 assert(Ty->getBitWidth() <= IntTy->getBitWidth() && 2153 "Cannot insert a larger integer!"); 2154 LLVM_DEBUG(dbgs() << " start: " << *V << "\n"); 2155 if (Ty != IntTy) { 2156 V = IRB.CreateZExt(V, IntTy, Name + ".ext"); 2157 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n"); 2158 } 2159 assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= 2160 DL.getTypeStoreSize(IntTy).getFixedSize() && 2161 "Element store outside of alloca store"); 2162 uint64_t ShAmt = 8 * Offset; 2163 if (DL.isBigEndian()) 2164 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() - 2165 DL.getTypeStoreSize(Ty).getFixedSize() - Offset); 2166 if (ShAmt) { 2167 V = IRB.CreateShl(V, ShAmt, Name + ".shift"); 2168 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n"); 2169 } 2170 2171 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) { 2172 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt); 2173 Old = IRB.CreateAnd(Old, Mask, Name + ".mask"); 2174 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n"); 2175 V = IRB.CreateOr(Old, V, Name + ".insert"); 2176 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n"); 2177 } 2178 return V; 2179 } 2180 2181 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, 2182 unsigned EndIndex, const Twine &Name) { 2183 VectorType *VecTy = cast<VectorType>(V->getType()); 2184 unsigned NumElements = EndIndex - BeginIndex; 2185 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2186 2187 if (NumElements == VecTy->getNumElements()) 2188 return V; 2189 2190 if (NumElements == 1) { 2191 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex), 2192 Name + ".extract"); 2193 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n"); 2194 return V; 2195 } 2196 2197 SmallVector<int, 8> Mask; 2198 Mask.reserve(NumElements); 2199 for (unsigned i = BeginIndex; i != EndIndex; ++i) 2200 Mask.push_back(i); 2201 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), Mask, 2202 Name + ".extract"); 2203 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n"); 2204 return V; 2205 } 2206 2207 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V, 2208 unsigned BeginIndex, const Twine &Name) { 2209 VectorType *VecTy = cast<VectorType>(Old->getType()); 2210 assert(VecTy && "Can only insert a vector into a vector"); 2211 2212 VectorType *Ty = dyn_cast<VectorType>(V->getType()); 2213 if (!Ty) { 2214 // Single element to insert. 2215 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex), 2216 Name + ".insert"); 2217 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n"); 2218 return V; 2219 } 2220 2221 assert(Ty->getNumElements() <= VecTy->getNumElements() && 2222 "Too many elements!"); 2223 if (Ty->getNumElements() == VecTy->getNumElements()) { 2224 assert(V->getType() == VecTy && "Vector type mismatch"); 2225 return V; 2226 } 2227 unsigned EndIndex = BeginIndex + Ty->getNumElements(); 2228 2229 // When inserting a smaller vector into the larger to store, we first 2230 // use a shuffle vector to widen it with undef elements, and then 2231 // a second shuffle vector to select between the loaded vector and the 2232 // incoming vector. 2233 SmallVector<Constant *, 8> Mask; 2234 Mask.reserve(VecTy->getNumElements()); 2235 for (unsigned i = 0; i != VecTy->getNumElements(); ++i) 2236 if (i >= BeginIndex && i < EndIndex) 2237 Mask.push_back(IRB.getInt32(i - BeginIndex)); 2238 else 2239 Mask.push_back(UndefValue::get(IRB.getInt32Ty())); 2240 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), 2241 ConstantVector::get(Mask), Name + ".expand"); 2242 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n"); 2243 2244 Mask.clear(); 2245 for (unsigned i = 0; i != VecTy->getNumElements(); ++i) 2246 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex)); 2247 2248 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend"); 2249 2250 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n"); 2251 return V; 2252 } 2253 2254 /// Visitor to rewrite instructions using p particular slice of an alloca 2255 /// to use a new alloca. 2256 /// 2257 /// Also implements the rewriting to vector-based accesses when the partition 2258 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic 2259 /// lives here. 2260 class llvm::sroa::AllocaSliceRewriter 2261 : public InstVisitor<AllocaSliceRewriter, bool> { 2262 // Befriend the base class so it can delegate to private visit methods. 2263 friend class InstVisitor<AllocaSliceRewriter, bool>; 2264 2265 using Base = InstVisitor<AllocaSliceRewriter, bool>; 2266 2267 const DataLayout &DL; 2268 AllocaSlices &AS; 2269 SROA &Pass; 2270 AllocaInst &OldAI, &NewAI; 2271 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset; 2272 Type *NewAllocaTy; 2273 2274 // This is a convenience and flag variable that will be null unless the new 2275 // alloca's integer operations should be widened to this integer type due to 2276 // passing isIntegerWideningViable above. If it is non-null, the desired 2277 // integer type will be stored here for easy access during rewriting. 2278 IntegerType *IntTy; 2279 2280 // If we are rewriting an alloca partition which can be written as pure 2281 // vector operations, we stash extra information here. When VecTy is 2282 // non-null, we have some strict guarantees about the rewritten alloca: 2283 // - The new alloca is exactly the size of the vector type here. 2284 // - The accesses all either map to the entire vector or to a single 2285 // element. 2286 // - The set of accessing instructions is only one of those handled above 2287 // in isVectorPromotionViable. Generally these are the same access kinds 2288 // which are promotable via mem2reg. 2289 VectorType *VecTy; 2290 Type *ElementTy; 2291 uint64_t ElementSize; 2292 2293 // The original offset of the slice currently being rewritten relative to 2294 // the original alloca. 2295 uint64_t BeginOffset = 0; 2296 uint64_t EndOffset = 0; 2297 2298 // The new offsets of the slice currently being rewritten relative to the 2299 // original alloca. 2300 uint64_t NewBeginOffset = 0, NewEndOffset = 0; 2301 2302 uint64_t SliceSize = 0; 2303 bool IsSplittable = false; 2304 bool IsSplit = false; 2305 Use *OldUse = nullptr; 2306 Instruction *OldPtr = nullptr; 2307 2308 // Track post-rewrite users which are PHI nodes and Selects. 2309 SmallSetVector<PHINode *, 8> &PHIUsers; 2310 SmallSetVector<SelectInst *, 8> &SelectUsers; 2311 2312 // Utility IR builder, whose name prefix is setup for each visited use, and 2313 // the insertion point is set to point to the user. 2314 IRBuilderTy IRB; 2315 2316 public: 2317 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass, 2318 AllocaInst &OldAI, AllocaInst &NewAI, 2319 uint64_t NewAllocaBeginOffset, 2320 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable, 2321 VectorType *PromotableVecTy, 2322 SmallSetVector<PHINode *, 8> &PHIUsers, 2323 SmallSetVector<SelectInst *, 8> &SelectUsers) 2324 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI), 2325 NewAllocaBeginOffset(NewAllocaBeginOffset), 2326 NewAllocaEndOffset(NewAllocaEndOffset), 2327 NewAllocaTy(NewAI.getAllocatedType()), 2328 IntTy( 2329 IsIntegerPromotable 2330 ? Type::getIntNTy(NewAI.getContext(), 2331 DL.getTypeSizeInBits(NewAI.getAllocatedType()) 2332 .getFixedSize()) 2333 : nullptr), 2334 VecTy(PromotableVecTy), 2335 ElementTy(VecTy ? VecTy->getElementType() : nullptr), 2336 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8 2337 : 0), 2338 PHIUsers(PHIUsers), SelectUsers(SelectUsers), 2339 IRB(NewAI.getContext(), ConstantFolder()) { 2340 if (VecTy) { 2341 assert((DL.getTypeSizeInBits(ElementTy).getFixedSize() % 8) == 0 && 2342 "Only multiple-of-8 sized vector elements are viable"); 2343 ++NumVectorized; 2344 } 2345 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy)); 2346 } 2347 2348 bool visit(AllocaSlices::const_iterator I) { 2349 bool CanSROA = true; 2350 BeginOffset = I->beginOffset(); 2351 EndOffset = I->endOffset(); 2352 IsSplittable = I->isSplittable(); 2353 IsSplit = 2354 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset; 2355 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : "")); 2356 LLVM_DEBUG(AS.printSlice(dbgs(), I, "")); 2357 LLVM_DEBUG(dbgs() << "\n"); 2358 2359 // Compute the intersecting offset range. 2360 assert(BeginOffset < NewAllocaEndOffset); 2361 assert(EndOffset > NewAllocaBeginOffset); 2362 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset); 2363 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset); 2364 2365 SliceSize = NewEndOffset - NewBeginOffset; 2366 2367 OldUse = I->getUse(); 2368 OldPtr = cast<Instruction>(OldUse->get()); 2369 2370 Instruction *OldUserI = cast<Instruction>(OldUse->getUser()); 2371 IRB.SetInsertPoint(OldUserI); 2372 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc()); 2373 IRB.getInserter().SetNamePrefix( 2374 Twine(NewAI.getName()) + "." + Twine(BeginOffset) + "."); 2375 2376 CanSROA &= visit(cast<Instruction>(OldUse->getUser())); 2377 if (VecTy || IntTy) 2378 assert(CanSROA); 2379 return CanSROA; 2380 } 2381 2382 private: 2383 // Make sure the other visit overloads are visible. 2384 using Base::visit; 2385 2386 // Every instruction which can end up as a user must have a rewrite rule. 2387 bool visitInstruction(Instruction &I) { 2388 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n"); 2389 llvm_unreachable("No rewrite rule for this instruction!"); 2390 } 2391 2392 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) { 2393 // Note that the offset computation can use BeginOffset or NewBeginOffset 2394 // interchangeably for unsplit slices. 2395 assert(IsSplit || BeginOffset == NewBeginOffset); 2396 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2397 2398 #ifndef NDEBUG 2399 StringRef OldName = OldPtr->getName(); 2400 // Skip through the last '.sroa.' component of the name. 2401 size_t LastSROAPrefix = OldName.rfind(".sroa."); 2402 if (LastSROAPrefix != StringRef::npos) { 2403 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa.")); 2404 // Look for an SROA slice index. 2405 size_t IndexEnd = OldName.find_first_not_of("0123456789"); 2406 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') { 2407 // Strip the index and look for the offset. 2408 OldName = OldName.substr(IndexEnd + 1); 2409 size_t OffsetEnd = OldName.find_first_not_of("0123456789"); 2410 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.') 2411 // Strip the offset. 2412 OldName = OldName.substr(OffsetEnd + 1); 2413 } 2414 } 2415 // Strip any SROA suffixes as well. 2416 OldName = OldName.substr(0, OldName.find(".sroa_")); 2417 #endif 2418 2419 return getAdjustedPtr(IRB, DL, &NewAI, 2420 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset), 2421 PointerTy, 2422 #ifndef NDEBUG 2423 Twine(OldName) + "." 2424 #else 2425 Twine() 2426 #endif 2427 ); 2428 } 2429 2430 /// Compute suitable alignment to access this slice of the *new* 2431 /// alloca. 2432 /// 2433 /// You can optionally pass a type to this routine and if that type's ABI 2434 /// alignment is itself suitable, this will return zero. 2435 Align getSliceAlign() { 2436 return commonAlignment(NewAI.getAlign(), 2437 NewBeginOffset - NewAllocaBeginOffset); 2438 } 2439 2440 unsigned getIndex(uint64_t Offset) { 2441 assert(VecTy && "Can only call getIndex when rewriting a vector"); 2442 uint64_t RelOffset = Offset - NewAllocaBeginOffset; 2443 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds"); 2444 uint32_t Index = RelOffset / ElementSize; 2445 assert(Index * ElementSize == RelOffset); 2446 return Index; 2447 } 2448 2449 void deleteIfTriviallyDead(Value *V) { 2450 Instruction *I = cast<Instruction>(V); 2451 if (isInstructionTriviallyDead(I)) 2452 Pass.DeadInsts.insert(I); 2453 } 2454 2455 Value *rewriteVectorizedLoadInst() { 2456 unsigned BeginIndex = getIndex(NewBeginOffset); 2457 unsigned EndIndex = getIndex(NewEndOffset); 2458 assert(EndIndex > BeginIndex && "Empty vector!"); 2459 2460 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2461 NewAI.getAlign(), "load"); 2462 return extractVector(IRB, V, BeginIndex, EndIndex, "vec"); 2463 } 2464 2465 Value *rewriteIntegerLoad(LoadInst &LI) { 2466 assert(IntTy && "We cannot insert an integer to the alloca"); 2467 assert(!LI.isVolatile()); 2468 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2469 NewAI.getAlign(), "load"); 2470 V = convertValue(DL, IRB, V, IntTy); 2471 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); 2472 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2473 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) { 2474 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8); 2475 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract"); 2476 } 2477 // It is possible that the extracted type is not the load type. This 2478 // happens if there is a load past the end of the alloca, and as 2479 // a consequence the slice is narrower but still a candidate for integer 2480 // lowering. To handle this case, we just zero extend the extracted 2481 // integer. 2482 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 && 2483 "Can only handle an extract for an overly wide load"); 2484 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8) 2485 V = IRB.CreateZExt(V, LI.getType()); 2486 return V; 2487 } 2488 2489 bool visitLoadInst(LoadInst &LI) { 2490 LLVM_DEBUG(dbgs() << " original: " << LI << "\n"); 2491 Value *OldOp = LI.getOperand(0); 2492 assert(OldOp == OldPtr); 2493 2494 AAMDNodes AATags; 2495 LI.getAAMetadata(AATags); 2496 2497 unsigned AS = LI.getPointerAddressSpace(); 2498 2499 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8) 2500 : LI.getType(); 2501 const bool IsLoadPastEnd = 2502 DL.getTypeStoreSize(TargetTy).getFixedSize() > SliceSize; 2503 bool IsPtrAdjusted = false; 2504 Value *V; 2505 if (VecTy) { 2506 V = rewriteVectorizedLoadInst(); 2507 } else if (IntTy && LI.getType()->isIntegerTy()) { 2508 V = rewriteIntegerLoad(LI); 2509 } else if (NewBeginOffset == NewAllocaBeginOffset && 2510 NewEndOffset == NewAllocaEndOffset && 2511 (canConvertValue(DL, NewAllocaTy, TargetTy) || 2512 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() && 2513 TargetTy->isIntegerTy()))) { 2514 LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2515 NewAI.getAlign(), LI.isVolatile(), 2516 LI.getName()); 2517 if (AATags) 2518 NewLI->setAAMetadata(AATags); 2519 if (LI.isVolatile()) 2520 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 2521 if (NewLI->isAtomic()) 2522 NewLI->setAlignment(LI.getAlign()); 2523 2524 // Any !nonnull metadata or !range metadata on the old load is also valid 2525 // on the new load. This is even true in some cases even when the loads 2526 // are different types, for example by mapping !nonnull metadata to 2527 // !range metadata by modeling the null pointer constant converted to the 2528 // integer type. 2529 // FIXME: Add support for range metadata here. Currently the utilities 2530 // for this don't propagate range metadata in trivial cases from one 2531 // integer load to another, don't handle non-addrspace-0 null pointers 2532 // correctly, and don't have any support for mapping ranges as the 2533 // integer type becomes winder or narrower. 2534 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull)) 2535 copyNonnullMetadata(LI, N, *NewLI); 2536 2537 // Try to preserve nonnull metadata 2538 V = NewLI; 2539 2540 // If this is an integer load past the end of the slice (which means the 2541 // bytes outside the slice are undef or this load is dead) just forcibly 2542 // fix the integer size with correct handling of endianness. 2543 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy)) 2544 if (auto *TITy = dyn_cast<IntegerType>(TargetTy)) 2545 if (AITy->getBitWidth() < TITy->getBitWidth()) { 2546 V = IRB.CreateZExt(V, TITy, "load.ext"); 2547 if (DL.isBigEndian()) 2548 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(), 2549 "endian_shift"); 2550 } 2551 } else { 2552 Type *LTy = TargetTy->getPointerTo(AS); 2553 LoadInst *NewLI = 2554 IRB.CreateAlignedLoad(TargetTy, getNewAllocaSlicePtr(IRB, LTy), 2555 getSliceAlign(), LI.isVolatile(), LI.getName()); 2556 if (AATags) 2557 NewLI->setAAMetadata(AATags); 2558 if (LI.isVolatile()) 2559 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 2560 2561 V = NewLI; 2562 IsPtrAdjusted = true; 2563 } 2564 V = convertValue(DL, IRB, V, TargetTy); 2565 2566 if (IsSplit) { 2567 assert(!LI.isVolatile()); 2568 assert(LI.getType()->isIntegerTy() && 2569 "Only integer type loads and stores are split"); 2570 assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedSize() && 2571 "Split load isn't smaller than original load"); 2572 assert(DL.typeSizeEqualsStoreSize(LI.getType()) && 2573 "Non-byte-multiple bit width"); 2574 // Move the insertion point just past the load so that we can refer to it. 2575 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI))); 2576 // Create a placeholder value with the same type as LI to use as the 2577 // basis for the new value. This allows us to replace the uses of LI with 2578 // the computed value, and then replace the placeholder with LI, leaving 2579 // LI only used for this computation. 2580 Value *Placeholder = new LoadInst( 2581 LI.getType(), UndefValue::get(LI.getType()->getPointerTo(AS)), "", 2582 false, Align(1)); 2583 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset, 2584 "insert"); 2585 LI.replaceAllUsesWith(V); 2586 Placeholder->replaceAllUsesWith(&LI); 2587 Placeholder->deleteValue(); 2588 } else { 2589 LI.replaceAllUsesWith(V); 2590 } 2591 2592 Pass.DeadInsts.insert(&LI); 2593 deleteIfTriviallyDead(OldOp); 2594 LLVM_DEBUG(dbgs() << " to: " << *V << "\n"); 2595 return !LI.isVolatile() && !IsPtrAdjusted; 2596 } 2597 2598 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp, 2599 AAMDNodes AATags) { 2600 if (V->getType() != VecTy) { 2601 unsigned BeginIndex = getIndex(NewBeginOffset); 2602 unsigned EndIndex = getIndex(NewEndOffset); 2603 assert(EndIndex > BeginIndex && "Empty vector!"); 2604 unsigned NumElements = EndIndex - BeginIndex; 2605 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2606 Type *SliceTy = (NumElements == 1) 2607 ? ElementTy 2608 : VectorType::get(ElementTy, NumElements); 2609 if (V->getType() != SliceTy) 2610 V = convertValue(DL, IRB, V, SliceTy); 2611 2612 // Mix in the existing elements. 2613 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2614 NewAI.getAlign(), "load"); 2615 V = insertVector(IRB, Old, V, BeginIndex, "vec"); 2616 } 2617 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign()); 2618 if (AATags) 2619 Store->setAAMetadata(AATags); 2620 Pass.DeadInsts.insert(&SI); 2621 2622 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 2623 return true; 2624 } 2625 2626 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) { 2627 assert(IntTy && "We cannot extract an integer from the alloca"); 2628 assert(!SI.isVolatile()); 2629 if (DL.getTypeSizeInBits(V->getType()).getFixedSize() != 2630 IntTy->getBitWidth()) { 2631 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2632 NewAI.getAlign(), "oldload"); 2633 Old = convertValue(DL, IRB, Old, IntTy); 2634 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); 2635 uint64_t Offset = BeginOffset - NewAllocaBeginOffset; 2636 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert"); 2637 } 2638 V = convertValue(DL, IRB, V, NewAllocaTy); 2639 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign()); 2640 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access, 2641 LLVMContext::MD_access_group}); 2642 if (AATags) 2643 Store->setAAMetadata(AATags); 2644 Pass.DeadInsts.insert(&SI); 2645 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 2646 return true; 2647 } 2648 2649 bool visitStoreInst(StoreInst &SI) { 2650 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 2651 Value *OldOp = SI.getOperand(1); 2652 assert(OldOp == OldPtr); 2653 2654 AAMDNodes AATags; 2655 SI.getAAMetadata(AATags); 2656 2657 Value *V = SI.getValueOperand(); 2658 2659 // Strip all inbounds GEPs and pointer casts to try to dig out any root 2660 // alloca that should be re-examined after promoting this alloca. 2661 if (V->getType()->isPointerTy()) 2662 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets())) 2663 Pass.PostPromotionWorklist.insert(AI); 2664 2665 if (SliceSize < DL.getTypeStoreSize(V->getType()).getFixedSize()) { 2666 assert(!SI.isVolatile()); 2667 assert(V->getType()->isIntegerTy() && 2668 "Only integer type loads and stores are split"); 2669 assert(DL.typeSizeEqualsStoreSize(V->getType()) && 2670 "Non-byte-multiple bit width"); 2671 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8); 2672 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset, 2673 "extract"); 2674 } 2675 2676 if (VecTy) 2677 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags); 2678 if (IntTy && V->getType()->isIntegerTy()) 2679 return rewriteIntegerStore(V, SI, AATags); 2680 2681 const bool IsStorePastEnd = 2682 DL.getTypeStoreSize(V->getType()).getFixedSize() > SliceSize; 2683 StoreInst *NewSI; 2684 if (NewBeginOffset == NewAllocaBeginOffset && 2685 NewEndOffset == NewAllocaEndOffset && 2686 (canConvertValue(DL, V->getType(), NewAllocaTy) || 2687 (IsStorePastEnd && NewAllocaTy->isIntegerTy() && 2688 V->getType()->isIntegerTy()))) { 2689 // If this is an integer store past the end of slice (and thus the bytes 2690 // past that point are irrelevant or this is unreachable), truncate the 2691 // value prior to storing. 2692 if (auto *VITy = dyn_cast<IntegerType>(V->getType())) 2693 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy)) 2694 if (VITy->getBitWidth() > AITy->getBitWidth()) { 2695 if (DL.isBigEndian()) 2696 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(), 2697 "endian_shift"); 2698 V = IRB.CreateTrunc(V, AITy, "load.trunc"); 2699 } 2700 2701 V = convertValue(DL, IRB, V, NewAllocaTy); 2702 NewSI = 2703 IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), SI.isVolatile()); 2704 } else { 2705 unsigned AS = SI.getPointerAddressSpace(); 2706 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS)); 2707 NewSI = 2708 IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(), SI.isVolatile()); 2709 } 2710 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access, 2711 LLVMContext::MD_access_group}); 2712 if (AATags) 2713 NewSI->setAAMetadata(AATags); 2714 if (SI.isVolatile()) 2715 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID()); 2716 if (NewSI->isAtomic()) 2717 NewSI->setAlignment(SI.getAlign()); 2718 Pass.DeadInsts.insert(&SI); 2719 deleteIfTriviallyDead(OldOp); 2720 2721 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n"); 2722 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile(); 2723 } 2724 2725 /// Compute an integer value from splatting an i8 across the given 2726 /// number of bytes. 2727 /// 2728 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't 2729 /// call this routine. 2730 /// FIXME: Heed the advice above. 2731 /// 2732 /// \param V The i8 value to splat. 2733 /// \param Size The number of bytes in the output (assuming i8 is one byte) 2734 Value *getIntegerSplat(Value *V, unsigned Size) { 2735 assert(Size > 0 && "Expected a positive number of bytes."); 2736 IntegerType *VTy = cast<IntegerType>(V->getType()); 2737 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte"); 2738 if (Size == 1) 2739 return V; 2740 2741 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8); 2742 V = IRB.CreateMul( 2743 IRB.CreateZExt(V, SplatIntTy, "zext"), 2744 ConstantExpr::getUDiv( 2745 Constant::getAllOnesValue(SplatIntTy), 2746 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()), 2747 SplatIntTy)), 2748 "isplat"); 2749 return V; 2750 } 2751 2752 /// Compute a vector splat for a given element value. 2753 Value *getVectorSplat(Value *V, unsigned NumElements) { 2754 V = IRB.CreateVectorSplat(NumElements, V, "vsplat"); 2755 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n"); 2756 return V; 2757 } 2758 2759 bool visitMemSetInst(MemSetInst &II) { 2760 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 2761 assert(II.getRawDest() == OldPtr); 2762 2763 AAMDNodes AATags; 2764 II.getAAMetadata(AATags); 2765 2766 // If the memset has a variable size, it cannot be split, just adjust the 2767 // pointer to the new alloca. 2768 if (!isa<Constant>(II.getLength())) { 2769 assert(!IsSplit); 2770 assert(NewBeginOffset == BeginOffset); 2771 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType())); 2772 II.setDestAlignment(getSliceAlign()); 2773 2774 deleteIfTriviallyDead(OldPtr); 2775 return false; 2776 } 2777 2778 // Record this instruction for deletion. 2779 Pass.DeadInsts.insert(&II); 2780 2781 Type *AllocaTy = NewAI.getAllocatedType(); 2782 Type *ScalarTy = AllocaTy->getScalarType(); 2783 2784 const bool CanContinue = [&]() { 2785 if (VecTy || IntTy) 2786 return true; 2787 if (BeginOffset > NewAllocaBeginOffset || 2788 EndOffset < NewAllocaEndOffset) 2789 return false; 2790 auto *C = cast<ConstantInt>(II.getLength()); 2791 if (C->getBitWidth() > 64) 2792 return false; 2793 const auto Len = C->getZExtValue(); 2794 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext()); 2795 auto *SrcTy = VectorType::get(Int8Ty, Len); 2796 return canConvertValue(DL, SrcTy, AllocaTy) && 2797 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedSize()); 2798 }(); 2799 2800 // If this doesn't map cleanly onto the alloca type, and that type isn't 2801 // a single value type, just emit a memset. 2802 if (!CanContinue) { 2803 Type *SizeTy = II.getLength()->getType(); 2804 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset); 2805 CallInst *New = IRB.CreateMemSet( 2806 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size, 2807 MaybeAlign(getSliceAlign()), II.isVolatile()); 2808 if (AATags) 2809 New->setAAMetadata(AATags); 2810 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 2811 return false; 2812 } 2813 2814 // If we can represent this as a simple value, we have to build the actual 2815 // value to store, which requires expanding the byte present in memset to 2816 // a sensible representation for the alloca type. This is essentially 2817 // splatting the byte to a sufficiently wide integer, splatting it across 2818 // any desired vector width, and bitcasting to the final type. 2819 Value *V; 2820 2821 if (VecTy) { 2822 // If this is a memset of a vectorized alloca, insert it. 2823 assert(ElementTy == ScalarTy); 2824 2825 unsigned BeginIndex = getIndex(NewBeginOffset); 2826 unsigned EndIndex = getIndex(NewEndOffset); 2827 assert(EndIndex > BeginIndex && "Empty vector!"); 2828 unsigned NumElements = EndIndex - BeginIndex; 2829 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2830 2831 Value *Splat = getIntegerSplat( 2832 II.getValue(), DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8); 2833 Splat = convertValue(DL, IRB, Splat, ElementTy); 2834 if (NumElements > 1) 2835 Splat = getVectorSplat(Splat, NumElements); 2836 2837 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2838 NewAI.getAlign(), "oldload"); 2839 V = insertVector(IRB, Old, Splat, BeginIndex, "vec"); 2840 } else if (IntTy) { 2841 // If this is a memset on an alloca where we can widen stores, insert the 2842 // set integer. 2843 assert(!II.isVolatile()); 2844 2845 uint64_t Size = NewEndOffset - NewBeginOffset; 2846 V = getIntegerSplat(II.getValue(), Size); 2847 2848 if (IntTy && (BeginOffset != NewAllocaBeginOffset || 2849 EndOffset != NewAllocaBeginOffset)) { 2850 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2851 NewAI.getAlign(), "oldload"); 2852 Old = convertValue(DL, IRB, Old, IntTy); 2853 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2854 V = insertInteger(DL, IRB, Old, V, Offset, "insert"); 2855 } else { 2856 assert(V->getType() == IntTy && 2857 "Wrong type for an alloca wide integer!"); 2858 } 2859 V = convertValue(DL, IRB, V, AllocaTy); 2860 } else { 2861 // Established these invariants above. 2862 assert(NewBeginOffset == NewAllocaBeginOffset); 2863 assert(NewEndOffset == NewAllocaEndOffset); 2864 2865 V = getIntegerSplat(II.getValue(), 2866 DL.getTypeSizeInBits(ScalarTy).getFixedSize() / 8); 2867 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy)) 2868 V = getVectorSplat(V, AllocaVecTy->getNumElements()); 2869 2870 V = convertValue(DL, IRB, V, AllocaTy); 2871 } 2872 2873 StoreInst *New = 2874 IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), II.isVolatile()); 2875 if (AATags) 2876 New->setAAMetadata(AATags); 2877 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 2878 return !II.isVolatile(); 2879 } 2880 2881 bool visitMemTransferInst(MemTransferInst &II) { 2882 // Rewriting of memory transfer instructions can be a bit tricky. We break 2883 // them into two categories: split intrinsics and unsplit intrinsics. 2884 2885 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 2886 2887 AAMDNodes AATags; 2888 II.getAAMetadata(AATags); 2889 2890 bool IsDest = &II.getRawDestUse() == OldUse; 2891 assert((IsDest && II.getRawDest() == OldPtr) || 2892 (!IsDest && II.getRawSource() == OldPtr)); 2893 2894 MaybeAlign SliceAlign = getSliceAlign(); 2895 2896 // For unsplit intrinsics, we simply modify the source and destination 2897 // pointers in place. This isn't just an optimization, it is a matter of 2898 // correctness. With unsplit intrinsics we may be dealing with transfers 2899 // within a single alloca before SROA ran, or with transfers that have 2900 // a variable length. We may also be dealing with memmove instead of 2901 // memcpy, and so simply updating the pointers is the necessary for us to 2902 // update both source and dest of a single call. 2903 if (!IsSplittable) { 2904 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2905 if (IsDest) { 2906 II.setDest(AdjustedPtr); 2907 II.setDestAlignment(SliceAlign); 2908 } 2909 else { 2910 II.setSource(AdjustedPtr); 2911 II.setSourceAlignment(SliceAlign); 2912 } 2913 2914 LLVM_DEBUG(dbgs() << " to: " << II << "\n"); 2915 deleteIfTriviallyDead(OldPtr); 2916 return false; 2917 } 2918 // For split transfer intrinsics we have an incredibly useful assurance: 2919 // the source and destination do not reside within the same alloca, and at 2920 // least one of them does not escape. This means that we can replace 2921 // memmove with memcpy, and we don't need to worry about all manner of 2922 // downsides to splitting and transforming the operations. 2923 2924 // If this doesn't map cleanly onto the alloca type, and that type isn't 2925 // a single value type, just emit a memcpy. 2926 bool EmitMemCpy = 2927 !VecTy && !IntTy && 2928 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset || 2929 SliceSize != 2930 DL.getTypeStoreSize(NewAI.getAllocatedType()).getFixedSize() || 2931 !NewAI.getAllocatedType()->isSingleValueType()); 2932 2933 // If we're just going to emit a memcpy, the alloca hasn't changed, and the 2934 // size hasn't been shrunk based on analysis of the viable range, this is 2935 // a no-op. 2936 if (EmitMemCpy && &OldAI == &NewAI) { 2937 // Ensure the start lines up. 2938 assert(NewBeginOffset == BeginOffset); 2939 2940 // Rewrite the size as needed. 2941 if (NewEndOffset != EndOffset) 2942 II.setLength(ConstantInt::get(II.getLength()->getType(), 2943 NewEndOffset - NewBeginOffset)); 2944 return false; 2945 } 2946 // Record this instruction for deletion. 2947 Pass.DeadInsts.insert(&II); 2948 2949 // Strip all inbounds GEPs and pointer casts to try to dig out any root 2950 // alloca that should be re-examined after rewriting this instruction. 2951 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest(); 2952 if (AllocaInst *AI = 2953 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) { 2954 assert(AI != &OldAI && AI != &NewAI && 2955 "Splittable transfers cannot reach the same alloca on both ends."); 2956 Pass.Worklist.insert(AI); 2957 } 2958 2959 Type *OtherPtrTy = OtherPtr->getType(); 2960 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace(); 2961 2962 // Compute the relative offset for the other pointer within the transfer. 2963 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS); 2964 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset); 2965 Align OtherAlign = 2966 assumeAligned(IsDest ? II.getSourceAlignment() : II.getDestAlignment()); 2967 OtherAlign = 2968 commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue()); 2969 2970 if (EmitMemCpy) { 2971 // Compute the other pointer, folding as much as possible to produce 2972 // a single, simple GEP in most cases. 2973 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy, 2974 OtherPtr->getName() + "."); 2975 2976 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2977 Type *SizeTy = II.getLength()->getType(); 2978 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset); 2979 2980 Value *DestPtr, *SrcPtr; 2981 MaybeAlign DestAlign, SrcAlign; 2982 // Note: IsDest is true iff we're copying into the new alloca slice 2983 if (IsDest) { 2984 DestPtr = OurPtr; 2985 DestAlign = SliceAlign; 2986 SrcPtr = OtherPtr; 2987 SrcAlign = OtherAlign; 2988 } else { 2989 DestPtr = OtherPtr; 2990 DestAlign = OtherAlign; 2991 SrcPtr = OurPtr; 2992 SrcAlign = SliceAlign; 2993 } 2994 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign, 2995 Size, II.isVolatile()); 2996 if (AATags) 2997 New->setAAMetadata(AATags); 2998 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 2999 return false; 3000 } 3001 3002 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset && 3003 NewEndOffset == NewAllocaEndOffset; 3004 uint64_t Size = NewEndOffset - NewBeginOffset; 3005 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0; 3006 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0; 3007 unsigned NumElements = EndIndex - BeginIndex; 3008 IntegerType *SubIntTy = 3009 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr; 3010 3011 // Reset the other pointer type to match the register type we're going to 3012 // use, but using the address space of the original other pointer. 3013 Type *OtherTy; 3014 if (VecTy && !IsWholeAlloca) { 3015 if (NumElements == 1) 3016 OtherTy = VecTy->getElementType(); 3017 else 3018 OtherTy = VectorType::get(VecTy->getElementType(), NumElements); 3019 } else if (IntTy && !IsWholeAlloca) { 3020 OtherTy = SubIntTy; 3021 } else { 3022 OtherTy = NewAllocaTy; 3023 } 3024 OtherPtrTy = OtherTy->getPointerTo(OtherAS); 3025 3026 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy, 3027 OtherPtr->getName() + "."); 3028 MaybeAlign SrcAlign = OtherAlign; 3029 Value *DstPtr = &NewAI; 3030 MaybeAlign DstAlign = SliceAlign; 3031 if (!IsDest) { 3032 std::swap(SrcPtr, DstPtr); 3033 std::swap(SrcAlign, DstAlign); 3034 } 3035 3036 Value *Src; 3037 if (VecTy && !IsWholeAlloca && !IsDest) { 3038 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 3039 NewAI.getAlign(), "load"); 3040 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec"); 3041 } else if (IntTy && !IsWholeAlloca && !IsDest) { 3042 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 3043 NewAI.getAlign(), "load"); 3044 Src = convertValue(DL, IRB, Src, IntTy); 3045 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 3046 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract"); 3047 } else { 3048 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign, 3049 II.isVolatile(), "copyload"); 3050 if (AATags) 3051 Load->setAAMetadata(AATags); 3052 Src = Load; 3053 } 3054 3055 if (VecTy && !IsWholeAlloca && IsDest) { 3056 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 3057 NewAI.getAlign(), "oldload"); 3058 Src = insertVector(IRB, Old, Src, BeginIndex, "vec"); 3059 } else if (IntTy && !IsWholeAlloca && IsDest) { 3060 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 3061 NewAI.getAlign(), "oldload"); 3062 Old = convertValue(DL, IRB, Old, IntTy); 3063 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 3064 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert"); 3065 Src = convertValue(DL, IRB, Src, NewAllocaTy); 3066 } 3067 3068 StoreInst *Store = cast<StoreInst>( 3069 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile())); 3070 if (AATags) 3071 Store->setAAMetadata(AATags); 3072 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 3073 return !II.isVolatile(); 3074 } 3075 3076 bool visitIntrinsicInst(IntrinsicInst &II) { 3077 assert(II.isLifetimeStartOrEnd()); 3078 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 3079 assert(II.getArgOperand(1) == OldPtr); 3080 3081 // Record this instruction for deletion. 3082 Pass.DeadInsts.insert(&II); 3083 3084 // Lifetime intrinsics are only promotable if they cover the whole alloca. 3085 // Therefore, we drop lifetime intrinsics which don't cover the whole 3086 // alloca. 3087 // (In theory, intrinsics which partially cover an alloca could be 3088 // promoted, but PromoteMemToReg doesn't handle that case.) 3089 // FIXME: Check whether the alloca is promotable before dropping the 3090 // lifetime intrinsics? 3091 if (NewBeginOffset != NewAllocaBeginOffset || 3092 NewEndOffset != NewAllocaEndOffset) 3093 return true; 3094 3095 ConstantInt *Size = 3096 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()), 3097 NewEndOffset - NewBeginOffset); 3098 // Lifetime intrinsics always expect an i8* so directly get such a pointer 3099 // for the new alloca slice. 3100 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace()); 3101 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy); 3102 Value *New; 3103 if (II.getIntrinsicID() == Intrinsic::lifetime_start) 3104 New = IRB.CreateLifetimeStart(Ptr, Size); 3105 else 3106 New = IRB.CreateLifetimeEnd(Ptr, Size); 3107 3108 (void)New; 3109 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 3110 3111 return true; 3112 } 3113 3114 void fixLoadStoreAlign(Instruction &Root) { 3115 // This algorithm implements the same visitor loop as 3116 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load 3117 // or store found. 3118 SmallPtrSet<Instruction *, 4> Visited; 3119 SmallVector<Instruction *, 4> Uses; 3120 Visited.insert(&Root); 3121 Uses.push_back(&Root); 3122 do { 3123 Instruction *I = Uses.pop_back_val(); 3124 3125 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 3126 LI->setAlignment(std::min(LI->getAlign(), getSliceAlign())); 3127 continue; 3128 } 3129 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 3130 SI->setAlignment(std::min(SI->getAlign(), getSliceAlign())); 3131 continue; 3132 } 3133 3134 assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) || 3135 isa<PHINode>(I) || isa<SelectInst>(I) || 3136 isa<GetElementPtrInst>(I)); 3137 for (User *U : I->users()) 3138 if (Visited.insert(cast<Instruction>(U)).second) 3139 Uses.push_back(cast<Instruction>(U)); 3140 } while (!Uses.empty()); 3141 } 3142 3143 bool visitPHINode(PHINode &PN) { 3144 LLVM_DEBUG(dbgs() << " original: " << PN << "\n"); 3145 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable"); 3146 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable"); 3147 3148 // We would like to compute a new pointer in only one place, but have it be 3149 // as local as possible to the PHI. To do that, we re-use the location of 3150 // the old pointer, which necessarily must be in the right position to 3151 // dominate the PHI. 3152 IRBuilderBase::InsertPointGuard Guard(IRB); 3153 if (isa<PHINode>(OldPtr)) 3154 IRB.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt()); 3155 else 3156 IRB.SetInsertPoint(OldPtr); 3157 IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc()); 3158 3159 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 3160 // Replace the operands which were using the old pointer. 3161 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr); 3162 3163 LLVM_DEBUG(dbgs() << " to: " << PN << "\n"); 3164 deleteIfTriviallyDead(OldPtr); 3165 3166 // Fix the alignment of any loads or stores using this PHI node. 3167 fixLoadStoreAlign(PN); 3168 3169 // PHIs can't be promoted on their own, but often can be speculated. We 3170 // check the speculation outside of the rewriter so that we see the 3171 // fully-rewritten alloca. 3172 PHIUsers.insert(&PN); 3173 return true; 3174 } 3175 3176 bool visitSelectInst(SelectInst &SI) { 3177 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 3178 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) && 3179 "Pointer isn't an operand!"); 3180 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable"); 3181 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable"); 3182 3183 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 3184 // Replace the operands which were using the old pointer. 3185 if (SI.getOperand(1) == OldPtr) 3186 SI.setOperand(1, NewPtr); 3187 if (SI.getOperand(2) == OldPtr) 3188 SI.setOperand(2, NewPtr); 3189 3190 LLVM_DEBUG(dbgs() << " to: " << SI << "\n"); 3191 deleteIfTriviallyDead(OldPtr); 3192 3193 // Fix the alignment of any loads or stores using this select. 3194 fixLoadStoreAlign(SI); 3195 3196 // Selects can't be promoted on their own, but often can be speculated. We 3197 // check the speculation outside of the rewriter so that we see the 3198 // fully-rewritten alloca. 3199 SelectUsers.insert(&SI); 3200 return true; 3201 } 3202 }; 3203 3204 namespace { 3205 3206 /// Visitor to rewrite aggregate loads and stores as scalar. 3207 /// 3208 /// This pass aggressively rewrites all aggregate loads and stores on 3209 /// a particular pointer (or any pointer derived from it which we can identify) 3210 /// with scalar loads and stores. 3211 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> { 3212 // Befriend the base class so it can delegate to private visit methods. 3213 friend class InstVisitor<AggLoadStoreRewriter, bool>; 3214 3215 /// Queue of pointer uses to analyze and potentially rewrite. 3216 SmallVector<Use *, 8> Queue; 3217 3218 /// Set to prevent us from cycling with phi nodes and loops. 3219 SmallPtrSet<User *, 8> Visited; 3220 3221 /// The current pointer use being rewritten. This is used to dig up the used 3222 /// value (as opposed to the user). 3223 Use *U = nullptr; 3224 3225 /// Used to calculate offsets, and hence alignment, of subobjects. 3226 const DataLayout &DL; 3227 3228 public: 3229 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {} 3230 3231 /// Rewrite loads and stores through a pointer and all pointers derived from 3232 /// it. 3233 bool rewrite(Instruction &I) { 3234 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n"); 3235 enqueueUsers(I); 3236 bool Changed = false; 3237 while (!Queue.empty()) { 3238 U = Queue.pop_back_val(); 3239 Changed |= visit(cast<Instruction>(U->getUser())); 3240 } 3241 return Changed; 3242 } 3243 3244 private: 3245 /// Enqueue all the users of the given instruction for further processing. 3246 /// This uses a set to de-duplicate users. 3247 void enqueueUsers(Instruction &I) { 3248 for (Use &U : I.uses()) 3249 if (Visited.insert(U.getUser()).second) 3250 Queue.push_back(&U); 3251 } 3252 3253 // Conservative default is to not rewrite anything. 3254 bool visitInstruction(Instruction &I) { return false; } 3255 3256 /// Generic recursive split emission class. 3257 template <typename Derived> class OpSplitter { 3258 protected: 3259 /// The builder used to form new instructions. 3260 IRBuilderTy IRB; 3261 3262 /// The indices which to be used with insert- or extractvalue to select the 3263 /// appropriate value within the aggregate. 3264 SmallVector<unsigned, 4> Indices; 3265 3266 /// The indices to a GEP instruction which will move Ptr to the correct slot 3267 /// within the aggregate. 3268 SmallVector<Value *, 4> GEPIndices; 3269 3270 /// The base pointer of the original op, used as a base for GEPing the 3271 /// split operations. 3272 Value *Ptr; 3273 3274 /// The base pointee type being GEPed into. 3275 Type *BaseTy; 3276 3277 /// Known alignment of the base pointer. 3278 Align BaseAlign; 3279 3280 /// To calculate offset of each component so we can correctly deduce 3281 /// alignments. 3282 const DataLayout &DL; 3283 3284 /// Initialize the splitter with an insertion point, Ptr and start with a 3285 /// single zero GEP index. 3286 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3287 Align BaseAlign, const DataLayout &DL) 3288 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), 3289 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {} 3290 3291 public: 3292 /// Generic recursive split emission routine. 3293 /// 3294 /// This method recursively splits an aggregate op (load or store) into 3295 /// scalar or vector ops. It splits recursively until it hits a single value 3296 /// and emits that single value operation via the template argument. 3297 /// 3298 /// The logic of this routine relies on GEPs and insertvalue and 3299 /// extractvalue all operating with the same fundamental index list, merely 3300 /// formatted differently (GEPs need actual values). 3301 /// 3302 /// \param Ty The type being split recursively into smaller ops. 3303 /// \param Agg The aggregate value being built up or stored, depending on 3304 /// whether this is splitting a load or a store respectively. 3305 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) { 3306 if (Ty->isSingleValueType()) { 3307 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices); 3308 return static_cast<Derived *>(this)->emitFunc( 3309 Ty, Agg, commonAlignment(BaseAlign, Offset), Name); 3310 } 3311 3312 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 3313 unsigned OldSize = Indices.size(); 3314 (void)OldSize; 3315 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size; 3316 ++Idx) { 3317 assert(Indices.size() == OldSize && "Did not return to the old size"); 3318 Indices.push_back(Idx); 3319 GEPIndices.push_back(IRB.getInt32(Idx)); 3320 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx)); 3321 GEPIndices.pop_back(); 3322 Indices.pop_back(); 3323 } 3324 return; 3325 } 3326 3327 if (StructType *STy = dyn_cast<StructType>(Ty)) { 3328 unsigned OldSize = Indices.size(); 3329 (void)OldSize; 3330 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size; 3331 ++Idx) { 3332 assert(Indices.size() == OldSize && "Did not return to the old size"); 3333 Indices.push_back(Idx); 3334 GEPIndices.push_back(IRB.getInt32(Idx)); 3335 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx)); 3336 GEPIndices.pop_back(); 3337 Indices.pop_back(); 3338 } 3339 return; 3340 } 3341 3342 llvm_unreachable("Only arrays and structs are aggregate loadable types"); 3343 } 3344 }; 3345 3346 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> { 3347 AAMDNodes AATags; 3348 3349 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3350 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL) 3351 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, 3352 DL), 3353 AATags(AATags) {} 3354 3355 /// Emit a leaf load of a single value. This is called at the leaves of the 3356 /// recursive emission to actually load values. 3357 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) { 3358 assert(Ty->isSingleValueType()); 3359 // Load the single value and insert it using the indices. 3360 Value *GEP = 3361 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep"); 3362 LoadInst *Load = 3363 IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load"); 3364 if (AATags) 3365 Load->setAAMetadata(AATags); 3366 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert"); 3367 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n"); 3368 } 3369 }; 3370 3371 bool visitLoadInst(LoadInst &LI) { 3372 assert(LI.getPointerOperand() == *U); 3373 if (!LI.isSimple() || LI.getType()->isSingleValueType()) 3374 return false; 3375 3376 // We have an aggregate being loaded, split it apart. 3377 LLVM_DEBUG(dbgs() << " original: " << LI << "\n"); 3378 AAMDNodes AATags; 3379 LI.getAAMetadata(AATags); 3380 LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags, 3381 getAdjustedAlignment(&LI, 0), DL); 3382 Value *V = UndefValue::get(LI.getType()); 3383 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca"); 3384 LI.replaceAllUsesWith(V); 3385 LI.eraseFromParent(); 3386 return true; 3387 } 3388 3389 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> { 3390 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3391 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL) 3392 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, 3393 DL), 3394 AATags(AATags) {} 3395 AAMDNodes AATags; 3396 /// Emit a leaf store of a single value. This is called at the leaves of the 3397 /// recursive emission to actually produce stores. 3398 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) { 3399 assert(Ty->isSingleValueType()); 3400 // Extract the single value and store it using the indices. 3401 // 3402 // The gep and extractvalue values are factored out of the CreateStore 3403 // call to make the output independent of the argument evaluation order. 3404 Value *ExtractValue = 3405 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"); 3406 Value *InBoundsGEP = 3407 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep"); 3408 StoreInst *Store = 3409 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment); 3410 if (AATags) 3411 Store->setAAMetadata(AATags); 3412 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 3413 } 3414 }; 3415 3416 bool visitStoreInst(StoreInst &SI) { 3417 if (!SI.isSimple() || SI.getPointerOperand() != *U) 3418 return false; 3419 Value *V = SI.getValueOperand(); 3420 if (V->getType()->isSingleValueType()) 3421 return false; 3422 3423 // We have an aggregate being stored, split it apart. 3424 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 3425 AAMDNodes AATags; 3426 SI.getAAMetadata(AATags); 3427 StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags, 3428 getAdjustedAlignment(&SI, 0), DL); 3429 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca"); 3430 SI.eraseFromParent(); 3431 return true; 3432 } 3433 3434 bool visitBitCastInst(BitCastInst &BC) { 3435 enqueueUsers(BC); 3436 return false; 3437 } 3438 3439 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) { 3440 enqueueUsers(ASC); 3441 return false; 3442 } 3443 3444 // Fold gep (select cond, ptr1, ptr2) => select cond, gep(ptr1), gep(ptr2) 3445 bool foldGEPSelect(GetElementPtrInst &GEPI) { 3446 if (!GEPI.hasAllConstantIndices()) 3447 return false; 3448 3449 SelectInst *Sel = cast<SelectInst>(GEPI.getPointerOperand()); 3450 3451 LLVM_DEBUG(dbgs() << " Rewriting gep(select) -> select(gep):" 3452 << "\n original: " << *Sel 3453 << "\n " << GEPI); 3454 3455 IRBuilderTy Builder(&GEPI); 3456 SmallVector<Value *, 4> Index(GEPI.idx_begin(), GEPI.idx_end()); 3457 bool IsInBounds = GEPI.isInBounds(); 3458 3459 Value *True = Sel->getTrueValue(); 3460 Value *NTrue = 3461 IsInBounds 3462 ? Builder.CreateInBoundsGEP(True, Index, 3463 True->getName() + ".sroa.gep") 3464 : Builder.CreateGEP(True, Index, True->getName() + ".sroa.gep"); 3465 3466 Value *False = Sel->getFalseValue(); 3467 3468 Value *NFalse = 3469 IsInBounds 3470 ? Builder.CreateInBoundsGEP(False, Index, 3471 False->getName() + ".sroa.gep") 3472 : Builder.CreateGEP(False, Index, False->getName() + ".sroa.gep"); 3473 3474 Value *NSel = Builder.CreateSelect(Sel->getCondition(), NTrue, NFalse, 3475 Sel->getName() + ".sroa.sel"); 3476 GEPI.replaceAllUsesWith(NSel); 3477 GEPI.eraseFromParent(); 3478 Instruction *NSelI = cast<Instruction>(NSel); 3479 Visited.insert(NSelI); 3480 enqueueUsers(*NSelI); 3481 3482 LLVM_DEBUG(dbgs() << "\n to: " << *NTrue 3483 << "\n " << *NFalse 3484 << "\n " << *NSel << '\n'); 3485 3486 return true; 3487 } 3488 3489 // Fold gep (phi ptr1, ptr2) => phi gep(ptr1), gep(ptr2) 3490 bool foldGEPPhi(GetElementPtrInst &GEPI) { 3491 if (!GEPI.hasAllConstantIndices()) 3492 return false; 3493 3494 PHINode *PHI = cast<PHINode>(GEPI.getPointerOperand()); 3495 if (GEPI.getParent() != PHI->getParent() || 3496 llvm::any_of(PHI->incoming_values(), [](Value *In) 3497 { Instruction *I = dyn_cast<Instruction>(In); 3498 return !I || isa<GetElementPtrInst>(I) || isa<PHINode>(I) || 3499 !I->getParent()->isLegalToHoistInto(); 3500 })) 3501 return false; 3502 3503 LLVM_DEBUG(dbgs() << " Rewriting gep(phi) -> phi(gep):" 3504 << "\n original: " << *PHI 3505 << "\n " << GEPI 3506 << "\n to: "); 3507 3508 SmallVector<Value *, 4> Index(GEPI.idx_begin(), GEPI.idx_end()); 3509 bool IsInBounds = GEPI.isInBounds(); 3510 IRBuilderTy PHIBuilder(GEPI.getParent()->getFirstNonPHI()); 3511 PHINode *NewPN = PHIBuilder.CreatePHI(GEPI.getType(), 3512 PHI->getNumIncomingValues(), 3513 PHI->getName() + ".sroa.phi"); 3514 for (unsigned I = 0, E = PHI->getNumIncomingValues(); I != E; ++I) { 3515 Instruction *In = cast<Instruction>(PHI->getIncomingValue(I)); 3516 3517 IRBuilderTy B(In->getParent(), std::next(In->getIterator())); 3518 Value *NewVal = IsInBounds 3519 ? B.CreateInBoundsGEP(In, Index, In->getName() + ".sroa.gep") 3520 : B.CreateGEP(In, Index, In->getName() + ".sroa.gep"); 3521 NewPN->addIncoming(NewVal, PHI->getIncomingBlock(I)); 3522 } 3523 3524 GEPI.replaceAllUsesWith(NewPN); 3525 GEPI.eraseFromParent(); 3526 Visited.insert(NewPN); 3527 enqueueUsers(*NewPN); 3528 3529 LLVM_DEBUG(for (Value *In : NewPN->incoming_values()) 3530 dbgs() << "\n " << *In; 3531 dbgs() << "\n " << *NewPN << '\n'); 3532 3533 return true; 3534 } 3535 3536 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) { 3537 if (isa<SelectInst>(GEPI.getPointerOperand()) && 3538 foldGEPSelect(GEPI)) 3539 return true; 3540 3541 if (isa<PHINode>(GEPI.getPointerOperand()) && 3542 foldGEPPhi(GEPI)) 3543 return true; 3544 3545 enqueueUsers(GEPI); 3546 return false; 3547 } 3548 3549 bool visitPHINode(PHINode &PN) { 3550 enqueueUsers(PN); 3551 return false; 3552 } 3553 3554 bool visitSelectInst(SelectInst &SI) { 3555 enqueueUsers(SI); 3556 return false; 3557 } 3558 }; 3559 3560 } // end anonymous namespace 3561 3562 /// Strip aggregate type wrapping. 3563 /// 3564 /// This removes no-op aggregate types wrapping an underlying type. It will 3565 /// strip as many layers of types as it can without changing either the type 3566 /// size or the allocated size. 3567 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) { 3568 if (Ty->isSingleValueType()) 3569 return Ty; 3570 3571 uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedSize(); 3572 uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedSize(); 3573 3574 Type *InnerTy; 3575 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { 3576 InnerTy = ArrTy->getElementType(); 3577 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 3578 const StructLayout *SL = DL.getStructLayout(STy); 3579 unsigned Index = SL->getElementContainingOffset(0); 3580 InnerTy = STy->getElementType(Index); 3581 } else { 3582 return Ty; 3583 } 3584 3585 if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedSize() || 3586 TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedSize()) 3587 return Ty; 3588 3589 return stripAggregateTypeWrapping(DL, InnerTy); 3590 } 3591 3592 /// Try to find a partition of the aggregate type passed in for a given 3593 /// offset and size. 3594 /// 3595 /// This recurses through the aggregate type and tries to compute a subtype 3596 /// based on the offset and size. When the offset and size span a sub-section 3597 /// of an array, it will even compute a new array type for that sub-section, 3598 /// and the same for structs. 3599 /// 3600 /// Note that this routine is very strict and tries to find a partition of the 3601 /// type which produces the *exact* right offset and size. It is not forgiving 3602 /// when the size or offset cause either end of type-based partition to be off. 3603 /// Also, this is a best-effort routine. It is reasonable to give up and not 3604 /// return a type if necessary. 3605 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset, 3606 uint64_t Size) { 3607 if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedSize() == Size) 3608 return stripAggregateTypeWrapping(DL, Ty); 3609 if (Offset > DL.getTypeAllocSize(Ty).getFixedSize() || 3610 (DL.getTypeAllocSize(Ty).getFixedSize() - Offset) < Size) 3611 return nullptr; 3612 3613 if (isa<ArrayType>(Ty) || isa<VectorType>(Ty)) { 3614 Type *ElementTy; 3615 uint64_t TyNumElements; 3616 if (auto *AT = dyn_cast<ArrayType>(Ty)) { 3617 ElementTy = AT->getElementType(); 3618 TyNumElements = AT->getNumElements(); 3619 } else { 3620 // FIXME: This isn't right for vectors with non-byte-sized or 3621 // non-power-of-two sized elements. 3622 auto *VT = cast<VectorType>(Ty); 3623 ElementTy = VT->getElementType(); 3624 TyNumElements = VT->getNumElements(); 3625 } 3626 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize(); 3627 uint64_t NumSkippedElements = Offset / ElementSize; 3628 if (NumSkippedElements >= TyNumElements) 3629 return nullptr; 3630 Offset -= NumSkippedElements * ElementSize; 3631 3632 // First check if we need to recurse. 3633 if (Offset > 0 || Size < ElementSize) { 3634 // Bail if the partition ends in a different array element. 3635 if ((Offset + Size) > ElementSize) 3636 return nullptr; 3637 // Recurse through the element type trying to peel off offset bytes. 3638 return getTypePartition(DL, ElementTy, Offset, Size); 3639 } 3640 assert(Offset == 0); 3641 3642 if (Size == ElementSize) 3643 return stripAggregateTypeWrapping(DL, ElementTy); 3644 assert(Size > ElementSize); 3645 uint64_t NumElements = Size / ElementSize; 3646 if (NumElements * ElementSize != Size) 3647 return nullptr; 3648 return ArrayType::get(ElementTy, NumElements); 3649 } 3650 3651 StructType *STy = dyn_cast<StructType>(Ty); 3652 if (!STy) 3653 return nullptr; 3654 3655 const StructLayout *SL = DL.getStructLayout(STy); 3656 if (Offset >= SL->getSizeInBytes()) 3657 return nullptr; 3658 uint64_t EndOffset = Offset + Size; 3659 if (EndOffset > SL->getSizeInBytes()) 3660 return nullptr; 3661 3662 unsigned Index = SL->getElementContainingOffset(Offset); 3663 Offset -= SL->getElementOffset(Index); 3664 3665 Type *ElementTy = STy->getElementType(Index); 3666 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize(); 3667 if (Offset >= ElementSize) 3668 return nullptr; // The offset points into alignment padding. 3669 3670 // See if any partition must be contained by the element. 3671 if (Offset > 0 || Size < ElementSize) { 3672 if ((Offset + Size) > ElementSize) 3673 return nullptr; 3674 return getTypePartition(DL, ElementTy, Offset, Size); 3675 } 3676 assert(Offset == 0); 3677 3678 if (Size == ElementSize) 3679 return stripAggregateTypeWrapping(DL, ElementTy); 3680 3681 StructType::element_iterator EI = STy->element_begin() + Index, 3682 EE = STy->element_end(); 3683 if (EndOffset < SL->getSizeInBytes()) { 3684 unsigned EndIndex = SL->getElementContainingOffset(EndOffset); 3685 if (Index == EndIndex) 3686 return nullptr; // Within a single element and its padding. 3687 3688 // Don't try to form "natural" types if the elements don't line up with the 3689 // expected size. 3690 // FIXME: We could potentially recurse down through the last element in the 3691 // sub-struct to find a natural end point. 3692 if (SL->getElementOffset(EndIndex) != EndOffset) 3693 return nullptr; 3694 3695 assert(Index < EndIndex); 3696 EE = STy->element_begin() + EndIndex; 3697 } 3698 3699 // Try to build up a sub-structure. 3700 StructType *SubTy = 3701 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked()); 3702 const StructLayout *SubSL = DL.getStructLayout(SubTy); 3703 if (Size != SubSL->getSizeInBytes()) 3704 return nullptr; // The sub-struct doesn't have quite the size needed. 3705 3706 return SubTy; 3707 } 3708 3709 /// Pre-split loads and stores to simplify rewriting. 3710 /// 3711 /// We want to break up the splittable load+store pairs as much as 3712 /// possible. This is important to do as a preprocessing step, as once we 3713 /// start rewriting the accesses to partitions of the alloca we lose the 3714 /// necessary information to correctly split apart paired loads and stores 3715 /// which both point into this alloca. The case to consider is something like 3716 /// the following: 3717 /// 3718 /// %a = alloca [12 x i8] 3719 /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0 3720 /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4 3721 /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8 3722 /// %iptr1 = bitcast i8* %gep1 to i64* 3723 /// %iptr2 = bitcast i8* %gep2 to i64* 3724 /// %fptr1 = bitcast i8* %gep1 to float* 3725 /// %fptr2 = bitcast i8* %gep2 to float* 3726 /// %fptr3 = bitcast i8* %gep3 to float* 3727 /// store float 0.0, float* %fptr1 3728 /// store float 1.0, float* %fptr2 3729 /// %v = load i64* %iptr1 3730 /// store i64 %v, i64* %iptr2 3731 /// %f1 = load float* %fptr2 3732 /// %f2 = load float* %fptr3 3733 /// 3734 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and 3735 /// promote everything so we recover the 2 SSA values that should have been 3736 /// there all along. 3737 /// 3738 /// \returns true if any changes are made. 3739 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) { 3740 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n"); 3741 3742 // Track the loads and stores which are candidates for pre-splitting here, in 3743 // the order they first appear during the partition scan. These give stable 3744 // iteration order and a basis for tracking which loads and stores we 3745 // actually split. 3746 SmallVector<LoadInst *, 4> Loads; 3747 SmallVector<StoreInst *, 4> Stores; 3748 3749 // We need to accumulate the splits required of each load or store where we 3750 // can find them via a direct lookup. This is important to cross-check loads 3751 // and stores against each other. We also track the slice so that we can kill 3752 // all the slices that end up split. 3753 struct SplitOffsets { 3754 Slice *S; 3755 std::vector<uint64_t> Splits; 3756 }; 3757 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap; 3758 3759 // Track loads out of this alloca which cannot, for any reason, be pre-split. 3760 // This is important as we also cannot pre-split stores of those loads! 3761 // FIXME: This is all pretty gross. It means that we can be more aggressive 3762 // in pre-splitting when the load feeding the store happens to come from 3763 // a separate alloca. Put another way, the effectiveness of SROA would be 3764 // decreased by a frontend which just concatenated all of its local allocas 3765 // into one big flat alloca. But defeating such patterns is exactly the job 3766 // SROA is tasked with! Sadly, to not have this discrepancy we would have 3767 // change store pre-splitting to actually force pre-splitting of the load 3768 // that feeds it *and all stores*. That makes pre-splitting much harder, but 3769 // maybe it would make it more principled? 3770 SmallPtrSet<LoadInst *, 8> UnsplittableLoads; 3771 3772 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n"); 3773 for (auto &P : AS.partitions()) { 3774 for (Slice &S : P) { 3775 Instruction *I = cast<Instruction>(S.getUse()->getUser()); 3776 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) { 3777 // If this is a load we have to track that it can't participate in any 3778 // pre-splitting. If this is a store of a load we have to track that 3779 // that load also can't participate in any pre-splitting. 3780 if (auto *LI = dyn_cast<LoadInst>(I)) 3781 UnsplittableLoads.insert(LI); 3782 else if (auto *SI = dyn_cast<StoreInst>(I)) 3783 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand())) 3784 UnsplittableLoads.insert(LI); 3785 continue; 3786 } 3787 assert(P.endOffset() > S.beginOffset() && 3788 "Empty or backwards partition!"); 3789 3790 // Determine if this is a pre-splittable slice. 3791 if (auto *LI = dyn_cast<LoadInst>(I)) { 3792 assert(!LI->isVolatile() && "Cannot split volatile loads!"); 3793 3794 // The load must be used exclusively to store into other pointers for 3795 // us to be able to arbitrarily pre-split it. The stores must also be 3796 // simple to avoid changing semantics. 3797 auto IsLoadSimplyStored = [](LoadInst *LI) { 3798 for (User *LU : LI->users()) { 3799 auto *SI = dyn_cast<StoreInst>(LU); 3800 if (!SI || !SI->isSimple()) 3801 return false; 3802 } 3803 return true; 3804 }; 3805 if (!IsLoadSimplyStored(LI)) { 3806 UnsplittableLoads.insert(LI); 3807 continue; 3808 } 3809 3810 Loads.push_back(LI); 3811 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 3812 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex())) 3813 // Skip stores *of* pointers. FIXME: This shouldn't even be possible! 3814 continue; 3815 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand()); 3816 if (!StoredLoad || !StoredLoad->isSimple()) 3817 continue; 3818 assert(!SI->isVolatile() && "Cannot split volatile stores!"); 3819 3820 Stores.push_back(SI); 3821 } else { 3822 // Other uses cannot be pre-split. 3823 continue; 3824 } 3825 3826 // Record the initial split. 3827 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n"); 3828 auto &Offsets = SplitOffsetsMap[I]; 3829 assert(Offsets.Splits.empty() && 3830 "Should not have splits the first time we see an instruction!"); 3831 Offsets.S = &S; 3832 Offsets.Splits.push_back(P.endOffset() - S.beginOffset()); 3833 } 3834 3835 // Now scan the already split slices, and add a split for any of them which 3836 // we're going to pre-split. 3837 for (Slice *S : P.splitSliceTails()) { 3838 auto SplitOffsetsMapI = 3839 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser())); 3840 if (SplitOffsetsMapI == SplitOffsetsMap.end()) 3841 continue; 3842 auto &Offsets = SplitOffsetsMapI->second; 3843 3844 assert(Offsets.S == S && "Found a mismatched slice!"); 3845 assert(!Offsets.Splits.empty() && 3846 "Cannot have an empty set of splits on the second partition!"); 3847 assert(Offsets.Splits.back() == 3848 P.beginOffset() - Offsets.S->beginOffset() && 3849 "Previous split does not end where this one begins!"); 3850 3851 // Record each split. The last partition's end isn't needed as the size 3852 // of the slice dictates that. 3853 if (S->endOffset() > P.endOffset()) 3854 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset()); 3855 } 3856 } 3857 3858 // We may have split loads where some of their stores are split stores. For 3859 // such loads and stores, we can only pre-split them if their splits exactly 3860 // match relative to their starting offset. We have to verify this prior to 3861 // any rewriting. 3862 Stores.erase( 3863 llvm::remove_if(Stores, 3864 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) { 3865 // Lookup the load we are storing in our map of split 3866 // offsets. 3867 auto *LI = cast<LoadInst>(SI->getValueOperand()); 3868 // If it was completely unsplittable, then we're done, 3869 // and this store can't be pre-split. 3870 if (UnsplittableLoads.count(LI)) 3871 return true; 3872 3873 auto LoadOffsetsI = SplitOffsetsMap.find(LI); 3874 if (LoadOffsetsI == SplitOffsetsMap.end()) 3875 return false; // Unrelated loads are definitely safe. 3876 auto &LoadOffsets = LoadOffsetsI->second; 3877 3878 // Now lookup the store's offsets. 3879 auto &StoreOffsets = SplitOffsetsMap[SI]; 3880 3881 // If the relative offsets of each split in the load and 3882 // store match exactly, then we can split them and we 3883 // don't need to remove them here. 3884 if (LoadOffsets.Splits == StoreOffsets.Splits) 3885 return false; 3886 3887 LLVM_DEBUG( 3888 dbgs() 3889 << " Mismatched splits for load and store:\n" 3890 << " " << *LI << "\n" 3891 << " " << *SI << "\n"); 3892 3893 // We've found a store and load that we need to split 3894 // with mismatched relative splits. Just give up on them 3895 // and remove both instructions from our list of 3896 // candidates. 3897 UnsplittableLoads.insert(LI); 3898 return true; 3899 }), 3900 Stores.end()); 3901 // Now we have to go *back* through all the stores, because a later store may 3902 // have caused an earlier store's load to become unsplittable and if it is 3903 // unsplittable for the later store, then we can't rely on it being split in 3904 // the earlier store either. 3905 Stores.erase(llvm::remove_if(Stores, 3906 [&UnsplittableLoads](StoreInst *SI) { 3907 auto *LI = 3908 cast<LoadInst>(SI->getValueOperand()); 3909 return UnsplittableLoads.count(LI); 3910 }), 3911 Stores.end()); 3912 // Once we've established all the loads that can't be split for some reason, 3913 // filter any that made it into our list out. 3914 Loads.erase(llvm::remove_if(Loads, 3915 [&UnsplittableLoads](LoadInst *LI) { 3916 return UnsplittableLoads.count(LI); 3917 }), 3918 Loads.end()); 3919 3920 // If no loads or stores are left, there is no pre-splitting to be done for 3921 // this alloca. 3922 if (Loads.empty() && Stores.empty()) 3923 return false; 3924 3925 // From here on, we can't fail and will be building new accesses, so rig up 3926 // an IR builder. 3927 IRBuilderTy IRB(&AI); 3928 3929 // Collect the new slices which we will merge into the alloca slices. 3930 SmallVector<Slice, 4> NewSlices; 3931 3932 // Track any allocas we end up splitting loads and stores for so we iterate 3933 // on them. 3934 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas; 3935 3936 // At this point, we have collected all of the loads and stores we can 3937 // pre-split, and the specific splits needed for them. We actually do the 3938 // splitting in a specific order in order to handle when one of the loads in 3939 // the value operand to one of the stores. 3940 // 3941 // First, we rewrite all of the split loads, and just accumulate each split 3942 // load in a parallel structure. We also build the slices for them and append 3943 // them to the alloca slices. 3944 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap; 3945 std::vector<LoadInst *> SplitLoads; 3946 const DataLayout &DL = AI.getModule()->getDataLayout(); 3947 for (LoadInst *LI : Loads) { 3948 SplitLoads.clear(); 3949 3950 IntegerType *Ty = cast<IntegerType>(LI->getType()); 3951 uint64_t LoadSize = Ty->getBitWidth() / 8; 3952 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!"); 3953 3954 auto &Offsets = SplitOffsetsMap[LI]; 3955 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && 3956 "Slice size should always match load size exactly!"); 3957 uint64_t BaseOffset = Offsets.S->beginOffset(); 3958 assert(BaseOffset + LoadSize > BaseOffset && 3959 "Cannot represent alloca access size using 64-bit integers!"); 3960 3961 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand()); 3962 IRB.SetInsertPoint(LI); 3963 3964 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n"); 3965 3966 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front(); 3967 int Idx = 0, Size = Offsets.Splits.size(); 3968 for (;;) { 3969 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8); 3970 auto AS = LI->getPointerAddressSpace(); 3971 auto *PartPtrTy = PartTy->getPointerTo(AS); 3972 LoadInst *PLoad = IRB.CreateAlignedLoad( 3973 PartTy, 3974 getAdjustedPtr(IRB, DL, BasePtr, 3975 APInt(DL.getIndexSizeInBits(AS), PartOffset), 3976 PartPtrTy, BasePtr->getName() + "."), 3977 getAdjustedAlignment(LI, PartOffset), 3978 /*IsVolatile*/ false, LI->getName()); 3979 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access, 3980 LLVMContext::MD_access_group}); 3981 3982 // Append this load onto the list of split loads so we can find it later 3983 // to rewrite the stores. 3984 SplitLoads.push_back(PLoad); 3985 3986 // Now build a new slice for the alloca. 3987 NewSlices.push_back( 3988 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize, 3989 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()), 3990 /*IsSplittable*/ false)); 3991 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset() 3992 << ", " << NewSlices.back().endOffset() 3993 << "): " << *PLoad << "\n"); 3994 3995 // See if we've handled all the splits. 3996 if (Idx >= Size) 3997 break; 3998 3999 // Setup the next partition. 4000 PartOffset = Offsets.Splits[Idx]; 4001 ++Idx; 4002 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset; 4003 } 4004 4005 // Now that we have the split loads, do the slow walk over all uses of the 4006 // load and rewrite them as split stores, or save the split loads to use 4007 // below if the store is going to be split there anyways. 4008 bool DeferredStores = false; 4009 for (User *LU : LI->users()) { 4010 StoreInst *SI = cast<StoreInst>(LU); 4011 if (!Stores.empty() && SplitOffsetsMap.count(SI)) { 4012 DeferredStores = true; 4013 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI 4014 << "\n"); 4015 continue; 4016 } 4017 4018 Value *StoreBasePtr = SI->getPointerOperand(); 4019 IRB.SetInsertPoint(SI); 4020 4021 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n"); 4022 4023 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) { 4024 LoadInst *PLoad = SplitLoads[Idx]; 4025 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1]; 4026 auto *PartPtrTy = 4027 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace()); 4028 4029 auto AS = SI->getPointerAddressSpace(); 4030 StoreInst *PStore = IRB.CreateAlignedStore( 4031 PLoad, 4032 getAdjustedPtr(IRB, DL, StoreBasePtr, 4033 APInt(DL.getIndexSizeInBits(AS), PartOffset), 4034 PartPtrTy, StoreBasePtr->getName() + "."), 4035 getAdjustedAlignment(SI, PartOffset), 4036 /*IsVolatile*/ false); 4037 PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access, 4038 LLVMContext::MD_access_group}); 4039 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n"); 4040 } 4041 4042 // We want to immediately iterate on any allocas impacted by splitting 4043 // this store, and we have to track any promotable alloca (indicated by 4044 // a direct store) as needing to be resplit because it is no longer 4045 // promotable. 4046 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) { 4047 ResplitPromotableAllocas.insert(OtherAI); 4048 Worklist.insert(OtherAI); 4049 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>( 4050 StoreBasePtr->stripInBoundsOffsets())) { 4051 Worklist.insert(OtherAI); 4052 } 4053 4054 // Mark the original store as dead. 4055 DeadInsts.insert(SI); 4056 } 4057 4058 // Save the split loads if there are deferred stores among the users. 4059 if (DeferredStores) 4060 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads))); 4061 4062 // Mark the original load as dead and kill the original slice. 4063 DeadInsts.insert(LI); 4064 Offsets.S->kill(); 4065 } 4066 4067 // Second, we rewrite all of the split stores. At this point, we know that 4068 // all loads from this alloca have been split already. For stores of such 4069 // loads, we can simply look up the pre-existing split loads. For stores of 4070 // other loads, we split those loads first and then write split stores of 4071 // them. 4072 for (StoreInst *SI : Stores) { 4073 auto *LI = cast<LoadInst>(SI->getValueOperand()); 4074 IntegerType *Ty = cast<IntegerType>(LI->getType()); 4075 uint64_t StoreSize = Ty->getBitWidth() / 8; 4076 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!"); 4077 4078 auto &Offsets = SplitOffsetsMap[SI]; 4079 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && 4080 "Slice size should always match load size exactly!"); 4081 uint64_t BaseOffset = Offsets.S->beginOffset(); 4082 assert(BaseOffset + StoreSize > BaseOffset && 4083 "Cannot represent alloca access size using 64-bit integers!"); 4084 4085 Value *LoadBasePtr = LI->getPointerOperand(); 4086 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand()); 4087 4088 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n"); 4089 4090 // Check whether we have an already split load. 4091 auto SplitLoadsMapI = SplitLoadsMap.find(LI); 4092 std::vector<LoadInst *> *SplitLoads = nullptr; 4093 if (SplitLoadsMapI != SplitLoadsMap.end()) { 4094 SplitLoads = &SplitLoadsMapI->second; 4095 assert(SplitLoads->size() == Offsets.Splits.size() + 1 && 4096 "Too few split loads for the number of splits in the store!"); 4097 } else { 4098 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n"); 4099 } 4100 4101 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front(); 4102 int Idx = 0, Size = Offsets.Splits.size(); 4103 for (;;) { 4104 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8); 4105 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace()); 4106 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace()); 4107 4108 // Either lookup a split load or create one. 4109 LoadInst *PLoad; 4110 if (SplitLoads) { 4111 PLoad = (*SplitLoads)[Idx]; 4112 } else { 4113 IRB.SetInsertPoint(LI); 4114 auto AS = LI->getPointerAddressSpace(); 4115 PLoad = IRB.CreateAlignedLoad( 4116 PartTy, 4117 getAdjustedPtr(IRB, DL, LoadBasePtr, 4118 APInt(DL.getIndexSizeInBits(AS), PartOffset), 4119 LoadPartPtrTy, LoadBasePtr->getName() + "."), 4120 getAdjustedAlignment(LI, PartOffset), 4121 /*IsVolatile*/ false, LI->getName()); 4122 } 4123 4124 // And store this partition. 4125 IRB.SetInsertPoint(SI); 4126 auto AS = SI->getPointerAddressSpace(); 4127 StoreInst *PStore = IRB.CreateAlignedStore( 4128 PLoad, 4129 getAdjustedPtr(IRB, DL, StoreBasePtr, 4130 APInt(DL.getIndexSizeInBits(AS), PartOffset), 4131 StorePartPtrTy, StoreBasePtr->getName() + "."), 4132 getAdjustedAlignment(SI, PartOffset), 4133 /*IsVolatile*/ false); 4134 4135 // Now build a new slice for the alloca. 4136 NewSlices.push_back( 4137 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize, 4138 &PStore->getOperandUse(PStore->getPointerOperandIndex()), 4139 /*IsSplittable*/ false)); 4140 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset() 4141 << ", " << NewSlices.back().endOffset() 4142 << "): " << *PStore << "\n"); 4143 if (!SplitLoads) { 4144 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n"); 4145 } 4146 4147 // See if we've finished all the splits. 4148 if (Idx >= Size) 4149 break; 4150 4151 // Setup the next partition. 4152 PartOffset = Offsets.Splits[Idx]; 4153 ++Idx; 4154 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset; 4155 } 4156 4157 // We want to immediately iterate on any allocas impacted by splitting 4158 // this load, which is only relevant if it isn't a load of this alloca and 4159 // thus we didn't already split the loads above. We also have to keep track 4160 // of any promotable allocas we split loads on as they can no longer be 4161 // promoted. 4162 if (!SplitLoads) { 4163 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) { 4164 assert(OtherAI != &AI && "We can't re-split our own alloca!"); 4165 ResplitPromotableAllocas.insert(OtherAI); 4166 Worklist.insert(OtherAI); 4167 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>( 4168 LoadBasePtr->stripInBoundsOffsets())) { 4169 assert(OtherAI != &AI && "We can't re-split our own alloca!"); 4170 Worklist.insert(OtherAI); 4171 } 4172 } 4173 4174 // Mark the original store as dead now that we've split it up and kill its 4175 // slice. Note that we leave the original load in place unless this store 4176 // was its only use. It may in turn be split up if it is an alloca load 4177 // for some other alloca, but it may be a normal load. This may introduce 4178 // redundant loads, but where those can be merged the rest of the optimizer 4179 // should handle the merging, and this uncovers SSA splits which is more 4180 // important. In practice, the original loads will almost always be fully 4181 // split and removed eventually, and the splits will be merged by any 4182 // trivial CSE, including instcombine. 4183 if (LI->hasOneUse()) { 4184 assert(*LI->user_begin() == SI && "Single use isn't this store!"); 4185 DeadInsts.insert(LI); 4186 } 4187 DeadInsts.insert(SI); 4188 Offsets.S->kill(); 4189 } 4190 4191 // Remove the killed slices that have ben pre-split. 4192 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }), 4193 AS.end()); 4194 4195 // Insert our new slices. This will sort and merge them into the sorted 4196 // sequence. 4197 AS.insert(NewSlices); 4198 4199 LLVM_DEBUG(dbgs() << " Pre-split slices:\n"); 4200 #ifndef NDEBUG 4201 for (auto I = AS.begin(), E = AS.end(); I != E; ++I) 4202 LLVM_DEBUG(AS.print(dbgs(), I, " ")); 4203 #endif 4204 4205 // Finally, don't try to promote any allocas that new require re-splitting. 4206 // They have already been added to the worklist above. 4207 PromotableAllocas.erase( 4208 llvm::remove_if( 4209 PromotableAllocas, 4210 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }), 4211 PromotableAllocas.end()); 4212 4213 return true; 4214 } 4215 4216 /// Rewrite an alloca partition's users. 4217 /// 4218 /// This routine drives both of the rewriting goals of the SROA pass. It tries 4219 /// to rewrite uses of an alloca partition to be conducive for SSA value 4220 /// promotion. If the partition needs a new, more refined alloca, this will 4221 /// build that new alloca, preserving as much type information as possible, and 4222 /// rewrite the uses of the old alloca to point at the new one and have the 4223 /// appropriate new offsets. It also evaluates how successful the rewrite was 4224 /// at enabling promotion and if it was successful queues the alloca to be 4225 /// promoted. 4226 AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS, 4227 Partition &P) { 4228 // Try to compute a friendly type for this partition of the alloca. This 4229 // won't always succeed, in which case we fall back to a legal integer type 4230 // or an i8 array of an appropriate size. 4231 Type *SliceTy = nullptr; 4232 const DataLayout &DL = AI.getModule()->getDataLayout(); 4233 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset())) 4234 if (DL.getTypeAllocSize(CommonUseTy).getFixedSize() >= P.size()) 4235 SliceTy = CommonUseTy; 4236 if (!SliceTy) 4237 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(), 4238 P.beginOffset(), P.size())) 4239 SliceTy = TypePartitionTy; 4240 if ((!SliceTy || (SliceTy->isArrayTy() && 4241 SliceTy->getArrayElementType()->isIntegerTy())) && 4242 DL.isLegalInteger(P.size() * 8)) 4243 SliceTy = Type::getIntNTy(*C, P.size() * 8); 4244 if (!SliceTy) 4245 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size()); 4246 assert(DL.getTypeAllocSize(SliceTy).getFixedSize() >= P.size()); 4247 4248 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL); 4249 4250 VectorType *VecTy = 4251 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL); 4252 if (VecTy) 4253 SliceTy = VecTy; 4254 4255 // Check for the case where we're going to rewrite to a new alloca of the 4256 // exact same type as the original, and with the same access offsets. In that 4257 // case, re-use the existing alloca, but still run through the rewriter to 4258 // perform phi and select speculation. 4259 // P.beginOffset() can be non-zero even with the same type in a case with 4260 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll). 4261 AllocaInst *NewAI; 4262 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) { 4263 NewAI = &AI; 4264 // FIXME: We should be able to bail at this point with "nothing changed". 4265 // FIXME: We might want to defer PHI speculation until after here. 4266 // FIXME: return nullptr; 4267 } else { 4268 // Make sure the alignment is compatible with P.beginOffset(). 4269 const Align Alignment = commonAlignment(AI.getAlign(), P.beginOffset()); 4270 // If we will get at least this much alignment from the type alone, leave 4271 // the alloca's alignment unconstrained. 4272 const bool IsUnconstrained = Alignment <= DL.getABITypeAlignment(SliceTy); 4273 NewAI = new AllocaInst( 4274 SliceTy, AI.getType()->getAddressSpace(), nullptr, 4275 IsUnconstrained ? DL.getPrefTypeAlign(SliceTy) : Alignment, 4276 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI); 4277 // Copy the old AI debug location over to the new one. 4278 NewAI->setDebugLoc(AI.getDebugLoc()); 4279 ++NumNewAllocas; 4280 } 4281 4282 LLVM_DEBUG(dbgs() << "Rewriting alloca partition " 4283 << "[" << P.beginOffset() << "," << P.endOffset() 4284 << ") to: " << *NewAI << "\n"); 4285 4286 // Track the high watermark on the worklist as it is only relevant for 4287 // promoted allocas. We will reset it to this point if the alloca is not in 4288 // fact scheduled for promotion. 4289 unsigned PPWOldSize = PostPromotionWorklist.size(); 4290 unsigned NumUses = 0; 4291 SmallSetVector<PHINode *, 8> PHIUsers; 4292 SmallSetVector<SelectInst *, 8> SelectUsers; 4293 4294 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(), 4295 P.endOffset(), IsIntegerPromotable, VecTy, 4296 PHIUsers, SelectUsers); 4297 bool Promotable = true; 4298 for (Slice *S : P.splitSliceTails()) { 4299 Promotable &= Rewriter.visit(S); 4300 ++NumUses; 4301 } 4302 for (Slice &S : P) { 4303 Promotable &= Rewriter.visit(&S); 4304 ++NumUses; 4305 } 4306 4307 NumAllocaPartitionUses += NumUses; 4308 MaxUsesPerAllocaPartition.updateMax(NumUses); 4309 4310 // Now that we've processed all the slices in the new partition, check if any 4311 // PHIs or Selects would block promotion. 4312 for (PHINode *PHI : PHIUsers) 4313 if (!isSafePHIToSpeculate(*PHI)) { 4314 Promotable = false; 4315 PHIUsers.clear(); 4316 SelectUsers.clear(); 4317 break; 4318 } 4319 4320 for (SelectInst *Sel : SelectUsers) 4321 if (!isSafeSelectToSpeculate(*Sel)) { 4322 Promotable = false; 4323 PHIUsers.clear(); 4324 SelectUsers.clear(); 4325 break; 4326 } 4327 4328 if (Promotable) { 4329 if (PHIUsers.empty() && SelectUsers.empty()) { 4330 // Promote the alloca. 4331 PromotableAllocas.push_back(NewAI); 4332 } else { 4333 // If we have either PHIs or Selects to speculate, add them to those 4334 // worklists and re-queue the new alloca so that we promote in on the 4335 // next iteration. 4336 for (PHINode *PHIUser : PHIUsers) 4337 SpeculatablePHIs.insert(PHIUser); 4338 for (SelectInst *SelectUser : SelectUsers) 4339 SpeculatableSelects.insert(SelectUser); 4340 Worklist.insert(NewAI); 4341 } 4342 } else { 4343 // Drop any post-promotion work items if promotion didn't happen. 4344 while (PostPromotionWorklist.size() > PPWOldSize) 4345 PostPromotionWorklist.pop_back(); 4346 4347 // We couldn't promote and we didn't create a new partition, nothing 4348 // happened. 4349 if (NewAI == &AI) 4350 return nullptr; 4351 4352 // If we can't promote the alloca, iterate on it to check for new 4353 // refinements exposed by splitting the current alloca. Don't iterate on an 4354 // alloca which didn't actually change and didn't get promoted. 4355 Worklist.insert(NewAI); 4356 } 4357 4358 return NewAI; 4359 } 4360 4361 /// Walks the slices of an alloca and form partitions based on them, 4362 /// rewriting each of their uses. 4363 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) { 4364 if (AS.begin() == AS.end()) 4365 return false; 4366 4367 unsigned NumPartitions = 0; 4368 bool Changed = false; 4369 const DataLayout &DL = AI.getModule()->getDataLayout(); 4370 4371 // First try to pre-split loads and stores. 4372 Changed |= presplitLoadsAndStores(AI, AS); 4373 4374 // Now that we have identified any pre-splitting opportunities, 4375 // mark loads and stores unsplittable except for the following case. 4376 // We leave a slice splittable if all other slices are disjoint or fully 4377 // included in the slice, such as whole-alloca loads and stores. 4378 // If we fail to split these during pre-splitting, we want to force them 4379 // to be rewritten into a partition. 4380 bool IsSorted = true; 4381 4382 uint64_t AllocaSize = 4383 DL.getTypeAllocSize(AI.getAllocatedType()).getFixedSize(); 4384 const uint64_t MaxBitVectorSize = 1024; 4385 if (AllocaSize <= MaxBitVectorSize) { 4386 // If a byte boundary is included in any load or store, a slice starting or 4387 // ending at the boundary is not splittable. 4388 SmallBitVector SplittableOffset(AllocaSize + 1, true); 4389 for (Slice &S : AS) 4390 for (unsigned O = S.beginOffset() + 1; 4391 O < S.endOffset() && O < AllocaSize; O++) 4392 SplittableOffset.reset(O); 4393 4394 for (Slice &S : AS) { 4395 if (!S.isSplittable()) 4396 continue; 4397 4398 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) && 4399 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()])) 4400 continue; 4401 4402 if (isa<LoadInst>(S.getUse()->getUser()) || 4403 isa<StoreInst>(S.getUse()->getUser())) { 4404 S.makeUnsplittable(); 4405 IsSorted = false; 4406 } 4407 } 4408 } 4409 else { 4410 // We only allow whole-alloca splittable loads and stores 4411 // for a large alloca to avoid creating too large BitVector. 4412 for (Slice &S : AS) { 4413 if (!S.isSplittable()) 4414 continue; 4415 4416 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize) 4417 continue; 4418 4419 if (isa<LoadInst>(S.getUse()->getUser()) || 4420 isa<StoreInst>(S.getUse()->getUser())) { 4421 S.makeUnsplittable(); 4422 IsSorted = false; 4423 } 4424 } 4425 } 4426 4427 if (!IsSorted) 4428 llvm::sort(AS); 4429 4430 /// Describes the allocas introduced by rewritePartition in order to migrate 4431 /// the debug info. 4432 struct Fragment { 4433 AllocaInst *Alloca; 4434 uint64_t Offset; 4435 uint64_t Size; 4436 Fragment(AllocaInst *AI, uint64_t O, uint64_t S) 4437 : Alloca(AI), Offset(O), Size(S) {} 4438 }; 4439 SmallVector<Fragment, 4> Fragments; 4440 4441 // Rewrite each partition. 4442 for (auto &P : AS.partitions()) { 4443 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) { 4444 Changed = true; 4445 if (NewAI != &AI) { 4446 uint64_t SizeOfByte = 8; 4447 uint64_t AllocaSize = 4448 DL.getTypeSizeInBits(NewAI->getAllocatedType()).getFixedSize(); 4449 // Don't include any padding. 4450 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte); 4451 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size)); 4452 } 4453 } 4454 ++NumPartitions; 4455 } 4456 4457 NumAllocaPartitions += NumPartitions; 4458 MaxPartitionsPerAlloca.updateMax(NumPartitions); 4459 4460 // Migrate debug information from the old alloca to the new alloca(s) 4461 // and the individual partitions. 4462 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI); 4463 if (!DbgDeclares.empty()) { 4464 auto *Var = DbgDeclares.front()->getVariable(); 4465 auto *Expr = DbgDeclares.front()->getExpression(); 4466 auto VarSize = Var->getSizeInBits(); 4467 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false); 4468 uint64_t AllocaSize = 4469 DL.getTypeSizeInBits(AI.getAllocatedType()).getFixedSize(); 4470 for (auto Fragment : Fragments) { 4471 // Create a fragment expression describing the new partition or reuse AI's 4472 // expression if there is only one partition. 4473 auto *FragmentExpr = Expr; 4474 if (Fragment.Size < AllocaSize || Expr->isFragment()) { 4475 // If this alloca is already a scalar replacement of a larger aggregate, 4476 // Fragment.Offset describes the offset inside the scalar. 4477 auto ExprFragment = Expr->getFragmentInfo(); 4478 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0; 4479 uint64_t Start = Offset + Fragment.Offset; 4480 uint64_t Size = Fragment.Size; 4481 if (ExprFragment) { 4482 uint64_t AbsEnd = 4483 ExprFragment->OffsetInBits + ExprFragment->SizeInBits; 4484 if (Start >= AbsEnd) 4485 // No need to describe a SROAed padding. 4486 continue; 4487 Size = std::min(Size, AbsEnd - Start); 4488 } 4489 // The new, smaller fragment is stenciled out from the old fragment. 4490 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) { 4491 assert(Start >= OrigFragment->OffsetInBits && 4492 "new fragment is outside of original fragment"); 4493 Start -= OrigFragment->OffsetInBits; 4494 } 4495 4496 // The alloca may be larger than the variable. 4497 if (VarSize) { 4498 if (Size > *VarSize) 4499 Size = *VarSize; 4500 if (Size == 0 || Start + Size > *VarSize) 4501 continue; 4502 } 4503 4504 // Avoid creating a fragment expression that covers the entire variable. 4505 if (!VarSize || *VarSize != Size) { 4506 if (auto E = 4507 DIExpression::createFragmentExpression(Expr, Start, Size)) 4508 FragmentExpr = *E; 4509 else 4510 continue; 4511 } 4512 } 4513 4514 // Remove any existing intrinsics describing the same alloca. 4515 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca)) 4516 OldDII->eraseFromParent(); 4517 4518 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr, 4519 DbgDeclares.front()->getDebugLoc(), &AI); 4520 } 4521 } 4522 return Changed; 4523 } 4524 4525 /// Clobber a use with undef, deleting the used value if it becomes dead. 4526 void SROA::clobberUse(Use &U) { 4527 Value *OldV = U; 4528 // Replace the use with an undef value. 4529 U = UndefValue::get(OldV->getType()); 4530 4531 // Check for this making an instruction dead. We have to garbage collect 4532 // all the dead instructions to ensure the uses of any alloca end up being 4533 // minimal. 4534 if (Instruction *OldI = dyn_cast<Instruction>(OldV)) 4535 if (isInstructionTriviallyDead(OldI)) { 4536 DeadInsts.insert(OldI); 4537 } 4538 } 4539 4540 /// Analyze an alloca for SROA. 4541 /// 4542 /// This analyzes the alloca to ensure we can reason about it, builds 4543 /// the slices of the alloca, and then hands it off to be split and 4544 /// rewritten as needed. 4545 bool SROA::runOnAlloca(AllocaInst &AI) { 4546 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n"); 4547 ++NumAllocasAnalyzed; 4548 4549 // Special case dead allocas, as they're trivial. 4550 if (AI.use_empty()) { 4551 AI.eraseFromParent(); 4552 return true; 4553 } 4554 const DataLayout &DL = AI.getModule()->getDataLayout(); 4555 4556 // Skip alloca forms that this analysis can't handle. 4557 auto *AT = AI.getAllocatedType(); 4558 if (AI.isArrayAllocation() || !AT->isSized() || isa<ScalableVectorType>(AT) || 4559 DL.getTypeAllocSize(AT).getFixedSize() == 0) 4560 return false; 4561 4562 bool Changed = false; 4563 4564 // First, split any FCA loads and stores touching this alloca to promote 4565 // better splitting and promotion opportunities. 4566 AggLoadStoreRewriter AggRewriter(DL); 4567 Changed |= AggRewriter.rewrite(AI); 4568 4569 // Build the slices using a recursive instruction-visiting builder. 4570 AllocaSlices AS(DL, AI); 4571 LLVM_DEBUG(AS.print(dbgs())); 4572 if (AS.isEscaped()) 4573 return Changed; 4574 4575 // Delete all the dead users of this alloca before splitting and rewriting it. 4576 for (Instruction *DeadUser : AS.getDeadUsers()) { 4577 // Free up everything used by this instruction. 4578 for (Use &DeadOp : DeadUser->operands()) 4579 clobberUse(DeadOp); 4580 4581 // Now replace the uses of this instruction. 4582 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType())); 4583 4584 // And mark it for deletion. 4585 DeadInsts.insert(DeadUser); 4586 Changed = true; 4587 } 4588 for (Use *DeadOp : AS.getDeadOperands()) { 4589 clobberUse(*DeadOp); 4590 Changed = true; 4591 } 4592 4593 // No slices to split. Leave the dead alloca for a later pass to clean up. 4594 if (AS.begin() == AS.end()) 4595 return Changed; 4596 4597 Changed |= splitAlloca(AI, AS); 4598 4599 LLVM_DEBUG(dbgs() << " Speculating PHIs\n"); 4600 while (!SpeculatablePHIs.empty()) 4601 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val()); 4602 4603 LLVM_DEBUG(dbgs() << " Speculating Selects\n"); 4604 while (!SpeculatableSelects.empty()) 4605 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val()); 4606 4607 return Changed; 4608 } 4609 4610 /// Delete the dead instructions accumulated in this run. 4611 /// 4612 /// Recursively deletes the dead instructions we've accumulated. This is done 4613 /// at the very end to maximize locality of the recursive delete and to 4614 /// minimize the problems of invalidated instruction pointers as such pointers 4615 /// are used heavily in the intermediate stages of the algorithm. 4616 /// 4617 /// We also record the alloca instructions deleted here so that they aren't 4618 /// subsequently handed to mem2reg to promote. 4619 bool SROA::deleteDeadInstructions( 4620 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) { 4621 bool Changed = false; 4622 while (!DeadInsts.empty()) { 4623 Instruction *I = DeadInsts.pop_back_val(); 4624 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n"); 4625 4626 // If the instruction is an alloca, find the possible dbg.declare connected 4627 // to it, and remove it too. We must do this before calling RAUW or we will 4628 // not be able to find it. 4629 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { 4630 DeletedAllocas.insert(AI); 4631 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI)) 4632 OldDII->eraseFromParent(); 4633 } 4634 4635 I->replaceAllUsesWith(UndefValue::get(I->getType())); 4636 4637 for (Use &Operand : I->operands()) 4638 if (Instruction *U = dyn_cast<Instruction>(Operand)) { 4639 // Zero out the operand and see if it becomes trivially dead. 4640 Operand = nullptr; 4641 if (isInstructionTriviallyDead(U)) 4642 DeadInsts.insert(U); 4643 } 4644 4645 ++NumDeleted; 4646 I->eraseFromParent(); 4647 Changed = true; 4648 } 4649 return Changed; 4650 } 4651 4652 /// Promote the allocas, using the best available technique. 4653 /// 4654 /// This attempts to promote whatever allocas have been identified as viable in 4655 /// the PromotableAllocas list. If that list is empty, there is nothing to do. 4656 /// This function returns whether any promotion occurred. 4657 bool SROA::promoteAllocas(Function &F) { 4658 if (PromotableAllocas.empty()) 4659 return false; 4660 4661 NumPromoted += PromotableAllocas.size(); 4662 4663 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n"); 4664 PromoteMemToReg(PromotableAllocas, *DT, AC); 4665 PromotableAllocas.clear(); 4666 return true; 4667 } 4668 4669 PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT, 4670 AssumptionCache &RunAC) { 4671 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n"); 4672 C = &F.getContext(); 4673 DT = &RunDT; 4674 AC = &RunAC; 4675 4676 BasicBlock &EntryBB = F.getEntryBlock(); 4677 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end()); 4678 I != E; ++I) { 4679 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { 4680 if (isa<ScalableVectorType>(AI->getAllocatedType())) { 4681 if (isAllocaPromotable(AI)) 4682 PromotableAllocas.push_back(AI); 4683 } else { 4684 Worklist.insert(AI); 4685 } 4686 } 4687 } 4688 4689 bool Changed = false; 4690 // A set of deleted alloca instruction pointers which should be removed from 4691 // the list of promotable allocas. 4692 SmallPtrSet<AllocaInst *, 4> DeletedAllocas; 4693 4694 do { 4695 while (!Worklist.empty()) { 4696 Changed |= runOnAlloca(*Worklist.pop_back_val()); 4697 Changed |= deleteDeadInstructions(DeletedAllocas); 4698 4699 // Remove the deleted allocas from various lists so that we don't try to 4700 // continue processing them. 4701 if (!DeletedAllocas.empty()) { 4702 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); }; 4703 Worklist.remove_if(IsInSet); 4704 PostPromotionWorklist.remove_if(IsInSet); 4705 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet), 4706 PromotableAllocas.end()); 4707 DeletedAllocas.clear(); 4708 } 4709 } 4710 4711 Changed |= promoteAllocas(F); 4712 4713 Worklist = PostPromotionWorklist; 4714 PostPromotionWorklist.clear(); 4715 } while (!Worklist.empty()); 4716 4717 if (!Changed) 4718 return PreservedAnalyses::all(); 4719 4720 PreservedAnalyses PA; 4721 PA.preserveSet<CFGAnalyses>(); 4722 PA.preserve<GlobalsAA>(); 4723 return PA; 4724 } 4725 4726 PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) { 4727 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F), 4728 AM.getResult<AssumptionAnalysis>(F)); 4729 } 4730 4731 /// A legacy pass for the legacy pass manager that wraps the \c SROA pass. 4732 /// 4733 /// This is in the llvm namespace purely to allow it to be a friend of the \c 4734 /// SROA pass. 4735 class llvm::sroa::SROALegacyPass : public FunctionPass { 4736 /// The SROA implementation. 4737 SROA Impl; 4738 4739 public: 4740 static char ID; 4741 4742 SROALegacyPass() : FunctionPass(ID) { 4743 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry()); 4744 } 4745 4746 bool runOnFunction(Function &F) override { 4747 if (skipFunction(F)) 4748 return false; 4749 4750 auto PA = Impl.runImpl( 4751 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 4752 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 4753 return !PA.areAllPreserved(); 4754 } 4755 4756 void getAnalysisUsage(AnalysisUsage &AU) const override { 4757 AU.addRequired<AssumptionCacheTracker>(); 4758 AU.addRequired<DominatorTreeWrapperPass>(); 4759 AU.addPreserved<GlobalsAAWrapperPass>(); 4760 AU.setPreservesCFG(); 4761 } 4762 4763 StringRef getPassName() const override { return "SROA"; } 4764 }; 4765 4766 char SROALegacyPass::ID = 0; 4767 4768 FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); } 4769 4770 INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa", 4771 "Scalar Replacement Of Aggregates", false, false) 4772 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4773 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 4774 INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates", 4775 false, false) 4776