Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1 | //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | /// \file |
| 10 | /// This transformation implements the well known scalar replacement of |
| 11 | /// aggregates transformation. It tries to identify promotable elements of an |
| 12 | /// aggregate alloca, and promote them to registers. It will also try to |
| 13 | /// convert uses of an element (or set of elements) of an alloca into a vector |
| 14 | /// or bitfield-style integer scalar if appropriate. |
| 15 | /// |
| 16 | /// It works to do this with minimal slicing of the alloca so that regions |
| 17 | /// which are merely transferred in and out of external memory remain unchanged |
| 18 | /// and are not decomposed to scalar code. |
| 19 | /// |
| 20 | /// Because this also performs alloca promotion, it can be thought of as also |
| 21 | /// serving the purpose of SSA formation. The algorithm iterates on the |
| 22 | /// function until all opportunities for promotion have been realized. |
| 23 | /// |
| 24 | //===----------------------------------------------------------------------===// |
| 25 | |
| 26 | #define DEBUG_TYPE "sroa" |
| 27 | #include "llvm/Transforms/Scalar.h" |
| 28 | #include "llvm/Constants.h" |
| 29 | #include "llvm/DIBuilder.h" |
| 30 | #include "llvm/DebugInfo.h" |
| 31 | #include "llvm/DerivedTypes.h" |
| 32 | #include "llvm/Function.h" |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 33 | #include "llvm/IRBuilder.h" |
| 34 | #include "llvm/Instructions.h" |
| 35 | #include "llvm/IntrinsicInst.h" |
| 36 | #include "llvm/LLVMContext.h" |
| 37 | #include "llvm/Module.h" |
| 38 | #include "llvm/Operator.h" |
| 39 | #include "llvm/Pass.h" |
| 40 | #include "llvm/ADT/SetVector.h" |
| 41 | #include "llvm/ADT/SmallVector.h" |
| 42 | #include "llvm/ADT/Statistic.h" |
| 43 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 44 | #include "llvm/Analysis/Dominators.h" |
| 45 | #include "llvm/Analysis/Loads.h" |
| 46 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 47 | #include "llvm/Support/CommandLine.h" |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 48 | #include "llvm/Support/Debug.h" |
| 49 | #include "llvm/Support/ErrorHandling.h" |
| 50 | #include "llvm/Support/GetElementPtrTypeIterator.h" |
| 51 | #include "llvm/Support/InstVisitor.h" |
| 52 | #include "llvm/Support/MathExtras.h" |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 53 | #include "llvm/Support/raw_ostream.h" |
| 54 | #include "llvm/Target/TargetData.h" |
| 55 | #include "llvm/Transforms/Utils/Local.h" |
| 56 | #include "llvm/Transforms/Utils/PromoteMemToReg.h" |
| 57 | #include "llvm/Transforms/Utils/SSAUpdater.h" |
| 58 | using namespace llvm; |
| 59 | |
| 60 | STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement"); |
| 61 | STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced"); |
| 62 | STATISTIC(NumPromoted, "Number of allocas promoted to SSA values"); |
| 63 | STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion"); |
| 64 | STATISTIC(NumDeleted, "Number of instructions deleted"); |
| 65 | STATISTIC(NumVectorized, "Number of vectorized aggregates"); |
| 66 | |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 67 | /// Hidden option to force the pass to not use DomTree and mem2reg, instead |
| 68 | /// forming SSA values through the SSAUpdater infrastructure. |
| 69 | static cl::opt<bool> |
| 70 | ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden); |
| 71 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 72 | namespace { |
| 73 | /// \brief Alloca partitioning representation. |
| 74 | /// |
| 75 | /// This class represents a partitioning of an alloca into slices, and |
| 76 | /// information about the nature of uses of each slice of the alloca. The goal |
| 77 | /// is that this information is sufficient to decide if and how to split the |
| 78 | /// alloca apart and replace slices with scalars. It is also intended that this |
Chandler Carruth | 7f5bede | 2012-09-14 10:18:49 +0000 | [diff] [blame] | 79 | /// structure can capture the relevant information needed both to decide about |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 80 | /// and to enact these transformations. |
| 81 | class AllocaPartitioning { |
| 82 | public: |
| 83 | /// \brief A common base class for representing a half-open byte range. |
| 84 | struct ByteRange { |
| 85 | /// \brief The beginning offset of the range. |
| 86 | uint64_t BeginOffset; |
| 87 | |
| 88 | /// \brief The ending offset, not included in the range. |
| 89 | uint64_t EndOffset; |
| 90 | |
| 91 | ByteRange() : BeginOffset(), EndOffset() {} |
| 92 | ByteRange(uint64_t BeginOffset, uint64_t EndOffset) |
| 93 | : BeginOffset(BeginOffset), EndOffset(EndOffset) {} |
| 94 | |
| 95 | /// \brief Support for ordering ranges. |
| 96 | /// |
| 97 | /// This provides an ordering over ranges such that start offsets are |
| 98 | /// always increasing, and within equal start offsets, the end offsets are |
Chandler Carruth | 7f5bede | 2012-09-14 10:18:49 +0000 | [diff] [blame] | 99 | /// decreasing. Thus the spanning range comes first in a cluster with the |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 100 | /// same start position. |
| 101 | bool operator<(const ByteRange &RHS) const { |
| 102 | if (BeginOffset < RHS.BeginOffset) return true; |
| 103 | if (BeginOffset > RHS.BeginOffset) return false; |
| 104 | if (EndOffset > RHS.EndOffset) return true; |
| 105 | return false; |
| 106 | } |
| 107 | |
| 108 | /// \brief Support comparison with a single offset to allow binary searches. |
Benjamin Kramer | 2d1c2a2 | 2012-09-17 16:42:36 +0000 | [diff] [blame] | 109 | friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) { |
| 110 | return LHS.BeginOffset < RHSOffset; |
| 111 | } |
| 112 | |
| 113 | friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset, |
| 114 | const ByteRange &RHS) { |
| 115 | return LHSOffset < RHS.BeginOffset; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 116 | } |
| 117 | |
| 118 | bool operator==(const ByteRange &RHS) const { |
| 119 | return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset; |
| 120 | } |
| 121 | bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); } |
| 122 | }; |
| 123 | |
| 124 | /// \brief A partition of an alloca. |
| 125 | /// |
| 126 | /// This structure represents a contiguous partition of the alloca. These are |
| 127 | /// formed by examining the uses of the alloca. During formation, they may |
| 128 | /// overlap but once an AllocaPartitioning is built, the Partitions within it |
| 129 | /// are all disjoint. |
| 130 | struct Partition : public ByteRange { |
| 131 | /// \brief Whether this partition is splittable into smaller partitions. |
| 132 | /// |
| 133 | /// We flag partitions as splittable when they are formed entirely due to |
Chandler Carruth | 7f5bede | 2012-09-14 10:18:49 +0000 | [diff] [blame] | 134 | /// accesses by trivially splittable operations such as memset and memcpy. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 135 | /// |
| 136 | /// FIXME: At some point we should consider loads and stores of FCAs to be |
| 137 | /// splittable and eagerly split them into scalar values. |
| 138 | bool IsSplittable; |
| 139 | |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 140 | /// \brief Test whether a partition has been marked as dead. |
| 141 | bool isDead() const { |
| 142 | if (BeginOffset == UINT64_MAX) { |
| 143 | assert(EndOffset == UINT64_MAX); |
| 144 | return true; |
| 145 | } |
| 146 | return false; |
| 147 | } |
| 148 | |
| 149 | /// \brief Kill a partition. |
| 150 | /// This is accomplished by setting both its beginning and end offset to |
| 151 | /// the maximum possible value. |
| 152 | void kill() { |
| 153 | assert(!isDead() && "He's Dead, Jim!"); |
| 154 | BeginOffset = EndOffset = UINT64_MAX; |
| 155 | } |
| 156 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 157 | Partition() : ByteRange(), IsSplittable() {} |
| 158 | Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable) |
| 159 | : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {} |
| 160 | }; |
| 161 | |
| 162 | /// \brief A particular use of a partition of the alloca. |
| 163 | /// |
| 164 | /// This structure is used to associate uses of a partition with it. They |
| 165 | /// mark the range of bytes which are referenced by a particular instruction, |
| 166 | /// and includes a handle to the user itself and the pointer value in use. |
| 167 | /// The bounds of these uses are determined by intersecting the bounds of the |
| 168 | /// memory use itself with a particular partition. As a consequence there is |
Chandler Carruth | 7f5bede | 2012-09-14 10:18:49 +0000 | [diff] [blame] | 169 | /// intentionally overlap between various uses of the same partition. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 170 | struct PartitionUse : public ByteRange { |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 171 | /// \brief The use in question. Provides access to both user and used value. |
Chandler Carruth | fdb1585 | 2012-10-02 18:57:13 +0000 | [diff] [blame] | 172 | /// |
| 173 | /// Note that this may be null if the partition use is *dead*, that is, it |
| 174 | /// should be ignored. |
| 175 | Use *U; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 176 | |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 177 | PartitionUse() : ByteRange(), U() {} |
| 178 | PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U) |
| 179 | : ByteRange(BeginOffset, EndOffset), U(U) {} |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 180 | }; |
| 181 | |
| 182 | /// \brief Construct a partitioning of a particular alloca. |
| 183 | /// |
| 184 | /// Construction does most of the work for partitioning the alloca. This |
| 185 | /// performs the necessary walks of users and builds a partitioning from it. |
| 186 | AllocaPartitioning(const TargetData &TD, AllocaInst &AI); |
| 187 | |
| 188 | /// \brief Test whether a pointer to the allocation escapes our analysis. |
| 189 | /// |
| 190 | /// If this is true, the partitioning is never fully built and should be |
| 191 | /// ignored. |
| 192 | bool isEscaped() const { return PointerEscapingInstr; } |
| 193 | |
| 194 | /// \brief Support for iterating over the partitions. |
| 195 | /// @{ |
| 196 | typedef SmallVectorImpl<Partition>::iterator iterator; |
| 197 | iterator begin() { return Partitions.begin(); } |
| 198 | iterator end() { return Partitions.end(); } |
| 199 | |
| 200 | typedef SmallVectorImpl<Partition>::const_iterator const_iterator; |
| 201 | const_iterator begin() const { return Partitions.begin(); } |
| 202 | const_iterator end() const { return Partitions.end(); } |
| 203 | /// @} |
| 204 | |
| 205 | /// \brief Support for iterating over and manipulating a particular |
| 206 | /// partition's uses. |
| 207 | /// |
| 208 | /// The iteration support provided for uses is more limited, but also |
| 209 | /// includes some manipulation routines to support rewriting the uses of |
| 210 | /// partitions during SROA. |
| 211 | /// @{ |
| 212 | typedef SmallVectorImpl<PartitionUse>::iterator use_iterator; |
| 213 | use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); } |
| 214 | use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); } |
| 215 | use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); } |
| 216 | use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); } |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 217 | |
| 218 | typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator; |
| 219 | const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); } |
| 220 | const_use_iterator use_begin(const_iterator I) const { |
| 221 | return Uses[I - begin()].begin(); |
| 222 | } |
| 223 | const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); } |
| 224 | const_use_iterator use_end(const_iterator I) const { |
| 225 | return Uses[I - begin()].end(); |
| 226 | } |
Chandler Carruth | a346f46 | 2012-10-02 17:49:47 +0000 | [diff] [blame] | 227 | |
| 228 | unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); } |
| 229 | unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); } |
| 230 | const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const { |
| 231 | return Uses[PIdx][UIdx]; |
| 232 | } |
| 233 | const PartitionUse &getUse(const_iterator I, unsigned UIdx) const { |
| 234 | return Uses[I - begin()][UIdx]; |
| 235 | } |
| 236 | |
| 237 | void use_push_back(unsigned Idx, const PartitionUse &PU) { |
| 238 | Uses[Idx].push_back(PU); |
| 239 | } |
| 240 | void use_push_back(const_iterator I, const PartitionUse &PU) { |
| 241 | Uses[I - begin()].push_back(PU); |
| 242 | } |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 243 | /// @} |
| 244 | |
| 245 | /// \brief Allow iterating the dead users for this alloca. |
| 246 | /// |
| 247 | /// These are instructions which will never actually use the alloca as they |
| 248 | /// are outside the allocated range. They are safe to replace with undef and |
| 249 | /// delete. |
| 250 | /// @{ |
| 251 | typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator; |
| 252 | dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); } |
| 253 | dead_user_iterator dead_user_end() const { return DeadUsers.end(); } |
| 254 | /// @} |
| 255 | |
Chandler Carruth | 7f5bede | 2012-09-14 10:18:49 +0000 | [diff] [blame] | 256 | /// \brief Allow iterating the dead expressions referring to this alloca. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 257 | /// |
| 258 | /// These are operands which have cannot actually be used to refer to the |
| 259 | /// alloca as they are outside its range and the user doesn't correct for |
| 260 | /// that. These mostly consist of PHI node inputs and the like which we just |
| 261 | /// need to replace with undef. |
| 262 | /// @{ |
| 263 | typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator; |
| 264 | dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); } |
| 265 | dead_op_iterator dead_op_end() const { return DeadOperands.end(); } |
| 266 | /// @} |
| 267 | |
| 268 | /// \brief MemTransferInst auxiliary data. |
| 269 | /// This struct provides some auxiliary data about memory transfer |
| 270 | /// intrinsics such as memcpy and memmove. These intrinsics can use two |
| 271 | /// different ranges within the same alloca, and provide other challenges to |
| 272 | /// correctly represent. We stash extra data to help us untangle this |
| 273 | /// after the partitioning is complete. |
| 274 | struct MemTransferOffsets { |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 275 | /// The destination begin and end offsets when the destination is within |
| 276 | /// this alloca. If the end offset is zero the destination is not within |
| 277 | /// this alloca. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 278 | uint64_t DestBegin, DestEnd; |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 279 | |
| 280 | /// The source begin and end offsets when the source is within this alloca. |
| 281 | /// If the end offset is zero, the source is not within this alloca. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 282 | uint64_t SourceBegin, SourceEnd; |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 283 | |
| 284 | /// Flag for whether an alloca is splittable. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 285 | bool IsSplittable; |
| 286 | }; |
| 287 | MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const { |
| 288 | return MemTransferInstData.lookup(&II); |
| 289 | } |
| 290 | |
| 291 | /// \brief Map from a PHI or select operand back to a partition. |
| 292 | /// |
| 293 | /// When manipulating PHI nodes or selects, they can use more than one |
| 294 | /// partition of an alloca. We store a special mapping to allow finding the |
| 295 | /// partition referenced by each of these operands, if any. |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 296 | iterator findPartitionForPHIOrSelectOperand(Use *U) { |
| 297 | SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt |
| 298 | = PHIOrSelectOpMap.find(U); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 299 | if (MapIt == PHIOrSelectOpMap.end()) |
| 300 | return end(); |
| 301 | |
| 302 | return begin() + MapIt->second.first; |
| 303 | } |
| 304 | |
| 305 | /// \brief Map from a PHI or select operand back to the specific use of |
| 306 | /// a partition. |
| 307 | /// |
| 308 | /// Similar to mapping these operands back to the partitions, this maps |
| 309 | /// directly to the use structure of that partition. |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 310 | use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) { |
| 311 | SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt |
| 312 | = PHIOrSelectOpMap.find(U); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 313 | assert(MapIt != PHIOrSelectOpMap.end()); |
| 314 | return Uses[MapIt->second.first].begin() + MapIt->second.second; |
| 315 | } |
| 316 | |
| 317 | /// \brief Compute a common type among the uses of a particular partition. |
| 318 | /// |
| 319 | /// This routines walks all of the uses of a particular partition and tries |
| 320 | /// to find a common type between them. Untyped operations such as memset and |
| 321 | /// memcpy are ignored. |
| 322 | Type *getCommonType(iterator I) const; |
| 323 | |
Chandler Carruth | ba13d2e | 2012-09-14 10:18:51 +0000 | [diff] [blame] | 324 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 325 | void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const; |
| 326 | void printUsers(raw_ostream &OS, const_iterator I, |
| 327 | StringRef Indent = " ") const; |
| 328 | void print(raw_ostream &OS) const; |
NAKAMURA Takumi | ad9f5b8 | 2012-09-14 10:06:10 +0000 | [diff] [blame] | 329 | void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const; |
| 330 | void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const; |
Chandler Carruth | ba13d2e | 2012-09-14 10:18:51 +0000 | [diff] [blame] | 331 | #endif |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 332 | |
| 333 | private: |
| 334 | template <typename DerivedT, typename RetT = void> class BuilderBase; |
| 335 | class PartitionBuilder; |
| 336 | friend class AllocaPartitioning::PartitionBuilder; |
| 337 | class UseBuilder; |
| 338 | friend class AllocaPartitioning::UseBuilder; |
| 339 | |
Benjamin Kramer | d080769 | 2012-09-14 13:08:09 +0000 | [diff] [blame] | 340 | #ifndef NDEBUG |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 341 | /// \brief Handle to alloca instruction to simplify method interfaces. |
| 342 | AllocaInst &AI; |
Benjamin Kramer | d080769 | 2012-09-14 13:08:09 +0000 | [diff] [blame] | 343 | #endif |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 344 | |
| 345 | /// \brief The instruction responsible for this alloca having no partitioning. |
| 346 | /// |
| 347 | /// When an instruction (potentially) escapes the pointer to the alloca, we |
| 348 | /// store a pointer to that here and abort trying to partition the alloca. |
| 349 | /// This will be null if the alloca is partitioned successfully. |
| 350 | Instruction *PointerEscapingInstr; |
| 351 | |
| 352 | /// \brief The partitions of the alloca. |
| 353 | /// |
| 354 | /// We store a vector of the partitions over the alloca here. This vector is |
| 355 | /// sorted by increasing begin offset, and then by decreasing end offset. See |
Chandler Carruth | 7f5bede | 2012-09-14 10:18:49 +0000 | [diff] [blame] | 356 | /// the Partition inner class for more details. Initially (during |
| 357 | /// construction) there are overlaps, but we form a disjoint sequence of |
| 358 | /// partitions while finishing construction and a fully constructed object is |
| 359 | /// expected to always have this as a disjoint space. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 360 | SmallVector<Partition, 8> Partitions; |
| 361 | |
| 362 | /// \brief The uses of the partitions. |
| 363 | /// |
| 364 | /// This is essentially a mapping from each partition to a list of uses of |
| 365 | /// that partition. The mapping is done with a Uses vector that has the exact |
| 366 | /// same number of entries as the partition vector. Each entry is itself |
| 367 | /// a vector of the uses. |
| 368 | SmallVector<SmallVector<PartitionUse, 2>, 8> Uses; |
| 369 | |
| 370 | /// \brief Instructions which will become dead if we rewrite the alloca. |
| 371 | /// |
| 372 | /// Note that these are not separated by partition. This is because we expect |
| 373 | /// a partitioned alloca to be completely rewritten or not rewritten at all. |
| 374 | /// If rewritten, all these instructions can simply be removed and replaced |
| 375 | /// with undef as they come from outside of the allocated space. |
| 376 | SmallVector<Instruction *, 8> DeadUsers; |
| 377 | |
| 378 | /// \brief Operands which will become dead if we rewrite the alloca. |
| 379 | /// |
| 380 | /// These are operands that in their particular use can be replaced with |
| 381 | /// undef when we rewrite the alloca. These show up in out-of-bounds inputs |
| 382 | /// to PHI nodes and the like. They aren't entirely dead (there might be |
| 383 | /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we |
| 384 | /// want to swap this particular input for undef to simplify the use lists of |
| 385 | /// the alloca. |
| 386 | SmallVector<Use *, 8> DeadOperands; |
| 387 | |
| 388 | /// \brief The underlying storage for auxiliary memcpy and memset info. |
| 389 | SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData; |
| 390 | |
| 391 | /// \brief A side datastructure used when building up the partitions and uses. |
| 392 | /// |
| 393 | /// This mapping is only really used during the initial building of the |
| 394 | /// partitioning so that we can retain information about PHI and select nodes |
| 395 | /// processed. |
| 396 | SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes; |
| 397 | |
| 398 | /// \brief Auxiliary information for particular PHI or select operands. |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 399 | SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 400 | |
| 401 | /// \brief A utility routine called from the constructor. |
| 402 | /// |
| 403 | /// This does what it says on the tin. It is the key of the alloca partition |
| 404 | /// splitting and merging. After it is called we have the desired disjoint |
| 405 | /// collection of partitions. |
| 406 | void splitAndMergePartitions(); |
| 407 | }; |
| 408 | } |
| 409 | |
| 410 | template <typename DerivedT, typename RetT> |
| 411 | class AllocaPartitioning::BuilderBase |
| 412 | : public InstVisitor<DerivedT, RetT> { |
| 413 | public: |
| 414 | BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P) |
| 415 | : TD(TD), |
| 416 | AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())), |
| 417 | P(P) { |
| 418 | enqueueUsers(AI, 0); |
| 419 | } |
| 420 | |
| 421 | protected: |
| 422 | const TargetData &TD; |
| 423 | const uint64_t AllocSize; |
| 424 | AllocaPartitioning &P; |
| 425 | |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 426 | SmallPtrSet<Use *, 8> VisitedUses; |
| 427 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 428 | struct OffsetUse { |
| 429 | Use *U; |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 430 | int64_t Offset; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 431 | }; |
| 432 | SmallVector<OffsetUse, 8> Queue; |
| 433 | |
| 434 | // The active offset and use while visiting. |
| 435 | Use *U; |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 436 | int64_t Offset; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 437 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 438 | void enqueueUsers(Instruction &I, int64_t UserOffset) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 439 | for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); |
| 440 | UI != UE; ++UI) { |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 441 | if (VisitedUses.insert(&UI.getUse())) { |
| 442 | OffsetUse OU = { &UI.getUse(), UserOffset }; |
| 443 | Queue.push_back(OU); |
| 444 | } |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 445 | } |
| 446 | } |
| 447 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 448 | bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 449 | GEPOffset = Offset; |
| 450 | for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI); |
| 451 | GTI != GTE; ++GTI) { |
| 452 | ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); |
| 453 | if (!OpC) |
| 454 | return false; |
| 455 | if (OpC->isZero()) |
| 456 | continue; |
| 457 | |
| 458 | // Handle a struct index, which adds its field offset to the pointer. |
| 459 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 460 | unsigned ElementIdx = OpC->getZExtValue(); |
| 461 | const StructLayout *SL = TD.getStructLayout(STy); |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 462 | uint64_t ElementOffset = SL->getElementOffset(ElementIdx); |
| 463 | // Check that we can continue to model this GEP in a signed 64-bit offset. |
| 464 | if (ElementOffset > INT64_MAX || |
| 465 | (GEPOffset >= 0 && |
| 466 | ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) { |
| 467 | DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding " |
| 468 | << "what can be represented in an int64_t!\n" |
| 469 | << " alloca: " << P.AI << "\n"); |
| 470 | return false; |
| 471 | } |
| 472 | if (GEPOffset < 0) |
| 473 | GEPOffset = ElementOffset + (uint64_t)-GEPOffset; |
| 474 | else |
| 475 | GEPOffset += ElementOffset; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 476 | continue; |
| 477 | } |
| 478 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 479 | APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits()); |
| 480 | Index *= APInt(Index.getBitWidth(), |
| 481 | TD.getTypeAllocSize(GTI.getIndexedType())); |
| 482 | Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset, |
| 483 | /*isSigned*/true); |
| 484 | // Check if the result can be stored in our int64_t offset. |
| 485 | if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) { |
| 486 | DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding " |
| 487 | << "what can be represented in an int64_t!\n" |
| 488 | << " alloca: " << P.AI << "\n"); |
| 489 | return false; |
| 490 | } |
| 491 | |
| 492 | GEPOffset = Index.getSExtValue(); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 493 | } |
| 494 | return true; |
| 495 | } |
| 496 | |
| 497 | Value *foldSelectInst(SelectInst &SI) { |
| 498 | // If the condition being selected on is a constant or the same value is |
| 499 | // being selected between, fold the select. Yes this does (rarely) happen |
| 500 | // early on. |
| 501 | if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition())) |
| 502 | return SI.getOperand(1+CI->isZero()); |
| 503 | if (SI.getOperand(1) == SI.getOperand(2)) { |
| 504 | assert(*U == SI.getOperand(1)); |
| 505 | return SI.getOperand(1); |
| 506 | } |
| 507 | return 0; |
| 508 | } |
| 509 | }; |
| 510 | |
| 511 | /// \brief Builder for the alloca partitioning. |
| 512 | /// |
| 513 | /// This class builds an alloca partitioning by recursively visiting the uses |
| 514 | /// of an alloca and splitting the partitions for each load and store at each |
| 515 | /// offset. |
| 516 | class AllocaPartitioning::PartitionBuilder |
| 517 | : public BuilderBase<PartitionBuilder, bool> { |
| 518 | friend class InstVisitor<PartitionBuilder, bool>; |
| 519 | |
| 520 | SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap; |
| 521 | |
| 522 | public: |
| 523 | PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P) |
Chandler Carruth | 2a9bf25 | 2012-09-14 09:30:33 +0000 | [diff] [blame] | 524 | : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {} |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 525 | |
| 526 | /// \brief Run the builder over the allocation. |
| 527 | bool operator()() { |
| 528 | // Note that we have to re-evaluate size on each trip through the loop as |
| 529 | // the queue grows at the tail. |
| 530 | for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) { |
| 531 | U = Queue[Idx].U; |
| 532 | Offset = Queue[Idx].Offset; |
| 533 | if (!visit(cast<Instruction>(U->getUser()))) |
| 534 | return false; |
| 535 | } |
| 536 | return true; |
| 537 | } |
| 538 | |
| 539 | private: |
| 540 | bool markAsEscaping(Instruction &I) { |
| 541 | P.PointerEscapingInstr = &I; |
| 542 | return false; |
| 543 | } |
| 544 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 545 | void insertUse(Instruction &I, int64_t Offset, uint64_t Size, |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 546 | bool IsSplittable = false) { |
Chandler Carruth | c303463 | 2012-09-25 10:03:40 +0000 | [diff] [blame] | 547 | // Completely skip uses which have a zero size or don't overlap the |
| 548 | // allocation. |
| 549 | if (Size == 0 || |
| 550 | (Offset >= 0 && (uint64_t)Offset >= AllocSize) || |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 551 | (Offset < 0 && (uint64_t)-Offset >= Size)) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 552 | DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset |
| 553 | << " which starts past the end of the " << AllocSize |
| 554 | << " byte alloca:\n" |
| 555 | << " alloca: " << P.AI << "\n" |
| 556 | << " use: " << I << "\n"); |
| 557 | return; |
| 558 | } |
| 559 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 560 | // Clamp the start to the beginning of the allocation. |
| 561 | if (Offset < 0) { |
| 562 | DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset |
| 563 | << " to start at the beginning of the alloca:\n" |
| 564 | << " alloca: " << P.AI << "\n" |
| 565 | << " use: " << I << "\n"); |
| 566 | Size -= (uint64_t)-Offset; |
| 567 | Offset = 0; |
| 568 | } |
| 569 | |
| 570 | uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size; |
| 571 | |
| 572 | // Clamp the end offset to the end of the allocation. Note that this is |
| 573 | // formulated to handle even the case where "BeginOffset + Size" overflows. |
| 574 | assert(AllocSize >= BeginOffset); // Established above. |
| 575 | if (Size > AllocSize - BeginOffset) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 576 | DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset |
| 577 | << " to remain within the " << AllocSize << " byte alloca:\n" |
| 578 | << " alloca: " << P.AI << "\n" |
| 579 | << " use: " << I << "\n"); |
| 580 | EndOffset = AllocSize; |
| 581 | } |
| 582 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 583 | Partition New(BeginOffset, EndOffset, IsSplittable); |
| 584 | P.Partitions.push_back(New); |
| 585 | } |
| 586 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 587 | bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 588 | uint64_t Size = TD.getTypeStoreSize(Ty); |
| 589 | |
| 590 | // If this memory access can be shown to *statically* extend outside the |
| 591 | // bounds of of the allocation, it's behavior is undefined, so simply |
| 592 | // ignore it. Note that this is more strict than the generic clamping |
| 593 | // behavior of insertUse. We also try to handle cases which might run the |
| 594 | // risk of overflow. |
| 595 | // FIXME: We should instead consider the pointer to have escaped if this |
| 596 | // function is being instrumented for addressing bugs or race conditions. |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 597 | if (Offset < 0 || (uint64_t)Offset >= AllocSize || |
| 598 | Size > (AllocSize - (uint64_t)Offset)) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 599 | DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte " |
| 600 | << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset |
| 601 | << " which extends past the end of the " << AllocSize |
| 602 | << " byte alloca:\n" |
| 603 | << " alloca: " << P.AI << "\n" |
| 604 | << " use: " << I << "\n"); |
| 605 | return true; |
| 606 | } |
| 607 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 608 | insertUse(I, Offset, Size); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 609 | return true; |
| 610 | } |
| 611 | |
| 612 | bool visitBitCastInst(BitCastInst &BC) { |
| 613 | enqueueUsers(BC, Offset); |
| 614 | return true; |
| 615 | } |
| 616 | |
| 617 | bool visitGetElementPtrInst(GetElementPtrInst &GEPI) { |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 618 | int64_t GEPOffset; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 619 | if (!computeConstantGEPOffset(GEPI, GEPOffset)) |
| 620 | return markAsEscaping(GEPI); |
| 621 | |
| 622 | enqueueUsers(GEPI, GEPOffset); |
| 623 | return true; |
| 624 | } |
| 625 | |
| 626 | bool visitLoadInst(LoadInst &LI) { |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 627 | assert((!LI.isSimple() || LI.getType()->isSingleValueType()) && |
| 628 | "All simple FCA loads should have been pre-split"); |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 629 | return handleLoadOrStore(LI.getType(), LI, Offset); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 630 | } |
| 631 | |
| 632 | bool visitStoreInst(StoreInst &SI) { |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 633 | Value *ValOp = SI.getValueOperand(); |
| 634 | if (ValOp == *U) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 635 | return markAsEscaping(SI); |
| 636 | |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 637 | assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) && |
| 638 | "All simple FCA stores should have been pre-split"); |
| 639 | return handleLoadOrStore(ValOp->getType(), SI, Offset); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 640 | } |
| 641 | |
| 642 | |
| 643 | bool visitMemSetInst(MemSetInst &II) { |
Chandler Carruth | b3dd9a1 | 2012-09-14 10:26:34 +0000 | [diff] [blame] | 644 | assert(II.getRawDest() == *U && "Pointer use is not the destination?"); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 645 | ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 646 | uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset; |
| 647 | insertUse(II, Offset, Size, Length); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 648 | return true; |
| 649 | } |
| 650 | |
| 651 | bool visitMemTransferInst(MemTransferInst &II) { |
| 652 | ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); |
| 653 | uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset; |
| 654 | if (!Size) |
| 655 | // Zero-length mem transfer intrinsics can be ignored entirely. |
| 656 | return true; |
| 657 | |
| 658 | MemTransferOffsets &Offsets = P.MemTransferInstData[&II]; |
| 659 | |
| 660 | // Only intrinsics with a constant length can be split. |
| 661 | Offsets.IsSplittable = Length; |
| 662 | |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 663 | if (*U == II.getRawDest()) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 664 | Offsets.DestBegin = Offset; |
| 665 | Offsets.DestEnd = Offset + Size; |
| 666 | } |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 667 | if (*U == II.getRawSource()) { |
| 668 | Offsets.SourceBegin = Offset; |
| 669 | Offsets.SourceEnd = Offset + Size; |
| 670 | } |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 671 | |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 672 | // If we have set up end offsets for both the source and the destination, |
| 673 | // we have found both sides of this transfer pointing at the same alloca. |
| 674 | bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd; |
| 675 | if (SeenBothEnds && II.getRawDest() != II.getRawSource()) { |
| 676 | unsigned PrevIdx = MemTransferPartitionMap[&II]; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 677 | |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 678 | // Check if the begin offsets match and this is a non-volatile transfer. |
| 679 | // In that case, we can completely elide the transfer. |
| 680 | if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) { |
| 681 | P.Partitions[PrevIdx].kill(); |
| 682 | return true; |
| 683 | } |
| 684 | |
| 685 | // Otherwise we have an offset transfer within the same alloca. We can't |
| 686 | // split those. |
| 687 | P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false; |
| 688 | } else if (SeenBothEnds) { |
| 689 | // Handle the case where this exact use provides both ends of the |
| 690 | // operation. |
| 691 | assert(II.getRawDest() == II.getRawSource()); |
| 692 | |
| 693 | // For non-volatile transfers this is a no-op. |
| 694 | if (!II.isVolatile()) |
| 695 | return true; |
| 696 | |
| 697 | // Otherwise just suppress splitting. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 698 | Offsets.IsSplittable = false; |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 699 | } |
| 700 | |
| 701 | |
| 702 | // Insert the use now that we've fixed up the splittable nature. |
| 703 | insertUse(II, Offset, Size, Offsets.IsSplittable); |
| 704 | |
| 705 | // Setup the mapping from intrinsic to partition of we've not seen both |
| 706 | // ends of this transfer. |
| 707 | if (!SeenBothEnds) { |
| 708 | unsigned NewIdx = P.Partitions.size() - 1; |
| 709 | bool Inserted |
| 710 | = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second; |
| 711 | assert(Inserted && |
| 712 | "Already have intrinsic in map but haven't seen both ends"); |
NAKAMURA Takumi | 0559d31 | 2012-10-05 13:56:23 +0000 | [diff] [blame^] | 713 | (void)Inserted; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 714 | } |
| 715 | |
| 716 | return true; |
| 717 | } |
| 718 | |
| 719 | // Disable SRoA for any intrinsics except for lifetime invariants. |
Chandler Carruth | 50754f0 | 2012-09-14 10:26:36 +0000 | [diff] [blame] | 720 | // FIXME: What about debug instrinsics? This matches old behavior, but |
| 721 | // doesn't make sense. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 722 | bool visitIntrinsicInst(IntrinsicInst &II) { |
| 723 | if (II.getIntrinsicID() == Intrinsic::lifetime_start || |
| 724 | II.getIntrinsicID() == Intrinsic::lifetime_end) { |
| 725 | ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0)); |
| 726 | uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue()); |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 727 | insertUse(II, Offset, Size, true); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 728 | return true; |
| 729 | } |
| 730 | |
| 731 | return markAsEscaping(II); |
| 732 | } |
| 733 | |
| 734 | Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) { |
| 735 | // We consider any PHI or select that results in a direct load or store of |
| 736 | // the same offset to be a viable use for partitioning purposes. These uses |
| 737 | // are considered unsplittable and the size is the maximum loaded or stored |
| 738 | // size. |
| 739 | SmallPtrSet<Instruction *, 4> Visited; |
| 740 | SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses; |
| 741 | Visited.insert(Root); |
| 742 | Uses.push_back(std::make_pair(cast<Instruction>(*U), Root)); |
Chandler Carruth | c303463 | 2012-09-25 10:03:40 +0000 | [diff] [blame] | 743 | // If there are no loads or stores, the access is dead. We mark that as |
| 744 | // a size zero access. |
| 745 | Size = 0; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 746 | do { |
| 747 | Instruction *I, *UsedI; |
| 748 | llvm::tie(UsedI, I) = Uses.pop_back_val(); |
| 749 | |
| 750 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
| 751 | Size = std::max(Size, TD.getTypeStoreSize(LI->getType())); |
| 752 | continue; |
| 753 | } |
| 754 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
| 755 | Value *Op = SI->getOperand(0); |
| 756 | if (Op == UsedI) |
| 757 | return SI; |
| 758 | Size = std::max(Size, TD.getTypeStoreSize(Op->getType())); |
| 759 | continue; |
| 760 | } |
| 761 | |
| 762 | if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) { |
| 763 | if (!GEP->hasAllZeroIndices()) |
| 764 | return GEP; |
| 765 | } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) && |
| 766 | !isa<SelectInst>(I)) { |
| 767 | return I; |
| 768 | } |
| 769 | |
| 770 | for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; |
| 771 | ++UI) |
| 772 | if (Visited.insert(cast<Instruction>(*UI))) |
| 773 | Uses.push_back(std::make_pair(I, cast<Instruction>(*UI))); |
| 774 | } while (!Uses.empty()); |
| 775 | |
| 776 | return 0; |
| 777 | } |
| 778 | |
| 779 | bool visitPHINode(PHINode &PN) { |
| 780 | // See if we already have computed info on this node. |
| 781 | std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN]; |
| 782 | if (PHIInfo.first) { |
| 783 | PHIInfo.second = true; |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 784 | insertUse(PN, Offset, PHIInfo.first); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 785 | return true; |
| 786 | } |
| 787 | |
| 788 | // Check for an unsafe use of the PHI node. |
| 789 | if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first)) |
| 790 | return markAsEscaping(*EscapingI); |
| 791 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 792 | insertUse(PN, Offset, PHIInfo.first); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 793 | return true; |
| 794 | } |
| 795 | |
| 796 | bool visitSelectInst(SelectInst &SI) { |
| 797 | if (Value *Result = foldSelectInst(SI)) { |
| 798 | if (Result == *U) |
| 799 | // If the result of the constant fold will be the pointer, recurse |
| 800 | // through the select as if we had RAUW'ed it. |
| 801 | enqueueUsers(SI, Offset); |
| 802 | |
| 803 | return true; |
| 804 | } |
| 805 | |
| 806 | // See if we already have computed info on this node. |
| 807 | std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI]; |
| 808 | if (SelectInfo.first) { |
| 809 | SelectInfo.second = true; |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 810 | insertUse(SI, Offset, SelectInfo.first); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 811 | return true; |
| 812 | } |
| 813 | |
| 814 | // Check for an unsafe use of the PHI node. |
| 815 | if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first)) |
| 816 | return markAsEscaping(*EscapingI); |
| 817 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 818 | insertUse(SI, Offset, SelectInfo.first); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 819 | return true; |
| 820 | } |
| 821 | |
| 822 | /// \brief Disable SROA entirely if there are unhandled users of the alloca. |
| 823 | bool visitInstruction(Instruction &I) { return markAsEscaping(I); } |
| 824 | }; |
| 825 | |
| 826 | |
| 827 | /// \brief Use adder for the alloca partitioning. |
| 828 | /// |
Chandler Carruth | 7f5bede | 2012-09-14 10:18:49 +0000 | [diff] [blame] | 829 | /// This class adds the uses of an alloca to all of the partitions which they |
| 830 | /// use. For splittable partitions, this can end up doing essentially a linear |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 831 | /// walk of the partitions, but the number of steps remains bounded by the |
| 832 | /// total result instruction size: |
| 833 | /// - The number of partitions is a result of the number unsplittable |
| 834 | /// instructions using the alloca. |
| 835 | /// - The number of users of each partition is at worst the total number of |
| 836 | /// splittable instructions using the alloca. |
| 837 | /// Thus we will produce N * M instructions in the end, where N are the number |
| 838 | /// of unsplittable uses and M are the number of splittable. This visitor does |
| 839 | /// the exact same number of updates to the partitioning. |
| 840 | /// |
| 841 | /// In the more common case, this visitor will leverage the fact that the |
| 842 | /// partition space is pre-sorted, and do a logarithmic search for the |
| 843 | /// partition needed, making the total visit a classical ((N + M) * log(N)) |
| 844 | /// complexity operation. |
| 845 | class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> { |
| 846 | friend class InstVisitor<UseBuilder>; |
| 847 | |
| 848 | /// \brief Set to de-duplicate dead instructions found in the use walk. |
| 849 | SmallPtrSet<Instruction *, 4> VisitedDeadInsts; |
| 850 | |
| 851 | public: |
| 852 | UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P) |
Chandler Carruth | 2a9bf25 | 2012-09-14 09:30:33 +0000 | [diff] [blame] | 853 | : BuilderBase<UseBuilder>(TD, AI, P) {} |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 854 | |
| 855 | /// \brief Run the builder over the allocation. |
| 856 | void operator()() { |
| 857 | // Note that we have to re-evaluate size on each trip through the loop as |
| 858 | // the queue grows at the tail. |
| 859 | for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) { |
| 860 | U = Queue[Idx].U; |
| 861 | Offset = Queue[Idx].Offset; |
| 862 | this->visit(cast<Instruction>(U->getUser())); |
| 863 | } |
| 864 | } |
| 865 | |
| 866 | private: |
| 867 | void markAsDead(Instruction &I) { |
| 868 | if (VisitedDeadInsts.insert(&I)) |
| 869 | P.DeadUsers.push_back(&I); |
| 870 | } |
| 871 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 872 | void insertUse(Instruction &User, int64_t Offset, uint64_t Size) { |
Chandler Carruth | c303463 | 2012-09-25 10:03:40 +0000 | [diff] [blame] | 873 | // If the use has a zero size or extends outside of the allocation, record |
| 874 | // it as a dead use for elimination later. |
| 875 | if (Size == 0 || (uint64_t)Offset >= AllocSize || |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 876 | (Offset < 0 && (uint64_t)-Offset >= Size)) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 877 | return markAsDead(User); |
| 878 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 879 | // Clamp the start to the beginning of the allocation. |
| 880 | if (Offset < 0) { |
| 881 | Size -= (uint64_t)-Offset; |
| 882 | Offset = 0; |
| 883 | } |
| 884 | |
| 885 | uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size; |
| 886 | |
| 887 | // Clamp the end offset to the end of the allocation. Note that this is |
| 888 | // formulated to handle even the case where "BeginOffset + Size" overflows. |
| 889 | assert(AllocSize >= BeginOffset); // Established above. |
| 890 | if (Size > AllocSize - BeginOffset) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 891 | EndOffset = AllocSize; |
| 892 | |
| 893 | // NB: This only works if we have zero overlapping partitions. |
| 894 | iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset); |
| 895 | if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset) |
| 896 | B = llvm::prior(B); |
| 897 | for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset; |
| 898 | ++I) { |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 899 | PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset), |
| 900 | std::min(I->EndOffset, EndOffset), U); |
| 901 | P.use_push_back(I, NewPU); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 902 | if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser())) |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 903 | P.PHIOrSelectOpMap[U] |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 904 | = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1); |
| 905 | } |
| 906 | } |
| 907 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 908 | void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 909 | uint64_t Size = TD.getTypeStoreSize(Ty); |
| 910 | |
| 911 | // If this memory access can be shown to *statically* extend outside the |
| 912 | // bounds of of the allocation, it's behavior is undefined, so simply |
| 913 | // ignore it. Note that this is more strict than the generic clamping |
| 914 | // behavior of insertUse. |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 915 | if (Offset < 0 || (uint64_t)Offset >= AllocSize || |
| 916 | Size > (AllocSize - (uint64_t)Offset)) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 917 | return markAsDead(I); |
| 918 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 919 | insertUse(I, Offset, Size); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 920 | } |
| 921 | |
| 922 | void visitBitCastInst(BitCastInst &BC) { |
| 923 | if (BC.use_empty()) |
| 924 | return markAsDead(BC); |
| 925 | |
| 926 | enqueueUsers(BC, Offset); |
| 927 | } |
| 928 | |
| 929 | void visitGetElementPtrInst(GetElementPtrInst &GEPI) { |
| 930 | if (GEPI.use_empty()) |
| 931 | return markAsDead(GEPI); |
| 932 | |
Chandler Carruth | 02e92a0 | 2012-09-23 11:43:14 +0000 | [diff] [blame] | 933 | int64_t GEPOffset; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 934 | if (!computeConstantGEPOffset(GEPI, GEPOffset)) |
| 935 | llvm_unreachable("Unable to compute constant offset for use"); |
| 936 | |
| 937 | enqueueUsers(GEPI, GEPOffset); |
| 938 | } |
| 939 | |
| 940 | void visitLoadInst(LoadInst &LI) { |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 941 | handleLoadOrStore(LI.getType(), LI, Offset); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 942 | } |
| 943 | |
| 944 | void visitStoreInst(StoreInst &SI) { |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 945 | handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 946 | } |
| 947 | |
| 948 | void visitMemSetInst(MemSetInst &II) { |
| 949 | ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 950 | uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset; |
| 951 | insertUse(II, Offset, Size); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 952 | } |
| 953 | |
| 954 | void visitMemTransferInst(MemTransferInst &II) { |
| 955 | ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength()); |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 956 | uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset; |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 957 | if (!Size) |
| 958 | return markAsDead(II); |
| 959 | |
| 960 | MemTransferOffsets &Offsets = P.MemTransferInstData[&II]; |
| 961 | if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd && |
| 962 | Offsets.DestBegin == Offsets.SourceBegin) |
| 963 | return markAsDead(II); // Skip identity transfers without side-effects. |
| 964 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 965 | insertUse(II, Offset, Size); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 966 | } |
| 967 | |
| 968 | void visitIntrinsicInst(IntrinsicInst &II) { |
| 969 | assert(II.getIntrinsicID() == Intrinsic::lifetime_start || |
| 970 | II.getIntrinsicID() == Intrinsic::lifetime_end); |
| 971 | |
| 972 | ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0)); |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 973 | insertUse(II, Offset, |
| 974 | std::min(AllocSize - Offset, Length->getLimitedValue())); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 975 | } |
| 976 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 977 | void insertPHIOrSelect(Instruction &User, uint64_t Offset) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 978 | uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first; |
| 979 | |
| 980 | // For PHI and select operands outside the alloca, we can't nuke the entire |
| 981 | // phi or select -- the other side might still be relevant, so we special |
| 982 | // case them here and use a separate structure to track the operands |
| 983 | // themselves which should be replaced with undef. |
| 984 | if (Offset >= AllocSize) { |
| 985 | P.DeadOperands.push_back(U); |
| 986 | return; |
| 987 | } |
| 988 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 989 | insertUse(User, Offset, Size); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 990 | } |
| 991 | void visitPHINode(PHINode &PN) { |
| 992 | if (PN.use_empty()) |
| 993 | return markAsDead(PN); |
| 994 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 995 | insertPHIOrSelect(PN, Offset); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 996 | } |
| 997 | void visitSelectInst(SelectInst &SI) { |
| 998 | if (SI.use_empty()) |
| 999 | return markAsDead(SI); |
| 1000 | |
| 1001 | if (Value *Result = foldSelectInst(SI)) { |
| 1002 | if (Result == *U) |
| 1003 | // If the result of the constant fold will be the pointer, recurse |
| 1004 | // through the select as if we had RAUW'ed it. |
| 1005 | enqueueUsers(SI, Offset); |
Chandler Carruth | d54a6b5 | 2012-09-21 23:36:40 +0000 | [diff] [blame] | 1006 | else |
| 1007 | // Otherwise the operand to the select is dead, and we can replace it |
| 1008 | // with undef. |
| 1009 | P.DeadOperands.push_back(U); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1010 | |
| 1011 | return; |
| 1012 | } |
| 1013 | |
Chandler Carruth | 63392ea | 2012-09-16 19:39:50 +0000 | [diff] [blame] | 1014 | insertPHIOrSelect(SI, Offset); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1015 | } |
| 1016 | |
| 1017 | /// \brief Unreachable, we've already visited the alloca once. |
| 1018 | void visitInstruction(Instruction &I) { |
| 1019 | llvm_unreachable("Unhandled instruction in use builder."); |
| 1020 | } |
| 1021 | }; |
| 1022 | |
| 1023 | void AllocaPartitioning::splitAndMergePartitions() { |
| 1024 | size_t NumDeadPartitions = 0; |
| 1025 | |
| 1026 | // Track the range of splittable partitions that we pass when accumulating |
| 1027 | // overlapping unsplittable partitions. |
| 1028 | uint64_t SplitEndOffset = 0ull; |
| 1029 | |
| 1030 | Partition New(0ull, 0ull, false); |
| 1031 | |
| 1032 | for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) { |
| 1033 | ++j; |
| 1034 | |
| 1035 | if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) { |
| 1036 | assert(New.BeginOffset == New.EndOffset); |
| 1037 | New = Partitions[i]; |
| 1038 | } else { |
| 1039 | assert(New.IsSplittable); |
| 1040 | New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset); |
| 1041 | } |
| 1042 | assert(New.BeginOffset != New.EndOffset); |
| 1043 | |
| 1044 | // Scan the overlapping partitions. |
| 1045 | while (j != e && New.EndOffset > Partitions[j].BeginOffset) { |
| 1046 | // If the new partition we are forming is splittable, stop at the first |
| 1047 | // unsplittable partition. |
| 1048 | if (New.IsSplittable && !Partitions[j].IsSplittable) |
| 1049 | break; |
| 1050 | |
| 1051 | // Grow the new partition to include any equally splittable range. 'j' is |
| 1052 | // always equally splittable when New is splittable, but when New is not |
| 1053 | // splittable, we may subsume some (or part of some) splitable partition |
| 1054 | // without growing the new one. |
| 1055 | if (New.IsSplittable == Partitions[j].IsSplittable) { |
| 1056 | New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset); |
| 1057 | } else { |
| 1058 | assert(!New.IsSplittable); |
| 1059 | assert(Partitions[j].IsSplittable); |
| 1060 | SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset); |
| 1061 | } |
| 1062 | |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 1063 | Partitions[j].kill(); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1064 | ++NumDeadPartitions; |
| 1065 | ++j; |
| 1066 | } |
| 1067 | |
| 1068 | // If the new partition is splittable, chop off the end as soon as the |
| 1069 | // unsplittable subsequent partition starts and ensure we eventually cover |
| 1070 | // the splittable area. |
| 1071 | if (j != e && New.IsSplittable) { |
| 1072 | SplitEndOffset = std::max(SplitEndOffset, New.EndOffset); |
| 1073 | New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset); |
| 1074 | } |
| 1075 | |
| 1076 | // Add the new partition if it differs from the original one and is |
| 1077 | // non-empty. We can end up with an empty partition here if it was |
| 1078 | // splittable but there is an unsplittable one that starts at the same |
| 1079 | // offset. |
| 1080 | if (New != Partitions[i]) { |
| 1081 | if (New.BeginOffset != New.EndOffset) |
| 1082 | Partitions.push_back(New); |
| 1083 | // Mark the old one for removal. |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 1084 | Partitions[i].kill(); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1085 | ++NumDeadPartitions; |
| 1086 | } |
| 1087 | |
| 1088 | New.BeginOffset = New.EndOffset; |
| 1089 | if (!New.IsSplittable) { |
| 1090 | New.EndOffset = std::max(New.EndOffset, SplitEndOffset); |
| 1091 | if (j != e && !Partitions[j].IsSplittable) |
| 1092 | New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset); |
| 1093 | New.IsSplittable = true; |
| 1094 | // If there is a trailing splittable partition which won't be fused into |
| 1095 | // the next splittable partition go ahead and add it onto the partitions |
| 1096 | // list. |
| 1097 | if (New.BeginOffset < New.EndOffset && |
| 1098 | (j == e || !Partitions[j].IsSplittable || |
| 1099 | New.EndOffset < Partitions[j].BeginOffset)) { |
| 1100 | Partitions.push_back(New); |
| 1101 | New.BeginOffset = New.EndOffset = 0ull; |
| 1102 | } |
| 1103 | } |
| 1104 | } |
| 1105 | |
| 1106 | // Re-sort the partitions now that they have been split and merged into |
| 1107 | // disjoint set of partitions. Also remove any of the dead partitions we've |
| 1108 | // replaced in the process. |
| 1109 | std::sort(Partitions.begin(), Partitions.end()); |
| 1110 | if (NumDeadPartitions) { |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 1111 | assert(Partitions.back().isDead()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1112 | assert((ptrdiff_t)NumDeadPartitions == |
| 1113 | std::count(Partitions.begin(), Partitions.end(), Partitions.back())); |
| 1114 | } |
| 1115 | Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end()); |
| 1116 | } |
| 1117 | |
| 1118 | AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI) |
Benjamin Kramer | d080769 | 2012-09-14 13:08:09 +0000 | [diff] [blame] | 1119 | : |
| 1120 | #ifndef NDEBUG |
| 1121 | AI(AI), |
| 1122 | #endif |
| 1123 | PointerEscapingInstr(0) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1124 | PartitionBuilder PB(TD, AI, *this); |
| 1125 | if (!PB()) |
| 1126 | return; |
| 1127 | |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 1128 | // Sort the uses. This arranges for the offsets to be in ascending order, |
| 1129 | // and the sizes to be in descending order. |
| 1130 | std::sort(Partitions.begin(), Partitions.end()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1131 | |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 1132 | // Remove any partitions from the back which are marked as dead. |
| 1133 | while (!Partitions.empty() && Partitions.back().isDead()) |
| 1134 | Partitions.pop_back(); |
| 1135 | |
| 1136 | if (Partitions.size() > 1) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1137 | // Intersect splittability for all partitions with equal offsets and sizes. |
| 1138 | // Then remove all but the first so that we have a sequence of non-equal but |
| 1139 | // potentially overlapping partitions. |
| 1140 | for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E; |
| 1141 | I = J) { |
| 1142 | ++J; |
| 1143 | while (J != E && *I == *J) { |
| 1144 | I->IsSplittable &= J->IsSplittable; |
| 1145 | ++J; |
| 1146 | } |
| 1147 | } |
| 1148 | Partitions.erase(std::unique(Partitions.begin(), Partitions.end()), |
| 1149 | Partitions.end()); |
| 1150 | |
| 1151 | // Split splittable and merge unsplittable partitions into a disjoint set |
| 1152 | // of partitions over the used space of the allocation. |
| 1153 | splitAndMergePartitions(); |
| 1154 | } |
| 1155 | |
| 1156 | // Now build up the user lists for each of these disjoint partitions by |
| 1157 | // re-walking the recursive users of the alloca. |
| 1158 | Uses.resize(Partitions.size()); |
| 1159 | UseBuilder UB(TD, AI, *this); |
| 1160 | UB(); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1161 | } |
| 1162 | |
| 1163 | Type *AllocaPartitioning::getCommonType(iterator I) const { |
| 1164 | Type *Ty = 0; |
| 1165 | for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) { |
Chandler Carruth | fdb1585 | 2012-10-02 18:57:13 +0000 | [diff] [blame] | 1166 | if (!UI->U) |
| 1167 | continue; // Skip dead uses. |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 1168 | if (isa<IntrinsicInst>(*UI->U->getUser())) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1169 | continue; |
| 1170 | if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset) |
Chandler Carruth | 7c8df7a | 2012-09-18 17:49:37 +0000 | [diff] [blame] | 1171 | continue; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1172 | |
| 1173 | Type *UserTy = 0; |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 1174 | if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1175 | UserTy = LI->getType(); |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 1176 | } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1177 | UserTy = SI->getValueOperand()->getType(); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1178 | } |
| 1179 | |
| 1180 | if (Ty && Ty != UserTy) |
| 1181 | return 0; |
| 1182 | |
| 1183 | Ty = UserTy; |
| 1184 | } |
| 1185 | return Ty; |
| 1186 | } |
| 1187 | |
Chandler Carruth | ba13d2e | 2012-09-14 10:18:51 +0000 | [diff] [blame] | 1188 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 1189 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1190 | void AllocaPartitioning::print(raw_ostream &OS, const_iterator I, |
| 1191 | StringRef Indent) const { |
| 1192 | OS << Indent << "partition #" << (I - begin()) |
| 1193 | << " [" << I->BeginOffset << "," << I->EndOffset << ")" |
| 1194 | << (I->IsSplittable ? " (splittable)" : "") |
| 1195 | << (Uses[I - begin()].empty() ? " (zero uses)" : "") |
| 1196 | << "\n"; |
| 1197 | } |
| 1198 | |
| 1199 | void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I, |
| 1200 | StringRef Indent) const { |
| 1201 | for (const_use_iterator UI = use_begin(I), UE = use_end(I); |
| 1202 | UI != UE; ++UI) { |
Chandler Carruth | fdb1585 | 2012-10-02 18:57:13 +0000 | [diff] [blame] | 1203 | if (!UI->U) |
| 1204 | continue; // Skip dead uses. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1205 | OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") " |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 1206 | << "used by: " << *UI->U->getUser() << "\n"; |
| 1207 | if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1208 | const MemTransferOffsets &MTO = MemTransferInstData.lookup(II); |
| 1209 | bool IsDest; |
| 1210 | if (!MTO.IsSplittable) |
| 1211 | IsDest = UI->BeginOffset == MTO.DestBegin; |
| 1212 | else |
| 1213 | IsDest = MTO.DestBegin != 0u; |
| 1214 | OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": " |
| 1215 | << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin) |
| 1216 | << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n"; |
| 1217 | } |
| 1218 | } |
| 1219 | } |
| 1220 | |
| 1221 | void AllocaPartitioning::print(raw_ostream &OS) const { |
| 1222 | if (PointerEscapingInstr) { |
| 1223 | OS << "No partitioning for alloca: " << AI << "\n" |
| 1224 | << " A pointer to this alloca escaped by:\n" |
| 1225 | << " " << *PointerEscapingInstr << "\n"; |
| 1226 | return; |
| 1227 | } |
| 1228 | |
| 1229 | OS << "Partitioning of alloca: " << AI << "\n"; |
| 1230 | unsigned Num = 0; |
| 1231 | for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) { |
| 1232 | print(OS, I); |
| 1233 | printUsers(OS, I); |
| 1234 | } |
| 1235 | } |
| 1236 | |
| 1237 | void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); } |
| 1238 | void AllocaPartitioning::dump() const { print(dbgs()); } |
| 1239 | |
Chandler Carruth | ba13d2e | 2012-09-14 10:18:51 +0000 | [diff] [blame] | 1240 | #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 1241 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1242 | |
| 1243 | namespace { |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 1244 | /// \brief Implementation of LoadAndStorePromoter for promoting allocas. |
| 1245 | /// |
| 1246 | /// This subclass of LoadAndStorePromoter adds overrides to handle promoting |
| 1247 | /// the loads and stores of an alloca instruction, as well as updating its |
| 1248 | /// debug information. This is used when a domtree is unavailable and thus |
| 1249 | /// mem2reg in its full form can't be used to handle promotion of allocas to |
| 1250 | /// scalar values. |
| 1251 | class AllocaPromoter : public LoadAndStorePromoter { |
| 1252 | AllocaInst &AI; |
| 1253 | DIBuilder &DIB; |
| 1254 | |
| 1255 | SmallVector<DbgDeclareInst *, 4> DDIs; |
| 1256 | SmallVector<DbgValueInst *, 4> DVIs; |
| 1257 | |
| 1258 | public: |
| 1259 | AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S, |
| 1260 | AllocaInst &AI, DIBuilder &DIB) |
| 1261 | : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {} |
| 1262 | |
| 1263 | void run(const SmallVectorImpl<Instruction*> &Insts) { |
| 1264 | // Remember which alloca we're promoting (for isInstInList). |
| 1265 | if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) { |
| 1266 | for (Value::use_iterator UI = DebugNode->use_begin(), |
| 1267 | UE = DebugNode->use_end(); |
| 1268 | UI != UE; ++UI) |
| 1269 | if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI)) |
| 1270 | DDIs.push_back(DDI); |
| 1271 | else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI)) |
| 1272 | DVIs.push_back(DVI); |
| 1273 | } |
| 1274 | |
| 1275 | LoadAndStorePromoter::run(Insts); |
| 1276 | AI.eraseFromParent(); |
| 1277 | while (!DDIs.empty()) |
| 1278 | DDIs.pop_back_val()->eraseFromParent(); |
| 1279 | while (!DVIs.empty()) |
| 1280 | DVIs.pop_back_val()->eraseFromParent(); |
| 1281 | } |
| 1282 | |
| 1283 | virtual bool isInstInList(Instruction *I, |
| 1284 | const SmallVectorImpl<Instruction*> &Insts) const { |
| 1285 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) |
| 1286 | return LI->getOperand(0) == &AI; |
| 1287 | return cast<StoreInst>(I)->getPointerOperand() == &AI; |
| 1288 | } |
| 1289 | |
| 1290 | virtual void updateDebugInfo(Instruction *Inst) const { |
| 1291 | for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(), |
| 1292 | E = DDIs.end(); I != E; ++I) { |
| 1293 | DbgDeclareInst *DDI = *I; |
| 1294 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) |
| 1295 | ConvertDebugDeclareToDebugValue(DDI, SI, DIB); |
| 1296 | else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) |
| 1297 | ConvertDebugDeclareToDebugValue(DDI, LI, DIB); |
| 1298 | } |
| 1299 | for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(), |
| 1300 | E = DVIs.end(); I != E; ++I) { |
| 1301 | DbgValueInst *DVI = *I; |
| 1302 | Value *Arg = NULL; |
| 1303 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { |
| 1304 | // If an argument is zero extended then use argument directly. The ZExt |
| 1305 | // may be zapped by an optimization pass in future. |
| 1306 | if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0))) |
| 1307 | Arg = dyn_cast<Argument>(ZExt->getOperand(0)); |
| 1308 | if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0))) |
| 1309 | Arg = dyn_cast<Argument>(SExt->getOperand(0)); |
| 1310 | if (!Arg) |
| 1311 | Arg = SI->getOperand(0); |
| 1312 | } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { |
| 1313 | Arg = LI->getOperand(0); |
| 1314 | } else { |
| 1315 | continue; |
| 1316 | } |
| 1317 | Instruction *DbgVal = |
| 1318 | DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()), |
| 1319 | Inst); |
| 1320 | DbgVal->setDebugLoc(DVI->getDebugLoc()); |
| 1321 | } |
| 1322 | } |
| 1323 | }; |
| 1324 | } // end anon namespace |
| 1325 | |
| 1326 | |
| 1327 | namespace { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1328 | /// \brief An optimization pass providing Scalar Replacement of Aggregates. |
| 1329 | /// |
| 1330 | /// This pass takes allocations which can be completely analyzed (that is, they |
| 1331 | /// don't escape) and tries to turn them into scalar SSA values. There are |
| 1332 | /// a few steps to this process. |
| 1333 | /// |
| 1334 | /// 1) It takes allocations of aggregates and analyzes the ways in which they |
| 1335 | /// are used to try to split them into smaller allocations, ideally of |
| 1336 | /// a single scalar data type. It will split up memcpy and memset accesses |
| 1337 | /// as necessary and try to isolate invidual scalar accesses. |
| 1338 | /// 2) It will transform accesses into forms which are suitable for SSA value |
| 1339 | /// promotion. This can be replacing a memset with a scalar store of an |
| 1340 | /// integer value, or it can involve speculating operations on a PHI or |
| 1341 | /// select to be a PHI or select of the results. |
| 1342 | /// 3) Finally, this will try to detect a pattern of accesses which map cleanly |
| 1343 | /// onto insert and extract operations on a vector value, and convert them to |
| 1344 | /// this form. By doing so, it will enable promotion of vector aggregates to |
| 1345 | /// SSA vector values. |
| 1346 | class SROA : public FunctionPass { |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 1347 | const bool RequiresDomTree; |
| 1348 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1349 | LLVMContext *C; |
| 1350 | const TargetData *TD; |
| 1351 | DominatorTree *DT; |
| 1352 | |
| 1353 | /// \brief Worklist of alloca instructions to simplify. |
| 1354 | /// |
| 1355 | /// Each alloca in the function is added to this. Each new alloca formed gets |
| 1356 | /// added to it as well to recursively simplify unless that alloca can be |
| 1357 | /// directly promoted. Finally, each time we rewrite a use of an alloca other |
| 1358 | /// the one being actively rewritten, we add it back onto the list if not |
| 1359 | /// already present to ensure it is re-visited. |
| 1360 | SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist; |
| 1361 | |
| 1362 | /// \brief A collection of instructions to delete. |
| 1363 | /// We try to batch deletions to simplify code and make things a bit more |
| 1364 | /// efficient. |
| 1365 | SmallVector<Instruction *, 8> DeadInsts; |
| 1366 | |
| 1367 | /// \brief A set to prevent repeatedly marking an instruction split into many |
| 1368 | /// uses as dead. Only used to guard insertion into DeadInsts. |
| 1369 | SmallPtrSet<Instruction *, 4> DeadSplitInsts; |
| 1370 | |
Chandler Carruth | b2d98c2 | 2012-10-04 12:33:50 +0000 | [diff] [blame] | 1371 | /// \brief Post-promotion worklist. |
| 1372 | /// |
| 1373 | /// Sometimes we discover an alloca which has a high probability of becoming |
| 1374 | /// viable for SROA after a round of promotion takes place. In those cases, |
| 1375 | /// the alloca is enqueued here for re-processing. |
| 1376 | /// |
| 1377 | /// Note that we have to be very careful to clear allocas out of this list in |
| 1378 | /// the event they are deleted. |
| 1379 | SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist; |
| 1380 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1381 | /// \brief A collection of alloca instructions we can directly promote. |
| 1382 | std::vector<AllocaInst *> PromotableAllocas; |
| 1383 | |
| 1384 | public: |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 1385 | SROA(bool RequiresDomTree = true) |
| 1386 | : FunctionPass(ID), RequiresDomTree(RequiresDomTree), |
| 1387 | C(0), TD(0), DT(0) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1388 | initializeSROAPass(*PassRegistry::getPassRegistry()); |
| 1389 | } |
| 1390 | bool runOnFunction(Function &F); |
| 1391 | void getAnalysisUsage(AnalysisUsage &AU) const; |
| 1392 | |
| 1393 | const char *getPassName() const { return "SROA"; } |
| 1394 | static char ID; |
| 1395 | |
| 1396 | private: |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 1397 | friend class PHIOrSelectSpeculator; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1398 | friend class AllocaPartitionRewriter; |
| 1399 | friend class AllocaPartitionVectorRewriter; |
| 1400 | |
| 1401 | bool rewriteAllocaPartition(AllocaInst &AI, |
| 1402 | AllocaPartitioning &P, |
| 1403 | AllocaPartitioning::iterator PI); |
| 1404 | bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P); |
| 1405 | bool runOnAlloca(AllocaInst &AI); |
Chandler Carruth | 8615cd2 | 2012-09-14 10:26:38 +0000 | [diff] [blame] | 1406 | void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas); |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 1407 | bool promoteAllocas(Function &F); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1408 | }; |
| 1409 | } |
| 1410 | |
| 1411 | char SROA::ID = 0; |
| 1412 | |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 1413 | FunctionPass *llvm::createSROAPass(bool RequiresDomTree) { |
| 1414 | return new SROA(RequiresDomTree); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1415 | } |
| 1416 | |
| 1417 | INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", |
| 1418 | false, false) |
| 1419 | INITIALIZE_PASS_DEPENDENCY(DominatorTree) |
| 1420 | INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", |
| 1421 | false, false) |
| 1422 | |
Chandler Carruth | 0e9da58 | 2012-10-05 01:29:06 +0000 | [diff] [blame] | 1423 | namespace { |
| 1424 | /// \brief Visitor to speculate PHIs and Selects where possible. |
| 1425 | class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> { |
| 1426 | // Befriend the base class so it can delegate to private visit methods. |
| 1427 | friend class llvm::InstVisitor<PHIOrSelectSpeculator>; |
| 1428 | |
| 1429 | const TargetData &TD; |
| 1430 | AllocaPartitioning &P; |
| 1431 | SROA &Pass; |
| 1432 | |
| 1433 | public: |
| 1434 | PHIOrSelectSpeculator(const TargetData &TD, AllocaPartitioning &P, SROA &Pass) |
| 1435 | : TD(TD), P(P), Pass(Pass) {} |
| 1436 | |
| 1437 | /// \brief Visit the users of an alloca partition and rewrite them. |
| 1438 | void visitUsers(AllocaPartitioning::const_iterator PI) { |
| 1439 | // Note that we need to use an index here as the underlying vector of uses |
| 1440 | // may be grown during speculation. However, we never need to re-visit the |
| 1441 | // new uses, and so we can use the initial size bound. |
| 1442 | for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) { |
| 1443 | const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx); |
| 1444 | if (!PU.U) |
| 1445 | continue; // Skip dead use. |
| 1446 | |
| 1447 | visit(cast<Instruction>(PU.U->getUser())); |
| 1448 | } |
| 1449 | } |
| 1450 | |
| 1451 | private: |
| 1452 | // By default, skip this instruction. |
| 1453 | void visitInstruction(Instruction &I) {} |
| 1454 | |
| 1455 | /// PHI instructions that use an alloca and are subsequently loaded can be |
| 1456 | /// rewritten to load both input pointers in the pred blocks and then PHI the |
| 1457 | /// results, allowing the load of the alloca to be promoted. |
| 1458 | /// From this: |
| 1459 | /// %P2 = phi [i32* %Alloca, i32* %Other] |
| 1460 | /// %V = load i32* %P2 |
| 1461 | /// to: |
| 1462 | /// %V1 = load i32* %Alloca -> will be mem2reg'd |
| 1463 | /// ... |
| 1464 | /// %V2 = load i32* %Other |
| 1465 | /// ... |
| 1466 | /// %V = phi [i32 %V1, i32 %V2] |
| 1467 | /// |
| 1468 | /// We can do this to a select if its only uses are loads and if the operands |
| 1469 | /// to the select can be loaded unconditionally. |
| 1470 | /// |
| 1471 | /// FIXME: This should be hoisted into a generic utility, likely in |
| 1472 | /// Transforms/Util/Local.h |
| 1473 | bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) { |
| 1474 | // For now, we can only do this promotion if the load is in the same block |
| 1475 | // as the PHI, and if there are no stores between the phi and load. |
| 1476 | // TODO: Allow recursive phi users. |
| 1477 | // TODO: Allow stores. |
| 1478 | BasicBlock *BB = PN.getParent(); |
| 1479 | unsigned MaxAlign = 0; |
| 1480 | for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end(); |
| 1481 | UI != UE; ++UI) { |
| 1482 | LoadInst *LI = dyn_cast<LoadInst>(*UI); |
| 1483 | if (LI == 0 || !LI->isSimple()) return false; |
| 1484 | |
| 1485 | // For now we only allow loads in the same block as the PHI. This is |
| 1486 | // a common case that happens when instcombine merges two loads through |
| 1487 | // a PHI. |
| 1488 | if (LI->getParent() != BB) return false; |
| 1489 | |
| 1490 | // Ensure that there are no instructions between the PHI and the load that |
| 1491 | // could store. |
| 1492 | for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI) |
| 1493 | if (BBI->mayWriteToMemory()) |
| 1494 | return false; |
| 1495 | |
| 1496 | MaxAlign = std::max(MaxAlign, LI->getAlignment()); |
| 1497 | Loads.push_back(LI); |
| 1498 | } |
| 1499 | |
| 1500 | // We can only transform this if it is safe to push the loads into the |
| 1501 | // predecessor blocks. The only thing to watch out for is that we can't put |
| 1502 | // a possibly trapping load in the predecessor if it is a critical edge. |
| 1503 | for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; |
| 1504 | ++Idx) { |
| 1505 | TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator(); |
| 1506 | Value *InVal = PN.getIncomingValue(Idx); |
| 1507 | |
| 1508 | // If the value is produced by the terminator of the predecessor (an |
| 1509 | // invoke) or it has side-effects, there is no valid place to put a load |
| 1510 | // in the predecessor. |
| 1511 | if (TI == InVal || TI->mayHaveSideEffects()) |
| 1512 | return false; |
| 1513 | |
| 1514 | // If the predecessor has a single successor, then the edge isn't |
| 1515 | // critical. |
| 1516 | if (TI->getNumSuccessors() == 1) |
| 1517 | continue; |
| 1518 | |
| 1519 | // If this pointer is always safe to load, or if we can prove that there |
| 1520 | // is already a load in the block, then we can move the load to the pred |
| 1521 | // block. |
| 1522 | if (InVal->isDereferenceablePointer() || |
| 1523 | isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD)) |
| 1524 | continue; |
| 1525 | |
| 1526 | return false; |
| 1527 | } |
| 1528 | |
| 1529 | return true; |
| 1530 | } |
| 1531 | |
| 1532 | void visitPHINode(PHINode &PN) { |
| 1533 | DEBUG(dbgs() << " original: " << PN << "\n"); |
| 1534 | |
| 1535 | SmallVector<LoadInst *, 4> Loads; |
| 1536 | if (!isSafePHIToSpeculate(PN, Loads)) |
| 1537 | return; |
| 1538 | |
| 1539 | assert(!Loads.empty()); |
| 1540 | |
| 1541 | Type *LoadTy = cast<PointerType>(PN.getType())->getElementType(); |
| 1542 | IRBuilder<> PHIBuilder(&PN); |
| 1543 | PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(), |
| 1544 | PN.getName() + ".sroa.speculated"); |
| 1545 | |
| 1546 | // Get the TBAA tag and alignment to use from one of the loads. It doesn't |
| 1547 | // matter which one we get and if any differ, it doesn't matter. |
| 1548 | LoadInst *SomeLoad = cast<LoadInst>(Loads.back()); |
| 1549 | MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa); |
| 1550 | unsigned Align = SomeLoad->getAlignment(); |
| 1551 | |
| 1552 | // Rewrite all loads of the PN to use the new PHI. |
| 1553 | do { |
| 1554 | LoadInst *LI = Loads.pop_back_val(); |
| 1555 | LI->replaceAllUsesWith(NewPN); |
| 1556 | Pass.DeadInsts.push_back(LI); |
| 1557 | } while (!Loads.empty()); |
| 1558 | |
| 1559 | // Inject loads into all of the pred blocks. |
| 1560 | for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) { |
| 1561 | BasicBlock *Pred = PN.getIncomingBlock(Idx); |
| 1562 | TerminatorInst *TI = Pred->getTerminator(); |
| 1563 | Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx)); |
| 1564 | Value *InVal = PN.getIncomingValue(Idx); |
| 1565 | IRBuilder<> PredBuilder(TI); |
| 1566 | |
| 1567 | LoadInst *Load |
| 1568 | = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." + |
| 1569 | Pred->getName())); |
| 1570 | ++NumLoadsSpeculated; |
| 1571 | Load->setAlignment(Align); |
| 1572 | if (TBAATag) |
| 1573 | Load->setMetadata(LLVMContext::MD_tbaa, TBAATag); |
| 1574 | NewPN->addIncoming(Load, Pred); |
| 1575 | |
| 1576 | Instruction *Ptr = dyn_cast<Instruction>(InVal); |
| 1577 | if (!Ptr) |
| 1578 | // No uses to rewrite. |
| 1579 | continue; |
| 1580 | |
| 1581 | // Try to lookup and rewrite any partition uses corresponding to this phi |
| 1582 | // input. |
| 1583 | AllocaPartitioning::iterator PI |
| 1584 | = P.findPartitionForPHIOrSelectOperand(InUse); |
| 1585 | if (PI == P.end()) |
| 1586 | continue; |
| 1587 | |
| 1588 | // Replace the Use in the PartitionUse for this operand with the Use |
| 1589 | // inside the load. |
| 1590 | AllocaPartitioning::use_iterator UI |
| 1591 | = P.findPartitionUseForPHIOrSelectOperand(InUse); |
| 1592 | assert(isa<PHINode>(*UI->U->getUser())); |
| 1593 | UI->U = &Load->getOperandUse(Load->getPointerOperandIndex()); |
| 1594 | } |
| 1595 | DEBUG(dbgs() << " speculated to: " << *NewPN << "\n"); |
| 1596 | } |
| 1597 | |
| 1598 | /// Select instructions that use an alloca and are subsequently loaded can be |
| 1599 | /// rewritten to load both input pointers and then select between the result, |
| 1600 | /// allowing the load of the alloca to be promoted. |
| 1601 | /// From this: |
| 1602 | /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other |
| 1603 | /// %V = load i32* %P2 |
| 1604 | /// to: |
| 1605 | /// %V1 = load i32* %Alloca -> will be mem2reg'd |
| 1606 | /// %V2 = load i32* %Other |
| 1607 | /// %V = select i1 %cond, i32 %V1, i32 %V2 |
| 1608 | /// |
| 1609 | /// We can do this to a select if its only uses are loads and if the operand |
| 1610 | /// to the select can be loaded unconditionally. |
| 1611 | bool isSafeSelectToSpeculate(SelectInst &SI, |
| 1612 | SmallVectorImpl<LoadInst *> &Loads) { |
| 1613 | Value *TValue = SI.getTrueValue(); |
| 1614 | Value *FValue = SI.getFalseValue(); |
| 1615 | bool TDerefable = TValue->isDereferenceablePointer(); |
| 1616 | bool FDerefable = FValue->isDereferenceablePointer(); |
| 1617 | |
| 1618 | for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end(); |
| 1619 | UI != UE; ++UI) { |
| 1620 | LoadInst *LI = dyn_cast<LoadInst>(*UI); |
| 1621 | if (LI == 0 || !LI->isSimple()) return false; |
| 1622 | |
| 1623 | // Both operands to the select need to be dereferencable, either |
| 1624 | // absolutely (e.g. allocas) or at this point because we can see other |
| 1625 | // accesses to it. |
| 1626 | if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI, |
| 1627 | LI->getAlignment(), &TD)) |
| 1628 | return false; |
| 1629 | if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI, |
| 1630 | LI->getAlignment(), &TD)) |
| 1631 | return false; |
| 1632 | Loads.push_back(LI); |
| 1633 | } |
| 1634 | |
| 1635 | return true; |
| 1636 | } |
| 1637 | |
| 1638 | void visitSelectInst(SelectInst &SI) { |
| 1639 | DEBUG(dbgs() << " original: " << SI << "\n"); |
| 1640 | IRBuilder<> IRB(&SI); |
| 1641 | |
| 1642 | // If the select isn't safe to speculate, just use simple logic to emit it. |
| 1643 | SmallVector<LoadInst *, 4> Loads; |
| 1644 | if (!isSafeSelectToSpeculate(SI, Loads)) |
| 1645 | return; |
| 1646 | |
| 1647 | Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) }; |
| 1648 | AllocaPartitioning::iterator PIs[2]; |
| 1649 | AllocaPartitioning::PartitionUse PUs[2]; |
| 1650 | for (unsigned i = 0, e = 2; i != e; ++i) { |
| 1651 | PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]); |
| 1652 | if (PIs[i] != P.end()) { |
| 1653 | // If the pointer is within the partitioning, remove the select from |
| 1654 | // its uses. We'll add in the new loads below. |
| 1655 | AllocaPartitioning::use_iterator UI |
| 1656 | = P.findPartitionUseForPHIOrSelectOperand(Ops[i]); |
| 1657 | PUs[i] = *UI; |
| 1658 | // Clear out the use here so that the offsets into the use list remain |
| 1659 | // stable but this use is ignored when rewriting. |
| 1660 | UI->U = 0; |
| 1661 | } |
| 1662 | } |
| 1663 | |
| 1664 | Value *TV = SI.getTrueValue(); |
| 1665 | Value *FV = SI.getFalseValue(); |
| 1666 | // Replace the loads of the select with a select of two loads. |
| 1667 | while (!Loads.empty()) { |
| 1668 | LoadInst *LI = Loads.pop_back_val(); |
| 1669 | |
| 1670 | IRB.SetInsertPoint(LI); |
| 1671 | LoadInst *TL = |
| 1672 | IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true"); |
| 1673 | LoadInst *FL = |
| 1674 | IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false"); |
| 1675 | NumLoadsSpeculated += 2; |
| 1676 | |
| 1677 | // Transfer alignment and TBAA info if present. |
| 1678 | TL->setAlignment(LI->getAlignment()); |
| 1679 | FL->setAlignment(LI->getAlignment()); |
| 1680 | if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) { |
| 1681 | TL->setMetadata(LLVMContext::MD_tbaa, Tag); |
| 1682 | FL->setMetadata(LLVMContext::MD_tbaa, Tag); |
| 1683 | } |
| 1684 | |
| 1685 | Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL, |
| 1686 | LI->getName() + ".sroa.speculated"); |
| 1687 | |
| 1688 | LoadInst *Loads[2] = { TL, FL }; |
| 1689 | for (unsigned i = 0, e = 2; i != e; ++i) { |
| 1690 | if (PIs[i] != P.end()) { |
| 1691 | Use *LoadUse = &Loads[i]->getOperandUse(0); |
| 1692 | assert(PUs[i].U->get() == LoadUse->get()); |
| 1693 | PUs[i].U = LoadUse; |
| 1694 | P.use_push_back(PIs[i], PUs[i]); |
| 1695 | } |
| 1696 | } |
| 1697 | |
| 1698 | DEBUG(dbgs() << " speculated to: " << *V << "\n"); |
| 1699 | LI->replaceAllUsesWith(V); |
| 1700 | Pass.DeadInsts.push_back(LI); |
| 1701 | } |
| 1702 | } |
| 1703 | }; |
| 1704 | } |
| 1705 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1706 | /// \brief Accumulate the constant offsets in a GEP into a single APInt offset. |
| 1707 | /// |
| 1708 | /// If the provided GEP is all-constant, the total byte offset formed by the |
| 1709 | /// GEP is computed and Offset is set to it. If the GEP has any non-constant |
| 1710 | /// operands, the function returns false and the value of Offset is unmodified. |
| 1711 | static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP, |
| 1712 | APInt &Offset) { |
| 1713 | APInt GEPOffset(Offset.getBitWidth(), 0); |
| 1714 | for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP); |
| 1715 | GTI != GTE; ++GTI) { |
| 1716 | ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand()); |
| 1717 | if (!OpC) |
| 1718 | return false; |
| 1719 | if (OpC->isZero()) continue; |
| 1720 | |
| 1721 | // Handle a struct index, which adds its field offset to the pointer. |
| 1722 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 1723 | unsigned ElementIdx = OpC->getZExtValue(); |
| 1724 | const StructLayout *SL = TD.getStructLayout(STy); |
| 1725 | GEPOffset += APInt(Offset.getBitWidth(), |
| 1726 | SL->getElementOffset(ElementIdx)); |
| 1727 | continue; |
| 1728 | } |
| 1729 | |
| 1730 | APInt TypeSize(Offset.getBitWidth(), |
| 1731 | TD.getTypeAllocSize(GTI.getIndexedType())); |
| 1732 | if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) { |
| 1733 | assert((VTy->getScalarSizeInBits() % 8) == 0 && |
| 1734 | "vector element size is not a multiple of 8, cannot GEP over it"); |
| 1735 | TypeSize = VTy->getScalarSizeInBits() / 8; |
| 1736 | } |
| 1737 | |
| 1738 | GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize; |
| 1739 | } |
| 1740 | Offset = GEPOffset; |
| 1741 | return true; |
| 1742 | } |
| 1743 | |
| 1744 | /// \brief Build a GEP out of a base pointer and indices. |
| 1745 | /// |
| 1746 | /// This will return the BasePtr if that is valid, or build a new GEP |
| 1747 | /// instruction using the IRBuilder if GEP-ing is needed. |
| 1748 | static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr, |
| 1749 | SmallVectorImpl<Value *> &Indices, |
| 1750 | const Twine &Prefix) { |
| 1751 | if (Indices.empty()) |
| 1752 | return BasePtr; |
| 1753 | |
| 1754 | // A single zero index is a no-op, so check for this and avoid building a GEP |
| 1755 | // in that case. |
| 1756 | if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero()) |
| 1757 | return BasePtr; |
| 1758 | |
| 1759 | return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx"); |
| 1760 | } |
| 1761 | |
| 1762 | /// \brief Get a natural GEP off of the BasePtr walking through Ty toward |
| 1763 | /// TargetTy without changing the offset of the pointer. |
| 1764 | /// |
| 1765 | /// This routine assumes we've already established a properly offset GEP with |
| 1766 | /// Indices, and arrived at the Ty type. The goal is to continue to GEP with |
| 1767 | /// zero-indices down through type layers until we find one the same as |
| 1768 | /// TargetTy. If we can't find one with the same type, we at least try to use |
| 1769 | /// one with the same size. If none of that works, we just produce the GEP as |
| 1770 | /// indicated by Indices to have the correct offset. |
| 1771 | static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD, |
| 1772 | Value *BasePtr, Type *Ty, Type *TargetTy, |
| 1773 | SmallVectorImpl<Value *> &Indices, |
| 1774 | const Twine &Prefix) { |
| 1775 | if (Ty == TargetTy) |
| 1776 | return buildGEP(IRB, BasePtr, Indices, Prefix); |
| 1777 | |
| 1778 | // See if we can descend into a struct and locate a field with the correct |
| 1779 | // type. |
| 1780 | unsigned NumLayers = 0; |
| 1781 | Type *ElementTy = Ty; |
| 1782 | do { |
| 1783 | if (ElementTy->isPointerTy()) |
| 1784 | break; |
| 1785 | if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) { |
| 1786 | ElementTy = SeqTy->getElementType(); |
| 1787 | Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0))); |
| 1788 | } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) { |
| 1789 | ElementTy = *STy->element_begin(); |
| 1790 | Indices.push_back(IRB.getInt32(0)); |
| 1791 | } else { |
| 1792 | break; |
| 1793 | } |
| 1794 | ++NumLayers; |
| 1795 | } while (ElementTy != TargetTy); |
| 1796 | if (ElementTy != TargetTy) |
| 1797 | Indices.erase(Indices.end() - NumLayers, Indices.end()); |
| 1798 | |
| 1799 | return buildGEP(IRB, BasePtr, Indices, Prefix); |
| 1800 | } |
| 1801 | |
| 1802 | /// \brief Recursively compute indices for a natural GEP. |
| 1803 | /// |
| 1804 | /// This is the recursive step for getNaturalGEPWithOffset that walks down the |
| 1805 | /// element types adding appropriate indices for the GEP. |
| 1806 | static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD, |
| 1807 | Value *Ptr, Type *Ty, APInt &Offset, |
| 1808 | Type *TargetTy, |
| 1809 | SmallVectorImpl<Value *> &Indices, |
| 1810 | const Twine &Prefix) { |
| 1811 | if (Offset == 0) |
| 1812 | return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix); |
| 1813 | |
| 1814 | // We can't recurse through pointer types. |
| 1815 | if (Ty->isPointerTy()) |
| 1816 | return 0; |
| 1817 | |
Chandler Carruth | 8ed1ed8 | 2012-09-14 10:30:40 +0000 | [diff] [blame] | 1818 | // We try to analyze GEPs over vectors here, but note that these GEPs are |
| 1819 | // extremely poorly defined currently. The long-term goal is to remove GEPing |
| 1820 | // over a vector from the IR completely. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1821 | if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) { |
| 1822 | unsigned ElementSizeInBits = VecTy->getScalarSizeInBits(); |
| 1823 | if (ElementSizeInBits % 8) |
Chandler Carruth | 8ed1ed8 | 2012-09-14 10:30:40 +0000 | [diff] [blame] | 1824 | return 0; // GEPs over non-multiple of 8 size vector elements are invalid. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1825 | APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8); |
| 1826 | APInt NumSkippedElements = Offset.udiv(ElementSize); |
| 1827 | if (NumSkippedElements.ugt(VecTy->getNumElements())) |
| 1828 | return 0; |
| 1829 | Offset -= NumSkippedElements * ElementSize; |
| 1830 | Indices.push_back(IRB.getInt(NumSkippedElements)); |
| 1831 | return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(), |
| 1832 | Offset, TargetTy, Indices, Prefix); |
| 1833 | } |
| 1834 | |
| 1835 | if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) { |
| 1836 | Type *ElementTy = ArrTy->getElementType(); |
| 1837 | APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy)); |
| 1838 | APInt NumSkippedElements = Offset.udiv(ElementSize); |
| 1839 | if (NumSkippedElements.ugt(ArrTy->getNumElements())) |
| 1840 | return 0; |
| 1841 | |
| 1842 | Offset -= NumSkippedElements * ElementSize; |
| 1843 | Indices.push_back(IRB.getInt(NumSkippedElements)); |
| 1844 | return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy, |
| 1845 | Indices, Prefix); |
| 1846 | } |
| 1847 | |
| 1848 | StructType *STy = dyn_cast<StructType>(Ty); |
| 1849 | if (!STy) |
| 1850 | return 0; |
| 1851 | |
| 1852 | const StructLayout *SL = TD.getStructLayout(STy); |
| 1853 | uint64_t StructOffset = Offset.getZExtValue(); |
Chandler Carruth | ad41dcf | 2012-09-14 10:30:42 +0000 | [diff] [blame] | 1854 | if (StructOffset >= SL->getSizeInBytes()) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1855 | return 0; |
| 1856 | unsigned Index = SL->getElementContainingOffset(StructOffset); |
| 1857 | Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index)); |
| 1858 | Type *ElementTy = STy->getElementType(Index); |
| 1859 | if (Offset.uge(TD.getTypeAllocSize(ElementTy))) |
| 1860 | return 0; // The offset points into alignment padding. |
| 1861 | |
| 1862 | Indices.push_back(IRB.getInt32(Index)); |
| 1863 | return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy, |
| 1864 | Indices, Prefix); |
| 1865 | } |
| 1866 | |
| 1867 | /// \brief Get a natural GEP from a base pointer to a particular offset and |
| 1868 | /// resulting in a particular type. |
| 1869 | /// |
| 1870 | /// The goal is to produce a "natural" looking GEP that works with the existing |
| 1871 | /// composite types to arrive at the appropriate offset and element type for |
| 1872 | /// a pointer. TargetTy is the element type the returned GEP should point-to if |
| 1873 | /// possible. We recurse by decreasing Offset, adding the appropriate index to |
| 1874 | /// Indices, and setting Ty to the result subtype. |
| 1875 | /// |
Chandler Carruth | 7f5bede | 2012-09-14 10:18:49 +0000 | [diff] [blame] | 1876 | /// If no natural GEP can be constructed, this function returns null. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1877 | static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD, |
| 1878 | Value *Ptr, APInt Offset, Type *TargetTy, |
| 1879 | SmallVectorImpl<Value *> &Indices, |
| 1880 | const Twine &Prefix) { |
| 1881 | PointerType *Ty = cast<PointerType>(Ptr->getType()); |
| 1882 | |
| 1883 | // Don't consider any GEPs through an i8* as natural unless the TargetTy is |
| 1884 | // an i8. |
| 1885 | if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8)) |
| 1886 | return 0; |
| 1887 | |
| 1888 | Type *ElementTy = Ty->getElementType(); |
Chandler Carruth | 38f35fd | 2012-09-18 22:37:19 +0000 | [diff] [blame] | 1889 | if (!ElementTy->isSized()) |
| 1890 | return 0; // We can't GEP through an unsized element. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 1891 | APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy)); |
| 1892 | if (ElementSize == 0) |
| 1893 | return 0; // Zero-length arrays can't help us build a natural GEP. |
| 1894 | APInt NumSkippedElements = Offset.udiv(ElementSize); |
| 1895 | |
| 1896 | Offset -= NumSkippedElements * ElementSize; |
| 1897 | Indices.push_back(IRB.getInt(NumSkippedElements)); |
| 1898 | return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy, |
| 1899 | Indices, Prefix); |
| 1900 | } |
| 1901 | |
| 1902 | /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the |
| 1903 | /// resulting pointer has PointerTy. |
| 1904 | /// |
| 1905 | /// This tries very hard to compute a "natural" GEP which arrives at the offset |
| 1906 | /// and produces the pointer type desired. Where it cannot, it will try to use |
| 1907 | /// the natural GEP to arrive at the offset and bitcast to the type. Where that |
| 1908 | /// fails, it will try to use an existing i8* and GEP to the byte offset and |
| 1909 | /// bitcast to the type. |
| 1910 | /// |
| 1911 | /// The strategy for finding the more natural GEPs is to peel off layers of the |
| 1912 | /// pointer, walking back through bit casts and GEPs, searching for a base |
| 1913 | /// pointer from which we can compute a natural GEP with the desired |
| 1914 | /// properities. The algorithm tries to fold as many constant indices into |
| 1915 | /// a single GEP as possible, thus making each GEP more independent of the |
| 1916 | /// surrounding code. |
| 1917 | static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD, |
| 1918 | Value *Ptr, APInt Offset, Type *PointerTy, |
| 1919 | const Twine &Prefix) { |
| 1920 | // Even though we don't look through PHI nodes, we could be called on an |
| 1921 | // instruction in an unreachable block, which may be on a cycle. |
| 1922 | SmallPtrSet<Value *, 4> Visited; |
| 1923 | Visited.insert(Ptr); |
| 1924 | SmallVector<Value *, 4> Indices; |
| 1925 | |
| 1926 | // We may end up computing an offset pointer that has the wrong type. If we |
| 1927 | // never are able to compute one directly that has the correct type, we'll |
| 1928 | // fall back to it, so keep it around here. |
| 1929 | Value *OffsetPtr = 0; |
| 1930 | |
| 1931 | // Remember any i8 pointer we come across to re-use if we need to do a raw |
| 1932 | // byte offset. |
| 1933 | Value *Int8Ptr = 0; |
| 1934 | APInt Int8PtrOffset(Offset.getBitWidth(), 0); |
| 1935 | |
| 1936 | Type *TargetTy = PointerTy->getPointerElementType(); |
| 1937 | |
| 1938 | do { |
| 1939 | // First fold any existing GEPs into the offset. |
| 1940 | while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) { |
| 1941 | APInt GEPOffset(Offset.getBitWidth(), 0); |
| 1942 | if (!accumulateGEPOffsets(TD, *GEP, GEPOffset)) |
| 1943 | break; |
| 1944 | Offset += GEPOffset; |
| 1945 | Ptr = GEP->getPointerOperand(); |
| 1946 | if (!Visited.insert(Ptr)) |
| 1947 | break; |
| 1948 | } |
| 1949 | |
| 1950 | // See if we can perform a natural GEP here. |
| 1951 | Indices.clear(); |
| 1952 | if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy, |
| 1953 | Indices, Prefix)) { |
| 1954 | if (P->getType() == PointerTy) { |
| 1955 | // Zap any offset pointer that we ended up computing in previous rounds. |
| 1956 | if (OffsetPtr && OffsetPtr->use_empty()) |
| 1957 | if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) |
| 1958 | I->eraseFromParent(); |
| 1959 | return P; |
| 1960 | } |
| 1961 | if (!OffsetPtr) { |
| 1962 | OffsetPtr = P; |
| 1963 | } |
| 1964 | } |
| 1965 | |
| 1966 | // Stash this pointer if we've found an i8*. |
| 1967 | if (Ptr->getType()->isIntegerTy(8)) { |
| 1968 | Int8Ptr = Ptr; |
| 1969 | Int8PtrOffset = Offset; |
| 1970 | } |
| 1971 | |
| 1972 | // Peel off a layer of the pointer and update the offset appropriately. |
| 1973 | if (Operator::getOpcode(Ptr) == Instruction::BitCast) { |
| 1974 | Ptr = cast<Operator>(Ptr)->getOperand(0); |
| 1975 | } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) { |
| 1976 | if (GA->mayBeOverridden()) |
| 1977 | break; |
| 1978 | Ptr = GA->getAliasee(); |
| 1979 | } else { |
| 1980 | break; |
| 1981 | } |
| 1982 | assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!"); |
| 1983 | } while (Visited.insert(Ptr)); |
| 1984 | |
| 1985 | if (!OffsetPtr) { |
| 1986 | if (!Int8Ptr) { |
| 1987 | Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(), |
| 1988 | Prefix + ".raw_cast"); |
| 1989 | Int8PtrOffset = Offset; |
| 1990 | } |
| 1991 | |
| 1992 | OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr : |
| 1993 | IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset), |
| 1994 | Prefix + ".raw_idx"); |
| 1995 | } |
| 1996 | Ptr = OffsetPtr; |
| 1997 | |
| 1998 | // On the off chance we were targeting i8*, guard the bitcast here. |
| 1999 | if (Ptr->getType() != PointerTy) |
| 2000 | Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast"); |
| 2001 | |
| 2002 | return Ptr; |
| 2003 | } |
| 2004 | |
| 2005 | /// \brief Test whether the given alloca partition can be promoted to a vector. |
| 2006 | /// |
| 2007 | /// This is a quick test to check whether we can rewrite a particular alloca |
| 2008 | /// partition (and its newly formed alloca) into a vector alloca with only |
| 2009 | /// whole-vector loads and stores such that it could be promoted to a vector |
| 2010 | /// SSA value. We only can ensure this for a limited set of operations, and we |
| 2011 | /// don't want to do the rewrites unless we are confident that the result will |
| 2012 | /// be promotable, so we have an early test here. |
| 2013 | static bool isVectorPromotionViable(const TargetData &TD, |
| 2014 | Type *AllocaTy, |
| 2015 | AllocaPartitioning &P, |
| 2016 | uint64_t PartitionBeginOffset, |
| 2017 | uint64_t PartitionEndOffset, |
| 2018 | AllocaPartitioning::const_use_iterator I, |
| 2019 | AllocaPartitioning::const_use_iterator E) { |
| 2020 | VectorType *Ty = dyn_cast<VectorType>(AllocaTy); |
| 2021 | if (!Ty) |
| 2022 | return false; |
| 2023 | |
| 2024 | uint64_t VecSize = TD.getTypeSizeInBits(Ty); |
| 2025 | uint64_t ElementSize = Ty->getScalarSizeInBits(); |
| 2026 | |
| 2027 | // While the definition of LLVM vectors is bitpacked, we don't support sizes |
| 2028 | // that aren't byte sized. |
| 2029 | if (ElementSize % 8) |
| 2030 | return false; |
| 2031 | assert((VecSize % 8) == 0 && "vector size not a multiple of element size?"); |
| 2032 | VecSize /= 8; |
| 2033 | ElementSize /= 8; |
| 2034 | |
| 2035 | for (; I != E; ++I) { |
Chandler Carruth | fdb1585 | 2012-10-02 18:57:13 +0000 | [diff] [blame] | 2036 | if (!I->U) |
| 2037 | continue; // Skip dead use. |
| 2038 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2039 | uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset; |
| 2040 | uint64_t BeginIndex = BeginOffset / ElementSize; |
| 2041 | if (BeginIndex * ElementSize != BeginOffset || |
| 2042 | BeginIndex >= Ty->getNumElements()) |
| 2043 | return false; |
| 2044 | uint64_t EndOffset = I->EndOffset - PartitionBeginOffset; |
| 2045 | uint64_t EndIndex = EndOffset / ElementSize; |
| 2046 | if (EndIndex * ElementSize != EndOffset || |
| 2047 | EndIndex > Ty->getNumElements()) |
| 2048 | return false; |
| 2049 | |
| 2050 | // FIXME: We should build shuffle vector instructions to handle |
| 2051 | // non-element-sized accesses. |
| 2052 | if ((EndOffset - BeginOffset) != ElementSize && |
| 2053 | (EndOffset - BeginOffset) != VecSize) |
| 2054 | return false; |
| 2055 | |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2056 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2057 | if (MI->isVolatile()) |
| 2058 | return false; |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2059 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2060 | const AllocaPartitioning::MemTransferOffsets &MTO |
| 2061 | = P.getMemTransferOffsets(*MTI); |
| 2062 | if (!MTO.IsSplittable) |
| 2063 | return false; |
| 2064 | } |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2065 | } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2066 | // Disable vector promotion when there are loads or stores of an FCA. |
| 2067 | return false; |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2068 | } else if (!isa<LoadInst>(I->U->getUser()) && |
| 2069 | !isa<StoreInst>(I->U->getUser())) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2070 | return false; |
| 2071 | } |
| 2072 | } |
| 2073 | return true; |
| 2074 | } |
| 2075 | |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2076 | /// \brief Test whether the given alloca partition can be promoted to an int. |
| 2077 | /// |
| 2078 | /// This is a quick test to check whether we can rewrite a particular alloca |
| 2079 | /// partition (and its newly formed alloca) into an integer alloca suitable for |
| 2080 | /// promotion to an SSA value. We only can ensure this for a limited set of |
| 2081 | /// operations, and we don't want to do the rewrites unless we are confident |
| 2082 | /// that the result will be promotable, so we have an early test here. |
| 2083 | static bool isIntegerPromotionViable(const TargetData &TD, |
| 2084 | Type *AllocaTy, |
Chandler Carruth | aa3cb33 | 2012-10-04 10:39:28 +0000 | [diff] [blame] | 2085 | uint64_t AllocBeginOffset, |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2086 | AllocaPartitioning &P, |
| 2087 | AllocaPartitioning::const_use_iterator I, |
| 2088 | AllocaPartitioning::const_use_iterator E) { |
| 2089 | IntegerType *Ty = dyn_cast<IntegerType>(AllocaTy); |
Chandler Carruth | aa3cb33 | 2012-10-04 10:39:28 +0000 | [diff] [blame] | 2090 | if (!Ty || 8*TD.getTypeStoreSize(Ty) != Ty->getBitWidth()) |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2091 | return false; |
| 2092 | |
| 2093 | // Check the uses to ensure the uses are (likely) promoteable integer uses. |
| 2094 | // Also ensure that the alloca has a covering load or store. We don't want |
| 2095 | // promote because of some other unsplittable entry (which we may make |
| 2096 | // splittable later) and lose the ability to promote each element access. |
| 2097 | bool WholeAllocaOp = false; |
| 2098 | for (; I != E; ++I) { |
Chandler Carruth | fdb1585 | 2012-10-02 18:57:13 +0000 | [diff] [blame] | 2099 | if (!I->U) |
| 2100 | continue; // Skip dead use. |
Chandler Carruth | aa3cb33 | 2012-10-04 10:39:28 +0000 | [diff] [blame] | 2101 | |
| 2102 | // We can't reasonably handle cases where the load or store extends past |
| 2103 | // the end of the aloca's type and into its padding. |
| 2104 | if ((I->EndOffset - AllocBeginOffset) > TD.getTypeStoreSize(Ty)) |
| 2105 | return false; |
| 2106 | |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2107 | if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) { |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2108 | if (LI->isVolatile() || !LI->getType()->isIntegerTy()) |
| 2109 | return false; |
| 2110 | if (LI->getType() == Ty) |
| 2111 | WholeAllocaOp = true; |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2112 | } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) { |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2113 | if (SI->isVolatile() || !SI->getValueOperand()->getType()->isIntegerTy()) |
| 2114 | return false; |
| 2115 | if (SI->getValueOperand()->getType() == Ty) |
| 2116 | WholeAllocaOp = true; |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2117 | } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) { |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2118 | if (MI->isVolatile()) |
| 2119 | return false; |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2120 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) { |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2121 | const AllocaPartitioning::MemTransferOffsets &MTO |
| 2122 | = P.getMemTransferOffsets(*MTI); |
| 2123 | if (!MTO.IsSplittable) |
| 2124 | return false; |
| 2125 | } |
| 2126 | } else { |
| 2127 | return false; |
| 2128 | } |
| 2129 | } |
| 2130 | return WholeAllocaOp; |
| 2131 | } |
| 2132 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2133 | namespace { |
| 2134 | /// \brief Visitor to rewrite instructions using a partition of an alloca to |
| 2135 | /// use a new alloca. |
| 2136 | /// |
| 2137 | /// Also implements the rewriting to vector-based accesses when the partition |
| 2138 | /// passes the isVectorPromotionViable predicate. Most of the rewriting logic |
| 2139 | /// lives here. |
| 2140 | class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter, |
| 2141 | bool> { |
| 2142 | // Befriend the base class so it can delegate to private visit methods. |
| 2143 | friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>; |
| 2144 | |
| 2145 | const TargetData &TD; |
| 2146 | AllocaPartitioning &P; |
| 2147 | SROA &Pass; |
| 2148 | AllocaInst &OldAI, &NewAI; |
| 2149 | const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset; |
| 2150 | |
| 2151 | // If we are rewriting an alloca partition which can be written as pure |
| 2152 | // vector operations, we stash extra information here. When VecTy is |
| 2153 | // non-null, we have some strict guarantees about the rewriten alloca: |
| 2154 | // - The new alloca is exactly the size of the vector type here. |
| 2155 | // - The accesses all either map to the entire vector or to a single |
| 2156 | // element. |
| 2157 | // - The set of accessing instructions is only one of those handled above |
| 2158 | // in isVectorPromotionViable. Generally these are the same access kinds |
| 2159 | // which are promotable via mem2reg. |
| 2160 | VectorType *VecTy; |
| 2161 | Type *ElementTy; |
| 2162 | uint64_t ElementSize; |
| 2163 | |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2164 | // This is a convenience and flag variable that will be null unless the new |
| 2165 | // alloca has a promotion-targeted integer type due to passing |
| 2166 | // isIntegerPromotionViable above. If it is non-null does, the desired |
| 2167 | // integer type will be stored here for easy access during rewriting. |
| 2168 | IntegerType *IntPromotionTy; |
| 2169 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2170 | // The offset of the partition user currently being rewritten. |
| 2171 | uint64_t BeginOffset, EndOffset; |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2172 | Use *OldUse; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2173 | Instruction *OldPtr; |
| 2174 | |
| 2175 | // The name prefix to use when rewriting instructions for this alloca. |
| 2176 | std::string NamePrefix; |
| 2177 | |
| 2178 | public: |
| 2179 | AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P, |
| 2180 | AllocaPartitioning::iterator PI, |
| 2181 | SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI, |
| 2182 | uint64_t NewBeginOffset, uint64_t NewEndOffset) |
| 2183 | : TD(TD), P(P), Pass(Pass), |
| 2184 | OldAI(OldAI), NewAI(NewAI), |
| 2185 | NewAllocaBeginOffset(NewBeginOffset), |
| 2186 | NewAllocaEndOffset(NewEndOffset), |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2187 | VecTy(), ElementTy(), ElementSize(), IntPromotionTy(), |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2188 | BeginOffset(), EndOffset() { |
| 2189 | } |
| 2190 | |
| 2191 | /// \brief Visit the users of the alloca partition and rewrite them. |
| 2192 | bool visitUsers(AllocaPartitioning::const_use_iterator I, |
| 2193 | AllocaPartitioning::const_use_iterator E) { |
| 2194 | if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P, |
| 2195 | NewAllocaBeginOffset, NewAllocaEndOffset, |
| 2196 | I, E)) { |
| 2197 | ++NumVectorized; |
| 2198 | VecTy = cast<VectorType>(NewAI.getAllocatedType()); |
| 2199 | ElementTy = VecTy->getElementType(); |
| 2200 | assert((VecTy->getScalarSizeInBits() % 8) == 0 && |
| 2201 | "Only multiple-of-8 sized vector elements are viable"); |
| 2202 | ElementSize = VecTy->getScalarSizeInBits() / 8; |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2203 | } else if (isIntegerPromotionViable(TD, NewAI.getAllocatedType(), |
Chandler Carruth | aa3cb33 | 2012-10-04 10:39:28 +0000 | [diff] [blame] | 2204 | NewAllocaBeginOffset, P, I, E)) { |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2205 | IntPromotionTy = cast<IntegerType>(NewAI.getAllocatedType()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2206 | } |
| 2207 | bool CanSROA = true; |
| 2208 | for (; I != E; ++I) { |
Chandler Carruth | fdb1585 | 2012-10-02 18:57:13 +0000 | [diff] [blame] | 2209 | if (!I->U) |
| 2210 | continue; // Skip dead uses. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2211 | BeginOffset = I->BeginOffset; |
| 2212 | EndOffset = I->EndOffset; |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2213 | OldUse = I->U; |
| 2214 | OldPtr = cast<Instruction>(I->U->get()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2215 | NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str(); |
Chandler Carruth | 77c1270 | 2012-10-01 01:49:22 +0000 | [diff] [blame] | 2216 | CanSROA &= visit(cast<Instruction>(I->U->getUser())); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2217 | } |
| 2218 | if (VecTy) { |
| 2219 | assert(CanSROA); |
| 2220 | VecTy = 0; |
| 2221 | ElementTy = 0; |
| 2222 | ElementSize = 0; |
| 2223 | } |
| 2224 | return CanSROA; |
| 2225 | } |
| 2226 | |
| 2227 | private: |
| 2228 | // Every instruction which can end up as a user must have a rewrite rule. |
| 2229 | bool visitInstruction(Instruction &I) { |
| 2230 | DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n"); |
| 2231 | llvm_unreachable("No rewrite rule for this instruction!"); |
| 2232 | } |
| 2233 | |
| 2234 | Twine getName(const Twine &Suffix) { |
| 2235 | return NamePrefix + Suffix; |
| 2236 | } |
| 2237 | |
| 2238 | Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) { |
| 2239 | assert(BeginOffset >= NewAllocaBeginOffset); |
| 2240 | APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset); |
| 2241 | return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName("")); |
| 2242 | } |
| 2243 | |
Chandler Carruth | f710fb1 | 2012-10-03 08:14:02 +0000 | [diff] [blame] | 2244 | /// \brief Compute suitable alignment to access an offset into the new alloca. |
| 2245 | unsigned getOffsetAlign(uint64_t Offset) { |
Chandler Carruth | 673850a | 2012-10-01 12:16:54 +0000 | [diff] [blame] | 2246 | unsigned NewAIAlign = NewAI.getAlignment(); |
| 2247 | if (!NewAIAlign) |
| 2248 | NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType()); |
| 2249 | return MinAlign(NewAIAlign, Offset); |
| 2250 | } |
Chandler Carruth | f710fb1 | 2012-10-03 08:14:02 +0000 | [diff] [blame] | 2251 | |
| 2252 | /// \brief Compute suitable alignment to access this partition of the new |
| 2253 | /// alloca. |
| 2254 | unsigned getPartitionAlign() { |
| 2255 | return getOffsetAlign(BeginOffset - NewAllocaBeginOffset); |
Chandler Carruth | 673850a | 2012-10-01 12:16:54 +0000 | [diff] [blame] | 2256 | } |
| 2257 | |
Chandler Carruth | f710fb1 | 2012-10-03 08:14:02 +0000 | [diff] [blame] | 2258 | /// \brief Compute suitable alignment to access a type at an offset of the |
| 2259 | /// new alloca. |
| 2260 | /// |
| 2261 | /// \returns zero if the type's ABI alignment is a suitable alignment, |
| 2262 | /// otherwise returns the maximal suitable alignment. |
| 2263 | unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) { |
| 2264 | unsigned Align = getOffsetAlign(Offset); |
| 2265 | return Align == TD.getABITypeAlignment(Ty) ? 0 : Align; |
| 2266 | } |
| 2267 | |
| 2268 | /// \brief Compute suitable alignment to access a type at the beginning of |
| 2269 | /// this partition of the new alloca. |
| 2270 | /// |
| 2271 | /// See \c getOffsetTypeAlign for details; this routine delegates to it. |
| 2272 | unsigned getPartitionTypeAlign(Type *Ty) { |
| 2273 | return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset); |
Chandler Carruth | 673850a | 2012-10-01 12:16:54 +0000 | [diff] [blame] | 2274 | } |
| 2275 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2276 | ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) { |
| 2277 | assert(VecTy && "Can only call getIndex when rewriting a vector"); |
| 2278 | uint64_t RelOffset = Offset - NewAllocaBeginOffset; |
| 2279 | assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds"); |
| 2280 | uint32_t Index = RelOffset / ElementSize; |
| 2281 | assert(Index * ElementSize == RelOffset); |
| 2282 | return IRB.getInt32(Index); |
| 2283 | } |
| 2284 | |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2285 | Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy, |
| 2286 | uint64_t Offset) { |
| 2287 | assert(IntPromotionTy && "Alloca is not an integer we can extract from"); |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2288 | Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), |
| 2289 | getName(".load")); |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2290 | assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset"); |
| 2291 | uint64_t RelOffset = Offset - NewAllocaBeginOffset; |
Chandler Carruth | aa3cb33 | 2012-10-04 10:39:28 +0000 | [diff] [blame] | 2292 | assert(TD.getTypeStoreSize(TargetTy) + RelOffset <= |
| 2293 | TD.getTypeStoreSize(IntPromotionTy) && |
| 2294 | "Element load outside of alloca store"); |
| 2295 | uint64_t ShAmt = 8*RelOffset; |
| 2296 | if (TD.isBigEndian()) |
| 2297 | ShAmt = 8*(TD.getTypeStoreSize(IntPromotionTy) - |
| 2298 | TD.getTypeStoreSize(TargetTy) - RelOffset); |
| 2299 | if (ShAmt) |
| 2300 | V = IRB.CreateLShr(V, ShAmt, getName(".shift")); |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2301 | if (TargetTy != IntPromotionTy) { |
| 2302 | assert(TargetTy->getBitWidth() < IntPromotionTy->getBitWidth() && |
| 2303 | "Cannot extract to a larger integer!"); |
| 2304 | V = IRB.CreateTrunc(V, TargetTy, getName(".trunc")); |
| 2305 | } |
| 2306 | return V; |
| 2307 | } |
| 2308 | |
| 2309 | StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) { |
| 2310 | IntegerType *Ty = cast<IntegerType>(V->getType()); |
| 2311 | if (Ty == IntPromotionTy) |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2312 | return IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment()); |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2313 | |
| 2314 | assert(Ty->getBitWidth() < IntPromotionTy->getBitWidth() && |
| 2315 | "Cannot insert a larger integer!"); |
| 2316 | V = IRB.CreateZExt(V, IntPromotionTy, getName(".ext")); |
| 2317 | assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset"); |
| 2318 | uint64_t RelOffset = Offset - NewAllocaBeginOffset; |
Chandler Carruth | aa3cb33 | 2012-10-04 10:39:28 +0000 | [diff] [blame] | 2319 | assert(TD.getTypeStoreSize(Ty) + RelOffset <= |
| 2320 | TD.getTypeStoreSize(IntPromotionTy) && |
| 2321 | "Element store outside of alloca store"); |
| 2322 | uint64_t ShAmt = 8*RelOffset; |
| 2323 | if (TD.isBigEndian()) |
| 2324 | ShAmt = 8*(TD.getTypeStoreSize(IntPromotionTy) - TD.getTypeStoreSize(Ty) |
| 2325 | - RelOffset); |
| 2326 | if (ShAmt) |
| 2327 | V = IRB.CreateShl(V, ShAmt, getName(".shift")); |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2328 | |
Chandler Carruth | aa3cb33 | 2012-10-04 10:39:28 +0000 | [diff] [blame] | 2329 | APInt Mask = ~Ty->getMask().zext(IntPromotionTy->getBitWidth()).shl(ShAmt); |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2330 | Value *Old = IRB.CreateAnd(IRB.CreateAlignedLoad(&NewAI, |
| 2331 | NewAI.getAlignment(), |
| 2332 | getName(".oldload")), |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2333 | Mask, getName(".mask")); |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2334 | return IRB.CreateAlignedStore(IRB.CreateOr(Old, V, getName(".insert")), |
| 2335 | &NewAI, NewAI.getAlignment()); |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2336 | } |
| 2337 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2338 | void deleteIfTriviallyDead(Value *V) { |
| 2339 | Instruction *I = cast<Instruction>(V); |
| 2340 | if (isInstructionTriviallyDead(I)) |
| 2341 | Pass.DeadInsts.push_back(I); |
| 2342 | } |
| 2343 | |
| 2344 | Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) { |
| 2345 | if (V->getType()->isIntegerTy() && Ty->isPointerTy()) |
| 2346 | return IRB.CreateIntToPtr(V, Ty); |
| 2347 | if (V->getType()->isPointerTy() && Ty->isIntegerTy()) |
| 2348 | return IRB.CreatePtrToInt(V, Ty); |
| 2349 | |
| 2350 | return IRB.CreateBitCast(V, Ty); |
| 2351 | } |
| 2352 | |
| 2353 | bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) { |
| 2354 | Value *Result; |
| 2355 | if (LI.getType() == VecTy->getElementType() || |
| 2356 | BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) { |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2357 | Result = IRB.CreateExtractElement( |
| 2358 | IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")), |
| 2359 | getIndex(IRB, BeginOffset), getName(".extract")); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2360 | } else { |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2361 | Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), |
| 2362 | getName(".load")); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2363 | } |
| 2364 | if (Result->getType() != LI.getType()) |
| 2365 | Result = getValueCast(IRB, Result, LI.getType()); |
| 2366 | LI.replaceAllUsesWith(Result); |
| 2367 | Pass.DeadInsts.push_back(&LI); |
| 2368 | |
| 2369 | DEBUG(dbgs() << " to: " << *Result << "\n"); |
| 2370 | return true; |
| 2371 | } |
| 2372 | |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2373 | bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) { |
| 2374 | assert(!LI.isVolatile()); |
| 2375 | Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()), |
| 2376 | BeginOffset); |
| 2377 | LI.replaceAllUsesWith(Result); |
| 2378 | Pass.DeadInsts.push_back(&LI); |
| 2379 | DEBUG(dbgs() << " to: " << *Result << "\n"); |
| 2380 | return true; |
| 2381 | } |
| 2382 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2383 | bool visitLoadInst(LoadInst &LI) { |
| 2384 | DEBUG(dbgs() << " original: " << LI << "\n"); |
| 2385 | Value *OldOp = LI.getOperand(0); |
| 2386 | assert(OldOp == OldPtr); |
| 2387 | IRBuilder<> IRB(&LI); |
| 2388 | |
| 2389 | if (VecTy) |
| 2390 | return rewriteVectorizedLoadInst(IRB, LI, OldOp); |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2391 | if (IntPromotionTy) |
| 2392 | return rewriteIntegerLoad(IRB, LI); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2393 | |
| 2394 | Value *NewPtr = getAdjustedAllocaPtr(IRB, |
| 2395 | LI.getPointerOperand()->getType()); |
| 2396 | LI.setOperand(0, NewPtr); |
Chandler Carruth | f710fb1 | 2012-10-03 08:14:02 +0000 | [diff] [blame] | 2397 | LI.setAlignment(getPartitionTypeAlign(LI.getType())); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2398 | DEBUG(dbgs() << " to: " << LI << "\n"); |
| 2399 | |
| 2400 | deleteIfTriviallyDead(OldOp); |
| 2401 | return NewPtr == &NewAI && !LI.isVolatile(); |
| 2402 | } |
| 2403 | |
| 2404 | bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI, |
| 2405 | Value *OldOp) { |
| 2406 | Value *V = SI.getValueOperand(); |
| 2407 | if (V->getType() == ElementTy || |
| 2408 | BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) { |
| 2409 | if (V->getType() != ElementTy) |
| 2410 | V = getValueCast(IRB, V, ElementTy); |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2411 | LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), |
| 2412 | getName(".load")); |
| 2413 | V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset), |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2414 | getName(".insert")); |
| 2415 | } else if (V->getType() != VecTy) { |
| 2416 | V = getValueCast(IRB, V, VecTy); |
| 2417 | } |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2418 | StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2419 | Pass.DeadInsts.push_back(&SI); |
| 2420 | |
| 2421 | (void)Store; |
| 2422 | DEBUG(dbgs() << " to: " << *Store << "\n"); |
| 2423 | return true; |
| 2424 | } |
| 2425 | |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2426 | bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) { |
| 2427 | assert(!SI.isVolatile()); |
| 2428 | StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset); |
| 2429 | Pass.DeadInsts.push_back(&SI); |
| 2430 | (void)Store; |
| 2431 | DEBUG(dbgs() << " to: " << *Store << "\n"); |
| 2432 | return true; |
| 2433 | } |
| 2434 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2435 | bool visitStoreInst(StoreInst &SI) { |
| 2436 | DEBUG(dbgs() << " original: " << SI << "\n"); |
| 2437 | Value *OldOp = SI.getOperand(1); |
| 2438 | assert(OldOp == OldPtr); |
| 2439 | IRBuilder<> IRB(&SI); |
| 2440 | |
| 2441 | if (VecTy) |
| 2442 | return rewriteVectorizedStoreInst(IRB, SI, OldOp); |
Chandler Carruth | bc4021f | 2012-09-24 00:34:20 +0000 | [diff] [blame] | 2443 | if (IntPromotionTy) |
| 2444 | return rewriteIntegerStore(IRB, SI); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2445 | |
Chandler Carruth | b2d98c2 | 2012-10-04 12:33:50 +0000 | [diff] [blame] | 2446 | // Strip all inbounds GEPs and pointer casts to try to dig out any root |
| 2447 | // alloca that should be re-examined after promoting this alloca. |
| 2448 | if (SI.getValueOperand()->getType()->isPointerTy()) |
| 2449 | if (AllocaInst *AI = dyn_cast<AllocaInst>(SI.getValueOperand() |
| 2450 | ->stripInBoundsOffsets())) |
| 2451 | Pass.PostPromotionWorklist.insert(AI); |
| 2452 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2453 | Value *NewPtr = getAdjustedAllocaPtr(IRB, |
| 2454 | SI.getPointerOperand()->getType()); |
| 2455 | SI.setOperand(1, NewPtr); |
Chandler Carruth | f710fb1 | 2012-10-03 08:14:02 +0000 | [diff] [blame] | 2456 | SI.setAlignment(getPartitionTypeAlign(SI.getValueOperand()->getType())); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2457 | DEBUG(dbgs() << " to: " << SI << "\n"); |
| 2458 | |
| 2459 | deleteIfTriviallyDead(OldOp); |
| 2460 | return NewPtr == &NewAI && !SI.isVolatile(); |
| 2461 | } |
| 2462 | |
| 2463 | bool visitMemSetInst(MemSetInst &II) { |
| 2464 | DEBUG(dbgs() << " original: " << II << "\n"); |
| 2465 | IRBuilder<> IRB(&II); |
| 2466 | assert(II.getRawDest() == OldPtr); |
| 2467 | |
| 2468 | // If the memset has a variable size, it cannot be split, just adjust the |
| 2469 | // pointer to the new alloca. |
| 2470 | if (!isa<Constant>(II.getLength())) { |
| 2471 | II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType())); |
Chandler Carruth | d0ac06d | 2012-09-26 10:59:22 +0000 | [diff] [blame] | 2472 | Type *CstTy = II.getAlignmentCst()->getType(); |
Chandler Carruth | f710fb1 | 2012-10-03 08:14:02 +0000 | [diff] [blame] | 2473 | II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign())); |
Chandler Carruth | d0ac06d | 2012-09-26 10:59:22 +0000 | [diff] [blame] | 2474 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2475 | deleteIfTriviallyDead(OldPtr); |
| 2476 | return false; |
| 2477 | } |
| 2478 | |
| 2479 | // Record this instruction for deletion. |
| 2480 | if (Pass.DeadSplitInsts.insert(&II)) |
| 2481 | Pass.DeadInsts.push_back(&II); |
| 2482 | |
| 2483 | Type *AllocaTy = NewAI.getAllocatedType(); |
| 2484 | Type *ScalarTy = AllocaTy->getScalarType(); |
| 2485 | |
| 2486 | // If this doesn't map cleanly onto the alloca type, and that type isn't |
| 2487 | // a single value type, just emit a memset. |
| 2488 | if (!VecTy && (BeginOffset != NewAllocaBeginOffset || |
| 2489 | EndOffset != NewAllocaEndOffset || |
| 2490 | !AllocaTy->isSingleValueType() || |
| 2491 | !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) { |
| 2492 | Type *SizeTy = II.getLength()->getType(); |
| 2493 | Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2494 | CallInst *New |
| 2495 | = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB, |
| 2496 | II.getRawDest()->getType()), |
Chandler Carruth | f710fb1 | 2012-10-03 08:14:02 +0000 | [diff] [blame] | 2497 | II.getValue(), Size, getPartitionAlign(), |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2498 | II.isVolatile()); |
| 2499 | (void)New; |
| 2500 | DEBUG(dbgs() << " to: " << *New << "\n"); |
| 2501 | return false; |
| 2502 | } |
| 2503 | |
| 2504 | // If we can represent this as a simple value, we have to build the actual |
| 2505 | // value to store, which requires expanding the byte present in memset to |
| 2506 | // a sensible representation for the alloca type. This is essentially |
| 2507 | // splatting the byte to a sufficiently wide integer, bitcasting to the |
| 2508 | // desired scalar type, and splatting it across any desired vector type. |
| 2509 | Value *V = II.getValue(); |
| 2510 | IntegerType *VTy = cast<IntegerType>(V->getType()); |
| 2511 | Type *IntTy = Type::getIntNTy(VTy->getContext(), |
| 2512 | TD.getTypeSizeInBits(ScalarTy)); |
| 2513 | if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth()) |
| 2514 | V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")), |
| 2515 | ConstantExpr::getUDiv( |
| 2516 | Constant::getAllOnesValue(IntTy), |
| 2517 | ConstantExpr::getZExt( |
| 2518 | Constant::getAllOnesValue(V->getType()), |
| 2519 | IntTy)), |
| 2520 | getName(".isplat")); |
| 2521 | if (V->getType() != ScalarTy) { |
| 2522 | if (ScalarTy->isPointerTy()) |
| 2523 | V = IRB.CreateIntToPtr(V, ScalarTy); |
| 2524 | else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy()) |
| 2525 | V = IRB.CreateBitCast(V, ScalarTy); |
| 2526 | else if (ScalarTy->isIntegerTy()) |
| 2527 | llvm_unreachable("Computed different integer types with equal widths"); |
| 2528 | else |
| 2529 | llvm_unreachable("Invalid scalar type"); |
| 2530 | } |
| 2531 | |
| 2532 | // If this is an element-wide memset of a vectorizable alloca, insert it. |
| 2533 | if (VecTy && (BeginOffset > NewAllocaBeginOffset || |
| 2534 | EndOffset < NewAllocaEndOffset)) { |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2535 | StoreInst *Store = IRB.CreateAlignedStore( |
| 2536 | IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI, |
| 2537 | NewAI.getAlignment(), |
| 2538 | getName(".load")), |
| 2539 | V, getIndex(IRB, BeginOffset), |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2540 | getName(".insert")), |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2541 | &NewAI, NewAI.getAlignment()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2542 | (void)Store; |
| 2543 | DEBUG(dbgs() << " to: " << *Store << "\n"); |
| 2544 | return true; |
| 2545 | } |
| 2546 | |
| 2547 | // Splat to a vector if needed. |
| 2548 | if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) { |
| 2549 | VectorType *SplatSourceTy = VectorType::get(V->getType(), 1); |
| 2550 | V = IRB.CreateShuffleVector( |
| 2551 | IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V, |
| 2552 | IRB.getInt32(0), getName(".vsplat.insert")), |
| 2553 | UndefValue::get(SplatSourceTy), |
| 2554 | ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)), |
| 2555 | getName(".vsplat.shuffle")); |
| 2556 | assert(V->getType() == VecTy); |
| 2557 | } |
| 2558 | |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2559 | Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(), |
| 2560 | II.isVolatile()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2561 | (void)New; |
| 2562 | DEBUG(dbgs() << " to: " << *New << "\n"); |
| 2563 | return !II.isVolatile(); |
| 2564 | } |
| 2565 | |
| 2566 | bool visitMemTransferInst(MemTransferInst &II) { |
| 2567 | // Rewriting of memory transfer instructions can be a bit tricky. We break |
| 2568 | // them into two categories: split intrinsics and unsplit intrinsics. |
| 2569 | |
| 2570 | DEBUG(dbgs() << " original: " << II << "\n"); |
| 2571 | IRBuilder<> IRB(&II); |
| 2572 | |
| 2573 | assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr); |
| 2574 | bool IsDest = II.getRawDest() == OldPtr; |
| 2575 | |
| 2576 | const AllocaPartitioning::MemTransferOffsets &MTO |
| 2577 | = P.getMemTransferOffsets(II); |
| 2578 | |
Chandler Carruth | 673850a | 2012-10-01 12:16:54 +0000 | [diff] [blame] | 2579 | // Compute the relative offset within the transfer. |
| 2580 | unsigned IntPtrWidth = TD.getPointerSizeInBits(); |
| 2581 | APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin |
| 2582 | : MTO.SourceBegin)); |
| 2583 | |
| 2584 | unsigned Align = II.getAlignment(); |
| 2585 | if (Align > 1) |
| 2586 | Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(), |
Chandler Carruth | f710fb1 | 2012-10-03 08:14:02 +0000 | [diff] [blame] | 2587 | MinAlign(II.getAlignment(), getPartitionAlign())); |
Chandler Carruth | 673850a | 2012-10-01 12:16:54 +0000 | [diff] [blame] | 2588 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2589 | // For unsplit intrinsics, we simply modify the source and destination |
| 2590 | // pointers in place. This isn't just an optimization, it is a matter of |
| 2591 | // correctness. With unsplit intrinsics we may be dealing with transfers |
| 2592 | // within a single alloca before SROA ran, or with transfers that have |
| 2593 | // a variable length. We may also be dealing with memmove instead of |
| 2594 | // memcpy, and so simply updating the pointers is the necessary for us to |
| 2595 | // update both source and dest of a single call. |
| 2596 | if (!MTO.IsSplittable) { |
| 2597 | Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource(); |
| 2598 | if (IsDest) |
| 2599 | II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType())); |
| 2600 | else |
| 2601 | II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType())); |
| 2602 | |
Chandler Carruth | d0ac06d | 2012-09-26 10:59:22 +0000 | [diff] [blame] | 2603 | Type *CstTy = II.getAlignmentCst()->getType(); |
Chandler Carruth | 673850a | 2012-10-01 12:16:54 +0000 | [diff] [blame] | 2604 | II.setAlignment(ConstantInt::get(CstTy, Align)); |
Chandler Carruth | d0ac06d | 2012-09-26 10:59:22 +0000 | [diff] [blame] | 2605 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2606 | DEBUG(dbgs() << " to: " << II << "\n"); |
| 2607 | deleteIfTriviallyDead(OldOp); |
| 2608 | return false; |
| 2609 | } |
| 2610 | // For split transfer intrinsics we have an incredibly useful assurance: |
| 2611 | // the source and destination do not reside within the same alloca, and at |
| 2612 | // least one of them does not escape. This means that we can replace |
| 2613 | // memmove with memcpy, and we don't need to worry about all manner of |
| 2614 | // downsides to splitting and transforming the operations. |
| 2615 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2616 | // If this doesn't map cleanly onto the alloca type, and that type isn't |
| 2617 | // a single value type, just emit a memcpy. |
| 2618 | bool EmitMemCpy |
| 2619 | = !VecTy && (BeginOffset != NewAllocaBeginOffset || |
| 2620 | EndOffset != NewAllocaEndOffset || |
| 2621 | !NewAI.getAllocatedType()->isSingleValueType()); |
| 2622 | |
| 2623 | // If we're just going to emit a memcpy, the alloca hasn't changed, and the |
| 2624 | // size hasn't been shrunk based on analysis of the viable range, this is |
| 2625 | // a no-op. |
| 2626 | if (EmitMemCpy && &OldAI == &NewAI) { |
| 2627 | uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin; |
| 2628 | uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd; |
| 2629 | // Ensure the start lines up. |
| 2630 | assert(BeginOffset == OrigBegin); |
Benjamin Kramer | d080769 | 2012-09-14 13:08:09 +0000 | [diff] [blame] | 2631 | (void)OrigBegin; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2632 | |
| 2633 | // Rewrite the size as needed. |
| 2634 | if (EndOffset != OrigEnd) |
| 2635 | II.setLength(ConstantInt::get(II.getLength()->getType(), |
| 2636 | EndOffset - BeginOffset)); |
| 2637 | return false; |
| 2638 | } |
| 2639 | // Record this instruction for deletion. |
| 2640 | if (Pass.DeadSplitInsts.insert(&II)) |
| 2641 | Pass.DeadInsts.push_back(&II); |
| 2642 | |
| 2643 | bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset || |
| 2644 | EndOffset < NewAllocaEndOffset); |
| 2645 | |
| 2646 | Type *OtherPtrTy = IsDest ? II.getRawSource()->getType() |
| 2647 | : II.getRawDest()->getType(); |
| 2648 | if (!EmitMemCpy) |
| 2649 | OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo() |
| 2650 | : NewAI.getType(); |
| 2651 | |
| 2652 | // Compute the other pointer, folding as much as possible to produce |
| 2653 | // a single, simple GEP in most cases. |
| 2654 | Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest(); |
| 2655 | OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy, |
| 2656 | getName("." + OtherPtr->getName())); |
| 2657 | |
| 2658 | // Strip all inbounds GEPs and pointer casts to try to dig out any root |
| 2659 | // alloca that should be re-examined after rewriting this instruction. |
| 2660 | if (AllocaInst *AI |
| 2661 | = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) |
Chandler Carruth | b3dca3f | 2012-09-26 07:41:40 +0000 | [diff] [blame] | 2662 | Pass.Worklist.insert(AI); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2663 | |
| 2664 | if (EmitMemCpy) { |
| 2665 | Value *OurPtr |
| 2666 | = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType() |
| 2667 | : II.getRawSource()->getType()); |
| 2668 | Type *SizeTy = II.getLength()->getType(); |
| 2669 | Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset); |
| 2670 | |
| 2671 | CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr, |
| 2672 | IsDest ? OtherPtr : OurPtr, |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2673 | Size, Align, II.isVolatile()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2674 | (void)New; |
| 2675 | DEBUG(dbgs() << " to: " << *New << "\n"); |
| 2676 | return false; |
| 2677 | } |
| 2678 | |
Chandler Carruth | 322e9ba | 2012-10-03 08:26:28 +0000 | [diff] [blame] | 2679 | // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy |
| 2680 | // is equivalent to 1, but that isn't true if we end up rewriting this as |
| 2681 | // a load or store. |
| 2682 | if (!Align) |
| 2683 | Align = 1; |
| 2684 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2685 | Value *SrcPtr = OtherPtr; |
| 2686 | Value *DstPtr = &NewAI; |
| 2687 | if (!IsDest) |
| 2688 | std::swap(SrcPtr, DstPtr); |
| 2689 | |
| 2690 | Value *Src; |
| 2691 | if (IsVectorElement && !IsDest) { |
| 2692 | // We have to extract rather than load. |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2693 | Src = IRB.CreateExtractElement( |
| 2694 | IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")), |
| 2695 | getIndex(IRB, BeginOffset), |
| 2696 | getName(".copyextract")); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2697 | } else { |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2698 | Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(), |
| 2699 | getName(".copyload")); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2700 | } |
| 2701 | |
| 2702 | if (IsVectorElement && IsDest) { |
| 2703 | // We have to insert into a loaded copy before storing. |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2704 | Src = IRB.CreateInsertElement( |
| 2705 | IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")), |
| 2706 | Src, getIndex(IRB, BeginOffset), |
| 2707 | getName(".insert")); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2708 | } |
| 2709 | |
Chandler Carruth | 81b001a | 2012-09-26 10:27:46 +0000 | [diff] [blame] | 2710 | StoreInst *Store = cast<StoreInst>( |
| 2711 | IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile())); |
| 2712 | (void)Store; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2713 | DEBUG(dbgs() << " to: " << *Store << "\n"); |
| 2714 | return !II.isVolatile(); |
| 2715 | } |
| 2716 | |
| 2717 | bool visitIntrinsicInst(IntrinsicInst &II) { |
| 2718 | assert(II.getIntrinsicID() == Intrinsic::lifetime_start || |
| 2719 | II.getIntrinsicID() == Intrinsic::lifetime_end); |
| 2720 | DEBUG(dbgs() << " original: " << II << "\n"); |
| 2721 | IRBuilder<> IRB(&II); |
| 2722 | assert(II.getArgOperand(1) == OldPtr); |
| 2723 | |
| 2724 | // Record this instruction for deletion. |
| 2725 | if (Pass.DeadSplitInsts.insert(&II)) |
| 2726 | Pass.DeadInsts.push_back(&II); |
| 2727 | |
| 2728 | ConstantInt *Size |
| 2729 | = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()), |
| 2730 | EndOffset - BeginOffset); |
| 2731 | Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType()); |
| 2732 | Value *New; |
| 2733 | if (II.getIntrinsicID() == Intrinsic::lifetime_start) |
| 2734 | New = IRB.CreateLifetimeStart(Ptr, Size); |
| 2735 | else |
| 2736 | New = IRB.CreateLifetimeEnd(Ptr, Size); |
| 2737 | |
| 2738 | DEBUG(dbgs() << " to: " << *New << "\n"); |
| 2739 | return true; |
| 2740 | } |
| 2741 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2742 | bool visitPHINode(PHINode &PN) { |
| 2743 | DEBUG(dbgs() << " original: " << PN << "\n"); |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 2744 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2745 | // We would like to compute a new pointer in only one place, but have it be |
| 2746 | // as local as possible to the PHI. To do that, we re-use the location of |
| 2747 | // the old pointer, which necessarily must be in the right position to |
| 2748 | // dominate the PHI. |
| 2749 | IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr)); |
| 2750 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2751 | Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType()); |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 2752 | // Replace the operands which were using the old pointer. |
| 2753 | User::op_iterator OI = PN.op_begin(), OE = PN.op_end(); |
| 2754 | for (; OI != OE; ++OI) |
| 2755 | if (*OI == OldPtr) |
| 2756 | *OI = NewPtr; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2757 | |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 2758 | DEBUG(dbgs() << " to: " << PN << "\n"); |
| 2759 | deleteIfTriviallyDead(OldPtr); |
| 2760 | return false; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2761 | } |
| 2762 | |
| 2763 | bool visitSelectInst(SelectInst &SI) { |
| 2764 | DEBUG(dbgs() << " original: " << SI << "\n"); |
| 2765 | IRBuilder<> IRB(&SI); |
| 2766 | |
| 2767 | // Find the operand we need to rewrite here. |
| 2768 | bool IsTrueVal = SI.getTrueValue() == OldPtr; |
| 2769 | if (IsTrueVal) |
| 2770 | assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!"); |
| 2771 | else |
| 2772 | assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!"); |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 2773 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2774 | Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType()); |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 2775 | SI.setOperand(IsTrueVal ? 1 : 2, NewPtr); |
| 2776 | DEBUG(dbgs() << " to: " << SI << "\n"); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2777 | deleteIfTriviallyDead(OldPtr); |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 2778 | return false; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2779 | } |
| 2780 | |
| 2781 | }; |
| 2782 | } |
| 2783 | |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2784 | namespace { |
| 2785 | /// \brief Visitor to rewrite aggregate loads and stores as scalar. |
| 2786 | /// |
| 2787 | /// This pass aggressively rewrites all aggregate loads and stores on |
| 2788 | /// a particular pointer (or any pointer derived from it which we can identify) |
| 2789 | /// with scalar loads and stores. |
| 2790 | class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> { |
| 2791 | // Befriend the base class so it can delegate to private visit methods. |
| 2792 | friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>; |
| 2793 | |
| 2794 | const TargetData &TD; |
| 2795 | |
| 2796 | /// Queue of pointer uses to analyze and potentially rewrite. |
| 2797 | SmallVector<Use *, 8> Queue; |
| 2798 | |
| 2799 | /// Set to prevent us from cycling with phi nodes and loops. |
| 2800 | SmallPtrSet<User *, 8> Visited; |
| 2801 | |
| 2802 | /// The current pointer use being rewritten. This is used to dig up the used |
| 2803 | /// value (as opposed to the user). |
| 2804 | Use *U; |
| 2805 | |
| 2806 | public: |
| 2807 | AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {} |
| 2808 | |
| 2809 | /// Rewrite loads and stores through a pointer and all pointers derived from |
| 2810 | /// it. |
| 2811 | bool rewrite(Instruction &I) { |
| 2812 | DEBUG(dbgs() << " Rewriting FCA loads and stores...\n"); |
| 2813 | enqueueUsers(I); |
| 2814 | bool Changed = false; |
| 2815 | while (!Queue.empty()) { |
| 2816 | U = Queue.pop_back_val(); |
| 2817 | Changed |= visit(cast<Instruction>(U->getUser())); |
| 2818 | } |
| 2819 | return Changed; |
| 2820 | } |
| 2821 | |
| 2822 | private: |
| 2823 | /// Enqueue all the users of the given instruction for further processing. |
| 2824 | /// This uses a set to de-duplicate users. |
| 2825 | void enqueueUsers(Instruction &I) { |
| 2826 | for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; |
| 2827 | ++UI) |
| 2828 | if (Visited.insert(*UI)) |
| 2829 | Queue.push_back(&UI.getUse()); |
| 2830 | } |
| 2831 | |
| 2832 | // Conservative default is to not rewrite anything. |
| 2833 | bool visitInstruction(Instruction &I) { return false; } |
| 2834 | |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2835 | /// \brief Generic recursive split emission class. |
Benjamin Kramer | 371d5d8 | 2012-09-18 17:06:32 +0000 | [diff] [blame] | 2836 | template <typename Derived> |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2837 | class OpSplitter { |
| 2838 | protected: |
| 2839 | /// The builder used to form new instructions. |
| 2840 | IRBuilder<> IRB; |
| 2841 | /// The indices which to be used with insert- or extractvalue to select the |
| 2842 | /// appropriate value within the aggregate. |
| 2843 | SmallVector<unsigned, 4> Indices; |
| 2844 | /// The indices to a GEP instruction which will move Ptr to the correct slot |
| 2845 | /// within the aggregate. |
| 2846 | SmallVector<Value *, 4> GEPIndices; |
| 2847 | /// The base pointer of the original op, used as a base for GEPing the |
| 2848 | /// split operations. |
| 2849 | Value *Ptr; |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2850 | |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2851 | /// Initialize the splitter with an insertion point, Ptr and start with a |
| 2852 | /// single zero GEP index. |
| 2853 | OpSplitter(Instruction *InsertionPoint, Value *Ptr) |
Benjamin Kramer | 371d5d8 | 2012-09-18 17:06:32 +0000 | [diff] [blame] | 2854 | : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {} |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2855 | |
| 2856 | public: |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2857 | /// \brief Generic recursive split emission routine. |
| 2858 | /// |
| 2859 | /// This method recursively splits an aggregate op (load or store) into |
| 2860 | /// scalar or vector ops. It splits recursively until it hits a single value |
| 2861 | /// and emits that single value operation via the template argument. |
| 2862 | /// |
| 2863 | /// The logic of this routine relies on GEPs and insertvalue and |
| 2864 | /// extractvalue all operating with the same fundamental index list, merely |
| 2865 | /// formatted differently (GEPs need actual values). |
| 2866 | /// |
| 2867 | /// \param Ty The type being split recursively into smaller ops. |
| 2868 | /// \param Agg The aggregate value being built up or stored, depending on |
| 2869 | /// whether this is splitting a load or a store respectively. |
| 2870 | void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) { |
| 2871 | if (Ty->isSingleValueType()) |
Benjamin Kramer | 371d5d8 | 2012-09-18 17:06:32 +0000 | [diff] [blame] | 2872 | return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name); |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2873 | |
| 2874 | if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { |
| 2875 | unsigned OldSize = Indices.size(); |
| 2876 | (void)OldSize; |
| 2877 | for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size; |
| 2878 | ++Idx) { |
| 2879 | assert(Indices.size() == OldSize && "Did not return to the old size"); |
| 2880 | Indices.push_back(Idx); |
| 2881 | GEPIndices.push_back(IRB.getInt32(Idx)); |
| 2882 | emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx)); |
| 2883 | GEPIndices.pop_back(); |
| 2884 | Indices.pop_back(); |
| 2885 | } |
| 2886 | return; |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2887 | } |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2888 | |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2889 | if (StructType *STy = dyn_cast<StructType>(Ty)) { |
| 2890 | unsigned OldSize = Indices.size(); |
| 2891 | (void)OldSize; |
| 2892 | for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size; |
| 2893 | ++Idx) { |
| 2894 | assert(Indices.size() == OldSize && "Did not return to the old size"); |
| 2895 | Indices.push_back(Idx); |
| 2896 | GEPIndices.push_back(IRB.getInt32(Idx)); |
| 2897 | emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx)); |
| 2898 | GEPIndices.pop_back(); |
| 2899 | Indices.pop_back(); |
| 2900 | } |
| 2901 | return; |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2902 | } |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2903 | |
| 2904 | llvm_unreachable("Only arrays and structs are aggregate loadable types"); |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2905 | } |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2906 | }; |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2907 | |
Benjamin Kramer | 371d5d8 | 2012-09-18 17:06:32 +0000 | [diff] [blame] | 2908 | struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> { |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2909 | LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr) |
Benjamin Kramer | 3b682bd | 2012-09-18 17:11:47 +0000 | [diff] [blame] | 2910 | : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {} |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2911 | |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2912 | /// Emit a leaf load of a single value. This is called at the leaves of the |
| 2913 | /// recursive emission to actually load values. |
Benjamin Kramer | 371d5d8 | 2012-09-18 17:06:32 +0000 | [diff] [blame] | 2914 | void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) { |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2915 | assert(Ty->isSingleValueType()); |
| 2916 | // Load the single value and insert it using the indices. |
| 2917 | Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices, |
| 2918 | Name + ".gep"), |
| 2919 | Name + ".load"); |
| 2920 | Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert"); |
| 2921 | DEBUG(dbgs() << " to: " << *Load << "\n"); |
| 2922 | } |
| 2923 | }; |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2924 | |
| 2925 | bool visitLoadInst(LoadInst &LI) { |
| 2926 | assert(LI.getPointerOperand() == *U); |
| 2927 | if (!LI.isSimple() || LI.getType()->isSingleValueType()) |
| 2928 | return false; |
| 2929 | |
| 2930 | // We have an aggregate being loaded, split it apart. |
| 2931 | DEBUG(dbgs() << " original: " << LI << "\n"); |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2932 | LoadOpSplitter Splitter(&LI, *U); |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2933 | Value *V = UndefValue::get(LI.getType()); |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2934 | Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca"); |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2935 | LI.replaceAllUsesWith(V); |
| 2936 | LI.eraseFromParent(); |
| 2937 | return true; |
| 2938 | } |
| 2939 | |
Benjamin Kramer | 371d5d8 | 2012-09-18 17:06:32 +0000 | [diff] [blame] | 2940 | struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> { |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2941 | StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr) |
Benjamin Kramer | 3b682bd | 2012-09-18 17:11:47 +0000 | [diff] [blame] | 2942 | : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {} |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2943 | |
| 2944 | /// Emit a leaf store of a single value. This is called at the leaves of the |
| 2945 | /// recursive emission to actually produce stores. |
Benjamin Kramer | 371d5d8 | 2012-09-18 17:06:32 +0000 | [diff] [blame] | 2946 | void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) { |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2947 | assert(Ty->isSingleValueType()); |
| 2948 | // Extract the single value and store it using the indices. |
| 2949 | Value *Store = IRB.CreateStore( |
| 2950 | IRB.CreateExtractValue(Agg, Indices, Name + ".extract"), |
| 2951 | IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep")); |
| 2952 | (void)Store; |
| 2953 | DEBUG(dbgs() << " to: " << *Store << "\n"); |
| 2954 | } |
| 2955 | }; |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2956 | |
| 2957 | bool visitStoreInst(StoreInst &SI) { |
| 2958 | if (!SI.isSimple() || SI.getPointerOperand() != *U) |
| 2959 | return false; |
| 2960 | Value *V = SI.getValueOperand(); |
| 2961 | if (V->getType()->isSingleValueType()) |
| 2962 | return false; |
| 2963 | |
| 2964 | // We have an aggregate being stored, split it apart. |
| 2965 | DEBUG(dbgs() << " original: " << SI << "\n"); |
Benjamin Kramer | 6e67b25 | 2012-09-18 16:20:46 +0000 | [diff] [blame] | 2966 | StoreOpSplitter Splitter(&SI, *U); |
| 2967 | Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca"); |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 2968 | SI.eraseFromParent(); |
| 2969 | return true; |
| 2970 | } |
| 2971 | |
| 2972 | bool visitBitCastInst(BitCastInst &BC) { |
| 2973 | enqueueUsers(BC); |
| 2974 | return false; |
| 2975 | } |
| 2976 | |
| 2977 | bool visitGetElementPtrInst(GetElementPtrInst &GEPI) { |
| 2978 | enqueueUsers(GEPI); |
| 2979 | return false; |
| 2980 | } |
| 2981 | |
| 2982 | bool visitPHINode(PHINode &PN) { |
| 2983 | enqueueUsers(PN); |
| 2984 | return false; |
| 2985 | } |
| 2986 | |
| 2987 | bool visitSelectInst(SelectInst &SI) { |
| 2988 | enqueueUsers(SI); |
| 2989 | return false; |
| 2990 | } |
| 2991 | }; |
| 2992 | } |
| 2993 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 2994 | /// \brief Try to find a partition of the aggregate type passed in for a given |
| 2995 | /// offset and size. |
| 2996 | /// |
| 2997 | /// This recurses through the aggregate type and tries to compute a subtype |
| 2998 | /// based on the offset and size. When the offset and size span a sub-section |
Chandler Carruth | 6b547a2 | 2012-09-14 11:08:31 +0000 | [diff] [blame] | 2999 | /// of an array, it will even compute a new array type for that sub-section, |
| 3000 | /// and the same for structs. |
| 3001 | /// |
| 3002 | /// Note that this routine is very strict and tries to find a partition of the |
| 3003 | /// type which produces the *exact* right offset and size. It is not forgiving |
| 3004 | /// when the size or offset cause either end of type-based partition to be off. |
| 3005 | /// Also, this is a best-effort routine. It is reasonable to give up and not |
| 3006 | /// return a type if necessary. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3007 | static Type *getTypePartition(const TargetData &TD, Type *Ty, |
| 3008 | uint64_t Offset, uint64_t Size) { |
| 3009 | if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size) |
| 3010 | return Ty; |
| 3011 | |
| 3012 | if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) { |
| 3013 | // We can't partition pointers... |
| 3014 | if (SeqTy->isPointerTy()) |
| 3015 | return 0; |
| 3016 | |
| 3017 | Type *ElementTy = SeqTy->getElementType(); |
| 3018 | uint64_t ElementSize = TD.getTypeAllocSize(ElementTy); |
| 3019 | uint64_t NumSkippedElements = Offset / ElementSize; |
| 3020 | if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) |
| 3021 | if (NumSkippedElements >= ArrTy->getNumElements()) |
| 3022 | return 0; |
| 3023 | if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) |
| 3024 | if (NumSkippedElements >= VecTy->getNumElements()) |
| 3025 | return 0; |
| 3026 | Offset -= NumSkippedElements * ElementSize; |
| 3027 | |
| 3028 | // First check if we need to recurse. |
| 3029 | if (Offset > 0 || Size < ElementSize) { |
| 3030 | // Bail if the partition ends in a different array element. |
| 3031 | if ((Offset + Size) > ElementSize) |
| 3032 | return 0; |
| 3033 | // Recurse through the element type trying to peel off offset bytes. |
| 3034 | return getTypePartition(TD, ElementTy, Offset, Size); |
| 3035 | } |
| 3036 | assert(Offset == 0); |
| 3037 | |
| 3038 | if (Size == ElementSize) |
| 3039 | return ElementTy; |
| 3040 | assert(Size > ElementSize); |
| 3041 | uint64_t NumElements = Size / ElementSize; |
| 3042 | if (NumElements * ElementSize != Size) |
| 3043 | return 0; |
| 3044 | return ArrayType::get(ElementTy, NumElements); |
| 3045 | } |
| 3046 | |
| 3047 | StructType *STy = dyn_cast<StructType>(Ty); |
| 3048 | if (!STy) |
| 3049 | return 0; |
| 3050 | |
| 3051 | const StructLayout *SL = TD.getStructLayout(STy); |
Chandler Carruth | 6b547a2 | 2012-09-14 11:08:31 +0000 | [diff] [blame] | 3052 | if (Offset >= SL->getSizeInBytes()) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3053 | return 0; |
| 3054 | uint64_t EndOffset = Offset + Size; |
| 3055 | if (EndOffset > SL->getSizeInBytes()) |
| 3056 | return 0; |
| 3057 | |
| 3058 | unsigned Index = SL->getElementContainingOffset(Offset); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3059 | Offset -= SL->getElementOffset(Index); |
| 3060 | |
| 3061 | Type *ElementTy = STy->getElementType(Index); |
| 3062 | uint64_t ElementSize = TD.getTypeAllocSize(ElementTy); |
| 3063 | if (Offset >= ElementSize) |
| 3064 | return 0; // The offset points into alignment padding. |
| 3065 | |
| 3066 | // See if any partition must be contained by the element. |
| 3067 | if (Offset > 0 || Size < ElementSize) { |
| 3068 | if ((Offset + Size) > ElementSize) |
| 3069 | return 0; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3070 | return getTypePartition(TD, ElementTy, Offset, Size); |
| 3071 | } |
| 3072 | assert(Offset == 0); |
| 3073 | |
| 3074 | if (Size == ElementSize) |
| 3075 | return ElementTy; |
| 3076 | |
| 3077 | StructType::element_iterator EI = STy->element_begin() + Index, |
| 3078 | EE = STy->element_end(); |
| 3079 | if (EndOffset < SL->getSizeInBytes()) { |
| 3080 | unsigned EndIndex = SL->getElementContainingOffset(EndOffset); |
| 3081 | if (Index == EndIndex) |
| 3082 | return 0; // Within a single element and its padding. |
Chandler Carruth | 6b547a2 | 2012-09-14 11:08:31 +0000 | [diff] [blame] | 3083 | |
| 3084 | // Don't try to form "natural" types if the elements don't line up with the |
| 3085 | // expected size. |
| 3086 | // FIXME: We could potentially recurse down through the last element in the |
| 3087 | // sub-struct to find a natural end point. |
| 3088 | if (SL->getElementOffset(EndIndex) != EndOffset) |
| 3089 | return 0; |
| 3090 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3091 | assert(Index < EndIndex); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3092 | EE = STy->element_begin() + EndIndex; |
| 3093 | } |
| 3094 | |
| 3095 | // Try to build up a sub-structure. |
| 3096 | SmallVector<Type *, 4> ElementTys; |
| 3097 | do { |
| 3098 | ElementTys.push_back(*EI++); |
| 3099 | } while (EI != EE); |
| 3100 | StructType *SubTy = StructType::get(STy->getContext(), ElementTys, |
| 3101 | STy->isPacked()); |
| 3102 | const StructLayout *SubSL = TD.getStructLayout(SubTy); |
Chandler Carruth | 6b547a2 | 2012-09-14 11:08:31 +0000 | [diff] [blame] | 3103 | if (Size != SubSL->getSizeInBytes()) |
| 3104 | return 0; // The sub-struct doesn't have quite the size needed. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3105 | |
Chandler Carruth | 6b547a2 | 2012-09-14 11:08:31 +0000 | [diff] [blame] | 3106 | return SubTy; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3107 | } |
| 3108 | |
| 3109 | /// \brief Rewrite an alloca partition's users. |
| 3110 | /// |
| 3111 | /// This routine drives both of the rewriting goals of the SROA pass. It tries |
| 3112 | /// to rewrite uses of an alloca partition to be conducive for SSA value |
| 3113 | /// promotion. If the partition needs a new, more refined alloca, this will |
| 3114 | /// build that new alloca, preserving as much type information as possible, and |
| 3115 | /// rewrite the uses of the old alloca to point at the new one and have the |
| 3116 | /// appropriate new offsets. It also evaluates how successful the rewrite was |
| 3117 | /// at enabling promotion and if it was successful queues the alloca to be |
| 3118 | /// promoted. |
| 3119 | bool SROA::rewriteAllocaPartition(AllocaInst &AI, |
| 3120 | AllocaPartitioning &P, |
| 3121 | AllocaPartitioning::iterator PI) { |
| 3122 | uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset; |
Chandler Carruth | fdb1585 | 2012-10-02 18:57:13 +0000 | [diff] [blame] | 3123 | bool IsLive = false; |
| 3124 | for (AllocaPartitioning::use_iterator UI = P.use_begin(PI), |
| 3125 | UE = P.use_end(PI); |
| 3126 | UI != UE && !IsLive; ++UI) |
| 3127 | if (UI->U) |
| 3128 | IsLive = true; |
| 3129 | if (!IsLive) |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3130 | return false; // No live uses left of this partition. |
| 3131 | |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 3132 | DEBUG(dbgs() << "Speculating PHIs and selects in partition " |
| 3133 | << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n"); |
| 3134 | |
| 3135 | PHIOrSelectSpeculator Speculator(*TD, P, *this); |
| 3136 | DEBUG(dbgs() << " speculating "); |
| 3137 | DEBUG(P.print(dbgs(), PI, "")); |
Chandler Carruth | a346f46 | 2012-10-02 17:49:47 +0000 | [diff] [blame] | 3138 | Speculator.visitUsers(PI); |
Chandler Carruth | 1e1b16c | 2012-10-01 10:54:05 +0000 | [diff] [blame] | 3139 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3140 | // Try to compute a friendly type for this partition of the alloca. This |
| 3141 | // won't always succeed, in which case we fall back to a legal integer type |
| 3142 | // or an i8 array of an appropriate size. |
| 3143 | Type *AllocaTy = 0; |
| 3144 | if (Type *PartitionTy = P.getCommonType(PI)) |
| 3145 | if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize) |
| 3146 | AllocaTy = PartitionTy; |
| 3147 | if (!AllocaTy) |
| 3148 | if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(), |
| 3149 | PI->BeginOffset, AllocaSize)) |
| 3150 | AllocaTy = PartitionTy; |
| 3151 | if ((!AllocaTy || |
| 3152 | (AllocaTy->isArrayTy() && |
| 3153 | AllocaTy->getArrayElementType()->isIntegerTy())) && |
| 3154 | TD->isLegalInteger(AllocaSize * 8)) |
| 3155 | AllocaTy = Type::getIntNTy(*C, AllocaSize * 8); |
| 3156 | if (!AllocaTy) |
| 3157 | AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize); |
Chandler Carruth | b3dd9a1 | 2012-09-14 10:26:34 +0000 | [diff] [blame] | 3158 | assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3159 | |
| 3160 | // Check for the case where we're going to rewrite to a new alloca of the |
| 3161 | // exact same type as the original, and with the same access offsets. In that |
| 3162 | // case, re-use the existing alloca, but still run through the rewriter to |
| 3163 | // performe phi and select speculation. |
| 3164 | AllocaInst *NewAI; |
| 3165 | if (AllocaTy == AI.getAllocatedType()) { |
| 3166 | assert(PI->BeginOffset == 0 && |
| 3167 | "Non-zero begin offset but same alloca type"); |
| 3168 | assert(PI == P.begin() && "Begin offset is zero on later partition"); |
| 3169 | NewAI = &AI; |
| 3170 | } else { |
Chandler Carruth | b67c9a5 | 2012-09-29 10:41:21 +0000 | [diff] [blame] | 3171 | unsigned Alignment = AI.getAlignment(); |
| 3172 | if (!Alignment) { |
| 3173 | // The minimum alignment which users can rely on when the explicit |
| 3174 | // alignment is omitted or zero is that required by the ABI for this |
| 3175 | // type. |
| 3176 | Alignment = TD->getABITypeAlignment(AI.getAllocatedType()); |
| 3177 | } |
| 3178 | Alignment = MinAlign(Alignment, PI->BeginOffset); |
| 3179 | // If we will get at least this much alignment from the type alone, leave |
| 3180 | // the alloca's alignment unconstrained. |
| 3181 | if (Alignment <= TD->getABITypeAlignment(AllocaTy)) |
| 3182 | Alignment = 0; |
| 3183 | NewAI = new AllocaInst(AllocaTy, 0, Alignment, |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3184 | AI.getName() + ".sroa." + Twine(PI - P.begin()), |
| 3185 | &AI); |
| 3186 | ++NumNewAllocas; |
| 3187 | } |
| 3188 | |
| 3189 | DEBUG(dbgs() << "Rewriting alloca partition " |
| 3190 | << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: " |
| 3191 | << *NewAI << "\n"); |
| 3192 | |
Chandler Carruth | b2d98c2 | 2012-10-04 12:33:50 +0000 | [diff] [blame] | 3193 | // Track the high watermark of the post-promotion worklist. We will reset it |
| 3194 | // to this point if the alloca is not in fact scheduled for promotion. |
| 3195 | unsigned PPWOldSize = PostPromotionWorklist.size(); |
| 3196 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3197 | AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI, |
| 3198 | PI->BeginOffset, PI->EndOffset); |
| 3199 | DEBUG(dbgs() << " rewriting "); |
| 3200 | DEBUG(P.print(dbgs(), PI, "")); |
Chandler Carruth | b2d98c2 | 2012-10-04 12:33:50 +0000 | [diff] [blame] | 3201 | bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI)); |
| 3202 | if (Promotable) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3203 | DEBUG(dbgs() << " and queuing for promotion\n"); |
| 3204 | PromotableAllocas.push_back(NewAI); |
| 3205 | } else if (NewAI != &AI) { |
| 3206 | // If we can't promote the alloca, iterate on it to check for new |
| 3207 | // refinements exposed by splitting the current alloca. Don't iterate on an |
| 3208 | // alloca which didn't actually change and didn't get promoted. |
| 3209 | Worklist.insert(NewAI); |
| 3210 | } |
Chandler Carruth | b2d98c2 | 2012-10-04 12:33:50 +0000 | [diff] [blame] | 3211 | |
| 3212 | // Drop any post-promotion work items if promotion didn't happen. |
| 3213 | if (!Promotable) |
| 3214 | while (PostPromotionWorklist.size() > PPWOldSize) |
| 3215 | PostPromotionWorklist.pop_back(); |
| 3216 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3217 | return true; |
| 3218 | } |
| 3219 | |
| 3220 | /// \brief Walks the partitioning of an alloca rewriting uses of each partition. |
| 3221 | bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) { |
| 3222 | bool Changed = false; |
| 3223 | for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE; |
| 3224 | ++PI) |
| 3225 | Changed |= rewriteAllocaPartition(AI, P, PI); |
| 3226 | |
| 3227 | return Changed; |
| 3228 | } |
| 3229 | |
| 3230 | /// \brief Analyze an alloca for SROA. |
| 3231 | /// |
| 3232 | /// This analyzes the alloca to ensure we can reason about it, builds |
| 3233 | /// a partitioning of the alloca, and then hands it off to be split and |
| 3234 | /// rewritten as needed. |
| 3235 | bool SROA::runOnAlloca(AllocaInst &AI) { |
| 3236 | DEBUG(dbgs() << "SROA alloca: " << AI << "\n"); |
| 3237 | ++NumAllocasAnalyzed; |
| 3238 | |
| 3239 | // Special case dead allocas, as they're trivial. |
| 3240 | if (AI.use_empty()) { |
| 3241 | AI.eraseFromParent(); |
| 3242 | return true; |
| 3243 | } |
| 3244 | |
| 3245 | // Skip alloca forms that this analysis can't handle. |
| 3246 | if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() || |
| 3247 | TD->getTypeAllocSize(AI.getAllocatedType()) == 0) |
| 3248 | return false; |
| 3249 | |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 3250 | bool Changed = false; |
| 3251 | |
| 3252 | // First, split any FCA loads and stores touching this alloca to promote |
| 3253 | // better splitting and promotion opportunities. |
| 3254 | AggLoadStoreRewriter AggRewriter(*TD); |
| 3255 | Changed |= AggRewriter.rewrite(AI); |
| 3256 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3257 | // Build the partition set using a recursive instruction-visiting builder. |
| 3258 | AllocaPartitioning P(*TD, AI); |
| 3259 | DEBUG(P.print(dbgs())); |
| 3260 | if (P.isEscaped()) |
Chandler Carruth | c370acd | 2012-09-18 12:57:43 +0000 | [diff] [blame] | 3261 | return Changed; |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3262 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3263 | // Delete all the dead users of this alloca before splitting and rewriting it. |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3264 | for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(), |
| 3265 | DE = P.dead_user_end(); |
| 3266 | DI != DE; ++DI) { |
| 3267 | Changed = true; |
| 3268 | (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType())); |
| 3269 | DeadInsts.push_back(*DI); |
| 3270 | } |
| 3271 | for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(), |
| 3272 | DE = P.dead_op_end(); |
| 3273 | DO != DE; ++DO) { |
| 3274 | Value *OldV = **DO; |
| 3275 | // Clobber the use with an undef value. |
| 3276 | **DO = UndefValue::get(OldV->getType()); |
| 3277 | if (Instruction *OldI = dyn_cast<Instruction>(OldV)) |
| 3278 | if (isInstructionTriviallyDead(OldI)) { |
| 3279 | Changed = true; |
| 3280 | DeadInsts.push_back(OldI); |
| 3281 | } |
| 3282 | } |
| 3283 | |
Chandler Carruth | fca3f40 | 2012-10-05 01:29:09 +0000 | [diff] [blame] | 3284 | // No partitions to split. Leave the dead alloca for a later pass to clean up. |
| 3285 | if (P.begin() == P.end()) |
| 3286 | return Changed; |
| 3287 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3288 | return splitAlloca(AI, P) || Changed; |
| 3289 | } |
| 3290 | |
Chandler Carruth | 8615cd2 | 2012-09-14 10:26:38 +0000 | [diff] [blame] | 3291 | /// \brief Delete the dead instructions accumulated in this run. |
| 3292 | /// |
| 3293 | /// Recursively deletes the dead instructions we've accumulated. This is done |
| 3294 | /// at the very end to maximize locality of the recursive delete and to |
| 3295 | /// minimize the problems of invalidated instruction pointers as such pointers |
| 3296 | /// are used heavily in the intermediate stages of the algorithm. |
| 3297 | /// |
| 3298 | /// We also record the alloca instructions deleted here so that they aren't |
| 3299 | /// subsequently handed to mem2reg to promote. |
| 3300 | void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) { |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3301 | DeadSplitInsts.clear(); |
| 3302 | while (!DeadInsts.empty()) { |
| 3303 | Instruction *I = DeadInsts.pop_back_val(); |
| 3304 | DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n"); |
| 3305 | |
| 3306 | for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) |
| 3307 | if (Instruction *U = dyn_cast<Instruction>(*OI)) { |
| 3308 | // Zero out the operand and see if it becomes trivially dead. |
| 3309 | *OI = 0; |
| 3310 | if (isInstructionTriviallyDead(U)) |
| 3311 | DeadInsts.push_back(U); |
| 3312 | } |
| 3313 | |
| 3314 | if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) |
| 3315 | DeletedAllocas.insert(AI); |
| 3316 | |
| 3317 | ++NumDeleted; |
| 3318 | I->eraseFromParent(); |
| 3319 | } |
| 3320 | } |
| 3321 | |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 3322 | /// \brief Promote the allocas, using the best available technique. |
| 3323 | /// |
| 3324 | /// This attempts to promote whatever allocas have been identified as viable in |
| 3325 | /// the PromotableAllocas list. If that list is empty, there is nothing to do. |
| 3326 | /// If there is a domtree available, we attempt to promote using the full power |
| 3327 | /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is |
| 3328 | /// based on the SSAUpdater utilities. This function returns whether any |
| 3329 | /// promotion occured. |
| 3330 | bool SROA::promoteAllocas(Function &F) { |
| 3331 | if (PromotableAllocas.empty()) |
| 3332 | return false; |
| 3333 | |
| 3334 | NumPromoted += PromotableAllocas.size(); |
| 3335 | |
| 3336 | if (DT && !ForceSSAUpdater) { |
| 3337 | DEBUG(dbgs() << "Promoting allocas with mem2reg...\n"); |
| 3338 | PromoteMemToReg(PromotableAllocas, *DT); |
| 3339 | PromotableAllocas.clear(); |
| 3340 | return true; |
| 3341 | } |
| 3342 | |
| 3343 | DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n"); |
| 3344 | SSAUpdater SSA; |
| 3345 | DIBuilder DIB(*F.getParent()); |
| 3346 | SmallVector<Instruction*, 64> Insts; |
| 3347 | |
| 3348 | for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) { |
| 3349 | AllocaInst *AI = PromotableAllocas[Idx]; |
| 3350 | for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end(); |
| 3351 | UI != UE;) { |
| 3352 | Instruction *I = cast<Instruction>(*UI++); |
| 3353 | // FIXME: Currently the SSAUpdater infrastructure doesn't reason about |
| 3354 | // lifetime intrinsics and so we strip them (and the bitcasts+GEPs |
| 3355 | // leading to them) here. Eventually it should use them to optimize the |
| 3356 | // scalar values produced. |
| 3357 | if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) { |
| 3358 | assert(onlyUsedByLifetimeMarkers(I) && |
| 3359 | "Found a bitcast used outside of a lifetime marker."); |
| 3360 | while (!I->use_empty()) |
| 3361 | cast<Instruction>(*I->use_begin())->eraseFromParent(); |
| 3362 | I->eraseFromParent(); |
| 3363 | continue; |
| 3364 | } |
| 3365 | if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { |
| 3366 | assert(II->getIntrinsicID() == Intrinsic::lifetime_start || |
| 3367 | II->getIntrinsicID() == Intrinsic::lifetime_end); |
| 3368 | II->eraseFromParent(); |
| 3369 | continue; |
| 3370 | } |
| 3371 | |
| 3372 | Insts.push_back(I); |
| 3373 | } |
| 3374 | AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts); |
| 3375 | Insts.clear(); |
| 3376 | } |
| 3377 | |
| 3378 | PromotableAllocas.clear(); |
| 3379 | return true; |
| 3380 | } |
| 3381 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3382 | namespace { |
| 3383 | /// \brief A predicate to test whether an alloca belongs to a set. |
| 3384 | class IsAllocaInSet { |
| 3385 | typedef SmallPtrSet<AllocaInst *, 4> SetType; |
| 3386 | const SetType &Set; |
| 3387 | |
| 3388 | public: |
Chandler Carruth | 75eac5f | 2012-10-03 00:03:00 +0000 | [diff] [blame] | 3389 | typedef AllocaInst *argument_type; |
| 3390 | |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3391 | IsAllocaInSet(const SetType &Set) : Set(Set) {} |
Chandler Carruth | 75eac5f | 2012-10-03 00:03:00 +0000 | [diff] [blame] | 3392 | bool operator()(AllocaInst *AI) const { return Set.count(AI); } |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3393 | }; |
| 3394 | } |
| 3395 | |
| 3396 | bool SROA::runOnFunction(Function &F) { |
| 3397 | DEBUG(dbgs() << "SROA function: " << F.getName() << "\n"); |
| 3398 | C = &F.getContext(); |
| 3399 | TD = getAnalysisIfAvailable<TargetData>(); |
| 3400 | if (!TD) { |
| 3401 | DEBUG(dbgs() << " Skipping SROA -- no target data!\n"); |
| 3402 | return false; |
| 3403 | } |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 3404 | DT = getAnalysisIfAvailable<DominatorTree>(); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3405 | |
| 3406 | BasicBlock &EntryBB = F.getEntryBlock(); |
| 3407 | for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end()); |
| 3408 | I != E; ++I) |
| 3409 | if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) |
| 3410 | Worklist.insert(AI); |
| 3411 | |
| 3412 | bool Changed = false; |
Chandler Carruth | 8615cd2 | 2012-09-14 10:26:38 +0000 | [diff] [blame] | 3413 | // A set of deleted alloca instruction pointers which should be removed from |
| 3414 | // the list of promotable allocas. |
| 3415 | SmallPtrSet<AllocaInst *, 4> DeletedAllocas; |
| 3416 | |
Chandler Carruth | b2d98c2 | 2012-10-04 12:33:50 +0000 | [diff] [blame] | 3417 | do { |
| 3418 | while (!Worklist.empty()) { |
| 3419 | Changed |= runOnAlloca(*Worklist.pop_back_val()); |
| 3420 | deleteDeadInstructions(DeletedAllocas); |
Chandler Carruth | 5c5b3cf | 2012-10-02 22:46:45 +0000 | [diff] [blame] | 3421 | |
Chandler Carruth | b2d98c2 | 2012-10-04 12:33:50 +0000 | [diff] [blame] | 3422 | // Remove the deleted allocas from various lists so that we don't try to |
| 3423 | // continue processing them. |
| 3424 | if (!DeletedAllocas.empty()) { |
| 3425 | Worklist.remove_if(IsAllocaInSet(DeletedAllocas)); |
| 3426 | PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas)); |
| 3427 | PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(), |
| 3428 | PromotableAllocas.end(), |
| 3429 | IsAllocaInSet(DeletedAllocas)), |
| 3430 | PromotableAllocas.end()); |
| 3431 | DeletedAllocas.clear(); |
| 3432 | } |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3433 | } |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3434 | |
Chandler Carruth | b2d98c2 | 2012-10-04 12:33:50 +0000 | [diff] [blame] | 3435 | Changed |= promoteAllocas(F); |
| 3436 | |
| 3437 | Worklist = PostPromotionWorklist; |
| 3438 | PostPromotionWorklist.clear(); |
| 3439 | } while (!Worklist.empty()); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3440 | |
| 3441 | return Changed; |
| 3442 | } |
| 3443 | |
| 3444 | void SROA::getAnalysisUsage(AnalysisUsage &AU) const { |
Chandler Carruth | 1c8db50 | 2012-09-15 11:43:14 +0000 | [diff] [blame] | 3445 | if (RequiresDomTree) |
| 3446 | AU.addRequired<DominatorTree>(); |
Chandler Carruth | 713aa94 | 2012-09-14 09:22:59 +0000 | [diff] [blame] | 3447 | AU.setPreservesCFG(); |
| 3448 | } |