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