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