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 MaybeAlign 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, MaybeAlign(LI->getAlignment())); 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 const MaybeAlign Align = MaybeAlign(SomeLoad->getAlignment()); 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.CreateLoad( 1306 LoadTy, InVal, 1307 (PN.getName() + ".sroa.speculate.load." + Pred->getName())); 1308 ++NumLoadsSpeculated; 1309 Load->setAlignment(Align); 1310 if (AATags) 1311 Load->setAAMetadata(AATags); 1312 NewPN->addIncoming(Load, Pred); 1313 InjectedLoads[Pred] = Load; 1314 } 1315 1316 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n"); 1317 PN.eraseFromParent(); 1318 } 1319 1320 /// Select instructions that use an alloca and are subsequently loaded can be 1321 /// rewritten to load both input pointers and then select between the result, 1322 /// allowing the load of the alloca to be promoted. 1323 /// From this: 1324 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other 1325 /// %V = load i32* %P2 1326 /// to: 1327 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1328 /// %V2 = load i32* %Other 1329 /// %V = select i1 %cond, i32 %V1, i32 %V2 1330 /// 1331 /// We can do this to a select if its only uses are loads and if the operand 1332 /// to the select can be loaded unconditionally. 1333 static bool isSafeSelectToSpeculate(SelectInst &SI) { 1334 Value *TValue = SI.getTrueValue(); 1335 Value *FValue = SI.getFalseValue(); 1336 const DataLayout &DL = SI.getModule()->getDataLayout(); 1337 1338 for (User *U : SI.users()) { 1339 LoadInst *LI = dyn_cast<LoadInst>(U); 1340 if (!LI || !LI->isSimple()) 1341 return false; 1342 1343 // Both operands to the select need to be dereferenceable, either 1344 // absolutely (e.g. allocas) or at this point because we can see other 1345 // accesses to it. 1346 if (!isSafeToLoadUnconditionally(TValue, LI->getType(), 1347 MaybeAlign(LI->getAlignment()), DL, LI)) 1348 return false; 1349 if (!isSafeToLoadUnconditionally(FValue, LI->getType(), 1350 MaybeAlign(LI->getAlignment()), DL, LI)) 1351 return false; 1352 } 1353 1354 return true; 1355 } 1356 1357 static void speculateSelectInstLoads(SelectInst &SI) { 1358 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 1359 1360 IRBuilderTy IRB(&SI); 1361 Value *TV = SI.getTrueValue(); 1362 Value *FV = SI.getFalseValue(); 1363 // Replace the loads of the select with a select of two loads. 1364 while (!SI.use_empty()) { 1365 LoadInst *LI = cast<LoadInst>(SI.user_back()); 1366 assert(LI->isSimple() && "We only speculate simple loads"); 1367 1368 IRB.SetInsertPoint(LI); 1369 LoadInst *TL = IRB.CreateLoad(LI->getType(), TV, 1370 LI->getName() + ".sroa.speculate.load.true"); 1371 LoadInst *FL = IRB.CreateLoad(LI->getType(), FV, 1372 LI->getName() + ".sroa.speculate.load.false"); 1373 NumLoadsSpeculated += 2; 1374 1375 // Transfer alignment and AA info if present. 1376 TL->setAlignment(MaybeAlign(LI->getAlignment())); 1377 FL->setAlignment(MaybeAlign(LI->getAlignment())); 1378 1379 AAMDNodes Tags; 1380 LI->getAAMetadata(Tags); 1381 if (Tags) { 1382 TL->setAAMetadata(Tags); 1383 FL->setAAMetadata(Tags); 1384 } 1385 1386 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL, 1387 LI->getName() + ".sroa.speculated"); 1388 1389 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n"); 1390 LI->replaceAllUsesWith(V); 1391 LI->eraseFromParent(); 1392 } 1393 SI.eraseFromParent(); 1394 } 1395 1396 /// Build a GEP out of a base pointer and indices. 1397 /// 1398 /// This will return the BasePtr if that is valid, or build a new GEP 1399 /// instruction using the IRBuilder if GEP-ing is needed. 1400 static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr, 1401 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) { 1402 if (Indices.empty()) 1403 return BasePtr; 1404 1405 // A single zero index is a no-op, so check for this and avoid building a GEP 1406 // in that case. 1407 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero()) 1408 return BasePtr; 1409 1410 return IRB.CreateInBoundsGEP(BasePtr->getType()->getPointerElementType(), 1411 BasePtr, Indices, NamePrefix + "sroa_idx"); 1412 } 1413 1414 /// Get a natural GEP off of the BasePtr walking through Ty toward 1415 /// TargetTy without changing the offset of the pointer. 1416 /// 1417 /// This routine assumes we've already established a properly offset GEP with 1418 /// Indices, and arrived at the Ty type. The goal is to continue to GEP with 1419 /// zero-indices down through type layers until we find one the same as 1420 /// TargetTy. If we can't find one with the same type, we at least try to use 1421 /// one with the same size. If none of that works, we just produce the GEP as 1422 /// indicated by Indices to have the correct offset. 1423 static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL, 1424 Value *BasePtr, Type *Ty, Type *TargetTy, 1425 SmallVectorImpl<Value *> &Indices, 1426 Twine NamePrefix) { 1427 if (Ty == TargetTy) 1428 return buildGEP(IRB, BasePtr, Indices, NamePrefix); 1429 1430 // Offset size to use for the indices. 1431 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType()); 1432 1433 // See if we can descend into a struct and locate a field with the correct 1434 // type. 1435 unsigned NumLayers = 0; 1436 Type *ElementTy = Ty; 1437 do { 1438 if (ElementTy->isPointerTy()) 1439 break; 1440 1441 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) { 1442 ElementTy = ArrayTy->getElementType(); 1443 Indices.push_back(IRB.getIntN(OffsetSize, 0)); 1444 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) { 1445 ElementTy = VectorTy->getElementType(); 1446 Indices.push_back(IRB.getInt32(0)); 1447 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) { 1448 if (STy->element_begin() == STy->element_end()) 1449 break; // Nothing left to descend into. 1450 ElementTy = *STy->element_begin(); 1451 Indices.push_back(IRB.getInt32(0)); 1452 } else { 1453 break; 1454 } 1455 ++NumLayers; 1456 } while (ElementTy != TargetTy); 1457 if (ElementTy != TargetTy) 1458 Indices.erase(Indices.end() - NumLayers, Indices.end()); 1459 1460 return buildGEP(IRB, BasePtr, Indices, NamePrefix); 1461 } 1462 1463 /// Recursively compute indices for a natural GEP. 1464 /// 1465 /// This is the recursive step for getNaturalGEPWithOffset that walks down the 1466 /// element types adding appropriate indices for the GEP. 1467 static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL, 1468 Value *Ptr, Type *Ty, APInt &Offset, 1469 Type *TargetTy, 1470 SmallVectorImpl<Value *> &Indices, 1471 Twine NamePrefix) { 1472 if (Offset == 0) 1473 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices, 1474 NamePrefix); 1475 1476 // We can't recurse through pointer types. 1477 if (Ty->isPointerTy()) 1478 return nullptr; 1479 1480 // We try to analyze GEPs over vectors here, but note that these GEPs are 1481 // extremely poorly defined currently. The long-term goal is to remove GEPing 1482 // over a vector from the IR completely. 1483 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) { 1484 unsigned ElementSizeInBits = 1485 DL.getTypeSizeInBits(VecTy->getScalarType()).getFixedSize(); 1486 if (ElementSizeInBits % 8 != 0) { 1487 // GEPs over non-multiple of 8 size vector elements are invalid. 1488 return nullptr; 1489 } 1490 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8); 1491 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1492 if (NumSkippedElements.ugt(VecTy->getNumElements())) 1493 return nullptr; 1494 Offset -= NumSkippedElements * ElementSize; 1495 Indices.push_back(IRB.getInt(NumSkippedElements)); 1496 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(), 1497 Offset, TargetTy, Indices, NamePrefix); 1498 } 1499 1500 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { 1501 Type *ElementTy = ArrTy->getElementType(); 1502 APInt ElementSize(Offset.getBitWidth(), 1503 DL.getTypeAllocSize(ElementTy).getFixedSize()); 1504 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1505 if (NumSkippedElements.ugt(ArrTy->getNumElements())) 1506 return nullptr; 1507 1508 Offset -= NumSkippedElements * ElementSize; 1509 Indices.push_back(IRB.getInt(NumSkippedElements)); 1510 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1511 Indices, NamePrefix); 1512 } 1513 1514 StructType *STy = dyn_cast<StructType>(Ty); 1515 if (!STy) 1516 return nullptr; 1517 1518 const StructLayout *SL = DL.getStructLayout(STy); 1519 uint64_t StructOffset = Offset.getZExtValue(); 1520 if (StructOffset >= SL->getSizeInBytes()) 1521 return nullptr; 1522 unsigned Index = SL->getElementContainingOffset(StructOffset); 1523 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index)); 1524 Type *ElementTy = STy->getElementType(Index); 1525 if (Offset.uge(DL.getTypeAllocSize(ElementTy).getFixedSize())) 1526 return nullptr; // The offset points into alignment padding. 1527 1528 Indices.push_back(IRB.getInt32(Index)); 1529 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1530 Indices, NamePrefix); 1531 } 1532 1533 /// Get a natural GEP from a base pointer to a particular offset and 1534 /// resulting in a particular type. 1535 /// 1536 /// The goal is to produce a "natural" looking GEP that works with the existing 1537 /// composite types to arrive at the appropriate offset and element type for 1538 /// a pointer. TargetTy is the element type the returned GEP should point-to if 1539 /// possible. We recurse by decreasing Offset, adding the appropriate index to 1540 /// Indices, and setting Ty to the result subtype. 1541 /// 1542 /// If no natural GEP can be constructed, this function returns null. 1543 static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL, 1544 Value *Ptr, APInt Offset, Type *TargetTy, 1545 SmallVectorImpl<Value *> &Indices, 1546 Twine NamePrefix) { 1547 PointerType *Ty = cast<PointerType>(Ptr->getType()); 1548 1549 // Don't consider any GEPs through an i8* as natural unless the TargetTy is 1550 // an i8. 1551 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8)) 1552 return nullptr; 1553 1554 Type *ElementTy = Ty->getElementType(); 1555 if (!ElementTy->isSized()) 1556 return nullptr; // We can't GEP through an unsized element. 1557 APInt ElementSize(Offset.getBitWidth(), 1558 DL.getTypeAllocSize(ElementTy).getFixedSize()); 1559 if (ElementSize == 0) 1560 return nullptr; // Zero-length arrays can't help us build a natural GEP. 1561 APInt NumSkippedElements = Offset.sdiv(ElementSize); 1562 1563 Offset -= NumSkippedElements * ElementSize; 1564 Indices.push_back(IRB.getInt(NumSkippedElements)); 1565 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy, 1566 Indices, NamePrefix); 1567 } 1568 1569 /// Compute an adjusted pointer from Ptr by Offset bytes where the 1570 /// resulting pointer has PointerTy. 1571 /// 1572 /// This tries very hard to compute a "natural" GEP which arrives at the offset 1573 /// and produces the pointer type desired. Where it cannot, it will try to use 1574 /// the natural GEP to arrive at the offset and bitcast to the type. Where that 1575 /// fails, it will try to use an existing i8* and GEP to the byte offset and 1576 /// bitcast to the type. 1577 /// 1578 /// The strategy for finding the more natural GEPs is to peel off layers of the 1579 /// pointer, walking back through bit casts and GEPs, searching for a base 1580 /// pointer from which we can compute a natural GEP with the desired 1581 /// properties. The algorithm tries to fold as many constant indices into 1582 /// a single GEP as possible, thus making each GEP more independent of the 1583 /// surrounding code. 1584 static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr, 1585 APInt Offset, Type *PointerTy, Twine NamePrefix) { 1586 // Even though we don't look through PHI nodes, we could be called on an 1587 // instruction in an unreachable block, which may be on a cycle. 1588 SmallPtrSet<Value *, 4> Visited; 1589 Visited.insert(Ptr); 1590 SmallVector<Value *, 4> Indices; 1591 1592 // We may end up computing an offset pointer that has the wrong type. If we 1593 // never are able to compute one directly that has the correct type, we'll 1594 // fall back to it, so keep it and the base it was computed from around here. 1595 Value *OffsetPtr = nullptr; 1596 Value *OffsetBasePtr; 1597 1598 // Remember any i8 pointer we come across to re-use if we need to do a raw 1599 // byte offset. 1600 Value *Int8Ptr = nullptr; 1601 APInt Int8PtrOffset(Offset.getBitWidth(), 0); 1602 1603 PointerType *TargetPtrTy = cast<PointerType>(PointerTy); 1604 Type *TargetTy = TargetPtrTy->getElementType(); 1605 1606 // As `addrspacecast` is , `Ptr` (the storage pointer) may have different 1607 // address space from the expected `PointerTy` (the pointer to be used). 1608 // Adjust the pointer type based the original storage pointer. 1609 auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace(); 1610 PointerTy = TargetTy->getPointerTo(AS); 1611 1612 do { 1613 // First fold any existing GEPs into the offset. 1614 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) { 1615 APInt GEPOffset(Offset.getBitWidth(), 0); 1616 if (!GEP->accumulateConstantOffset(DL, GEPOffset)) 1617 break; 1618 Offset += GEPOffset; 1619 Ptr = GEP->getPointerOperand(); 1620 if (!Visited.insert(Ptr).second) 1621 break; 1622 } 1623 1624 // See if we can perform a natural GEP here. 1625 Indices.clear(); 1626 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy, 1627 Indices, NamePrefix)) { 1628 // If we have a new natural pointer at the offset, clear out any old 1629 // offset pointer we computed. Unless it is the base pointer or 1630 // a non-instruction, we built a GEP we don't need. Zap it. 1631 if (OffsetPtr && OffsetPtr != OffsetBasePtr) 1632 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) { 1633 assert(I->use_empty() && "Built a GEP with uses some how!"); 1634 I->eraseFromParent(); 1635 } 1636 OffsetPtr = P; 1637 OffsetBasePtr = Ptr; 1638 // If we also found a pointer of the right type, we're done. 1639 if (P->getType() == PointerTy) 1640 break; 1641 } 1642 1643 // Stash this pointer if we've found an i8*. 1644 if (Ptr->getType()->isIntegerTy(8)) { 1645 Int8Ptr = Ptr; 1646 Int8PtrOffset = Offset; 1647 } 1648 1649 // Peel off a layer of the pointer and update the offset appropriately. 1650 if (Operator::getOpcode(Ptr) == Instruction::BitCast) { 1651 Ptr = cast<Operator>(Ptr)->getOperand(0); 1652 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) { 1653 if (GA->isInterposable()) 1654 break; 1655 Ptr = GA->getAliasee(); 1656 } else { 1657 break; 1658 } 1659 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!"); 1660 } while (Visited.insert(Ptr).second); 1661 1662 if (!OffsetPtr) { 1663 if (!Int8Ptr) { 1664 Int8Ptr = IRB.CreateBitCast( 1665 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()), 1666 NamePrefix + "sroa_raw_cast"); 1667 Int8PtrOffset = Offset; 1668 } 1669 1670 OffsetPtr = Int8PtrOffset == 0 1671 ? Int8Ptr 1672 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr, 1673 IRB.getInt(Int8PtrOffset), 1674 NamePrefix + "sroa_raw_idx"); 1675 } 1676 Ptr = OffsetPtr; 1677 1678 // On the off chance we were targeting i8*, guard the bitcast here. 1679 if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) { 1680 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr, 1681 TargetPtrTy, 1682 NamePrefix + "sroa_cast"); 1683 } 1684 1685 return Ptr; 1686 } 1687 1688 /// Compute the adjusted alignment for a load or store from an offset. 1689 static Align getAdjustedAlignment(Instruction *I, uint64_t Offset, 1690 const DataLayout &DL) { 1691 MaybeAlign Alignment; 1692 Type *Ty; 1693 if (auto *LI = dyn_cast<LoadInst>(I)) { 1694 Alignment = MaybeAlign(LI->getAlignment()); 1695 Ty = LI->getType(); 1696 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 1697 Alignment = MaybeAlign(SI->getAlignment()); 1698 Ty = SI->getValueOperand()->getType(); 1699 } else { 1700 llvm_unreachable("Only loads and stores are allowed!"); 1701 } 1702 return commonAlignment(DL.getValueOrABITypeAlignment(Alignment, Ty), Offset); 1703 } 1704 1705 /// Test whether we can convert a value from the old to the new type. 1706 /// 1707 /// This predicate should be used to guard calls to convertValue in order to 1708 /// ensure that we only try to convert viable values. The strategy is that we 1709 /// will peel off single element struct and array wrappings to get to an 1710 /// underlying value, and convert that value. 1711 static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) { 1712 if (OldTy == NewTy) 1713 return true; 1714 1715 // For integer types, we can't handle any bit-width differences. This would 1716 // break both vector conversions with extension and introduce endianness 1717 // issues when in conjunction with loads and stores. 1718 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) { 1719 assert(cast<IntegerType>(OldTy)->getBitWidth() != 1720 cast<IntegerType>(NewTy)->getBitWidth() && 1721 "We can't have the same bitwidth for different int types"); 1722 return false; 1723 } 1724 1725 if (DL.getTypeSizeInBits(NewTy).getFixedSize() != 1726 DL.getTypeSizeInBits(OldTy).getFixedSize()) 1727 return false; 1728 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType()) 1729 return false; 1730 1731 // We can convert pointers to integers and vice-versa. Same for vectors 1732 // of pointers and integers. 1733 OldTy = OldTy->getScalarType(); 1734 NewTy = NewTy->getScalarType(); 1735 if (NewTy->isPointerTy() || OldTy->isPointerTy()) { 1736 if (NewTy->isPointerTy() && OldTy->isPointerTy()) { 1737 return cast<PointerType>(NewTy)->getPointerAddressSpace() == 1738 cast<PointerType>(OldTy)->getPointerAddressSpace(); 1739 } 1740 1741 // We can convert integers to integral pointers, but not to non-integral 1742 // pointers. 1743 if (OldTy->isIntegerTy()) 1744 return !DL.isNonIntegralPointerType(NewTy); 1745 1746 // We can convert integral pointers to integers, but non-integral pointers 1747 // need to remain pointers. 1748 if (!DL.isNonIntegralPointerType(OldTy)) 1749 return NewTy->isIntegerTy(); 1750 1751 return false; 1752 } 1753 1754 return true; 1755 } 1756 1757 /// Generic routine to convert an SSA value to a value of a different 1758 /// type. 1759 /// 1760 /// This will try various different casting techniques, such as bitcasts, 1761 /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test 1762 /// two types for viability with this routine. 1763 static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V, 1764 Type *NewTy) { 1765 Type *OldTy = V->getType(); 1766 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type"); 1767 1768 if (OldTy == NewTy) 1769 return V; 1770 1771 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) && 1772 "Integer types must be the exact same to convert."); 1773 1774 // See if we need inttoptr for this type pair. A cast involving both scalars 1775 // and vectors requires and additional bitcast. 1776 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) { 1777 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8* 1778 if (OldTy->isVectorTy() && !NewTy->isVectorTy()) 1779 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)), 1780 NewTy); 1781 1782 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*> 1783 if (!OldTy->isVectorTy() && NewTy->isVectorTy()) 1784 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)), 1785 NewTy); 1786 1787 return IRB.CreateIntToPtr(V, NewTy); 1788 } 1789 1790 // See if we need ptrtoint for this type pair. A cast involving both scalars 1791 // and vectors requires and additional bitcast. 1792 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) { 1793 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128 1794 if (OldTy->isVectorTy() && !NewTy->isVectorTy()) 1795 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)), 1796 NewTy); 1797 1798 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32> 1799 if (!OldTy->isVectorTy() && NewTy->isVectorTy()) 1800 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)), 1801 NewTy); 1802 1803 return IRB.CreatePtrToInt(V, NewTy); 1804 } 1805 1806 return IRB.CreateBitCast(V, NewTy); 1807 } 1808 1809 /// Test whether the given slice use can be promoted to a vector. 1810 /// 1811 /// This function is called to test each entry in a partition which is slated 1812 /// for a single slice. 1813 static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S, 1814 VectorType *Ty, 1815 uint64_t ElementSize, 1816 const DataLayout &DL) { 1817 // First validate the slice offsets. 1818 uint64_t BeginOffset = 1819 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset(); 1820 uint64_t BeginIndex = BeginOffset / ElementSize; 1821 if (BeginIndex * ElementSize != BeginOffset || 1822 BeginIndex >= Ty->getNumElements()) 1823 return false; 1824 uint64_t EndOffset = 1825 std::min(S.endOffset(), P.endOffset()) - P.beginOffset(); 1826 uint64_t EndIndex = EndOffset / ElementSize; 1827 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements()) 1828 return false; 1829 1830 assert(EndIndex > BeginIndex && "Empty vector!"); 1831 uint64_t NumElements = EndIndex - BeginIndex; 1832 Type *SliceTy = (NumElements == 1) 1833 ? Ty->getElementType() 1834 : VectorType::get(Ty->getElementType(), NumElements); 1835 1836 Type *SplitIntTy = 1837 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8); 1838 1839 Use *U = S.getUse(); 1840 1841 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) { 1842 if (MI->isVolatile()) 1843 return false; 1844 if (!S.isSplittable()) 1845 return false; // Skip any unsplittable intrinsics. 1846 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) { 1847 if (!II->isLifetimeStartOrEnd()) 1848 return false; 1849 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) { 1850 // Disable vector promotion when there are loads or stores of an FCA. 1851 return false; 1852 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 1853 if (LI->isVolatile()) 1854 return false; 1855 Type *LTy = LI->getType(); 1856 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) { 1857 assert(LTy->isIntegerTy()); 1858 LTy = SplitIntTy; 1859 } 1860 if (!canConvertValue(DL, SliceTy, LTy)) 1861 return false; 1862 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 1863 if (SI->isVolatile()) 1864 return false; 1865 Type *STy = SI->getValueOperand()->getType(); 1866 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) { 1867 assert(STy->isIntegerTy()); 1868 STy = SplitIntTy; 1869 } 1870 if (!canConvertValue(DL, STy, SliceTy)) 1871 return false; 1872 } else { 1873 return false; 1874 } 1875 1876 return true; 1877 } 1878 1879 /// Test whether the given alloca partitioning and range of slices can be 1880 /// promoted to a vector. 1881 /// 1882 /// This is a quick test to check whether we can rewrite a particular alloca 1883 /// partition (and its newly formed alloca) into a vector alloca with only 1884 /// whole-vector loads and stores such that it could be promoted to a vector 1885 /// SSA value. We only can ensure this for a limited set of operations, and we 1886 /// don't want to do the rewrites unless we are confident that the result will 1887 /// be promotable, so we have an early test here. 1888 static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) { 1889 // Collect the candidate types for vector-based promotion. Also track whether 1890 // we have different element types. 1891 SmallVector<VectorType *, 4> CandidateTys; 1892 Type *CommonEltTy = nullptr; 1893 bool HaveCommonEltTy = true; 1894 auto CheckCandidateType = [&](Type *Ty) { 1895 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 1896 // Return if bitcast to vectors is different for total size in bits. 1897 if (!CandidateTys.empty()) { 1898 VectorType *V = CandidateTys[0]; 1899 if (DL.getTypeSizeInBits(VTy).getFixedSize() != 1900 DL.getTypeSizeInBits(V).getFixedSize()) { 1901 CandidateTys.clear(); 1902 return; 1903 } 1904 } 1905 CandidateTys.push_back(VTy); 1906 if (!CommonEltTy) 1907 CommonEltTy = VTy->getElementType(); 1908 else if (CommonEltTy != VTy->getElementType()) 1909 HaveCommonEltTy = false; 1910 } 1911 }; 1912 // Consider any loads or stores that are the exact size of the slice. 1913 for (const Slice &S : P) 1914 if (S.beginOffset() == P.beginOffset() && 1915 S.endOffset() == P.endOffset()) { 1916 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser())) 1917 CheckCandidateType(LI->getType()); 1918 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) 1919 CheckCandidateType(SI->getValueOperand()->getType()); 1920 } 1921 1922 // If we didn't find a vector type, nothing to do here. 1923 if (CandidateTys.empty()) 1924 return nullptr; 1925 1926 // Remove non-integer vector types if we had multiple common element types. 1927 // FIXME: It'd be nice to replace them with integer vector types, but we can't 1928 // do that until all the backends are known to produce good code for all 1929 // integer vector types. 1930 if (!HaveCommonEltTy) { 1931 CandidateTys.erase( 1932 llvm::remove_if(CandidateTys, 1933 [](VectorType *VTy) { 1934 return !VTy->getElementType()->isIntegerTy(); 1935 }), 1936 CandidateTys.end()); 1937 1938 // If there were no integer vector types, give up. 1939 if (CandidateTys.empty()) 1940 return nullptr; 1941 1942 // Rank the remaining candidate vector types. This is easy because we know 1943 // they're all integer vectors. We sort by ascending number of elements. 1944 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) { 1945 (void)DL; 1946 assert(DL.getTypeSizeInBits(RHSTy).getFixedSize() == 1947 DL.getTypeSizeInBits(LHSTy).getFixedSize() && 1948 "Cannot have vector types of different sizes!"); 1949 assert(RHSTy->getElementType()->isIntegerTy() && 1950 "All non-integer types eliminated!"); 1951 assert(LHSTy->getElementType()->isIntegerTy() && 1952 "All non-integer types eliminated!"); 1953 return RHSTy->getNumElements() < LHSTy->getNumElements(); 1954 }; 1955 llvm::sort(CandidateTys, RankVectorTypes); 1956 CandidateTys.erase( 1957 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes), 1958 CandidateTys.end()); 1959 } else { 1960 // The only way to have the same element type in every vector type is to 1961 // have the same vector type. Check that and remove all but one. 1962 #ifndef NDEBUG 1963 for (VectorType *VTy : CandidateTys) { 1964 assert(VTy->getElementType() == CommonEltTy && 1965 "Unaccounted for element type!"); 1966 assert(VTy == CandidateTys[0] && 1967 "Different vector types with the same element type!"); 1968 } 1969 #endif 1970 CandidateTys.resize(1); 1971 } 1972 1973 // Try each vector type, and return the one which works. 1974 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) { 1975 uint64_t ElementSize = 1976 DL.getTypeSizeInBits(VTy->getElementType()).getFixedSize(); 1977 1978 // While the definition of LLVM vectors is bitpacked, we don't support sizes 1979 // that aren't byte sized. 1980 if (ElementSize % 8) 1981 return false; 1982 assert((DL.getTypeSizeInBits(VTy).getFixedSize() % 8) == 0 && 1983 "vector size not a multiple of element size?"); 1984 ElementSize /= 8; 1985 1986 for (const Slice &S : P) 1987 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL)) 1988 return false; 1989 1990 for (const Slice *S : P.splitSliceTails()) 1991 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL)) 1992 return false; 1993 1994 return true; 1995 }; 1996 for (VectorType *VTy : CandidateTys) 1997 if (CheckVectorTypeForPromotion(VTy)) 1998 return VTy; 1999 2000 return nullptr; 2001 } 2002 2003 /// Test whether a slice of an alloca is valid for integer widening. 2004 /// 2005 /// This implements the necessary checking for the \c isIntegerWideningViable 2006 /// test below on a single slice of the alloca. 2007 static bool isIntegerWideningViableForSlice(const Slice &S, 2008 uint64_t AllocBeginOffset, 2009 Type *AllocaTy, 2010 const DataLayout &DL, 2011 bool &WholeAllocaOp) { 2012 uint64_t Size = DL.getTypeStoreSize(AllocaTy).getFixedSize(); 2013 2014 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset; 2015 uint64_t RelEnd = S.endOffset() - AllocBeginOffset; 2016 2017 // We can't reasonably handle cases where the load or store extends past 2018 // the end of the alloca's type and into its padding. 2019 if (RelEnd > Size) 2020 return false; 2021 2022 Use *U = S.getUse(); 2023 2024 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) { 2025 if (LI->isVolatile()) 2026 return false; 2027 // We can't handle loads that extend past the allocated memory. 2028 if (DL.getTypeStoreSize(LI->getType()).getFixedSize() > Size) 2029 return false; 2030 // So far, AllocaSliceRewriter does not support widening split slice tails 2031 // in rewriteIntegerLoad. 2032 if (S.beginOffset() < AllocBeginOffset) 2033 return false; 2034 // Note that we don't count vector loads or stores as whole-alloca 2035 // operations which enable integer widening because we would prefer to use 2036 // vector widening instead. 2037 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size) 2038 WholeAllocaOp = true; 2039 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) { 2040 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize()) 2041 return false; 2042 } else if (RelBegin != 0 || RelEnd != Size || 2043 !canConvertValue(DL, AllocaTy, LI->getType())) { 2044 // Non-integer loads need to be convertible from the alloca type so that 2045 // they are promotable. 2046 return false; 2047 } 2048 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) { 2049 Type *ValueTy = SI->getValueOperand()->getType(); 2050 if (SI->isVolatile()) 2051 return false; 2052 // We can't handle stores that extend past the allocated memory. 2053 if (DL.getTypeStoreSize(ValueTy).getFixedSize() > Size) 2054 return false; 2055 // So far, AllocaSliceRewriter does not support widening split slice tails 2056 // in rewriteIntegerStore. 2057 if (S.beginOffset() < AllocBeginOffset) 2058 return false; 2059 // Note that we don't count vector loads or stores as whole-alloca 2060 // operations which enable integer widening because we would prefer to use 2061 // vector widening instead. 2062 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size) 2063 WholeAllocaOp = true; 2064 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) { 2065 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy).getFixedSize()) 2066 return false; 2067 } else if (RelBegin != 0 || RelEnd != Size || 2068 !canConvertValue(DL, ValueTy, AllocaTy)) { 2069 // Non-integer stores need to be convertible to the alloca type so that 2070 // they are promotable. 2071 return false; 2072 } 2073 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) { 2074 if (MI->isVolatile() || !isa<Constant>(MI->getLength())) 2075 return false; 2076 if (!S.isSplittable()) 2077 return false; // Skip any unsplittable intrinsics. 2078 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) { 2079 if (!II->isLifetimeStartOrEnd()) 2080 return false; 2081 } else { 2082 return false; 2083 } 2084 2085 return true; 2086 } 2087 2088 /// Test whether the given alloca partition's integer operations can be 2089 /// widened to promotable ones. 2090 /// 2091 /// This is a quick test to check whether we can rewrite the integer loads and 2092 /// stores to a particular alloca into wider loads and stores and be able to 2093 /// promote the resulting alloca. 2094 static bool isIntegerWideningViable(Partition &P, Type *AllocaTy, 2095 const DataLayout &DL) { 2096 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy).getFixedSize(); 2097 // Don't create integer types larger than the maximum bitwidth. 2098 if (SizeInBits > IntegerType::MAX_INT_BITS) 2099 return false; 2100 2101 // Don't try to handle allocas with bit-padding. 2102 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy).getFixedSize()) 2103 return false; 2104 2105 // We need to ensure that an integer type with the appropriate bitwidth can 2106 // be converted to the alloca type, whatever that is. We don't want to force 2107 // the alloca itself to have an integer type if there is a more suitable one. 2108 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits); 2109 if (!canConvertValue(DL, AllocaTy, IntTy) || 2110 !canConvertValue(DL, IntTy, AllocaTy)) 2111 return false; 2112 2113 // While examining uses, we ensure that the alloca has a covering load or 2114 // store. We don't want to widen the integer operations only to fail to 2115 // promote due to some other unsplittable entry (which we may make splittable 2116 // later). However, if there are only splittable uses, go ahead and assume 2117 // that we cover the alloca. 2118 // FIXME: We shouldn't consider split slices that happen to start in the 2119 // partition here... 2120 bool WholeAllocaOp = 2121 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits); 2122 2123 for (const Slice &S : P) 2124 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL, 2125 WholeAllocaOp)) 2126 return false; 2127 2128 for (const Slice *S : P.splitSliceTails()) 2129 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL, 2130 WholeAllocaOp)) 2131 return false; 2132 2133 return WholeAllocaOp; 2134 } 2135 2136 static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V, 2137 IntegerType *Ty, uint64_t Offset, 2138 const Twine &Name) { 2139 LLVM_DEBUG(dbgs() << " start: " << *V << "\n"); 2140 IntegerType *IntTy = cast<IntegerType>(V->getType()); 2141 assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= 2142 DL.getTypeStoreSize(IntTy).getFixedSize() && 2143 "Element extends past full value"); 2144 uint64_t ShAmt = 8 * Offset; 2145 if (DL.isBigEndian()) 2146 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() - 2147 DL.getTypeStoreSize(Ty).getFixedSize() - Offset); 2148 if (ShAmt) { 2149 V = IRB.CreateLShr(V, ShAmt, Name + ".shift"); 2150 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n"); 2151 } 2152 assert(Ty->getBitWidth() <= IntTy->getBitWidth() && 2153 "Cannot extract to a larger integer!"); 2154 if (Ty != IntTy) { 2155 V = IRB.CreateTrunc(V, Ty, Name + ".trunc"); 2156 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n"); 2157 } 2158 return V; 2159 } 2160 2161 static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old, 2162 Value *V, uint64_t Offset, const Twine &Name) { 2163 IntegerType *IntTy = cast<IntegerType>(Old->getType()); 2164 IntegerType *Ty = cast<IntegerType>(V->getType()); 2165 assert(Ty->getBitWidth() <= IntTy->getBitWidth() && 2166 "Cannot insert a larger integer!"); 2167 LLVM_DEBUG(dbgs() << " start: " << *V << "\n"); 2168 if (Ty != IntTy) { 2169 V = IRB.CreateZExt(V, IntTy, Name + ".ext"); 2170 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n"); 2171 } 2172 assert(DL.getTypeStoreSize(Ty).getFixedSize() + Offset <= 2173 DL.getTypeStoreSize(IntTy).getFixedSize() && 2174 "Element store outside of alloca store"); 2175 uint64_t ShAmt = 8 * Offset; 2176 if (DL.isBigEndian()) 2177 ShAmt = 8 * (DL.getTypeStoreSize(IntTy).getFixedSize() - 2178 DL.getTypeStoreSize(Ty).getFixedSize() - Offset); 2179 if (ShAmt) { 2180 V = IRB.CreateShl(V, ShAmt, Name + ".shift"); 2181 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n"); 2182 } 2183 2184 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) { 2185 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt); 2186 Old = IRB.CreateAnd(Old, Mask, Name + ".mask"); 2187 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n"); 2188 V = IRB.CreateOr(Old, V, Name + ".insert"); 2189 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n"); 2190 } 2191 return V; 2192 } 2193 2194 static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex, 2195 unsigned EndIndex, const Twine &Name) { 2196 VectorType *VecTy = cast<VectorType>(V->getType()); 2197 unsigned NumElements = EndIndex - BeginIndex; 2198 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2199 2200 if (NumElements == VecTy->getNumElements()) 2201 return V; 2202 2203 if (NumElements == 1) { 2204 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex), 2205 Name + ".extract"); 2206 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n"); 2207 return V; 2208 } 2209 2210 SmallVector<Constant *, 8> Mask; 2211 Mask.reserve(NumElements); 2212 for (unsigned i = BeginIndex; i != EndIndex; ++i) 2213 Mask.push_back(IRB.getInt32(i)); 2214 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), 2215 ConstantVector::get(Mask), Name + ".extract"); 2216 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n"); 2217 return V; 2218 } 2219 2220 static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V, 2221 unsigned BeginIndex, const Twine &Name) { 2222 VectorType *VecTy = cast<VectorType>(Old->getType()); 2223 assert(VecTy && "Can only insert a vector into a vector"); 2224 2225 VectorType *Ty = dyn_cast<VectorType>(V->getType()); 2226 if (!Ty) { 2227 // Single element to insert. 2228 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex), 2229 Name + ".insert"); 2230 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n"); 2231 return V; 2232 } 2233 2234 assert(Ty->getNumElements() <= VecTy->getNumElements() && 2235 "Too many elements!"); 2236 if (Ty->getNumElements() == VecTy->getNumElements()) { 2237 assert(V->getType() == VecTy && "Vector type mismatch"); 2238 return V; 2239 } 2240 unsigned EndIndex = BeginIndex + Ty->getNumElements(); 2241 2242 // When inserting a smaller vector into the larger to store, we first 2243 // use a shuffle vector to widen it with undef elements, and then 2244 // a second shuffle vector to select between the loaded vector and the 2245 // incoming vector. 2246 SmallVector<Constant *, 8> Mask; 2247 Mask.reserve(VecTy->getNumElements()); 2248 for (unsigned i = 0; i != VecTy->getNumElements(); ++i) 2249 if (i >= BeginIndex && i < EndIndex) 2250 Mask.push_back(IRB.getInt32(i - BeginIndex)); 2251 else 2252 Mask.push_back(UndefValue::get(IRB.getInt32Ty())); 2253 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()), 2254 ConstantVector::get(Mask), Name + ".expand"); 2255 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n"); 2256 2257 Mask.clear(); 2258 for (unsigned i = 0; i != VecTy->getNumElements(); ++i) 2259 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex)); 2260 2261 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend"); 2262 2263 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n"); 2264 return V; 2265 } 2266 2267 /// Visitor to rewrite instructions using p particular slice of an alloca 2268 /// to use a new alloca. 2269 /// 2270 /// Also implements the rewriting to vector-based accesses when the partition 2271 /// passes the isVectorPromotionViable predicate. Most of the rewriting logic 2272 /// lives here. 2273 class llvm::sroa::AllocaSliceRewriter 2274 : public InstVisitor<AllocaSliceRewriter, bool> { 2275 // Befriend the base class so it can delegate to private visit methods. 2276 friend class InstVisitor<AllocaSliceRewriter, bool>; 2277 2278 using Base = InstVisitor<AllocaSliceRewriter, bool>; 2279 2280 const DataLayout &DL; 2281 AllocaSlices &AS; 2282 SROA &Pass; 2283 AllocaInst &OldAI, &NewAI; 2284 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset; 2285 Type *NewAllocaTy; 2286 2287 // This is a convenience and flag variable that will be null unless the new 2288 // alloca's integer operations should be widened to this integer type due to 2289 // passing isIntegerWideningViable above. If it is non-null, the desired 2290 // integer type will be stored here for easy access during rewriting. 2291 IntegerType *IntTy; 2292 2293 // If we are rewriting an alloca partition which can be written as pure 2294 // vector operations, we stash extra information here. When VecTy is 2295 // non-null, we have some strict guarantees about the rewritten alloca: 2296 // - The new alloca is exactly the size of the vector type here. 2297 // - The accesses all either map to the entire vector or to a single 2298 // element. 2299 // - The set of accessing instructions is only one of those handled above 2300 // in isVectorPromotionViable. Generally these are the same access kinds 2301 // which are promotable via mem2reg. 2302 VectorType *VecTy; 2303 Type *ElementTy; 2304 uint64_t ElementSize; 2305 2306 // The original offset of the slice currently being rewritten relative to 2307 // the original alloca. 2308 uint64_t BeginOffset = 0; 2309 uint64_t EndOffset = 0; 2310 2311 // The new offsets of the slice currently being rewritten relative to the 2312 // original alloca. 2313 uint64_t NewBeginOffset = 0, NewEndOffset = 0; 2314 2315 uint64_t SliceSize = 0; 2316 bool IsSplittable = false; 2317 bool IsSplit = false; 2318 Use *OldUse = nullptr; 2319 Instruction *OldPtr = nullptr; 2320 2321 // Track post-rewrite users which are PHI nodes and Selects. 2322 SmallSetVector<PHINode *, 8> &PHIUsers; 2323 SmallSetVector<SelectInst *, 8> &SelectUsers; 2324 2325 // Utility IR builder, whose name prefix is setup for each visited use, and 2326 // the insertion point is set to point to the user. 2327 IRBuilderTy IRB; 2328 2329 public: 2330 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass, 2331 AllocaInst &OldAI, AllocaInst &NewAI, 2332 uint64_t NewAllocaBeginOffset, 2333 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable, 2334 VectorType *PromotableVecTy, 2335 SmallSetVector<PHINode *, 8> &PHIUsers, 2336 SmallSetVector<SelectInst *, 8> &SelectUsers) 2337 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI), 2338 NewAllocaBeginOffset(NewAllocaBeginOffset), 2339 NewAllocaEndOffset(NewAllocaEndOffset), 2340 NewAllocaTy(NewAI.getAllocatedType()), 2341 IntTy( 2342 IsIntegerPromotable 2343 ? Type::getIntNTy(NewAI.getContext(), 2344 DL.getTypeSizeInBits(NewAI.getAllocatedType()) 2345 .getFixedSize()) 2346 : nullptr), 2347 VecTy(PromotableVecTy), 2348 ElementTy(VecTy ? VecTy->getElementType() : nullptr), 2349 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8 2350 : 0), 2351 PHIUsers(PHIUsers), SelectUsers(SelectUsers), 2352 IRB(NewAI.getContext(), ConstantFolder()) { 2353 if (VecTy) { 2354 assert((DL.getTypeSizeInBits(ElementTy).getFixedSize() % 8) == 0 && 2355 "Only multiple-of-8 sized vector elements are viable"); 2356 ++NumVectorized; 2357 } 2358 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy)); 2359 } 2360 2361 bool visit(AllocaSlices::const_iterator I) { 2362 bool CanSROA = true; 2363 BeginOffset = I->beginOffset(); 2364 EndOffset = I->endOffset(); 2365 IsSplittable = I->isSplittable(); 2366 IsSplit = 2367 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset; 2368 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : "")); 2369 LLVM_DEBUG(AS.printSlice(dbgs(), I, "")); 2370 LLVM_DEBUG(dbgs() << "\n"); 2371 2372 // Compute the intersecting offset range. 2373 assert(BeginOffset < NewAllocaEndOffset); 2374 assert(EndOffset > NewAllocaBeginOffset); 2375 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset); 2376 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset); 2377 2378 SliceSize = NewEndOffset - NewBeginOffset; 2379 2380 OldUse = I->getUse(); 2381 OldPtr = cast<Instruction>(OldUse->get()); 2382 2383 Instruction *OldUserI = cast<Instruction>(OldUse->getUser()); 2384 IRB.SetInsertPoint(OldUserI); 2385 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc()); 2386 IRB.getInserter().SetNamePrefix( 2387 Twine(NewAI.getName()) + "." + Twine(BeginOffset) + "."); 2388 2389 CanSROA &= visit(cast<Instruction>(OldUse->getUser())); 2390 if (VecTy || IntTy) 2391 assert(CanSROA); 2392 return CanSROA; 2393 } 2394 2395 private: 2396 // Make sure the other visit overloads are visible. 2397 using Base::visit; 2398 2399 // Every instruction which can end up as a user must have a rewrite rule. 2400 bool visitInstruction(Instruction &I) { 2401 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n"); 2402 llvm_unreachable("No rewrite rule for this instruction!"); 2403 } 2404 2405 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) { 2406 // Note that the offset computation can use BeginOffset or NewBeginOffset 2407 // interchangeably for unsplit slices. 2408 assert(IsSplit || BeginOffset == NewBeginOffset); 2409 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2410 2411 #ifndef NDEBUG 2412 StringRef OldName = OldPtr->getName(); 2413 // Skip through the last '.sroa.' component of the name. 2414 size_t LastSROAPrefix = OldName.rfind(".sroa."); 2415 if (LastSROAPrefix != StringRef::npos) { 2416 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa.")); 2417 // Look for an SROA slice index. 2418 size_t IndexEnd = OldName.find_first_not_of("0123456789"); 2419 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') { 2420 // Strip the index and look for the offset. 2421 OldName = OldName.substr(IndexEnd + 1); 2422 size_t OffsetEnd = OldName.find_first_not_of("0123456789"); 2423 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.') 2424 // Strip the offset. 2425 OldName = OldName.substr(OffsetEnd + 1); 2426 } 2427 } 2428 // Strip any SROA suffixes as well. 2429 OldName = OldName.substr(0, OldName.find(".sroa_")); 2430 #endif 2431 2432 return getAdjustedPtr(IRB, DL, &NewAI, 2433 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset), 2434 PointerTy, 2435 #ifndef NDEBUG 2436 Twine(OldName) + "." 2437 #else 2438 Twine() 2439 #endif 2440 ); 2441 } 2442 2443 /// Compute suitable alignment to access this slice of the *new* 2444 /// alloca. 2445 /// 2446 /// You can optionally pass a type to this routine and if that type's ABI 2447 /// alignment is itself suitable, this will return zero. 2448 MaybeAlign getSliceAlign(Type *Ty = nullptr) { 2449 const MaybeAlign NewAIAlign = DL.getValueOrABITypeAlignment( 2450 MaybeAlign(NewAI.getAlignment()), NewAI.getAllocatedType()); 2451 const MaybeAlign Align = 2452 commonAlignment(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset); 2453 return (Ty && Align && Align->value() == DL.getABITypeAlignment(Ty)) 2454 ? None 2455 : Align; 2456 } 2457 2458 unsigned getIndex(uint64_t Offset) { 2459 assert(VecTy && "Can only call getIndex when rewriting a vector"); 2460 uint64_t RelOffset = Offset - NewAllocaBeginOffset; 2461 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds"); 2462 uint32_t Index = RelOffset / ElementSize; 2463 assert(Index * ElementSize == RelOffset); 2464 return Index; 2465 } 2466 2467 void deleteIfTriviallyDead(Value *V) { 2468 Instruction *I = cast<Instruction>(V); 2469 if (isInstructionTriviallyDead(I)) 2470 Pass.DeadInsts.insert(I); 2471 } 2472 2473 Value *rewriteVectorizedLoadInst() { 2474 unsigned BeginIndex = getIndex(NewBeginOffset); 2475 unsigned EndIndex = getIndex(NewEndOffset); 2476 assert(EndIndex > BeginIndex && "Empty vector!"); 2477 2478 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2479 NewAI.getAlign(), "load"); 2480 return extractVector(IRB, V, BeginIndex, EndIndex, "vec"); 2481 } 2482 2483 Value *rewriteIntegerLoad(LoadInst &LI) { 2484 assert(IntTy && "We cannot insert an integer to the alloca"); 2485 assert(!LI.isVolatile()); 2486 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2487 NewAI.getAlign(), "load"); 2488 V = convertValue(DL, IRB, V, IntTy); 2489 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); 2490 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2491 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) { 2492 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8); 2493 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract"); 2494 } 2495 // It is possible that the extracted type is not the load type. This 2496 // happens if there is a load past the end of the alloca, and as 2497 // a consequence the slice is narrower but still a candidate for integer 2498 // lowering. To handle this case, we just zero extend the extracted 2499 // integer. 2500 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 && 2501 "Can only handle an extract for an overly wide load"); 2502 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8) 2503 V = IRB.CreateZExt(V, LI.getType()); 2504 return V; 2505 } 2506 2507 bool visitLoadInst(LoadInst &LI) { 2508 LLVM_DEBUG(dbgs() << " original: " << LI << "\n"); 2509 Value *OldOp = LI.getOperand(0); 2510 assert(OldOp == OldPtr); 2511 2512 AAMDNodes AATags; 2513 LI.getAAMetadata(AATags); 2514 2515 unsigned AS = LI.getPointerAddressSpace(); 2516 2517 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8) 2518 : LI.getType(); 2519 const bool IsLoadPastEnd = 2520 DL.getTypeStoreSize(TargetTy).getFixedSize() > SliceSize; 2521 bool IsPtrAdjusted = false; 2522 Value *V; 2523 if (VecTy) { 2524 V = rewriteVectorizedLoadInst(); 2525 } else if (IntTy && LI.getType()->isIntegerTy()) { 2526 V = rewriteIntegerLoad(LI); 2527 } else if (NewBeginOffset == NewAllocaBeginOffset && 2528 NewEndOffset == NewAllocaEndOffset && 2529 (canConvertValue(DL, NewAllocaTy, TargetTy) || 2530 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() && 2531 TargetTy->isIntegerTy()))) { 2532 LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2533 NewAI.getAlign(), LI.isVolatile(), 2534 LI.getName()); 2535 if (AATags) 2536 NewLI->setAAMetadata(AATags); 2537 if (LI.isVolatile()) 2538 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 2539 if (NewLI->isAtomic()) 2540 NewLI->setAlignment(LI.getAlign()); 2541 2542 // Any !nonnull metadata or !range metadata on the old load is also valid 2543 // on the new load. This is even true in some cases even when the loads 2544 // are different types, for example by mapping !nonnull metadata to 2545 // !range metadata by modeling the null pointer constant converted to the 2546 // integer type. 2547 // FIXME: Add support for range metadata here. Currently the utilities 2548 // for this don't propagate range metadata in trivial cases from one 2549 // integer load to another, don't handle non-addrspace-0 null pointers 2550 // correctly, and don't have any support for mapping ranges as the 2551 // integer type becomes winder or narrower. 2552 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull)) 2553 copyNonnullMetadata(LI, N, *NewLI); 2554 2555 // Try to preserve nonnull metadata 2556 V = NewLI; 2557 2558 // If this is an integer load past the end of the slice (which means the 2559 // bytes outside the slice are undef or this load is dead) just forcibly 2560 // fix the integer size with correct handling of endianness. 2561 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy)) 2562 if (auto *TITy = dyn_cast<IntegerType>(TargetTy)) 2563 if (AITy->getBitWidth() < TITy->getBitWidth()) { 2564 V = IRB.CreateZExt(V, TITy, "load.ext"); 2565 if (DL.isBigEndian()) 2566 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(), 2567 "endian_shift"); 2568 } 2569 } else { 2570 Type *LTy = TargetTy->getPointerTo(AS); 2571 LoadInst *NewLI = IRB.CreateAlignedLoad( 2572 TargetTy, getNewAllocaSlicePtr(IRB, LTy), getSliceAlign(TargetTy), 2573 LI.isVolatile(), LI.getName()); 2574 if (AATags) 2575 NewLI->setAAMetadata(AATags); 2576 if (LI.isVolatile()) 2577 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 2578 2579 V = NewLI; 2580 IsPtrAdjusted = true; 2581 } 2582 V = convertValue(DL, IRB, V, TargetTy); 2583 2584 if (IsSplit) { 2585 assert(!LI.isVolatile()); 2586 assert(LI.getType()->isIntegerTy() && 2587 "Only integer type loads and stores are split"); 2588 assert(SliceSize < DL.getTypeStoreSize(LI.getType()).getFixedSize() && 2589 "Split load isn't smaller than original load"); 2590 assert(DL.typeSizeEqualsStoreSize(LI.getType()) && 2591 "Non-byte-multiple bit width"); 2592 // Move the insertion point just past the load so that we can refer to it. 2593 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI))); 2594 // Create a placeholder value with the same type as LI to use as the 2595 // basis for the new value. This allows us to replace the uses of LI with 2596 // the computed value, and then replace the placeholder with LI, leaving 2597 // LI only used for this computation. 2598 Value *Placeholder = new LoadInst( 2599 LI.getType(), UndefValue::get(LI.getType()->getPointerTo(AS))); 2600 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset, 2601 "insert"); 2602 LI.replaceAllUsesWith(V); 2603 Placeholder->replaceAllUsesWith(&LI); 2604 Placeholder->deleteValue(); 2605 } else { 2606 LI.replaceAllUsesWith(V); 2607 } 2608 2609 Pass.DeadInsts.insert(&LI); 2610 deleteIfTriviallyDead(OldOp); 2611 LLVM_DEBUG(dbgs() << " to: " << *V << "\n"); 2612 return !LI.isVolatile() && !IsPtrAdjusted; 2613 } 2614 2615 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp, 2616 AAMDNodes AATags) { 2617 if (V->getType() != VecTy) { 2618 unsigned BeginIndex = getIndex(NewBeginOffset); 2619 unsigned EndIndex = getIndex(NewEndOffset); 2620 assert(EndIndex > BeginIndex && "Empty vector!"); 2621 unsigned NumElements = EndIndex - BeginIndex; 2622 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2623 Type *SliceTy = (NumElements == 1) 2624 ? ElementTy 2625 : VectorType::get(ElementTy, NumElements); 2626 if (V->getType() != SliceTy) 2627 V = convertValue(DL, IRB, V, SliceTy); 2628 2629 // Mix in the existing elements. 2630 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2631 NewAI.getAlign(), "load"); 2632 V = insertVector(IRB, Old, V, BeginIndex, "vec"); 2633 } 2634 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign()); 2635 if (AATags) 2636 Store->setAAMetadata(AATags); 2637 Pass.DeadInsts.insert(&SI); 2638 2639 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 2640 return true; 2641 } 2642 2643 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) { 2644 assert(IntTy && "We cannot extract an integer from the alloca"); 2645 assert(!SI.isVolatile()); 2646 if (DL.getTypeSizeInBits(V->getType()).getFixedSize() != 2647 IntTy->getBitWidth()) { 2648 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2649 NewAI.getAlign(), "oldload"); 2650 Old = convertValue(DL, IRB, Old, IntTy); 2651 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset"); 2652 uint64_t Offset = BeginOffset - NewAllocaBeginOffset; 2653 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert"); 2654 } 2655 V = convertValue(DL, IRB, V, NewAllocaTy); 2656 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign()); 2657 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access, 2658 LLVMContext::MD_access_group}); 2659 if (AATags) 2660 Store->setAAMetadata(AATags); 2661 Pass.DeadInsts.insert(&SI); 2662 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 2663 return true; 2664 } 2665 2666 bool visitStoreInst(StoreInst &SI) { 2667 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 2668 Value *OldOp = SI.getOperand(1); 2669 assert(OldOp == OldPtr); 2670 2671 AAMDNodes AATags; 2672 SI.getAAMetadata(AATags); 2673 2674 Value *V = SI.getValueOperand(); 2675 2676 // Strip all inbounds GEPs and pointer casts to try to dig out any root 2677 // alloca that should be re-examined after promoting this alloca. 2678 if (V->getType()->isPointerTy()) 2679 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets())) 2680 Pass.PostPromotionWorklist.insert(AI); 2681 2682 if (SliceSize < DL.getTypeStoreSize(V->getType()).getFixedSize()) { 2683 assert(!SI.isVolatile()); 2684 assert(V->getType()->isIntegerTy() && 2685 "Only integer type loads and stores are split"); 2686 assert(DL.typeSizeEqualsStoreSize(V->getType()) && 2687 "Non-byte-multiple bit width"); 2688 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8); 2689 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset, 2690 "extract"); 2691 } 2692 2693 if (VecTy) 2694 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags); 2695 if (IntTy && V->getType()->isIntegerTy()) 2696 return rewriteIntegerStore(V, SI, AATags); 2697 2698 const bool IsStorePastEnd = 2699 DL.getTypeStoreSize(V->getType()).getFixedSize() > SliceSize; 2700 StoreInst *NewSI; 2701 if (NewBeginOffset == NewAllocaBeginOffset && 2702 NewEndOffset == NewAllocaEndOffset && 2703 (canConvertValue(DL, V->getType(), NewAllocaTy) || 2704 (IsStorePastEnd && NewAllocaTy->isIntegerTy() && 2705 V->getType()->isIntegerTy()))) { 2706 // If this is an integer store past the end of slice (and thus the bytes 2707 // past that point are irrelevant or this is unreachable), truncate the 2708 // value prior to storing. 2709 if (auto *VITy = dyn_cast<IntegerType>(V->getType())) 2710 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy)) 2711 if (VITy->getBitWidth() > AITy->getBitWidth()) { 2712 if (DL.isBigEndian()) 2713 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(), 2714 "endian_shift"); 2715 V = IRB.CreateTrunc(V, AITy, "load.trunc"); 2716 } 2717 2718 V = convertValue(DL, IRB, V, NewAllocaTy); 2719 NewSI = 2720 IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), SI.isVolatile()); 2721 } else { 2722 unsigned AS = SI.getPointerAddressSpace(); 2723 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS)); 2724 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()), 2725 SI.isVolatile()); 2726 } 2727 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access, 2728 LLVMContext::MD_access_group}); 2729 if (AATags) 2730 NewSI->setAAMetadata(AATags); 2731 if (SI.isVolatile()) 2732 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID()); 2733 if (NewSI->isAtomic()) 2734 NewSI->setAlignment(SI.getAlign()); 2735 Pass.DeadInsts.insert(&SI); 2736 deleteIfTriviallyDead(OldOp); 2737 2738 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n"); 2739 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile(); 2740 } 2741 2742 /// Compute an integer value from splatting an i8 across the given 2743 /// number of bytes. 2744 /// 2745 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't 2746 /// call this routine. 2747 /// FIXME: Heed the advice above. 2748 /// 2749 /// \param V The i8 value to splat. 2750 /// \param Size The number of bytes in the output (assuming i8 is one byte) 2751 Value *getIntegerSplat(Value *V, unsigned Size) { 2752 assert(Size > 0 && "Expected a positive number of bytes."); 2753 IntegerType *VTy = cast<IntegerType>(V->getType()); 2754 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte"); 2755 if (Size == 1) 2756 return V; 2757 2758 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8); 2759 V = IRB.CreateMul( 2760 IRB.CreateZExt(V, SplatIntTy, "zext"), 2761 ConstantExpr::getUDiv( 2762 Constant::getAllOnesValue(SplatIntTy), 2763 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()), 2764 SplatIntTy)), 2765 "isplat"); 2766 return V; 2767 } 2768 2769 /// Compute a vector splat for a given element value. 2770 Value *getVectorSplat(Value *V, unsigned NumElements) { 2771 V = IRB.CreateVectorSplat(NumElements, V, "vsplat"); 2772 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n"); 2773 return V; 2774 } 2775 2776 bool visitMemSetInst(MemSetInst &II) { 2777 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 2778 assert(II.getRawDest() == OldPtr); 2779 2780 AAMDNodes AATags; 2781 II.getAAMetadata(AATags); 2782 2783 // If the memset has a variable size, it cannot be split, just adjust the 2784 // pointer to the new alloca. 2785 if (!isa<Constant>(II.getLength())) { 2786 assert(!IsSplit); 2787 assert(NewBeginOffset == BeginOffset); 2788 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType())); 2789 II.setDestAlignment(getSliceAlign()); 2790 2791 deleteIfTriviallyDead(OldPtr); 2792 return false; 2793 } 2794 2795 // Record this instruction for deletion. 2796 Pass.DeadInsts.insert(&II); 2797 2798 Type *AllocaTy = NewAI.getAllocatedType(); 2799 Type *ScalarTy = AllocaTy->getScalarType(); 2800 2801 const bool CanContinue = [&]() { 2802 if (VecTy || IntTy) 2803 return true; 2804 if (BeginOffset > NewAllocaBeginOffset || 2805 EndOffset < NewAllocaEndOffset) 2806 return false; 2807 auto *C = cast<ConstantInt>(II.getLength()); 2808 if (C->getBitWidth() > 64) 2809 return false; 2810 const auto Len = C->getZExtValue(); 2811 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext()); 2812 auto *SrcTy = VectorType::get(Int8Ty, Len); 2813 return canConvertValue(DL, SrcTy, AllocaTy) && 2814 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy).getFixedSize()); 2815 }(); 2816 2817 // If this doesn't map cleanly onto the alloca type, and that type isn't 2818 // a single value type, just emit a memset. 2819 if (!CanContinue) { 2820 Type *SizeTy = II.getLength()->getType(); 2821 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset); 2822 CallInst *New = IRB.CreateMemSet( 2823 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size, 2824 MaybeAlign(getSliceAlign()), II.isVolatile()); 2825 if (AATags) 2826 New->setAAMetadata(AATags); 2827 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 2828 return false; 2829 } 2830 2831 // If we can represent this as a simple value, we have to build the actual 2832 // value to store, which requires expanding the byte present in memset to 2833 // a sensible representation for the alloca type. This is essentially 2834 // splatting the byte to a sufficiently wide integer, splatting it across 2835 // any desired vector width, and bitcasting to the final type. 2836 Value *V; 2837 2838 if (VecTy) { 2839 // If this is a memset of a vectorized alloca, insert it. 2840 assert(ElementTy == ScalarTy); 2841 2842 unsigned BeginIndex = getIndex(NewBeginOffset); 2843 unsigned EndIndex = getIndex(NewEndOffset); 2844 assert(EndIndex > BeginIndex && "Empty vector!"); 2845 unsigned NumElements = EndIndex - BeginIndex; 2846 assert(NumElements <= VecTy->getNumElements() && "Too many elements!"); 2847 2848 Value *Splat = getIntegerSplat( 2849 II.getValue(), DL.getTypeSizeInBits(ElementTy).getFixedSize() / 8); 2850 Splat = convertValue(DL, IRB, Splat, ElementTy); 2851 if (NumElements > 1) 2852 Splat = getVectorSplat(Splat, NumElements); 2853 2854 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2855 NewAI.getAlign(), "oldload"); 2856 V = insertVector(IRB, Old, Splat, BeginIndex, "vec"); 2857 } else if (IntTy) { 2858 // If this is a memset on an alloca where we can widen stores, insert the 2859 // set integer. 2860 assert(!II.isVolatile()); 2861 2862 uint64_t Size = NewEndOffset - NewBeginOffset; 2863 V = getIntegerSplat(II.getValue(), Size); 2864 2865 if (IntTy && (BeginOffset != NewAllocaBeginOffset || 2866 EndOffset != NewAllocaBeginOffset)) { 2867 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 2868 NewAI.getAlign(), "oldload"); 2869 Old = convertValue(DL, IRB, Old, IntTy); 2870 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 2871 V = insertInteger(DL, IRB, Old, V, Offset, "insert"); 2872 } else { 2873 assert(V->getType() == IntTy && 2874 "Wrong type for an alloca wide integer!"); 2875 } 2876 V = convertValue(DL, IRB, V, AllocaTy); 2877 } else { 2878 // Established these invariants above. 2879 assert(NewBeginOffset == NewAllocaBeginOffset); 2880 assert(NewEndOffset == NewAllocaEndOffset); 2881 2882 V = getIntegerSplat(II.getValue(), 2883 DL.getTypeSizeInBits(ScalarTy).getFixedSize() / 8); 2884 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy)) 2885 V = getVectorSplat(V, AllocaVecTy->getNumElements()); 2886 2887 V = convertValue(DL, IRB, V, AllocaTy); 2888 } 2889 2890 StoreInst *New = 2891 IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlign(), II.isVolatile()); 2892 if (AATags) 2893 New->setAAMetadata(AATags); 2894 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 2895 return !II.isVolatile(); 2896 } 2897 2898 bool visitMemTransferInst(MemTransferInst &II) { 2899 // Rewriting of memory transfer instructions can be a bit tricky. We break 2900 // them into two categories: split intrinsics and unsplit intrinsics. 2901 2902 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 2903 2904 AAMDNodes AATags; 2905 II.getAAMetadata(AATags); 2906 2907 bool IsDest = &II.getRawDestUse() == OldUse; 2908 assert((IsDest && II.getRawDest() == OldPtr) || 2909 (!IsDest && II.getRawSource() == OldPtr)); 2910 2911 MaybeAlign SliceAlign = getSliceAlign(); 2912 2913 // For unsplit intrinsics, we simply modify the source and destination 2914 // pointers in place. This isn't just an optimization, it is a matter of 2915 // correctness. With unsplit intrinsics we may be dealing with transfers 2916 // within a single alloca before SROA ran, or with transfers that have 2917 // a variable length. We may also be dealing with memmove instead of 2918 // memcpy, and so simply updating the pointers is the necessary for us to 2919 // update both source and dest of a single call. 2920 if (!IsSplittable) { 2921 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2922 if (IsDest) { 2923 II.setDest(AdjustedPtr); 2924 II.setDestAlignment(SliceAlign); 2925 } 2926 else { 2927 II.setSource(AdjustedPtr); 2928 II.setSourceAlignment(SliceAlign); 2929 } 2930 2931 LLVM_DEBUG(dbgs() << " to: " << II << "\n"); 2932 deleteIfTriviallyDead(OldPtr); 2933 return false; 2934 } 2935 // For split transfer intrinsics we have an incredibly useful assurance: 2936 // the source and destination do not reside within the same alloca, and at 2937 // least one of them does not escape. This means that we can replace 2938 // memmove with memcpy, and we don't need to worry about all manner of 2939 // downsides to splitting and transforming the operations. 2940 2941 // If this doesn't map cleanly onto the alloca type, and that type isn't 2942 // a single value type, just emit a memcpy. 2943 bool EmitMemCpy = 2944 !VecTy && !IntTy && 2945 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset || 2946 SliceSize != 2947 DL.getTypeStoreSize(NewAI.getAllocatedType()).getFixedSize() || 2948 !NewAI.getAllocatedType()->isSingleValueType()); 2949 2950 // If we're just going to emit a memcpy, the alloca hasn't changed, and the 2951 // size hasn't been shrunk based on analysis of the viable range, this is 2952 // a no-op. 2953 if (EmitMemCpy && &OldAI == &NewAI) { 2954 // Ensure the start lines up. 2955 assert(NewBeginOffset == BeginOffset); 2956 2957 // Rewrite the size as needed. 2958 if (NewEndOffset != EndOffset) 2959 II.setLength(ConstantInt::get(II.getLength()->getType(), 2960 NewEndOffset - NewBeginOffset)); 2961 return false; 2962 } 2963 // Record this instruction for deletion. 2964 Pass.DeadInsts.insert(&II); 2965 2966 // Strip all inbounds GEPs and pointer casts to try to dig out any root 2967 // alloca that should be re-examined after rewriting this instruction. 2968 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest(); 2969 if (AllocaInst *AI = 2970 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) { 2971 assert(AI != &OldAI && AI != &NewAI && 2972 "Splittable transfers cannot reach the same alloca on both ends."); 2973 Pass.Worklist.insert(AI); 2974 } 2975 2976 Type *OtherPtrTy = OtherPtr->getType(); 2977 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace(); 2978 2979 // Compute the relative offset for the other pointer within the transfer. 2980 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS); 2981 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset); 2982 Align OtherAlign = 2983 assumeAligned(IsDest ? II.getSourceAlignment() : II.getDestAlignment()); 2984 OtherAlign = 2985 commonAlignment(OtherAlign, OtherOffset.zextOrTrunc(64).getZExtValue()); 2986 2987 if (EmitMemCpy) { 2988 // Compute the other pointer, folding as much as possible to produce 2989 // a single, simple GEP in most cases. 2990 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy, 2991 OtherPtr->getName() + "."); 2992 2993 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 2994 Type *SizeTy = II.getLength()->getType(); 2995 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset); 2996 2997 Value *DestPtr, *SrcPtr; 2998 MaybeAlign DestAlign, SrcAlign; 2999 // Note: IsDest is true iff we're copying into the new alloca slice 3000 if (IsDest) { 3001 DestPtr = OurPtr; 3002 DestAlign = SliceAlign; 3003 SrcPtr = OtherPtr; 3004 SrcAlign = OtherAlign; 3005 } else { 3006 DestPtr = OtherPtr; 3007 DestAlign = OtherAlign; 3008 SrcPtr = OurPtr; 3009 SrcAlign = SliceAlign; 3010 } 3011 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign, 3012 Size, II.isVolatile()); 3013 if (AATags) 3014 New->setAAMetadata(AATags); 3015 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 3016 return false; 3017 } 3018 3019 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset && 3020 NewEndOffset == NewAllocaEndOffset; 3021 uint64_t Size = NewEndOffset - NewBeginOffset; 3022 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0; 3023 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0; 3024 unsigned NumElements = EndIndex - BeginIndex; 3025 IntegerType *SubIntTy = 3026 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr; 3027 3028 // Reset the other pointer type to match the register type we're going to 3029 // use, but using the address space of the original other pointer. 3030 Type *OtherTy; 3031 if (VecTy && !IsWholeAlloca) { 3032 if (NumElements == 1) 3033 OtherTy = VecTy->getElementType(); 3034 else 3035 OtherTy = VectorType::get(VecTy->getElementType(), NumElements); 3036 } else if (IntTy && !IsWholeAlloca) { 3037 OtherTy = SubIntTy; 3038 } else { 3039 OtherTy = NewAllocaTy; 3040 } 3041 OtherPtrTy = OtherTy->getPointerTo(OtherAS); 3042 3043 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy, 3044 OtherPtr->getName() + "."); 3045 MaybeAlign SrcAlign = OtherAlign; 3046 Value *DstPtr = &NewAI; 3047 MaybeAlign DstAlign = SliceAlign; 3048 if (!IsDest) { 3049 std::swap(SrcPtr, DstPtr); 3050 std::swap(SrcAlign, DstAlign); 3051 } 3052 3053 Value *Src; 3054 if (VecTy && !IsWholeAlloca && !IsDest) { 3055 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 3056 NewAI.getAlign(), "load"); 3057 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec"); 3058 } else if (IntTy && !IsWholeAlloca && !IsDest) { 3059 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 3060 NewAI.getAlign(), "load"); 3061 Src = convertValue(DL, IRB, Src, IntTy); 3062 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 3063 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract"); 3064 } else { 3065 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign, 3066 II.isVolatile(), "copyload"); 3067 if (AATags) 3068 Load->setAAMetadata(AATags); 3069 Src = Load; 3070 } 3071 3072 if (VecTy && !IsWholeAlloca && IsDest) { 3073 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 3074 NewAI.getAlign(), "oldload"); 3075 Src = insertVector(IRB, Old, Src, BeginIndex, "vec"); 3076 } else if (IntTy && !IsWholeAlloca && IsDest) { 3077 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI, 3078 NewAI.getAlign(), "oldload"); 3079 Old = convertValue(DL, IRB, Old, IntTy); 3080 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset; 3081 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert"); 3082 Src = convertValue(DL, IRB, Src, NewAllocaTy); 3083 } 3084 3085 StoreInst *Store = cast<StoreInst>( 3086 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile())); 3087 if (AATags) 3088 Store->setAAMetadata(AATags); 3089 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 3090 return !II.isVolatile(); 3091 } 3092 3093 bool visitIntrinsicInst(IntrinsicInst &II) { 3094 assert(II.isLifetimeStartOrEnd()); 3095 LLVM_DEBUG(dbgs() << " original: " << II << "\n"); 3096 assert(II.getArgOperand(1) == OldPtr); 3097 3098 // Record this instruction for deletion. 3099 Pass.DeadInsts.insert(&II); 3100 3101 // Lifetime intrinsics are only promotable if they cover the whole alloca. 3102 // Therefore, we drop lifetime intrinsics which don't cover the whole 3103 // alloca. 3104 // (In theory, intrinsics which partially cover an alloca could be 3105 // promoted, but PromoteMemToReg doesn't handle that case.) 3106 // FIXME: Check whether the alloca is promotable before dropping the 3107 // lifetime intrinsics? 3108 if (NewBeginOffset != NewAllocaBeginOffset || 3109 NewEndOffset != NewAllocaEndOffset) 3110 return true; 3111 3112 ConstantInt *Size = 3113 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()), 3114 NewEndOffset - NewBeginOffset); 3115 // Lifetime intrinsics always expect an i8* so directly get such a pointer 3116 // for the new alloca slice. 3117 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace()); 3118 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy); 3119 Value *New; 3120 if (II.getIntrinsicID() == Intrinsic::lifetime_start) 3121 New = IRB.CreateLifetimeStart(Ptr, Size); 3122 else 3123 New = IRB.CreateLifetimeEnd(Ptr, Size); 3124 3125 (void)New; 3126 LLVM_DEBUG(dbgs() << " to: " << *New << "\n"); 3127 3128 return true; 3129 } 3130 3131 void fixLoadStoreAlign(Instruction &Root) { 3132 // This algorithm implements the same visitor loop as 3133 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load 3134 // or store found. 3135 SmallPtrSet<Instruction *, 4> Visited; 3136 SmallVector<Instruction *, 4> Uses; 3137 Visited.insert(&Root); 3138 Uses.push_back(&Root); 3139 do { 3140 Instruction *I = Uses.pop_back_val(); 3141 3142 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 3143 MaybeAlign LoadAlign = DL.getValueOrABITypeAlignment( 3144 MaybeAlign(LI->getAlignment()), LI->getType()); 3145 LI->setAlignment(std::min(LoadAlign, getSliceAlign())); 3146 continue; 3147 } 3148 if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 3149 Value *Op = SI->getOperand(0); 3150 MaybeAlign StoreAlign = DL.getValueOrABITypeAlignment( 3151 MaybeAlign(SI->getAlignment()), Op->getType()); 3152 SI->setAlignment(std::min(StoreAlign, getSliceAlign())); 3153 continue; 3154 } 3155 3156 assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) || 3157 isa<PHINode>(I) || isa<SelectInst>(I) || 3158 isa<GetElementPtrInst>(I)); 3159 for (User *U : I->users()) 3160 if (Visited.insert(cast<Instruction>(U)).second) 3161 Uses.push_back(cast<Instruction>(U)); 3162 } while (!Uses.empty()); 3163 } 3164 3165 bool visitPHINode(PHINode &PN) { 3166 LLVM_DEBUG(dbgs() << " original: " << PN << "\n"); 3167 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable"); 3168 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable"); 3169 3170 // We would like to compute a new pointer in only one place, but have it be 3171 // as local as possible to the PHI. To do that, we re-use the location of 3172 // the old pointer, which necessarily must be in the right position to 3173 // dominate the PHI. 3174 IRBuilderBase::InsertPointGuard Guard(IRB); 3175 if (isa<PHINode>(OldPtr)) 3176 IRB.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt()); 3177 else 3178 IRB.SetInsertPoint(OldPtr); 3179 IRB.SetCurrentDebugLocation(OldPtr->getDebugLoc()); 3180 3181 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 3182 // Replace the operands which were using the old pointer. 3183 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr); 3184 3185 LLVM_DEBUG(dbgs() << " to: " << PN << "\n"); 3186 deleteIfTriviallyDead(OldPtr); 3187 3188 // Fix the alignment of any loads or stores using this PHI node. 3189 fixLoadStoreAlign(PN); 3190 3191 // PHIs can't be promoted on their own, but often can be speculated. We 3192 // check the speculation outside of the rewriter so that we see the 3193 // fully-rewritten alloca. 3194 PHIUsers.insert(&PN); 3195 return true; 3196 } 3197 3198 bool visitSelectInst(SelectInst &SI) { 3199 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 3200 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) && 3201 "Pointer isn't an operand!"); 3202 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable"); 3203 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable"); 3204 3205 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType()); 3206 // Replace the operands which were using the old pointer. 3207 if (SI.getOperand(1) == OldPtr) 3208 SI.setOperand(1, NewPtr); 3209 if (SI.getOperand(2) == OldPtr) 3210 SI.setOperand(2, NewPtr); 3211 3212 LLVM_DEBUG(dbgs() << " to: " << SI << "\n"); 3213 deleteIfTriviallyDead(OldPtr); 3214 3215 // Fix the alignment of any loads or stores using this select. 3216 fixLoadStoreAlign(SI); 3217 3218 // Selects can't be promoted on their own, but often can be speculated. We 3219 // check the speculation outside of the rewriter so that we see the 3220 // fully-rewritten alloca. 3221 SelectUsers.insert(&SI); 3222 return true; 3223 } 3224 }; 3225 3226 namespace { 3227 3228 /// Visitor to rewrite aggregate loads and stores as scalar. 3229 /// 3230 /// This pass aggressively rewrites all aggregate loads and stores on 3231 /// a particular pointer (or any pointer derived from it which we can identify) 3232 /// with scalar loads and stores. 3233 class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> { 3234 // Befriend the base class so it can delegate to private visit methods. 3235 friend class InstVisitor<AggLoadStoreRewriter, bool>; 3236 3237 /// Queue of pointer uses to analyze and potentially rewrite. 3238 SmallVector<Use *, 8> Queue; 3239 3240 /// Set to prevent us from cycling with phi nodes and loops. 3241 SmallPtrSet<User *, 8> Visited; 3242 3243 /// The current pointer use being rewritten. This is used to dig up the used 3244 /// value (as opposed to the user). 3245 Use *U = nullptr; 3246 3247 /// Used to calculate offsets, and hence alignment, of subobjects. 3248 const DataLayout &DL; 3249 3250 public: 3251 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {} 3252 3253 /// Rewrite loads and stores through a pointer and all pointers derived from 3254 /// it. 3255 bool rewrite(Instruction &I) { 3256 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n"); 3257 enqueueUsers(I); 3258 bool Changed = false; 3259 while (!Queue.empty()) { 3260 U = Queue.pop_back_val(); 3261 Changed |= visit(cast<Instruction>(U->getUser())); 3262 } 3263 return Changed; 3264 } 3265 3266 private: 3267 /// Enqueue all the users of the given instruction for further processing. 3268 /// This uses a set to de-duplicate users. 3269 void enqueueUsers(Instruction &I) { 3270 for (Use &U : I.uses()) 3271 if (Visited.insert(U.getUser()).second) 3272 Queue.push_back(&U); 3273 } 3274 3275 // Conservative default is to not rewrite anything. 3276 bool visitInstruction(Instruction &I) { return false; } 3277 3278 /// Generic recursive split emission class. 3279 template <typename Derived> class OpSplitter { 3280 protected: 3281 /// The builder used to form new instructions. 3282 IRBuilderTy IRB; 3283 3284 /// The indices which to be used with insert- or extractvalue to select the 3285 /// appropriate value within the aggregate. 3286 SmallVector<unsigned, 4> Indices; 3287 3288 /// The indices to a GEP instruction which will move Ptr to the correct slot 3289 /// within the aggregate. 3290 SmallVector<Value *, 4> GEPIndices; 3291 3292 /// The base pointer of the original op, used as a base for GEPing the 3293 /// split operations. 3294 Value *Ptr; 3295 3296 /// The base pointee type being GEPed into. 3297 Type *BaseTy; 3298 3299 /// Known alignment of the base pointer. 3300 Align BaseAlign; 3301 3302 /// To calculate offset of each component so we can correctly deduce 3303 /// alignments. 3304 const DataLayout &DL; 3305 3306 /// Initialize the splitter with an insertion point, Ptr and start with a 3307 /// single zero GEP index. 3308 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3309 Align BaseAlign, const DataLayout &DL) 3310 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr), 3311 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {} 3312 3313 public: 3314 /// Generic recursive split emission routine. 3315 /// 3316 /// This method recursively splits an aggregate op (load or store) into 3317 /// scalar or vector ops. It splits recursively until it hits a single value 3318 /// and emits that single value operation via the template argument. 3319 /// 3320 /// The logic of this routine relies on GEPs and insertvalue and 3321 /// extractvalue all operating with the same fundamental index list, merely 3322 /// formatted differently (GEPs need actual values). 3323 /// 3324 /// \param Ty The type being split recursively into smaller ops. 3325 /// \param Agg The aggregate value being built up or stored, depending on 3326 /// whether this is splitting a load or a store respectively. 3327 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) { 3328 if (Ty->isSingleValueType()) { 3329 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices); 3330 return static_cast<Derived *>(this)->emitFunc( 3331 Ty, Agg, commonAlignment(BaseAlign, Offset), Name); 3332 } 3333 3334 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 3335 unsigned OldSize = Indices.size(); 3336 (void)OldSize; 3337 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size; 3338 ++Idx) { 3339 assert(Indices.size() == OldSize && "Did not return to the old size"); 3340 Indices.push_back(Idx); 3341 GEPIndices.push_back(IRB.getInt32(Idx)); 3342 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx)); 3343 GEPIndices.pop_back(); 3344 Indices.pop_back(); 3345 } 3346 return; 3347 } 3348 3349 if (StructType *STy = dyn_cast<StructType>(Ty)) { 3350 unsigned OldSize = Indices.size(); 3351 (void)OldSize; 3352 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size; 3353 ++Idx) { 3354 assert(Indices.size() == OldSize && "Did not return to the old size"); 3355 Indices.push_back(Idx); 3356 GEPIndices.push_back(IRB.getInt32(Idx)); 3357 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx)); 3358 GEPIndices.pop_back(); 3359 Indices.pop_back(); 3360 } 3361 return; 3362 } 3363 3364 llvm_unreachable("Only arrays and structs are aggregate loadable types"); 3365 } 3366 }; 3367 3368 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> { 3369 AAMDNodes AATags; 3370 3371 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3372 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL) 3373 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, 3374 DL), 3375 AATags(AATags) {} 3376 3377 /// Emit a leaf load of a single value. This is called at the leaves of the 3378 /// recursive emission to actually load values. 3379 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) { 3380 assert(Ty->isSingleValueType()); 3381 // Load the single value and insert it using the indices. 3382 Value *GEP = 3383 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep"); 3384 LoadInst *Load = 3385 IRB.CreateAlignedLoad(Ty, GEP, Alignment, Name + ".load"); 3386 if (AATags) 3387 Load->setAAMetadata(AATags); 3388 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert"); 3389 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n"); 3390 } 3391 }; 3392 3393 bool visitLoadInst(LoadInst &LI) { 3394 assert(LI.getPointerOperand() == *U); 3395 if (!LI.isSimple() || LI.getType()->isSingleValueType()) 3396 return false; 3397 3398 // We have an aggregate being loaded, split it apart. 3399 LLVM_DEBUG(dbgs() << " original: " << LI << "\n"); 3400 AAMDNodes AATags; 3401 LI.getAAMetadata(AATags); 3402 LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags, 3403 getAdjustedAlignment(&LI, 0, DL), DL); 3404 Value *V = UndefValue::get(LI.getType()); 3405 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca"); 3406 LI.replaceAllUsesWith(V); 3407 LI.eraseFromParent(); 3408 return true; 3409 } 3410 3411 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> { 3412 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy, 3413 AAMDNodes AATags, Align BaseAlign, const DataLayout &DL) 3414 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign, 3415 DL), 3416 AATags(AATags) {} 3417 AAMDNodes AATags; 3418 /// Emit a leaf store of a single value. This is called at the leaves of the 3419 /// recursive emission to actually produce stores. 3420 void emitFunc(Type *Ty, Value *&Agg, Align Alignment, const Twine &Name) { 3421 assert(Ty->isSingleValueType()); 3422 // Extract the single value and store it using the indices. 3423 // 3424 // The gep and extractvalue values are factored out of the CreateStore 3425 // call to make the output independent of the argument evaluation order. 3426 Value *ExtractValue = 3427 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"); 3428 Value *InBoundsGEP = 3429 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep"); 3430 StoreInst *Store = 3431 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Alignment); 3432 if (AATags) 3433 Store->setAAMetadata(AATags); 3434 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n"); 3435 } 3436 }; 3437 3438 bool visitStoreInst(StoreInst &SI) { 3439 if (!SI.isSimple() || SI.getPointerOperand() != *U) 3440 return false; 3441 Value *V = SI.getValueOperand(); 3442 if (V->getType()->isSingleValueType()) 3443 return false; 3444 3445 // We have an aggregate being stored, split it apart. 3446 LLVM_DEBUG(dbgs() << " original: " << SI << "\n"); 3447 AAMDNodes AATags; 3448 SI.getAAMetadata(AATags); 3449 StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags, 3450 getAdjustedAlignment(&SI, 0, DL), DL); 3451 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca"); 3452 SI.eraseFromParent(); 3453 return true; 3454 } 3455 3456 bool visitBitCastInst(BitCastInst &BC) { 3457 enqueueUsers(BC); 3458 return false; 3459 } 3460 3461 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) { 3462 enqueueUsers(ASC); 3463 return false; 3464 } 3465 3466 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) { 3467 enqueueUsers(GEPI); 3468 return false; 3469 } 3470 3471 bool visitPHINode(PHINode &PN) { 3472 enqueueUsers(PN); 3473 return false; 3474 } 3475 3476 bool visitSelectInst(SelectInst &SI) { 3477 enqueueUsers(SI); 3478 return false; 3479 } 3480 }; 3481 3482 } // end anonymous namespace 3483 3484 /// Strip aggregate type wrapping. 3485 /// 3486 /// This removes no-op aggregate types wrapping an underlying type. It will 3487 /// strip as many layers of types as it can without changing either the type 3488 /// size or the allocated size. 3489 static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) { 3490 if (Ty->isSingleValueType()) 3491 return Ty; 3492 3493 uint64_t AllocSize = DL.getTypeAllocSize(Ty).getFixedSize(); 3494 uint64_t TypeSize = DL.getTypeSizeInBits(Ty).getFixedSize(); 3495 3496 Type *InnerTy; 3497 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { 3498 InnerTy = ArrTy->getElementType(); 3499 } else if (StructType *STy = dyn_cast<StructType>(Ty)) { 3500 const StructLayout *SL = DL.getStructLayout(STy); 3501 unsigned Index = SL->getElementContainingOffset(0); 3502 InnerTy = STy->getElementType(Index); 3503 } else { 3504 return Ty; 3505 } 3506 3507 if (AllocSize > DL.getTypeAllocSize(InnerTy).getFixedSize() || 3508 TypeSize > DL.getTypeSizeInBits(InnerTy).getFixedSize()) 3509 return Ty; 3510 3511 return stripAggregateTypeWrapping(DL, InnerTy); 3512 } 3513 3514 /// Try to find a partition of the aggregate type passed in for a given 3515 /// offset and size. 3516 /// 3517 /// This recurses through the aggregate type and tries to compute a subtype 3518 /// based on the offset and size. When the offset and size span a sub-section 3519 /// of an array, it will even compute a new array type for that sub-section, 3520 /// and the same for structs. 3521 /// 3522 /// Note that this routine is very strict and tries to find a partition of the 3523 /// type which produces the *exact* right offset and size. It is not forgiving 3524 /// when the size or offset cause either end of type-based partition to be off. 3525 /// Also, this is a best-effort routine. It is reasonable to give up and not 3526 /// return a type if necessary. 3527 static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset, 3528 uint64_t Size) { 3529 if (Offset == 0 && DL.getTypeAllocSize(Ty).getFixedSize() == Size) 3530 return stripAggregateTypeWrapping(DL, Ty); 3531 if (Offset > DL.getTypeAllocSize(Ty).getFixedSize() || 3532 (DL.getTypeAllocSize(Ty).getFixedSize() - Offset) < Size) 3533 return nullptr; 3534 3535 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) { 3536 Type *ElementTy = SeqTy->getElementType(); 3537 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize(); 3538 uint64_t NumSkippedElements = Offset / ElementSize; 3539 if (NumSkippedElements >= SeqTy->getNumElements()) 3540 return nullptr; 3541 Offset -= NumSkippedElements * ElementSize; 3542 3543 // First check if we need to recurse. 3544 if (Offset > 0 || Size < ElementSize) { 3545 // Bail if the partition ends in a different array element. 3546 if ((Offset + Size) > ElementSize) 3547 return nullptr; 3548 // Recurse through the element type trying to peel off offset bytes. 3549 return getTypePartition(DL, ElementTy, Offset, Size); 3550 } 3551 assert(Offset == 0); 3552 3553 if (Size == ElementSize) 3554 return stripAggregateTypeWrapping(DL, ElementTy); 3555 assert(Size > ElementSize); 3556 uint64_t NumElements = Size / ElementSize; 3557 if (NumElements * ElementSize != Size) 3558 return nullptr; 3559 return ArrayType::get(ElementTy, NumElements); 3560 } 3561 3562 StructType *STy = dyn_cast<StructType>(Ty); 3563 if (!STy) 3564 return nullptr; 3565 3566 const StructLayout *SL = DL.getStructLayout(STy); 3567 if (Offset >= SL->getSizeInBytes()) 3568 return nullptr; 3569 uint64_t EndOffset = Offset + Size; 3570 if (EndOffset > SL->getSizeInBytes()) 3571 return nullptr; 3572 3573 unsigned Index = SL->getElementContainingOffset(Offset); 3574 Offset -= SL->getElementOffset(Index); 3575 3576 Type *ElementTy = STy->getElementType(Index); 3577 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy).getFixedSize(); 3578 if (Offset >= ElementSize) 3579 return nullptr; // The offset points into alignment padding. 3580 3581 // See if any partition must be contained by the element. 3582 if (Offset > 0 || Size < ElementSize) { 3583 if ((Offset + Size) > ElementSize) 3584 return nullptr; 3585 return getTypePartition(DL, ElementTy, Offset, Size); 3586 } 3587 assert(Offset == 0); 3588 3589 if (Size == ElementSize) 3590 return stripAggregateTypeWrapping(DL, ElementTy); 3591 3592 StructType::element_iterator EI = STy->element_begin() + Index, 3593 EE = STy->element_end(); 3594 if (EndOffset < SL->getSizeInBytes()) { 3595 unsigned EndIndex = SL->getElementContainingOffset(EndOffset); 3596 if (Index == EndIndex) 3597 return nullptr; // Within a single element and its padding. 3598 3599 // Don't try to form "natural" types if the elements don't line up with the 3600 // expected size. 3601 // FIXME: We could potentially recurse down through the last element in the 3602 // sub-struct to find a natural end point. 3603 if (SL->getElementOffset(EndIndex) != EndOffset) 3604 return nullptr; 3605 3606 assert(Index < EndIndex); 3607 EE = STy->element_begin() + EndIndex; 3608 } 3609 3610 // Try to build up a sub-structure. 3611 StructType *SubTy = 3612 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked()); 3613 const StructLayout *SubSL = DL.getStructLayout(SubTy); 3614 if (Size != SubSL->getSizeInBytes()) 3615 return nullptr; // The sub-struct doesn't have quite the size needed. 3616 3617 return SubTy; 3618 } 3619 3620 /// Pre-split loads and stores to simplify rewriting. 3621 /// 3622 /// We want to break up the splittable load+store pairs as much as 3623 /// possible. This is important to do as a preprocessing step, as once we 3624 /// start rewriting the accesses to partitions of the alloca we lose the 3625 /// necessary information to correctly split apart paired loads and stores 3626 /// which both point into this alloca. The case to consider is something like 3627 /// the following: 3628 /// 3629 /// %a = alloca [12 x i8] 3630 /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0 3631 /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4 3632 /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8 3633 /// %iptr1 = bitcast i8* %gep1 to i64* 3634 /// %iptr2 = bitcast i8* %gep2 to i64* 3635 /// %fptr1 = bitcast i8* %gep1 to float* 3636 /// %fptr2 = bitcast i8* %gep2 to float* 3637 /// %fptr3 = bitcast i8* %gep3 to float* 3638 /// store float 0.0, float* %fptr1 3639 /// store float 1.0, float* %fptr2 3640 /// %v = load i64* %iptr1 3641 /// store i64 %v, i64* %iptr2 3642 /// %f1 = load float* %fptr2 3643 /// %f2 = load float* %fptr3 3644 /// 3645 /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and 3646 /// promote everything so we recover the 2 SSA values that should have been 3647 /// there all along. 3648 /// 3649 /// \returns true if any changes are made. 3650 bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) { 3651 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n"); 3652 3653 // Track the loads and stores which are candidates for pre-splitting here, in 3654 // the order they first appear during the partition scan. These give stable 3655 // iteration order and a basis for tracking which loads and stores we 3656 // actually split. 3657 SmallVector<LoadInst *, 4> Loads; 3658 SmallVector<StoreInst *, 4> Stores; 3659 3660 // We need to accumulate the splits required of each load or store where we 3661 // can find them via a direct lookup. This is important to cross-check loads 3662 // and stores against each other. We also track the slice so that we can kill 3663 // all the slices that end up split. 3664 struct SplitOffsets { 3665 Slice *S; 3666 std::vector<uint64_t> Splits; 3667 }; 3668 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap; 3669 3670 // Track loads out of this alloca which cannot, for any reason, be pre-split. 3671 // This is important as we also cannot pre-split stores of those loads! 3672 // FIXME: This is all pretty gross. It means that we can be more aggressive 3673 // in pre-splitting when the load feeding the store happens to come from 3674 // a separate alloca. Put another way, the effectiveness of SROA would be 3675 // decreased by a frontend which just concatenated all of its local allocas 3676 // into one big flat alloca. But defeating such patterns is exactly the job 3677 // SROA is tasked with! Sadly, to not have this discrepancy we would have 3678 // change store pre-splitting to actually force pre-splitting of the load 3679 // that feeds it *and all stores*. That makes pre-splitting much harder, but 3680 // maybe it would make it more principled? 3681 SmallPtrSet<LoadInst *, 8> UnsplittableLoads; 3682 3683 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n"); 3684 for (auto &P : AS.partitions()) { 3685 for (Slice &S : P) { 3686 Instruction *I = cast<Instruction>(S.getUse()->getUser()); 3687 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) { 3688 // If this is a load we have to track that it can't participate in any 3689 // pre-splitting. If this is a store of a load we have to track that 3690 // that load also can't participate in any pre-splitting. 3691 if (auto *LI = dyn_cast<LoadInst>(I)) 3692 UnsplittableLoads.insert(LI); 3693 else if (auto *SI = dyn_cast<StoreInst>(I)) 3694 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand())) 3695 UnsplittableLoads.insert(LI); 3696 continue; 3697 } 3698 assert(P.endOffset() > S.beginOffset() && 3699 "Empty or backwards partition!"); 3700 3701 // Determine if this is a pre-splittable slice. 3702 if (auto *LI = dyn_cast<LoadInst>(I)) { 3703 assert(!LI->isVolatile() && "Cannot split volatile loads!"); 3704 3705 // The load must be used exclusively to store into other pointers for 3706 // us to be able to arbitrarily pre-split it. The stores must also be 3707 // simple to avoid changing semantics. 3708 auto IsLoadSimplyStored = [](LoadInst *LI) { 3709 for (User *LU : LI->users()) { 3710 auto *SI = dyn_cast<StoreInst>(LU); 3711 if (!SI || !SI->isSimple()) 3712 return false; 3713 } 3714 return true; 3715 }; 3716 if (!IsLoadSimplyStored(LI)) { 3717 UnsplittableLoads.insert(LI); 3718 continue; 3719 } 3720 3721 Loads.push_back(LI); 3722 } else if (auto *SI = dyn_cast<StoreInst>(I)) { 3723 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex())) 3724 // Skip stores *of* pointers. FIXME: This shouldn't even be possible! 3725 continue; 3726 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand()); 3727 if (!StoredLoad || !StoredLoad->isSimple()) 3728 continue; 3729 assert(!SI->isVolatile() && "Cannot split volatile stores!"); 3730 3731 Stores.push_back(SI); 3732 } else { 3733 // Other uses cannot be pre-split. 3734 continue; 3735 } 3736 3737 // Record the initial split. 3738 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n"); 3739 auto &Offsets = SplitOffsetsMap[I]; 3740 assert(Offsets.Splits.empty() && 3741 "Should not have splits the first time we see an instruction!"); 3742 Offsets.S = &S; 3743 Offsets.Splits.push_back(P.endOffset() - S.beginOffset()); 3744 } 3745 3746 // Now scan the already split slices, and add a split for any of them which 3747 // we're going to pre-split. 3748 for (Slice *S : P.splitSliceTails()) { 3749 auto SplitOffsetsMapI = 3750 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser())); 3751 if (SplitOffsetsMapI == SplitOffsetsMap.end()) 3752 continue; 3753 auto &Offsets = SplitOffsetsMapI->second; 3754 3755 assert(Offsets.S == S && "Found a mismatched slice!"); 3756 assert(!Offsets.Splits.empty() && 3757 "Cannot have an empty set of splits on the second partition!"); 3758 assert(Offsets.Splits.back() == 3759 P.beginOffset() - Offsets.S->beginOffset() && 3760 "Previous split does not end where this one begins!"); 3761 3762 // Record each split. The last partition's end isn't needed as the size 3763 // of the slice dictates that. 3764 if (S->endOffset() > P.endOffset()) 3765 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset()); 3766 } 3767 } 3768 3769 // We may have split loads where some of their stores are split stores. For 3770 // such loads and stores, we can only pre-split them if their splits exactly 3771 // match relative to their starting offset. We have to verify this prior to 3772 // any rewriting. 3773 Stores.erase( 3774 llvm::remove_if(Stores, 3775 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) { 3776 // Lookup the load we are storing in our map of split 3777 // offsets. 3778 auto *LI = cast<LoadInst>(SI->getValueOperand()); 3779 // If it was completely unsplittable, then we're done, 3780 // and this store can't be pre-split. 3781 if (UnsplittableLoads.count(LI)) 3782 return true; 3783 3784 auto LoadOffsetsI = SplitOffsetsMap.find(LI); 3785 if (LoadOffsetsI == SplitOffsetsMap.end()) 3786 return false; // Unrelated loads are definitely safe. 3787 auto &LoadOffsets = LoadOffsetsI->second; 3788 3789 // Now lookup the store's offsets. 3790 auto &StoreOffsets = SplitOffsetsMap[SI]; 3791 3792 // If the relative offsets of each split in the load and 3793 // store match exactly, then we can split them and we 3794 // don't need to remove them here. 3795 if (LoadOffsets.Splits == StoreOffsets.Splits) 3796 return false; 3797 3798 LLVM_DEBUG( 3799 dbgs() 3800 << " Mismatched splits for load and store:\n" 3801 << " " << *LI << "\n" 3802 << " " << *SI << "\n"); 3803 3804 // We've found a store and load that we need to split 3805 // with mismatched relative splits. Just give up on them 3806 // and remove both instructions from our list of 3807 // candidates. 3808 UnsplittableLoads.insert(LI); 3809 return true; 3810 }), 3811 Stores.end()); 3812 // Now we have to go *back* through all the stores, because a later store may 3813 // have caused an earlier store's load to become unsplittable and if it is 3814 // unsplittable for the later store, then we can't rely on it being split in 3815 // the earlier store either. 3816 Stores.erase(llvm::remove_if(Stores, 3817 [&UnsplittableLoads](StoreInst *SI) { 3818 auto *LI = 3819 cast<LoadInst>(SI->getValueOperand()); 3820 return UnsplittableLoads.count(LI); 3821 }), 3822 Stores.end()); 3823 // Once we've established all the loads that can't be split for some reason, 3824 // filter any that made it into our list out. 3825 Loads.erase(llvm::remove_if(Loads, 3826 [&UnsplittableLoads](LoadInst *LI) { 3827 return UnsplittableLoads.count(LI); 3828 }), 3829 Loads.end()); 3830 3831 // If no loads or stores are left, there is no pre-splitting to be done for 3832 // this alloca. 3833 if (Loads.empty() && Stores.empty()) 3834 return false; 3835 3836 // From here on, we can't fail and will be building new accesses, so rig up 3837 // an IR builder. 3838 IRBuilderTy IRB(&AI); 3839 3840 // Collect the new slices which we will merge into the alloca slices. 3841 SmallVector<Slice, 4> NewSlices; 3842 3843 // Track any allocas we end up splitting loads and stores for so we iterate 3844 // on them. 3845 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas; 3846 3847 // At this point, we have collected all of the loads and stores we can 3848 // pre-split, and the specific splits needed for them. We actually do the 3849 // splitting in a specific order in order to handle when one of the loads in 3850 // the value operand to one of the stores. 3851 // 3852 // First, we rewrite all of the split loads, and just accumulate each split 3853 // load in a parallel structure. We also build the slices for them and append 3854 // them to the alloca slices. 3855 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap; 3856 std::vector<LoadInst *> SplitLoads; 3857 const DataLayout &DL = AI.getModule()->getDataLayout(); 3858 for (LoadInst *LI : Loads) { 3859 SplitLoads.clear(); 3860 3861 IntegerType *Ty = cast<IntegerType>(LI->getType()); 3862 uint64_t LoadSize = Ty->getBitWidth() / 8; 3863 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!"); 3864 3865 auto &Offsets = SplitOffsetsMap[LI]; 3866 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && 3867 "Slice size should always match load size exactly!"); 3868 uint64_t BaseOffset = Offsets.S->beginOffset(); 3869 assert(BaseOffset + LoadSize > BaseOffset && 3870 "Cannot represent alloca access size using 64-bit integers!"); 3871 3872 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand()); 3873 IRB.SetInsertPoint(LI); 3874 3875 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n"); 3876 3877 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front(); 3878 int Idx = 0, Size = Offsets.Splits.size(); 3879 for (;;) { 3880 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8); 3881 auto AS = LI->getPointerAddressSpace(); 3882 auto *PartPtrTy = PartTy->getPointerTo(AS); 3883 LoadInst *PLoad = IRB.CreateAlignedLoad( 3884 PartTy, 3885 getAdjustedPtr(IRB, DL, BasePtr, 3886 APInt(DL.getIndexSizeInBits(AS), PartOffset), 3887 PartPtrTy, BasePtr->getName() + "."), 3888 getAdjustedAlignment(LI, PartOffset, DL), 3889 /*IsVolatile*/ false, LI->getName()); 3890 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access, 3891 LLVMContext::MD_access_group}); 3892 3893 // Append this load onto the list of split loads so we can find it later 3894 // to rewrite the stores. 3895 SplitLoads.push_back(PLoad); 3896 3897 // Now build a new slice for the alloca. 3898 NewSlices.push_back( 3899 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize, 3900 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()), 3901 /*IsSplittable*/ false)); 3902 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset() 3903 << ", " << NewSlices.back().endOffset() 3904 << "): " << *PLoad << "\n"); 3905 3906 // See if we've handled all the splits. 3907 if (Idx >= Size) 3908 break; 3909 3910 // Setup the next partition. 3911 PartOffset = Offsets.Splits[Idx]; 3912 ++Idx; 3913 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset; 3914 } 3915 3916 // Now that we have the split loads, do the slow walk over all uses of the 3917 // load and rewrite them as split stores, or save the split loads to use 3918 // below if the store is going to be split there anyways. 3919 bool DeferredStores = false; 3920 for (User *LU : LI->users()) { 3921 StoreInst *SI = cast<StoreInst>(LU); 3922 if (!Stores.empty() && SplitOffsetsMap.count(SI)) { 3923 DeferredStores = true; 3924 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI 3925 << "\n"); 3926 continue; 3927 } 3928 3929 Value *StoreBasePtr = SI->getPointerOperand(); 3930 IRB.SetInsertPoint(SI); 3931 3932 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n"); 3933 3934 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) { 3935 LoadInst *PLoad = SplitLoads[Idx]; 3936 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1]; 3937 auto *PartPtrTy = 3938 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace()); 3939 3940 auto AS = SI->getPointerAddressSpace(); 3941 StoreInst *PStore = IRB.CreateAlignedStore( 3942 PLoad, 3943 getAdjustedPtr(IRB, DL, StoreBasePtr, 3944 APInt(DL.getIndexSizeInBits(AS), PartOffset), 3945 PartPtrTy, StoreBasePtr->getName() + "."), 3946 getAdjustedAlignment(SI, PartOffset, DL), 3947 /*IsVolatile*/ false); 3948 PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access, 3949 LLVMContext::MD_access_group}); 3950 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n"); 3951 } 3952 3953 // We want to immediately iterate on any allocas impacted by splitting 3954 // this store, and we have to track any promotable alloca (indicated by 3955 // a direct store) as needing to be resplit because it is no longer 3956 // promotable. 3957 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) { 3958 ResplitPromotableAllocas.insert(OtherAI); 3959 Worklist.insert(OtherAI); 3960 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>( 3961 StoreBasePtr->stripInBoundsOffsets())) { 3962 Worklist.insert(OtherAI); 3963 } 3964 3965 // Mark the original store as dead. 3966 DeadInsts.insert(SI); 3967 } 3968 3969 // Save the split loads if there are deferred stores among the users. 3970 if (DeferredStores) 3971 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads))); 3972 3973 // Mark the original load as dead and kill the original slice. 3974 DeadInsts.insert(LI); 3975 Offsets.S->kill(); 3976 } 3977 3978 // Second, we rewrite all of the split stores. At this point, we know that 3979 // all loads from this alloca have been split already. For stores of such 3980 // loads, we can simply look up the pre-existing split loads. For stores of 3981 // other loads, we split those loads first and then write split stores of 3982 // them. 3983 for (StoreInst *SI : Stores) { 3984 auto *LI = cast<LoadInst>(SI->getValueOperand()); 3985 IntegerType *Ty = cast<IntegerType>(LI->getType()); 3986 uint64_t StoreSize = Ty->getBitWidth() / 8; 3987 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!"); 3988 3989 auto &Offsets = SplitOffsetsMap[SI]; 3990 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && 3991 "Slice size should always match load size exactly!"); 3992 uint64_t BaseOffset = Offsets.S->beginOffset(); 3993 assert(BaseOffset + StoreSize > BaseOffset && 3994 "Cannot represent alloca access size using 64-bit integers!"); 3995 3996 Value *LoadBasePtr = LI->getPointerOperand(); 3997 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand()); 3998 3999 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n"); 4000 4001 // Check whether we have an already split load. 4002 auto SplitLoadsMapI = SplitLoadsMap.find(LI); 4003 std::vector<LoadInst *> *SplitLoads = nullptr; 4004 if (SplitLoadsMapI != SplitLoadsMap.end()) { 4005 SplitLoads = &SplitLoadsMapI->second; 4006 assert(SplitLoads->size() == Offsets.Splits.size() + 1 && 4007 "Too few split loads for the number of splits in the store!"); 4008 } else { 4009 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n"); 4010 } 4011 4012 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front(); 4013 int Idx = 0, Size = Offsets.Splits.size(); 4014 for (;;) { 4015 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8); 4016 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace()); 4017 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace()); 4018 4019 // Either lookup a split load or create one. 4020 LoadInst *PLoad; 4021 if (SplitLoads) { 4022 PLoad = (*SplitLoads)[Idx]; 4023 } else { 4024 IRB.SetInsertPoint(LI); 4025 auto AS = LI->getPointerAddressSpace(); 4026 PLoad = IRB.CreateAlignedLoad( 4027 PartTy, 4028 getAdjustedPtr(IRB, DL, LoadBasePtr, 4029 APInt(DL.getIndexSizeInBits(AS), PartOffset), 4030 LoadPartPtrTy, LoadBasePtr->getName() + "."), 4031 getAdjustedAlignment(LI, PartOffset, DL), 4032 /*IsVolatile*/ false, LI->getName()); 4033 } 4034 4035 // And store this partition. 4036 IRB.SetInsertPoint(SI); 4037 auto AS = SI->getPointerAddressSpace(); 4038 StoreInst *PStore = IRB.CreateAlignedStore( 4039 PLoad, 4040 getAdjustedPtr(IRB, DL, StoreBasePtr, 4041 APInt(DL.getIndexSizeInBits(AS), PartOffset), 4042 StorePartPtrTy, StoreBasePtr->getName() + "."), 4043 getAdjustedAlignment(SI, PartOffset, DL), 4044 /*IsVolatile*/ false); 4045 4046 // Now build a new slice for the alloca. 4047 NewSlices.push_back( 4048 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize, 4049 &PStore->getOperandUse(PStore->getPointerOperandIndex()), 4050 /*IsSplittable*/ false)); 4051 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset() 4052 << ", " << NewSlices.back().endOffset() 4053 << "): " << *PStore << "\n"); 4054 if (!SplitLoads) { 4055 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n"); 4056 } 4057 4058 // See if we've finished all the splits. 4059 if (Idx >= Size) 4060 break; 4061 4062 // Setup the next partition. 4063 PartOffset = Offsets.Splits[Idx]; 4064 ++Idx; 4065 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset; 4066 } 4067 4068 // We want to immediately iterate on any allocas impacted by splitting 4069 // this load, which is only relevant if it isn't a load of this alloca and 4070 // thus we didn't already split the loads above. We also have to keep track 4071 // of any promotable allocas we split loads on as they can no longer be 4072 // promoted. 4073 if (!SplitLoads) { 4074 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) { 4075 assert(OtherAI != &AI && "We can't re-split our own alloca!"); 4076 ResplitPromotableAllocas.insert(OtherAI); 4077 Worklist.insert(OtherAI); 4078 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>( 4079 LoadBasePtr->stripInBoundsOffsets())) { 4080 assert(OtherAI != &AI && "We can't re-split our own alloca!"); 4081 Worklist.insert(OtherAI); 4082 } 4083 } 4084 4085 // Mark the original store as dead now that we've split it up and kill its 4086 // slice. Note that we leave the original load in place unless this store 4087 // was its only use. It may in turn be split up if it is an alloca load 4088 // for some other alloca, but it may be a normal load. This may introduce 4089 // redundant loads, but where those can be merged the rest of the optimizer 4090 // should handle the merging, and this uncovers SSA splits which is more 4091 // important. In practice, the original loads will almost always be fully 4092 // split and removed eventually, and the splits will be merged by any 4093 // trivial CSE, including instcombine. 4094 if (LI->hasOneUse()) { 4095 assert(*LI->user_begin() == SI && "Single use isn't this store!"); 4096 DeadInsts.insert(LI); 4097 } 4098 DeadInsts.insert(SI); 4099 Offsets.S->kill(); 4100 } 4101 4102 // Remove the killed slices that have ben pre-split. 4103 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }), 4104 AS.end()); 4105 4106 // Insert our new slices. This will sort and merge them into the sorted 4107 // sequence. 4108 AS.insert(NewSlices); 4109 4110 LLVM_DEBUG(dbgs() << " Pre-split slices:\n"); 4111 #ifndef NDEBUG 4112 for (auto I = AS.begin(), E = AS.end(); I != E; ++I) 4113 LLVM_DEBUG(AS.print(dbgs(), I, " ")); 4114 #endif 4115 4116 // Finally, don't try to promote any allocas that new require re-splitting. 4117 // They have already been added to the worklist above. 4118 PromotableAllocas.erase( 4119 llvm::remove_if( 4120 PromotableAllocas, 4121 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }), 4122 PromotableAllocas.end()); 4123 4124 return true; 4125 } 4126 4127 /// Rewrite an alloca partition's users. 4128 /// 4129 /// This routine drives both of the rewriting goals of the SROA pass. It tries 4130 /// to rewrite uses of an alloca partition to be conducive for SSA value 4131 /// promotion. If the partition needs a new, more refined alloca, this will 4132 /// build that new alloca, preserving as much type information as possible, and 4133 /// rewrite the uses of the old alloca to point at the new one and have the 4134 /// appropriate new offsets. It also evaluates how successful the rewrite was 4135 /// at enabling promotion and if it was successful queues the alloca to be 4136 /// promoted. 4137 AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS, 4138 Partition &P) { 4139 // Try to compute a friendly type for this partition of the alloca. This 4140 // won't always succeed, in which case we fall back to a legal integer type 4141 // or an i8 array of an appropriate size. 4142 Type *SliceTy = nullptr; 4143 const DataLayout &DL = AI.getModule()->getDataLayout(); 4144 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset())) 4145 if (DL.getTypeAllocSize(CommonUseTy).getFixedSize() >= P.size()) 4146 SliceTy = CommonUseTy; 4147 if (!SliceTy) 4148 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(), 4149 P.beginOffset(), P.size())) 4150 SliceTy = TypePartitionTy; 4151 if ((!SliceTy || (SliceTy->isArrayTy() && 4152 SliceTy->getArrayElementType()->isIntegerTy())) && 4153 DL.isLegalInteger(P.size() * 8)) 4154 SliceTy = Type::getIntNTy(*C, P.size() * 8); 4155 if (!SliceTy) 4156 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size()); 4157 assert(DL.getTypeAllocSize(SliceTy).getFixedSize() >= P.size()); 4158 4159 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL); 4160 4161 VectorType *VecTy = 4162 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL); 4163 if (VecTy) 4164 SliceTy = VecTy; 4165 4166 // Check for the case where we're going to rewrite to a new alloca of the 4167 // exact same type as the original, and with the same access offsets. In that 4168 // case, re-use the existing alloca, but still run through the rewriter to 4169 // perform phi and select speculation. 4170 // P.beginOffset() can be non-zero even with the same type in a case with 4171 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll). 4172 AllocaInst *NewAI; 4173 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) { 4174 NewAI = &AI; 4175 // FIXME: We should be able to bail at this point with "nothing changed". 4176 // FIXME: We might want to defer PHI speculation until after here. 4177 // FIXME: return nullptr; 4178 } else { 4179 // If alignment is unspecified we fallback on the one required by the ABI 4180 // for this type. We also make sure the alignment is compatible with 4181 // P.beginOffset(). 4182 const Align Alignment = commonAlignment( 4183 DL.getValueOrABITypeAlignment(MaybeAlign(AI.getAlignment()), 4184 AI.getAllocatedType()), 4185 P.beginOffset()); 4186 // If we will get at least this much alignment from the type alone, leave 4187 // the alloca's alignment unconstrained. 4188 const bool IsUnconstrained = Alignment <= DL.getABITypeAlignment(SliceTy); 4189 NewAI = new AllocaInst( 4190 SliceTy, AI.getType()->getAddressSpace(), nullptr, 4191 IsUnconstrained ? MaybeAlign() : Alignment, 4192 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI); 4193 // Copy the old AI debug location over to the new one. 4194 NewAI->setDebugLoc(AI.getDebugLoc()); 4195 ++NumNewAllocas; 4196 } 4197 4198 LLVM_DEBUG(dbgs() << "Rewriting alloca partition " 4199 << "[" << P.beginOffset() << "," << P.endOffset() 4200 << ") to: " << *NewAI << "\n"); 4201 4202 // Track the high watermark on the worklist as it is only relevant for 4203 // promoted allocas. We will reset it to this point if the alloca is not in 4204 // fact scheduled for promotion. 4205 unsigned PPWOldSize = PostPromotionWorklist.size(); 4206 unsigned NumUses = 0; 4207 SmallSetVector<PHINode *, 8> PHIUsers; 4208 SmallSetVector<SelectInst *, 8> SelectUsers; 4209 4210 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(), 4211 P.endOffset(), IsIntegerPromotable, VecTy, 4212 PHIUsers, SelectUsers); 4213 bool Promotable = true; 4214 for (Slice *S : P.splitSliceTails()) { 4215 Promotable &= Rewriter.visit(S); 4216 ++NumUses; 4217 } 4218 for (Slice &S : P) { 4219 Promotable &= Rewriter.visit(&S); 4220 ++NumUses; 4221 } 4222 4223 NumAllocaPartitionUses += NumUses; 4224 MaxUsesPerAllocaPartition.updateMax(NumUses); 4225 4226 // Now that we've processed all the slices in the new partition, check if any 4227 // PHIs or Selects would block promotion. 4228 for (PHINode *PHI : PHIUsers) 4229 if (!isSafePHIToSpeculate(*PHI)) { 4230 Promotable = false; 4231 PHIUsers.clear(); 4232 SelectUsers.clear(); 4233 break; 4234 } 4235 4236 for (SelectInst *Sel : SelectUsers) 4237 if (!isSafeSelectToSpeculate(*Sel)) { 4238 Promotable = false; 4239 PHIUsers.clear(); 4240 SelectUsers.clear(); 4241 break; 4242 } 4243 4244 if (Promotable) { 4245 if (PHIUsers.empty() && SelectUsers.empty()) { 4246 // Promote the alloca. 4247 PromotableAllocas.push_back(NewAI); 4248 } else { 4249 // If we have either PHIs or Selects to speculate, add them to those 4250 // worklists and re-queue the new alloca so that we promote in on the 4251 // next iteration. 4252 for (PHINode *PHIUser : PHIUsers) 4253 SpeculatablePHIs.insert(PHIUser); 4254 for (SelectInst *SelectUser : SelectUsers) 4255 SpeculatableSelects.insert(SelectUser); 4256 Worklist.insert(NewAI); 4257 } 4258 } else { 4259 // Drop any post-promotion work items if promotion didn't happen. 4260 while (PostPromotionWorklist.size() > PPWOldSize) 4261 PostPromotionWorklist.pop_back(); 4262 4263 // We couldn't promote and we didn't create a new partition, nothing 4264 // happened. 4265 if (NewAI == &AI) 4266 return nullptr; 4267 4268 // If we can't promote the alloca, iterate on it to check for new 4269 // refinements exposed by splitting the current alloca. Don't iterate on an 4270 // alloca which didn't actually change and didn't get promoted. 4271 Worklist.insert(NewAI); 4272 } 4273 4274 return NewAI; 4275 } 4276 4277 /// Walks the slices of an alloca and form partitions based on them, 4278 /// rewriting each of their uses. 4279 bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) { 4280 if (AS.begin() == AS.end()) 4281 return false; 4282 4283 unsigned NumPartitions = 0; 4284 bool Changed = false; 4285 const DataLayout &DL = AI.getModule()->getDataLayout(); 4286 4287 // First try to pre-split loads and stores. 4288 Changed |= presplitLoadsAndStores(AI, AS); 4289 4290 // Now that we have identified any pre-splitting opportunities, 4291 // mark loads and stores unsplittable except for the following case. 4292 // We leave a slice splittable if all other slices are disjoint or fully 4293 // included in the slice, such as whole-alloca loads and stores. 4294 // If we fail to split these during pre-splitting, we want to force them 4295 // to be rewritten into a partition. 4296 bool IsSorted = true; 4297 4298 uint64_t AllocaSize = 4299 DL.getTypeAllocSize(AI.getAllocatedType()).getFixedSize(); 4300 const uint64_t MaxBitVectorSize = 1024; 4301 if (AllocaSize <= MaxBitVectorSize) { 4302 // If a byte boundary is included in any load or store, a slice starting or 4303 // ending at the boundary is not splittable. 4304 SmallBitVector SplittableOffset(AllocaSize + 1, true); 4305 for (Slice &S : AS) 4306 for (unsigned O = S.beginOffset() + 1; 4307 O < S.endOffset() && O < AllocaSize; O++) 4308 SplittableOffset.reset(O); 4309 4310 for (Slice &S : AS) { 4311 if (!S.isSplittable()) 4312 continue; 4313 4314 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) && 4315 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()])) 4316 continue; 4317 4318 if (isa<LoadInst>(S.getUse()->getUser()) || 4319 isa<StoreInst>(S.getUse()->getUser())) { 4320 S.makeUnsplittable(); 4321 IsSorted = false; 4322 } 4323 } 4324 } 4325 else { 4326 // We only allow whole-alloca splittable loads and stores 4327 // for a large alloca to avoid creating too large BitVector. 4328 for (Slice &S : AS) { 4329 if (!S.isSplittable()) 4330 continue; 4331 4332 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize) 4333 continue; 4334 4335 if (isa<LoadInst>(S.getUse()->getUser()) || 4336 isa<StoreInst>(S.getUse()->getUser())) { 4337 S.makeUnsplittable(); 4338 IsSorted = false; 4339 } 4340 } 4341 } 4342 4343 if (!IsSorted) 4344 llvm::sort(AS); 4345 4346 /// Describes the allocas introduced by rewritePartition in order to migrate 4347 /// the debug info. 4348 struct Fragment { 4349 AllocaInst *Alloca; 4350 uint64_t Offset; 4351 uint64_t Size; 4352 Fragment(AllocaInst *AI, uint64_t O, uint64_t S) 4353 : Alloca(AI), Offset(O), Size(S) {} 4354 }; 4355 SmallVector<Fragment, 4> Fragments; 4356 4357 // Rewrite each partition. 4358 for (auto &P : AS.partitions()) { 4359 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) { 4360 Changed = true; 4361 if (NewAI != &AI) { 4362 uint64_t SizeOfByte = 8; 4363 uint64_t AllocaSize = 4364 DL.getTypeSizeInBits(NewAI->getAllocatedType()).getFixedSize(); 4365 // Don't include any padding. 4366 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte); 4367 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size)); 4368 } 4369 } 4370 ++NumPartitions; 4371 } 4372 4373 NumAllocaPartitions += NumPartitions; 4374 MaxPartitionsPerAlloca.updateMax(NumPartitions); 4375 4376 // Migrate debug information from the old alloca to the new alloca(s) 4377 // and the individual partitions. 4378 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI); 4379 if (!DbgDeclares.empty()) { 4380 auto *Var = DbgDeclares.front()->getVariable(); 4381 auto *Expr = DbgDeclares.front()->getExpression(); 4382 auto VarSize = Var->getSizeInBits(); 4383 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false); 4384 uint64_t AllocaSize = 4385 DL.getTypeSizeInBits(AI.getAllocatedType()).getFixedSize(); 4386 for (auto Fragment : Fragments) { 4387 // Create a fragment expression describing the new partition or reuse AI's 4388 // expression if there is only one partition. 4389 auto *FragmentExpr = Expr; 4390 if (Fragment.Size < AllocaSize || Expr->isFragment()) { 4391 // If this alloca is already a scalar replacement of a larger aggregate, 4392 // Fragment.Offset describes the offset inside the scalar. 4393 auto ExprFragment = Expr->getFragmentInfo(); 4394 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0; 4395 uint64_t Start = Offset + Fragment.Offset; 4396 uint64_t Size = Fragment.Size; 4397 if (ExprFragment) { 4398 uint64_t AbsEnd = 4399 ExprFragment->OffsetInBits + ExprFragment->SizeInBits; 4400 if (Start >= AbsEnd) 4401 // No need to describe a SROAed padding. 4402 continue; 4403 Size = std::min(Size, AbsEnd - Start); 4404 } 4405 // The new, smaller fragment is stenciled out from the old fragment. 4406 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) { 4407 assert(Start >= OrigFragment->OffsetInBits && 4408 "new fragment is outside of original fragment"); 4409 Start -= OrigFragment->OffsetInBits; 4410 } 4411 4412 // The alloca may be larger than the variable. 4413 if (VarSize) { 4414 if (Size > *VarSize) 4415 Size = *VarSize; 4416 if (Size == 0 || Start + Size > *VarSize) 4417 continue; 4418 } 4419 4420 // Avoid creating a fragment expression that covers the entire variable. 4421 if (!VarSize || *VarSize != Size) { 4422 if (auto E = 4423 DIExpression::createFragmentExpression(Expr, Start, Size)) 4424 FragmentExpr = *E; 4425 else 4426 continue; 4427 } 4428 } 4429 4430 // Remove any existing intrinsics describing the same alloca. 4431 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca)) 4432 OldDII->eraseFromParent(); 4433 4434 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr, 4435 DbgDeclares.front()->getDebugLoc(), &AI); 4436 } 4437 } 4438 return Changed; 4439 } 4440 4441 /// Clobber a use with undef, deleting the used value if it becomes dead. 4442 void SROA::clobberUse(Use &U) { 4443 Value *OldV = U; 4444 // Replace the use with an undef value. 4445 U = UndefValue::get(OldV->getType()); 4446 4447 // Check for this making an instruction dead. We have to garbage collect 4448 // all the dead instructions to ensure the uses of any alloca end up being 4449 // minimal. 4450 if (Instruction *OldI = dyn_cast<Instruction>(OldV)) 4451 if (isInstructionTriviallyDead(OldI)) { 4452 DeadInsts.insert(OldI); 4453 } 4454 } 4455 4456 /// Analyze an alloca for SROA. 4457 /// 4458 /// This analyzes the alloca to ensure we can reason about it, builds 4459 /// the slices of the alloca, and then hands it off to be split and 4460 /// rewritten as needed. 4461 bool SROA::runOnAlloca(AllocaInst &AI) { 4462 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n"); 4463 ++NumAllocasAnalyzed; 4464 4465 // Special case dead allocas, as they're trivial. 4466 if (AI.use_empty()) { 4467 AI.eraseFromParent(); 4468 return true; 4469 } 4470 const DataLayout &DL = AI.getModule()->getDataLayout(); 4471 4472 // Skip alloca forms that this analysis can't handle. 4473 auto *AT = AI.getAllocatedType(); 4474 if (AI.isArrayAllocation() || !AT->isSized() || 4475 (isa<VectorType>(AT) && cast<VectorType>(AT)->isScalable()) || 4476 DL.getTypeAllocSize(AT).getFixedSize() == 0) 4477 return false; 4478 4479 bool Changed = false; 4480 4481 // First, split any FCA loads and stores touching this alloca to promote 4482 // better splitting and promotion opportunities. 4483 AggLoadStoreRewriter AggRewriter(DL); 4484 Changed |= AggRewriter.rewrite(AI); 4485 4486 // Build the slices using a recursive instruction-visiting builder. 4487 AllocaSlices AS(DL, AI); 4488 LLVM_DEBUG(AS.print(dbgs())); 4489 if (AS.isEscaped()) 4490 return Changed; 4491 4492 // Delete all the dead users of this alloca before splitting and rewriting it. 4493 for (Instruction *DeadUser : AS.getDeadUsers()) { 4494 // Free up everything used by this instruction. 4495 for (Use &DeadOp : DeadUser->operands()) 4496 clobberUse(DeadOp); 4497 4498 // Now replace the uses of this instruction. 4499 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType())); 4500 4501 // And mark it for deletion. 4502 DeadInsts.insert(DeadUser); 4503 Changed = true; 4504 } 4505 for (Use *DeadOp : AS.getDeadOperands()) { 4506 clobberUse(*DeadOp); 4507 Changed = true; 4508 } 4509 4510 // No slices to split. Leave the dead alloca for a later pass to clean up. 4511 if (AS.begin() == AS.end()) 4512 return Changed; 4513 4514 Changed |= splitAlloca(AI, AS); 4515 4516 LLVM_DEBUG(dbgs() << " Speculating PHIs\n"); 4517 while (!SpeculatablePHIs.empty()) 4518 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val()); 4519 4520 LLVM_DEBUG(dbgs() << " Speculating Selects\n"); 4521 while (!SpeculatableSelects.empty()) 4522 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val()); 4523 4524 return Changed; 4525 } 4526 4527 /// Delete the dead instructions accumulated in this run. 4528 /// 4529 /// Recursively deletes the dead instructions we've accumulated. This is done 4530 /// at the very end to maximize locality of the recursive delete and to 4531 /// minimize the problems of invalidated instruction pointers as such pointers 4532 /// are used heavily in the intermediate stages of the algorithm. 4533 /// 4534 /// We also record the alloca instructions deleted here so that they aren't 4535 /// subsequently handed to mem2reg to promote. 4536 bool SROA::deleteDeadInstructions( 4537 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) { 4538 bool Changed = false; 4539 while (!DeadInsts.empty()) { 4540 Instruction *I = DeadInsts.pop_back_val(); 4541 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n"); 4542 4543 // If the instruction is an alloca, find the possible dbg.declare connected 4544 // to it, and remove it too. We must do this before calling RAUW or we will 4545 // not be able to find it. 4546 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { 4547 DeletedAllocas.insert(AI); 4548 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI)) 4549 OldDII->eraseFromParent(); 4550 } 4551 4552 I->replaceAllUsesWith(UndefValue::get(I->getType())); 4553 4554 for (Use &Operand : I->operands()) 4555 if (Instruction *U = dyn_cast<Instruction>(Operand)) { 4556 // Zero out the operand and see if it becomes trivially dead. 4557 Operand = nullptr; 4558 if (isInstructionTriviallyDead(U)) 4559 DeadInsts.insert(U); 4560 } 4561 4562 ++NumDeleted; 4563 I->eraseFromParent(); 4564 Changed = true; 4565 } 4566 return Changed; 4567 } 4568 4569 /// Promote the allocas, using the best available technique. 4570 /// 4571 /// This attempts to promote whatever allocas have been identified as viable in 4572 /// the PromotableAllocas list. If that list is empty, there is nothing to do. 4573 /// This function returns whether any promotion occurred. 4574 bool SROA::promoteAllocas(Function &F) { 4575 if (PromotableAllocas.empty()) 4576 return false; 4577 4578 NumPromoted += PromotableAllocas.size(); 4579 4580 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n"); 4581 PromoteMemToReg(PromotableAllocas, *DT, AC); 4582 PromotableAllocas.clear(); 4583 return true; 4584 } 4585 4586 PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT, 4587 AssumptionCache &RunAC) { 4588 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n"); 4589 C = &F.getContext(); 4590 DT = &RunDT; 4591 AC = &RunAC; 4592 4593 BasicBlock &EntryBB = F.getEntryBlock(); 4594 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end()); 4595 I != E; ++I) { 4596 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) { 4597 if (isa<VectorType>(AI->getAllocatedType()) && 4598 cast<VectorType>(AI->getAllocatedType())->isScalable()) { 4599 if (isAllocaPromotable(AI)) 4600 PromotableAllocas.push_back(AI); 4601 } else { 4602 Worklist.insert(AI); 4603 } 4604 } 4605 } 4606 4607 bool Changed = false; 4608 // A set of deleted alloca instruction pointers which should be removed from 4609 // the list of promotable allocas. 4610 SmallPtrSet<AllocaInst *, 4> DeletedAllocas; 4611 4612 do { 4613 while (!Worklist.empty()) { 4614 Changed |= runOnAlloca(*Worklist.pop_back_val()); 4615 Changed |= deleteDeadInstructions(DeletedAllocas); 4616 4617 // Remove the deleted allocas from various lists so that we don't try to 4618 // continue processing them. 4619 if (!DeletedAllocas.empty()) { 4620 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); }; 4621 Worklist.remove_if(IsInSet); 4622 PostPromotionWorklist.remove_if(IsInSet); 4623 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet), 4624 PromotableAllocas.end()); 4625 DeletedAllocas.clear(); 4626 } 4627 } 4628 4629 Changed |= promoteAllocas(F); 4630 4631 Worklist = PostPromotionWorklist; 4632 PostPromotionWorklist.clear(); 4633 } while (!Worklist.empty()); 4634 4635 if (!Changed) 4636 return PreservedAnalyses::all(); 4637 4638 PreservedAnalyses PA; 4639 PA.preserveSet<CFGAnalyses>(); 4640 PA.preserve<GlobalsAA>(); 4641 return PA; 4642 } 4643 4644 PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) { 4645 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F), 4646 AM.getResult<AssumptionAnalysis>(F)); 4647 } 4648 4649 /// A legacy pass for the legacy pass manager that wraps the \c SROA pass. 4650 /// 4651 /// This is in the llvm namespace purely to allow it to be a friend of the \c 4652 /// SROA pass. 4653 class llvm::sroa::SROALegacyPass : public FunctionPass { 4654 /// The SROA implementation. 4655 SROA Impl; 4656 4657 public: 4658 static char ID; 4659 4660 SROALegacyPass() : FunctionPass(ID) { 4661 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry()); 4662 } 4663 4664 bool runOnFunction(Function &F) override { 4665 if (skipFunction(F)) 4666 return false; 4667 4668 auto PA = Impl.runImpl( 4669 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(), 4670 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 4671 return !PA.areAllPreserved(); 4672 } 4673 4674 void getAnalysisUsage(AnalysisUsage &AU) const override { 4675 AU.addRequired<AssumptionCacheTracker>(); 4676 AU.addRequired<DominatorTreeWrapperPass>(); 4677 AU.addPreserved<GlobalsAAWrapperPass>(); 4678 AU.setPreservesCFG(); 4679 } 4680 4681 StringRef getPassName() const override { return "SROA"; } 4682 }; 4683 4684 char SROALegacyPass::ID = 0; 4685 4686 FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); } 4687 4688 INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa", 4689 "Scalar Replacement Of Aggregates", false, false) 4690 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4691 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 4692 INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates", 4693 false, false) 4694