blob: cb9838ef67443ed1dc79e482ebaf04db0cacc840 [file] [log] [blame]
Chandler Carruth713aa942012-09-14 09:22:59 +00001//===- 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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/Loads.h"
34#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000035#include "llvm/Constants.h"
36#include "llvm/DIBuilder.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/DataLayout.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000038#include "llvm/DebugInfo.h"
39#include "llvm/DerivedTypes.h"
40#include "llvm/Function.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000041#include "llvm/IRBuilder.h"
Chandler Carruth84bcf932012-11-30 03:08:41 +000042#include "llvm/InstVisitor.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000043#include "llvm/Instructions.h"
44#include "llvm/IntrinsicInst.h"
45#include "llvm/LLVMContext.h"
46#include "llvm/Module.h"
47#include "llvm/Operator.h"
48#include "llvm/Pass.h"
Chandler Carruth1c8db502012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000050#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/GetElementPtrTypeIterator.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000053#include "llvm/Support/MathExtras.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000055#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
57#include "llvm/Transforms/Utils/SSAUpdater.h"
58using namespace llvm;
59
60STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
61STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
62STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
63STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
64STATISTIC(NumDeleted, "Number of instructions deleted");
65STATISTIC(NumVectorized, "Number of vectorized aggregates");
66
Chandler Carruth1c8db502012-09-15 11:43:14 +000067/// Hidden option to force the pass to not use DomTree and mem2reg, instead
68/// forming SSA values through the SSAUpdater infrastructure.
69static cl::opt<bool>
70ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
71
Chandler Carruth713aa942012-09-14 09:22:59 +000072namespace {
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 Carruth7f5bede2012-09-14 10:18:49 +000079/// structure can capture the relevant information needed both to decide about
Chandler Carruth713aa942012-09-14 09:22:59 +000080/// and to enact these transformations.
81class AllocaPartitioning {
82public:
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 Carruth7f5bede2012-09-14 10:18:49 +000099 /// decreasing. Thus the spanning range comes first in a cluster with the
Chandler Carruth713aa942012-09-14 09:22:59 +0000100 /// 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 Kramer2d1c2a22012-09-17 16:42:36 +0000109 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 Carruth713aa942012-09-14 09:22:59 +0000116 }
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 Carruth7f5bede2012-09-14 10:18:49 +0000134 /// accesses by trivially splittable operations such as memset and memcpy.
Chandler Carruth713aa942012-09-14 09:22:59 +0000135 bool IsSplittable;
136
Chandler Carruthfca3f402012-10-05 01:29:09 +0000137 /// \brief Test whether a partition has been marked as dead.
138 bool isDead() const {
139 if (BeginOffset == UINT64_MAX) {
140 assert(EndOffset == UINT64_MAX);
141 return true;
142 }
143 return false;
144 }
145
146 /// \brief Kill a partition.
147 /// This is accomplished by setting both its beginning and end offset to
148 /// the maximum possible value.
149 void kill() {
150 assert(!isDead() && "He's Dead, Jim!");
151 BeginOffset = EndOffset = UINT64_MAX;
152 }
153
Chandler Carruth713aa942012-09-14 09:22:59 +0000154 Partition() : ByteRange(), IsSplittable() {}
155 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
156 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
157 };
158
159 /// \brief A particular use of a partition of the alloca.
160 ///
161 /// This structure is used to associate uses of a partition with it. They
162 /// mark the range of bytes which are referenced by a particular instruction,
163 /// and includes a handle to the user itself and the pointer value in use.
164 /// The bounds of these uses are determined by intersecting the bounds of the
165 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000166 /// intentionally overlap between various uses of the same partition.
Chandler Carruth713aa942012-09-14 09:22:59 +0000167 struct PartitionUse : public ByteRange {
Chandler Carruth77c12702012-10-01 01:49:22 +0000168 /// \brief The use in question. Provides access to both user and used value.
Chandler Carruthfdb15852012-10-02 18:57:13 +0000169 ///
170 /// Note that this may be null if the partition use is *dead*, that is, it
171 /// should be ignored.
172 Use *U;
Chandler Carruth713aa942012-09-14 09:22:59 +0000173
Chandler Carruth77c12702012-10-01 01:49:22 +0000174 PartitionUse() : ByteRange(), U() {}
175 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
176 : ByteRange(BeginOffset, EndOffset), U(U) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000177 };
178
179 /// \brief Construct a partitioning of a particular alloca.
180 ///
181 /// Construction does most of the work for partitioning the alloca. This
182 /// performs the necessary walks of users and builds a partitioning from it.
Micah Villmow3574eca2012-10-08 16:38:25 +0000183 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
Chandler Carruth713aa942012-09-14 09:22:59 +0000184
185 /// \brief Test whether a pointer to the allocation escapes our analysis.
186 ///
187 /// If this is true, the partitioning is never fully built and should be
188 /// ignored.
189 bool isEscaped() const { return PointerEscapingInstr; }
190
191 /// \brief Support for iterating over the partitions.
192 /// @{
193 typedef SmallVectorImpl<Partition>::iterator iterator;
194 iterator begin() { return Partitions.begin(); }
195 iterator end() { return Partitions.end(); }
196
197 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
198 const_iterator begin() const { return Partitions.begin(); }
199 const_iterator end() const { return Partitions.end(); }
200 /// @}
201
202 /// \brief Support for iterating over and manipulating a particular
203 /// partition's uses.
204 ///
205 /// The iteration support provided for uses is more limited, but also
206 /// includes some manipulation routines to support rewriting the uses of
207 /// partitions during SROA.
208 /// @{
209 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
210 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
211 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
212 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
213 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth713aa942012-09-14 09:22:59 +0000214
215 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
216 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
217 const_use_iterator use_begin(const_iterator I) const {
218 return Uses[I - begin()].begin();
219 }
220 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
221 const_use_iterator use_end(const_iterator I) const {
222 return Uses[I - begin()].end();
223 }
Chandler Carrutha346f462012-10-02 17:49:47 +0000224
225 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
226 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
227 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
228 return Uses[PIdx][UIdx];
229 }
230 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
231 return Uses[I - begin()][UIdx];
232 }
233
234 void use_push_back(unsigned Idx, const PartitionUse &PU) {
235 Uses[Idx].push_back(PU);
236 }
237 void use_push_back(const_iterator I, const PartitionUse &PU) {
238 Uses[I - begin()].push_back(PU);
239 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000240 /// @}
241
242 /// \brief Allow iterating the dead users for this alloca.
243 ///
244 /// These are instructions which will never actually use the alloca as they
245 /// are outside the allocated range. They are safe to replace with undef and
246 /// delete.
247 /// @{
248 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
249 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
250 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
251 /// @}
252
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000253 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000254 ///
255 /// These are operands which have cannot actually be used to refer to the
256 /// alloca as they are outside its range and the user doesn't correct for
257 /// that. These mostly consist of PHI node inputs and the like which we just
258 /// need to replace with undef.
259 /// @{
260 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
261 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
262 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
263 /// @}
264
265 /// \brief MemTransferInst auxiliary data.
266 /// This struct provides some auxiliary data about memory transfer
267 /// intrinsics such as memcpy and memmove. These intrinsics can use two
268 /// different ranges within the same alloca, and provide other challenges to
269 /// correctly represent. We stash extra data to help us untangle this
270 /// after the partitioning is complete.
271 struct MemTransferOffsets {
Chandler Carruthfca3f402012-10-05 01:29:09 +0000272 /// The destination begin and end offsets when the destination is within
273 /// this alloca. If the end offset is zero the destination is not within
274 /// this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000275 uint64_t DestBegin, DestEnd;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000276
277 /// The source begin and end offsets when the source is within this alloca.
278 /// If the end offset is zero, the source is not within this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000279 uint64_t SourceBegin, SourceEnd;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000280
281 /// Flag for whether an alloca is splittable.
Chandler Carruth713aa942012-09-14 09:22:59 +0000282 bool IsSplittable;
283 };
284 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
285 return MemTransferInstData.lookup(&II);
286 }
287
288 /// \brief Map from a PHI or select operand back to a partition.
289 ///
290 /// When manipulating PHI nodes or selects, they can use more than one
291 /// partition of an alloca. We store a special mapping to allow finding the
292 /// partition referenced by each of these operands, if any.
Chandler Carruth77c12702012-10-01 01:49:22 +0000293 iterator findPartitionForPHIOrSelectOperand(Use *U) {
294 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
295 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000296 if (MapIt == PHIOrSelectOpMap.end())
297 return end();
298
299 return begin() + MapIt->second.first;
300 }
301
302 /// \brief Map from a PHI or select operand back to the specific use of
303 /// a partition.
304 ///
305 /// Similar to mapping these operands back to the partitions, this maps
306 /// directly to the use structure of that partition.
Chandler Carruth77c12702012-10-01 01:49:22 +0000307 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
308 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
309 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000310 assert(MapIt != PHIOrSelectOpMap.end());
311 return Uses[MapIt->second.first].begin() + MapIt->second.second;
312 }
313
314 /// \brief Compute a common type among the uses of a particular partition.
315 ///
316 /// This routines walks all of the uses of a particular partition and tries
317 /// to find a common type between them. Untyped operations such as memset and
318 /// memcpy are ignored.
319 Type *getCommonType(iterator I) const;
320
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000321#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000322 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
323 void printUsers(raw_ostream &OS, const_iterator I,
324 StringRef Indent = " ") const;
325 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000326 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
327 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000328#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000329
330private:
331 template <typename DerivedT, typename RetT = void> class BuilderBase;
332 class PartitionBuilder;
333 friend class AllocaPartitioning::PartitionBuilder;
334 class UseBuilder;
335 friend class AllocaPartitioning::UseBuilder;
336
Chandler Carruth3a902d02012-11-20 10:23:07 +0000337#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000338 /// \brief Handle to alloca instruction to simplify method interfaces.
339 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000340#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000341
342 /// \brief The instruction responsible for this alloca having no partitioning.
343 ///
344 /// When an instruction (potentially) escapes the pointer to the alloca, we
345 /// store a pointer to that here and abort trying to partition the alloca.
346 /// This will be null if the alloca is partitioned successfully.
347 Instruction *PointerEscapingInstr;
348
349 /// \brief The partitions of the alloca.
350 ///
351 /// We store a vector of the partitions over the alloca here. This vector is
352 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000353 /// the Partition inner class for more details. Initially (during
354 /// construction) there are overlaps, but we form a disjoint sequence of
355 /// partitions while finishing construction and a fully constructed object is
356 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000357 SmallVector<Partition, 8> Partitions;
358
359 /// \brief The uses of the partitions.
360 ///
361 /// This is essentially a mapping from each partition to a list of uses of
362 /// that partition. The mapping is done with a Uses vector that has the exact
363 /// same number of entries as the partition vector. Each entry is itself
364 /// a vector of the uses.
365 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
366
367 /// \brief Instructions which will become dead if we rewrite the alloca.
368 ///
369 /// Note that these are not separated by partition. This is because we expect
370 /// a partitioned alloca to be completely rewritten or not rewritten at all.
371 /// If rewritten, all these instructions can simply be removed and replaced
372 /// with undef as they come from outside of the allocated space.
373 SmallVector<Instruction *, 8> DeadUsers;
374
375 /// \brief Operands which will become dead if we rewrite the alloca.
376 ///
377 /// These are operands that in their particular use can be replaced with
378 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
379 /// to PHI nodes and the like. They aren't entirely dead (there might be
380 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
381 /// want to swap this particular input for undef to simplify the use lists of
382 /// the alloca.
383 SmallVector<Use *, 8> DeadOperands;
384
385 /// \brief The underlying storage for auxiliary memcpy and memset info.
386 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
387
388 /// \brief A side datastructure used when building up the partitions and uses.
389 ///
390 /// This mapping is only really used during the initial building of the
391 /// partitioning so that we can retain information about PHI and select nodes
392 /// processed.
393 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
394
395 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth77c12702012-10-01 01:49:22 +0000396 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth713aa942012-09-14 09:22:59 +0000397
398 /// \brief A utility routine called from the constructor.
399 ///
400 /// This does what it says on the tin. It is the key of the alloca partition
401 /// splitting and merging. After it is called we have the desired disjoint
402 /// collection of partitions.
403 void splitAndMergePartitions();
404};
405}
406
407template <typename DerivedT, typename RetT>
408class AllocaPartitioning::BuilderBase
409 : public InstVisitor<DerivedT, RetT> {
410public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000411 BuilderBase(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth713aa942012-09-14 09:22:59 +0000412 : TD(TD),
413 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
414 P(P) {
415 enqueueUsers(AI, 0);
416 }
417
418protected:
Micah Villmow3574eca2012-10-08 16:38:25 +0000419 const DataLayout &TD;
Chandler Carruth713aa942012-09-14 09:22:59 +0000420 const uint64_t AllocSize;
421 AllocaPartitioning &P;
422
Chandler Carruth77c12702012-10-01 01:49:22 +0000423 SmallPtrSet<Use *, 8> VisitedUses;
424
Chandler Carruth713aa942012-09-14 09:22:59 +0000425 struct OffsetUse {
426 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000427 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000428 };
429 SmallVector<OffsetUse, 8> Queue;
430
431 // The active offset and use while visiting.
432 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000433 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000434
Chandler Carruth02e92a02012-09-23 11:43:14 +0000435 void enqueueUsers(Instruction &I, int64_t UserOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000436 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
437 UI != UE; ++UI) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000438 if (VisitedUses.insert(&UI.getUse())) {
439 OffsetUse OU = { &UI.getUse(), UserOffset };
440 Queue.push_back(OU);
441 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000442 }
443 }
444
Chandler Carruth02e92a02012-09-23 11:43:14 +0000445 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000446 GEPOffset = Offset;
447 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
448 GTI != GTE; ++GTI) {
449 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
450 if (!OpC)
451 return false;
452 if (OpC->isZero())
453 continue;
454
455 // Handle a struct index, which adds its field offset to the pointer.
456 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
457 unsigned ElementIdx = OpC->getZExtValue();
458 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth02e92a02012-09-23 11:43:14 +0000459 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
460 // Check that we can continue to model this GEP in a signed 64-bit offset.
461 if (ElementOffset > INT64_MAX ||
462 (GEPOffset >= 0 &&
463 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
464 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
465 << "what can be represented in an int64_t!\n"
466 << " alloca: " << P.AI << "\n");
467 return false;
468 }
469 if (GEPOffset < 0)
470 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
471 else
472 GEPOffset += ElementOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000473 continue;
474 }
475
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000476 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
Chandler Carruth02e92a02012-09-23 11:43:14 +0000477 Index *= APInt(Index.getBitWidth(),
478 TD.getTypeAllocSize(GTI.getIndexedType()));
479 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
480 /*isSigned*/true);
481 // Check if the result can be stored in our int64_t offset.
482 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
483 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
484 << "what can be represented in an int64_t!\n"
485 << " alloca: " << P.AI << "\n");
486 return false;
487 }
488
489 GEPOffset = Index.getSExtValue();
Chandler Carruth713aa942012-09-14 09:22:59 +0000490 }
491 return true;
492 }
493
494 Value *foldSelectInst(SelectInst &SI) {
495 // If the condition being selected on is a constant or the same value is
496 // being selected between, fold the select. Yes this does (rarely) happen
497 // early on.
498 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
499 return SI.getOperand(1+CI->isZero());
500 if (SI.getOperand(1) == SI.getOperand(2)) {
501 assert(*U == SI.getOperand(1));
502 return SI.getOperand(1);
503 }
504 return 0;
505 }
506};
507
508/// \brief Builder for the alloca partitioning.
509///
510/// This class builds an alloca partitioning by recursively visiting the uses
511/// of an alloca and splitting the partitions for each load and store at each
512/// offset.
513class AllocaPartitioning::PartitionBuilder
514 : public BuilderBase<PartitionBuilder, bool> {
515 friend class InstVisitor<PartitionBuilder, bool>;
516
517 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
518
519public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000520 PartitionBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000521 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000522
523 /// \brief Run the builder over the allocation.
524 bool operator()() {
525 // Note that we have to re-evaluate size on each trip through the loop as
526 // the queue grows at the tail.
527 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
528 U = Queue[Idx].U;
529 Offset = Queue[Idx].Offset;
530 if (!visit(cast<Instruction>(U->getUser())))
531 return false;
532 }
533 return true;
534 }
535
536private:
537 bool markAsEscaping(Instruction &I) {
538 P.PointerEscapingInstr = &I;
539 return false;
540 }
541
Chandler Carruth02e92a02012-09-23 11:43:14 +0000542 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000543 bool IsSplittable = false) {
Chandler Carruthe74a4a72012-12-03 10:59:55 +0000544 // Completely skip uses which have a zero size or start either before or
545 // past the end of the allocation.
546 if (Size == 0 || Offset < 0 || (uint64_t)Offset >= AllocSize) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000547 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthe74a4a72012-12-03 10:59:55 +0000548 << " which has zero size or starts outside of the "
549 << AllocSize << " byte alloca:\n"
Chandler Carruth713aa942012-09-14 09:22:59 +0000550 << " alloca: " << P.AI << "\n"
551 << " use: " << I << "\n");
552 return;
553 }
554
Chandler Carruth02e92a02012-09-23 11:43:14 +0000555 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
556
557 // Clamp the end offset to the end of the allocation. Note that this is
558 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carruth17679292012-11-20 10:02:19 +0000559 // NOTE! This may appear superficially to be something we could ignore
560 // entirely, but that is not so! There may be PHI-node uses where some
561 // instructions are dead but not others. We can't completely ignore the
562 // PHI node, and so have to record at least the information here.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000563 assert(AllocSize >= BeginOffset); // Established above.
564 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000565 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
566 << " to remain within the " << AllocSize << " byte alloca:\n"
567 << " alloca: " << P.AI << "\n"
568 << " use: " << I << "\n");
569 EndOffset = AllocSize;
570 }
571
Chandler Carruth713aa942012-09-14 09:22:59 +0000572 Partition New(BeginOffset, EndOffset, IsSplittable);
573 P.Partitions.push_back(New);
574 }
575
Chandler Carrutha2b88162012-10-25 04:37:07 +0000576 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset,
577 bool IsVolatile) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000578 uint64_t Size = TD.getTypeStoreSize(Ty);
579
580 // If this memory access can be shown to *statically* extend outside the
581 // bounds of of the allocation, it's behavior is undefined, so simply
582 // ignore it. Note that this is more strict than the generic clamping
583 // behavior of insertUse. We also try to handle cases which might run the
584 // risk of overflow.
585 // FIXME: We should instead consider the pointer to have escaped if this
586 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000587 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
588 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000589 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
590 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
591 << " which extends past the end of the " << AllocSize
592 << " byte alloca:\n"
593 << " alloca: " << P.AI << "\n"
594 << " use: " << I << "\n");
595 return true;
596 }
597
Chandler Carrutha2b88162012-10-25 04:37:07 +0000598 // We allow splitting of loads and stores where the type is an integer type
599 // and which cover the entire alloca. Such integer loads and stores
600 // often require decomposition into fine grained loads and stores.
601 bool IsSplittable = false;
602 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
603 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
604
605 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth713aa942012-09-14 09:22:59 +0000606 return true;
607 }
608
609 bool visitBitCastInst(BitCastInst &BC) {
610 enqueueUsers(BC, Offset);
611 return true;
612 }
613
614 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000615 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000616 if (!computeConstantGEPOffset(GEPI, GEPOffset))
617 return markAsEscaping(GEPI);
618
619 enqueueUsers(GEPI, GEPOffset);
620 return true;
621 }
622
623 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000624 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
625 "All simple FCA loads should have been pre-split");
Chandler Carrutha2b88162012-10-25 04:37:07 +0000626 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +0000627 }
628
629 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000630 Value *ValOp = SI.getValueOperand();
631 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000632 return markAsEscaping(SI);
633
Chandler Carruthc370acd2012-09-18 12:57:43 +0000634 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
635 "All simple FCA stores should have been pre-split");
Chandler Carrutha2b88162012-10-25 04:37:07 +0000636 return handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +0000637 }
638
639
640 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000641 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000642 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000643 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
644 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000645 return true;
646 }
647
648 bool visitMemTransferInst(MemTransferInst &II) {
649 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
650 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
651 if (!Size)
652 // Zero-length mem transfer intrinsics can be ignored entirely.
653 return true;
654
655 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
656
657 // Only intrinsics with a constant length can be split.
658 Offsets.IsSplittable = Length;
659
Chandler Carruthfca3f402012-10-05 01:29:09 +0000660 if (*U == II.getRawDest()) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000661 Offsets.DestBegin = Offset;
662 Offsets.DestEnd = Offset + Size;
663 }
Chandler Carruthfca3f402012-10-05 01:29:09 +0000664 if (*U == II.getRawSource()) {
665 Offsets.SourceBegin = Offset;
666 Offsets.SourceEnd = Offset + Size;
667 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000668
Chandler Carruthfca3f402012-10-05 01:29:09 +0000669 // If we have set up end offsets for both the source and the destination,
670 // we have found both sides of this transfer pointing at the same alloca.
671 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
672 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
673 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth713aa942012-09-14 09:22:59 +0000674
Chandler Carruthfca3f402012-10-05 01:29:09 +0000675 // Check if the begin offsets match and this is a non-volatile transfer.
676 // In that case, we can completely elide the transfer.
677 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
678 P.Partitions[PrevIdx].kill();
679 return true;
680 }
681
682 // Otherwise we have an offset transfer within the same alloca. We can't
683 // split those.
684 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
685 } else if (SeenBothEnds) {
686 // Handle the case where this exact use provides both ends of the
687 // operation.
688 assert(II.getRawDest() == II.getRawSource());
689
690 // For non-volatile transfers this is a no-op.
691 if (!II.isVolatile())
692 return true;
693
694 // Otherwise just suppress splitting.
Chandler Carruth713aa942012-09-14 09:22:59 +0000695 Offsets.IsSplittable = false;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000696 }
697
698
699 // Insert the use now that we've fixed up the splittable nature.
700 insertUse(II, Offset, Size, Offsets.IsSplittable);
701
702 // Setup the mapping from intrinsic to partition of we've not seen both
703 // ends of this transfer.
704 if (!SeenBothEnds) {
705 unsigned NewIdx = P.Partitions.size() - 1;
706 bool Inserted
707 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
708 assert(Inserted &&
709 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi0559d312012-10-05 13:56:23 +0000710 (void)Inserted;
Chandler Carruth713aa942012-09-14 09:22:59 +0000711 }
712
713 return true;
714 }
715
716 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000717 // FIXME: What about debug instrinsics? This matches old behavior, but
718 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000719 bool visitIntrinsicInst(IntrinsicInst &II) {
720 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
721 II.getIntrinsicID() == Intrinsic::lifetime_end) {
722 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
723 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000724 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000725 return true;
726 }
727
728 return markAsEscaping(II);
729 }
730
731 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
732 // We consider any PHI or select that results in a direct load or store of
733 // the same offset to be a viable use for partitioning purposes. These uses
734 // are considered unsplittable and the size is the maximum loaded or stored
735 // size.
736 SmallPtrSet<Instruction *, 4> Visited;
737 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
738 Visited.insert(Root);
739 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000740 // If there are no loads or stores, the access is dead. We mark that as
741 // a size zero access.
742 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000743 do {
744 Instruction *I, *UsedI;
745 llvm::tie(UsedI, I) = Uses.pop_back_val();
746
747 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
748 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
749 continue;
750 }
751 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
752 Value *Op = SI->getOperand(0);
753 if (Op == UsedI)
754 return SI;
755 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
756 continue;
757 }
758
759 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
760 if (!GEP->hasAllZeroIndices())
761 return GEP;
762 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
763 !isa<SelectInst>(I)) {
764 return I;
765 }
766
767 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
768 ++UI)
769 if (Visited.insert(cast<Instruction>(*UI)))
770 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
771 } while (!Uses.empty());
772
773 return 0;
774 }
775
776 bool visitPHINode(PHINode &PN) {
777 // See if we already have computed info on this node.
778 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
779 if (PHIInfo.first) {
780 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000781 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000782 return true;
783 }
784
785 // Check for an unsafe use of the PHI node.
786 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
787 return markAsEscaping(*EscapingI);
788
Chandler Carruth63392ea2012-09-16 19:39:50 +0000789 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000790 return true;
791 }
792
793 bool visitSelectInst(SelectInst &SI) {
794 if (Value *Result = foldSelectInst(SI)) {
795 if (Result == *U)
796 // If the result of the constant fold will be the pointer, recurse
797 // through the select as if we had RAUW'ed it.
798 enqueueUsers(SI, Offset);
799
800 return true;
801 }
802
803 // See if we already have computed info on this node.
804 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
805 if (SelectInfo.first) {
806 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000807 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000808 return true;
809 }
810
811 // Check for an unsafe use of the PHI node.
812 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
813 return markAsEscaping(*EscapingI);
814
Chandler Carruth63392ea2012-09-16 19:39:50 +0000815 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000816 return true;
817 }
818
819 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
820 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
821};
822
823
824/// \brief Use adder for the alloca partitioning.
825///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000826/// This class adds the uses of an alloca to all of the partitions which they
827/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000828/// walk of the partitions, but the number of steps remains bounded by the
829/// total result instruction size:
830/// - The number of partitions is a result of the number unsplittable
831/// instructions using the alloca.
832/// - The number of users of each partition is at worst the total number of
833/// splittable instructions using the alloca.
834/// Thus we will produce N * M instructions in the end, where N are the number
835/// of unsplittable uses and M are the number of splittable. This visitor does
836/// the exact same number of updates to the partitioning.
837///
838/// In the more common case, this visitor will leverage the fact that the
839/// partition space is pre-sorted, and do a logarithmic search for the
840/// partition needed, making the total visit a classical ((N + M) * log(N))
841/// complexity operation.
842class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
843 friend class InstVisitor<UseBuilder>;
844
845 /// \brief Set to de-duplicate dead instructions found in the use walk.
846 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
847
848public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000849 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000850 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000851
852 /// \brief Run the builder over the allocation.
853 void operator()() {
854 // Note that we have to re-evaluate size on each trip through the loop as
855 // the queue grows at the tail.
856 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
857 U = Queue[Idx].U;
858 Offset = Queue[Idx].Offset;
859 this->visit(cast<Instruction>(U->getUser()));
860 }
861 }
862
863private:
864 void markAsDead(Instruction &I) {
865 if (VisitedDeadInsts.insert(&I))
866 P.DeadUsers.push_back(&I);
867 }
868
Chandler Carruth02e92a02012-09-23 11:43:14 +0000869 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000870 // If the use has a zero size or extends outside of the allocation, record
871 // it as a dead use for elimination later.
Chandler Carruthe74a4a72012-12-03 10:59:55 +0000872 if (Size == 0 || Offset < 0 || (uint64_t)Offset >= AllocSize)
Chandler Carruth713aa942012-09-14 09:22:59 +0000873 return markAsDead(User);
874
Chandler Carruth02e92a02012-09-23 11:43:14 +0000875 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
876
877 // Clamp the end offset to the end of the allocation. Note that this is
878 // formulated to handle even the case where "BeginOffset + Size" overflows.
879 assert(AllocSize >= BeginOffset); // Established above.
880 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000881 EndOffset = AllocSize;
882
883 // NB: This only works if we have zero overlapping partitions.
884 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
885 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
886 B = llvm::prior(B);
887 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
888 ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000889 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
890 std::min(I->EndOffset, EndOffset), U);
891 P.use_push_back(I, NewPU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000892 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth77c12702012-10-01 01:49:22 +0000893 P.PHIOrSelectOpMap[U]
Chandler Carruth713aa942012-09-14 09:22:59 +0000894 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
895 }
896 }
897
Chandler Carruth02e92a02012-09-23 11:43:14 +0000898 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000899 uint64_t Size = TD.getTypeStoreSize(Ty);
900
901 // If this memory access can be shown to *statically* extend outside the
902 // bounds of of the allocation, it's behavior is undefined, so simply
903 // ignore it. Note that this is more strict than the generic clamping
904 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000905 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
906 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000907 return markAsDead(I);
908
Chandler Carruth63392ea2012-09-16 19:39:50 +0000909 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000910 }
911
912 void visitBitCastInst(BitCastInst &BC) {
913 if (BC.use_empty())
914 return markAsDead(BC);
915
916 enqueueUsers(BC, Offset);
917 }
918
919 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
920 if (GEPI.use_empty())
921 return markAsDead(GEPI);
922
Chandler Carruth02e92a02012-09-23 11:43:14 +0000923 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000924 if (!computeConstantGEPOffset(GEPI, GEPOffset))
925 llvm_unreachable("Unable to compute constant offset for use");
926
927 enqueueUsers(GEPI, GEPOffset);
928 }
929
930 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000931 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000932 }
933
934 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000935 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000936 }
937
938 void visitMemSetInst(MemSetInst &II) {
939 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000940 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
941 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000942 }
943
944 void visitMemTransferInst(MemTransferInst &II) {
945 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000946 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000947 if (!Size)
948 return markAsDead(II);
949
950 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
951 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
952 Offsets.DestBegin == Offsets.SourceBegin)
953 return markAsDead(II); // Skip identity transfers without side-effects.
954
Chandler Carruth63392ea2012-09-16 19:39:50 +0000955 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000956 }
957
958 void visitIntrinsicInst(IntrinsicInst &II) {
959 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
960 II.getIntrinsicID() == Intrinsic::lifetime_end);
961
962 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000963 insertUse(II, Offset,
964 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000965 }
966
Chandler Carruth63392ea2012-09-16 19:39:50 +0000967 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000968 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
969
970 // For PHI and select operands outside the alloca, we can't nuke the entire
971 // phi or select -- the other side might still be relevant, so we special
972 // case them here and use a separate structure to track the operands
973 // themselves which should be replaced with undef.
974 if (Offset >= AllocSize) {
975 P.DeadOperands.push_back(U);
976 return;
977 }
978
Chandler Carruth63392ea2012-09-16 19:39:50 +0000979 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000980 }
981 void visitPHINode(PHINode &PN) {
982 if (PN.use_empty())
983 return markAsDead(PN);
984
Chandler Carruth63392ea2012-09-16 19:39:50 +0000985 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000986 }
987 void visitSelectInst(SelectInst &SI) {
988 if (SI.use_empty())
989 return markAsDead(SI);
990
991 if (Value *Result = foldSelectInst(SI)) {
992 if (Result == *U)
993 // If the result of the constant fold will be the pointer, recurse
994 // through the select as if we had RAUW'ed it.
995 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +0000996 else
997 // Otherwise the operand to the select is dead, and we can replace it
998 // with undef.
999 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +00001000
1001 return;
1002 }
1003
Chandler Carruth63392ea2012-09-16 19:39:50 +00001004 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00001005 }
1006
1007 /// \brief Unreachable, we've already visited the alloca once.
1008 void visitInstruction(Instruction &I) {
1009 llvm_unreachable("Unhandled instruction in use builder.");
1010 }
1011};
1012
1013void AllocaPartitioning::splitAndMergePartitions() {
1014 size_t NumDeadPartitions = 0;
1015
1016 // Track the range of splittable partitions that we pass when accumulating
1017 // overlapping unsplittable partitions.
1018 uint64_t SplitEndOffset = 0ull;
1019
1020 Partition New(0ull, 0ull, false);
1021
1022 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1023 ++j;
1024
1025 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1026 assert(New.BeginOffset == New.EndOffset);
1027 New = Partitions[i];
1028 } else {
1029 assert(New.IsSplittable);
1030 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1031 }
1032 assert(New.BeginOffset != New.EndOffset);
1033
1034 // Scan the overlapping partitions.
1035 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1036 // If the new partition we are forming is splittable, stop at the first
1037 // unsplittable partition.
1038 if (New.IsSplittable && !Partitions[j].IsSplittable)
1039 break;
1040
1041 // Grow the new partition to include any equally splittable range. 'j' is
1042 // always equally splittable when New is splittable, but when New is not
1043 // splittable, we may subsume some (or part of some) splitable partition
1044 // without growing the new one.
1045 if (New.IsSplittable == Partitions[j].IsSplittable) {
1046 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1047 } else {
1048 assert(!New.IsSplittable);
1049 assert(Partitions[j].IsSplittable);
1050 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1051 }
1052
Chandler Carruthfca3f402012-10-05 01:29:09 +00001053 Partitions[j].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001054 ++NumDeadPartitions;
1055 ++j;
1056 }
1057
1058 // If the new partition is splittable, chop off the end as soon as the
1059 // unsplittable subsequent partition starts and ensure we eventually cover
1060 // the splittable area.
1061 if (j != e && New.IsSplittable) {
1062 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1063 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1064 }
1065
1066 // Add the new partition if it differs from the original one and is
1067 // non-empty. We can end up with an empty partition here if it was
1068 // splittable but there is an unsplittable one that starts at the same
1069 // offset.
1070 if (New != Partitions[i]) {
1071 if (New.BeginOffset != New.EndOffset)
1072 Partitions.push_back(New);
1073 // Mark the old one for removal.
Chandler Carruthfca3f402012-10-05 01:29:09 +00001074 Partitions[i].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001075 ++NumDeadPartitions;
1076 }
1077
1078 New.BeginOffset = New.EndOffset;
1079 if (!New.IsSplittable) {
1080 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1081 if (j != e && !Partitions[j].IsSplittable)
1082 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1083 New.IsSplittable = true;
1084 // If there is a trailing splittable partition which won't be fused into
1085 // the next splittable partition go ahead and add it onto the partitions
1086 // list.
1087 if (New.BeginOffset < New.EndOffset &&
1088 (j == e || !Partitions[j].IsSplittable ||
1089 New.EndOffset < Partitions[j].BeginOffset)) {
1090 Partitions.push_back(New);
1091 New.BeginOffset = New.EndOffset = 0ull;
1092 }
1093 }
1094 }
1095
1096 // Re-sort the partitions now that they have been split and merged into
1097 // disjoint set of partitions. Also remove any of the dead partitions we've
1098 // replaced in the process.
1099 std::sort(Partitions.begin(), Partitions.end());
1100 if (NumDeadPartitions) {
Chandler Carruthfca3f402012-10-05 01:29:09 +00001101 assert(Partitions.back().isDead());
Chandler Carruth713aa942012-09-14 09:22:59 +00001102 assert((ptrdiff_t)NumDeadPartitions ==
1103 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1104 }
1105 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1106}
1107
Micah Villmow3574eca2012-10-08 16:38:25 +00001108AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001109 :
Chandler Carruth3a902d02012-11-20 10:23:07 +00001110#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001111 AI(AI),
1112#endif
1113 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001114 PartitionBuilder PB(TD, AI, *this);
1115 if (!PB())
1116 return;
1117
Chandler Carruthfca3f402012-10-05 01:29:09 +00001118 // Sort the uses. This arranges for the offsets to be in ascending order,
1119 // and the sizes to be in descending order.
1120 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth713aa942012-09-14 09:22:59 +00001121
Chandler Carruthfca3f402012-10-05 01:29:09 +00001122 // Remove any partitions from the back which are marked as dead.
1123 while (!Partitions.empty() && Partitions.back().isDead())
1124 Partitions.pop_back();
1125
1126 if (Partitions.size() > 1) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001127 // Intersect splittability for all partitions with equal offsets and sizes.
1128 // Then remove all but the first so that we have a sequence of non-equal but
1129 // potentially overlapping partitions.
1130 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1131 I = J) {
1132 ++J;
1133 while (J != E && *I == *J) {
1134 I->IsSplittable &= J->IsSplittable;
1135 ++J;
1136 }
1137 }
1138 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1139 Partitions.end());
1140
1141 // Split splittable and merge unsplittable partitions into a disjoint set
1142 // of partitions over the used space of the allocation.
1143 splitAndMergePartitions();
1144 }
1145
1146 // Now build up the user lists for each of these disjoint partitions by
1147 // re-walking the recursive users of the alloca.
1148 Uses.resize(Partitions.size());
1149 UseBuilder UB(TD, AI, *this);
1150 UB();
Chandler Carruth713aa942012-09-14 09:22:59 +00001151}
1152
1153Type *AllocaPartitioning::getCommonType(iterator I) const {
1154 Type *Ty = 0;
1155 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001156 if (!UI->U)
1157 continue; // Skip dead uses.
Chandler Carruth77c12702012-10-01 01:49:22 +00001158 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth713aa942012-09-14 09:22:59 +00001159 continue;
1160 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001161 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001162
1163 Type *UserTy = 0;
Chandler Carruth77c12702012-10-01 01:49:22 +00001164 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001165 UserTy = LI->getType();
Chandler Carruth77c12702012-10-01 01:49:22 +00001166 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001167 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha2b88162012-10-25 04:37:07 +00001168 } else {
1169 return 0; // Bail if we have weird uses.
1170 }
1171
1172 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1173 // If the type is larger than the partition, skip it. We only encounter
1174 // this for split integer operations where we want to use the type of the
1175 // entity causing the split.
1176 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1177 continue;
1178
1179 // If we have found an integer type use covering the alloca, use that
1180 // regardless of the other types, as integers are often used for a "bucket
1181 // of bits" type.
1182 return ITy;
Chandler Carruth713aa942012-09-14 09:22:59 +00001183 }
1184
1185 if (Ty && Ty != UserTy)
1186 return 0;
1187
1188 Ty = UserTy;
1189 }
1190 return Ty;
1191}
1192
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001193#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1194
Chandler Carruth713aa942012-09-14 09:22:59 +00001195void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1196 StringRef Indent) const {
1197 OS << Indent << "partition #" << (I - begin())
1198 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1199 << (I->IsSplittable ? " (splittable)" : "")
1200 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1201 << "\n";
1202}
1203
1204void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1205 StringRef Indent) const {
1206 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1207 UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001208 if (!UI->U)
1209 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00001210 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth77c12702012-10-01 01:49:22 +00001211 << "used by: " << *UI->U->getUser() << "\n";
1212 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001213 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1214 bool IsDest;
1215 if (!MTO.IsSplittable)
1216 IsDest = UI->BeginOffset == MTO.DestBegin;
1217 else
1218 IsDest = MTO.DestBegin != 0u;
1219 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1220 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1221 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1222 }
1223 }
1224}
1225
1226void AllocaPartitioning::print(raw_ostream &OS) const {
1227 if (PointerEscapingInstr) {
1228 OS << "No partitioning for alloca: " << AI << "\n"
1229 << " A pointer to this alloca escaped by:\n"
1230 << " " << *PointerEscapingInstr << "\n";
1231 return;
1232 }
1233
1234 OS << "Partitioning of alloca: " << AI << "\n";
1235 unsigned Num = 0;
1236 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1237 print(OS, I);
1238 printUsers(OS, I);
1239 }
1240}
1241
1242void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1243void AllocaPartitioning::dump() const { print(dbgs()); }
1244
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001245#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1246
Chandler Carruth713aa942012-09-14 09:22:59 +00001247
1248namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001249/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1250///
1251/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1252/// the loads and stores of an alloca instruction, as well as updating its
1253/// debug information. This is used when a domtree is unavailable and thus
1254/// mem2reg in its full form can't be used to handle promotion of allocas to
1255/// scalar values.
1256class AllocaPromoter : public LoadAndStorePromoter {
1257 AllocaInst &AI;
1258 DIBuilder &DIB;
1259
1260 SmallVector<DbgDeclareInst *, 4> DDIs;
1261 SmallVector<DbgValueInst *, 4> DVIs;
1262
1263public:
1264 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1265 AllocaInst &AI, DIBuilder &DIB)
1266 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1267
1268 void run(const SmallVectorImpl<Instruction*> &Insts) {
1269 // Remember which alloca we're promoting (for isInstInList).
1270 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1271 for (Value::use_iterator UI = DebugNode->use_begin(),
1272 UE = DebugNode->use_end();
1273 UI != UE; ++UI)
1274 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1275 DDIs.push_back(DDI);
1276 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1277 DVIs.push_back(DVI);
1278 }
1279
1280 LoadAndStorePromoter::run(Insts);
1281 AI.eraseFromParent();
1282 while (!DDIs.empty())
1283 DDIs.pop_back_val()->eraseFromParent();
1284 while (!DVIs.empty())
1285 DVIs.pop_back_val()->eraseFromParent();
1286 }
1287
1288 virtual bool isInstInList(Instruction *I,
1289 const SmallVectorImpl<Instruction*> &Insts) const {
1290 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1291 return LI->getOperand(0) == &AI;
1292 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1293 }
1294
1295 virtual void updateDebugInfo(Instruction *Inst) const {
1296 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1297 E = DDIs.end(); I != E; ++I) {
1298 DbgDeclareInst *DDI = *I;
1299 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1300 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1301 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1302 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1303 }
1304 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1305 E = DVIs.end(); I != E; ++I) {
1306 DbgValueInst *DVI = *I;
1307 Value *Arg = NULL;
1308 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1309 // If an argument is zero extended then use argument directly. The ZExt
1310 // may be zapped by an optimization pass in future.
1311 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1312 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1313 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1314 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1315 if (!Arg)
1316 Arg = SI->getOperand(0);
1317 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1318 Arg = LI->getOperand(0);
1319 } else {
1320 continue;
1321 }
1322 Instruction *DbgVal =
1323 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1324 Inst);
1325 DbgVal->setDebugLoc(DVI->getDebugLoc());
1326 }
1327 }
1328};
1329} // end anon namespace
1330
1331
1332namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001333/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1334///
1335/// This pass takes allocations which can be completely analyzed (that is, they
1336/// don't escape) and tries to turn them into scalar SSA values. There are
1337/// a few steps to this process.
1338///
1339/// 1) It takes allocations of aggregates and analyzes the ways in which they
1340/// are used to try to split them into smaller allocations, ideally of
1341/// a single scalar data type. It will split up memcpy and memset accesses
1342/// as necessary and try to isolate invidual scalar accesses.
1343/// 2) It will transform accesses into forms which are suitable for SSA value
1344/// promotion. This can be replacing a memset with a scalar store of an
1345/// integer value, or it can involve speculating operations on a PHI or
1346/// select to be a PHI or select of the results.
1347/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1348/// onto insert and extract operations on a vector value, and convert them to
1349/// this form. By doing so, it will enable promotion of vector aggregates to
1350/// SSA vector values.
1351class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001352 const bool RequiresDomTree;
1353
Chandler Carruth713aa942012-09-14 09:22:59 +00001354 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +00001355 const DataLayout *TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00001356 DominatorTree *DT;
1357
1358 /// \brief Worklist of alloca instructions to simplify.
1359 ///
1360 /// Each alloca in the function is added to this. Each new alloca formed gets
1361 /// added to it as well to recursively simplify unless that alloca can be
1362 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1363 /// the one being actively rewritten, we add it back onto the list if not
1364 /// already present to ensure it is re-visited.
1365 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1366
1367 /// \brief A collection of instructions to delete.
1368 /// We try to batch deletions to simplify code and make things a bit more
1369 /// efficient.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001370 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth713aa942012-09-14 09:22:59 +00001371
Chandler Carruthb2d98c22012-10-04 12:33:50 +00001372 /// \brief Post-promotion worklist.
1373 ///
1374 /// Sometimes we discover an alloca which has a high probability of becoming
1375 /// viable for SROA after a round of promotion takes place. In those cases,
1376 /// the alloca is enqueued here for re-processing.
1377 ///
1378 /// Note that we have to be very careful to clear allocas out of this list in
1379 /// the event they are deleted.
1380 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1381
Chandler Carruth713aa942012-09-14 09:22:59 +00001382 /// \brief A collection of alloca instructions we can directly promote.
1383 std::vector<AllocaInst *> PromotableAllocas;
1384
1385public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001386 SROA(bool RequiresDomTree = true)
1387 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1388 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001389 initializeSROAPass(*PassRegistry::getPassRegistry());
1390 }
1391 bool runOnFunction(Function &F);
1392 void getAnalysisUsage(AnalysisUsage &AU) const;
1393
1394 const char *getPassName() const { return "SROA"; }
1395 static char ID;
1396
1397private:
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001398 friend class PHIOrSelectSpeculator;
Chandler Carruth713aa942012-09-14 09:22:59 +00001399 friend class AllocaPartitionRewriter;
1400 friend class AllocaPartitionVectorRewriter;
1401
1402 bool rewriteAllocaPartition(AllocaInst &AI,
1403 AllocaPartitioning &P,
1404 AllocaPartitioning::iterator PI);
1405 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1406 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001407 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001408 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001409};
1410}
1411
1412char SROA::ID = 0;
1413
Chandler Carruth1c8db502012-09-15 11:43:14 +00001414FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1415 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001416}
1417
1418INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1419 false, false)
1420INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1421INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1422 false, false)
1423
Chandler Carruth0e9da582012-10-05 01:29:06 +00001424namespace {
1425/// \brief Visitor to speculate PHIs and Selects where possible.
1426class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1427 // Befriend the base class so it can delegate to private visit methods.
1428 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1429
Micah Villmow3574eca2012-10-08 16:38:25 +00001430 const DataLayout &TD;
Chandler Carruth0e9da582012-10-05 01:29:06 +00001431 AllocaPartitioning &P;
1432 SROA &Pass;
1433
1434public:
Micah Villmow3574eca2012-10-08 16:38:25 +00001435 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth0e9da582012-10-05 01:29:06 +00001436 : TD(TD), P(P), Pass(Pass) {}
1437
1438 /// \brief Visit the users of an alloca partition and rewrite them.
1439 void visitUsers(AllocaPartitioning::const_iterator PI) {
1440 // Note that we need to use an index here as the underlying vector of uses
1441 // may be grown during speculation. However, we never need to re-visit the
1442 // new uses, and so we can use the initial size bound.
1443 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1444 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1445 if (!PU.U)
1446 continue; // Skip dead use.
1447
1448 visit(cast<Instruction>(PU.U->getUser()));
1449 }
1450 }
1451
1452private:
1453 // By default, skip this instruction.
1454 void visitInstruction(Instruction &I) {}
1455
1456 /// PHI instructions that use an alloca and are subsequently loaded can be
1457 /// rewritten to load both input pointers in the pred blocks and then PHI the
1458 /// results, allowing the load of the alloca to be promoted.
1459 /// From this:
1460 /// %P2 = phi [i32* %Alloca, i32* %Other]
1461 /// %V = load i32* %P2
1462 /// to:
1463 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1464 /// ...
1465 /// %V2 = load i32* %Other
1466 /// ...
1467 /// %V = phi [i32 %V1, i32 %V2]
1468 ///
1469 /// We can do this to a select if its only uses are loads and if the operands
1470 /// to the select can be loaded unconditionally.
1471 ///
1472 /// FIXME: This should be hoisted into a generic utility, likely in
1473 /// Transforms/Util/Local.h
1474 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1475 // For now, we can only do this promotion if the load is in the same block
1476 // as the PHI, and if there are no stores between the phi and load.
1477 // TODO: Allow recursive phi users.
1478 // TODO: Allow stores.
1479 BasicBlock *BB = PN.getParent();
1480 unsigned MaxAlign = 0;
1481 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1482 UI != UE; ++UI) {
1483 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1484 if (LI == 0 || !LI->isSimple()) return false;
1485
1486 // For now we only allow loads in the same block as the PHI. This is
1487 // a common case that happens when instcombine merges two loads through
1488 // a PHI.
1489 if (LI->getParent() != BB) return false;
1490
1491 // Ensure that there are no instructions between the PHI and the load that
1492 // could store.
1493 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1494 if (BBI->mayWriteToMemory())
1495 return false;
1496
1497 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1498 Loads.push_back(LI);
1499 }
1500
1501 // We can only transform this if it is safe to push the loads into the
1502 // predecessor blocks. The only thing to watch out for is that we can't put
1503 // a possibly trapping load in the predecessor if it is a critical edge.
1504 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1505 ++Idx) {
1506 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1507 Value *InVal = PN.getIncomingValue(Idx);
1508
1509 // If the value is produced by the terminator of the predecessor (an
1510 // invoke) or it has side-effects, there is no valid place to put a load
1511 // in the predecessor.
1512 if (TI == InVal || TI->mayHaveSideEffects())
1513 return false;
1514
1515 // If the predecessor has a single successor, then the edge isn't
1516 // critical.
1517 if (TI->getNumSuccessors() == 1)
1518 continue;
1519
1520 // If this pointer is always safe to load, or if we can prove that there
1521 // is already a load in the block, then we can move the load to the pred
1522 // block.
1523 if (InVal->isDereferenceablePointer() ||
1524 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1525 continue;
1526
1527 return false;
1528 }
1529
1530 return true;
1531 }
1532
1533 void visitPHINode(PHINode &PN) {
1534 DEBUG(dbgs() << " original: " << PN << "\n");
1535
1536 SmallVector<LoadInst *, 4> Loads;
1537 if (!isSafePHIToSpeculate(PN, Loads))
1538 return;
1539
1540 assert(!Loads.empty());
1541
1542 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1543 IRBuilder<> PHIBuilder(&PN);
1544 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1545 PN.getName() + ".sroa.speculated");
1546
1547 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1548 // matter which one we get and if any differ, it doesn't matter.
1549 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1550 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1551 unsigned Align = SomeLoad->getAlignment();
1552
1553 // Rewrite all loads of the PN to use the new PHI.
1554 do {
1555 LoadInst *LI = Loads.pop_back_val();
1556 LI->replaceAllUsesWith(NewPN);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001557 Pass.DeadInsts.insert(LI);
Chandler Carruth0e9da582012-10-05 01:29:06 +00001558 } while (!Loads.empty());
1559
1560 // Inject loads into all of the pred blocks.
1561 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1562 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1563 TerminatorInst *TI = Pred->getTerminator();
1564 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1565 Value *InVal = PN.getIncomingValue(Idx);
1566 IRBuilder<> PredBuilder(TI);
1567
1568 LoadInst *Load
1569 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1570 Pred->getName()));
1571 ++NumLoadsSpeculated;
1572 Load->setAlignment(Align);
1573 if (TBAATag)
1574 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1575 NewPN->addIncoming(Load, Pred);
1576
1577 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1578 if (!Ptr)
1579 // No uses to rewrite.
1580 continue;
1581
1582 // Try to lookup and rewrite any partition uses corresponding to this phi
1583 // input.
1584 AllocaPartitioning::iterator PI
1585 = P.findPartitionForPHIOrSelectOperand(InUse);
1586 if (PI == P.end())
1587 continue;
1588
1589 // Replace the Use in the PartitionUse for this operand with the Use
1590 // inside the load.
1591 AllocaPartitioning::use_iterator UI
1592 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1593 assert(isa<PHINode>(*UI->U->getUser()));
1594 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1595 }
1596 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1597 }
1598
1599 /// Select instructions that use an alloca and are subsequently loaded can be
1600 /// rewritten to load both input pointers and then select between the result,
1601 /// allowing the load of the alloca to be promoted.
1602 /// From this:
1603 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1604 /// %V = load i32* %P2
1605 /// to:
1606 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1607 /// %V2 = load i32* %Other
1608 /// %V = select i1 %cond, i32 %V1, i32 %V2
1609 ///
1610 /// We can do this to a select if its only uses are loads and if the operand
1611 /// to the select can be loaded unconditionally.
1612 bool isSafeSelectToSpeculate(SelectInst &SI,
1613 SmallVectorImpl<LoadInst *> &Loads) {
1614 Value *TValue = SI.getTrueValue();
1615 Value *FValue = SI.getFalseValue();
1616 bool TDerefable = TValue->isDereferenceablePointer();
1617 bool FDerefable = FValue->isDereferenceablePointer();
1618
1619 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1620 UI != UE; ++UI) {
1621 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1622 if (LI == 0 || !LI->isSimple()) return false;
1623
1624 // Both operands to the select need to be dereferencable, either
1625 // absolutely (e.g. allocas) or at this point because we can see other
1626 // accesses to it.
1627 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1628 LI->getAlignment(), &TD))
1629 return false;
1630 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1631 LI->getAlignment(), &TD))
1632 return false;
1633 Loads.push_back(LI);
1634 }
1635
1636 return true;
1637 }
1638
1639 void visitSelectInst(SelectInst &SI) {
1640 DEBUG(dbgs() << " original: " << SI << "\n");
1641 IRBuilder<> IRB(&SI);
1642
1643 // If the select isn't safe to speculate, just use simple logic to emit it.
1644 SmallVector<LoadInst *, 4> Loads;
1645 if (!isSafeSelectToSpeculate(SI, Loads))
1646 return;
1647
1648 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1649 AllocaPartitioning::iterator PIs[2];
1650 AllocaPartitioning::PartitionUse PUs[2];
1651 for (unsigned i = 0, e = 2; i != e; ++i) {
1652 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1653 if (PIs[i] != P.end()) {
1654 // If the pointer is within the partitioning, remove the select from
1655 // its uses. We'll add in the new loads below.
1656 AllocaPartitioning::use_iterator UI
1657 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1658 PUs[i] = *UI;
1659 // Clear out the use here so that the offsets into the use list remain
1660 // stable but this use is ignored when rewriting.
1661 UI->U = 0;
1662 }
1663 }
1664
1665 Value *TV = SI.getTrueValue();
1666 Value *FV = SI.getFalseValue();
1667 // Replace the loads of the select with a select of two loads.
1668 while (!Loads.empty()) {
1669 LoadInst *LI = Loads.pop_back_val();
1670
1671 IRB.SetInsertPoint(LI);
1672 LoadInst *TL =
1673 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1674 LoadInst *FL =
1675 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1676 NumLoadsSpeculated += 2;
1677
1678 // Transfer alignment and TBAA info if present.
1679 TL->setAlignment(LI->getAlignment());
1680 FL->setAlignment(LI->getAlignment());
1681 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1682 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1683 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1684 }
1685
1686 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1687 LI->getName() + ".sroa.speculated");
1688
1689 LoadInst *Loads[2] = { TL, FL };
1690 for (unsigned i = 0, e = 2; i != e; ++i) {
1691 if (PIs[i] != P.end()) {
1692 Use *LoadUse = &Loads[i]->getOperandUse(0);
1693 assert(PUs[i].U->get() == LoadUse->get());
1694 PUs[i].U = LoadUse;
1695 P.use_push_back(PIs[i], PUs[i]);
1696 }
1697 }
1698
1699 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1700 LI->replaceAllUsesWith(V);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00001701 Pass.DeadInsts.insert(LI);
Chandler Carruth0e9da582012-10-05 01:29:06 +00001702 }
1703 }
1704};
1705}
1706
Chandler Carruth713aa942012-09-14 09:22:59 +00001707/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1708///
1709/// If the provided GEP is all-constant, the total byte offset formed by the
1710/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1711/// operands, the function returns false and the value of Offset is unmodified.
Micah Villmow3574eca2012-10-08 16:38:25 +00001712static bool accumulateGEPOffsets(const DataLayout &TD, GEPOperator &GEP,
Chandler Carruth713aa942012-09-14 09:22:59 +00001713 APInt &Offset) {
1714 APInt GEPOffset(Offset.getBitWidth(), 0);
1715 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1716 GTI != GTE; ++GTI) {
1717 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1718 if (!OpC)
1719 return false;
1720 if (OpC->isZero()) continue;
1721
1722 // Handle a struct index, which adds its field offset to the pointer.
1723 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1724 unsigned ElementIdx = OpC->getZExtValue();
1725 const StructLayout *SL = TD.getStructLayout(STy);
1726 GEPOffset += APInt(Offset.getBitWidth(),
1727 SL->getElementOffset(ElementIdx));
1728 continue;
1729 }
1730
1731 APInt TypeSize(Offset.getBitWidth(),
1732 TD.getTypeAllocSize(GTI.getIndexedType()));
1733 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1734 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1735 "vector element size is not a multiple of 8, cannot GEP over it");
1736 TypeSize = VTy->getScalarSizeInBits() / 8;
1737 }
1738
1739 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1740 }
1741 Offset = GEPOffset;
1742 return true;
1743}
1744
1745/// \brief Build a GEP out of a base pointer and indices.
1746///
1747/// This will return the BasePtr if that is valid, or build a new GEP
1748/// instruction using the IRBuilder if GEP-ing is needed.
1749static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1750 SmallVectorImpl<Value *> &Indices,
1751 const Twine &Prefix) {
1752 if (Indices.empty())
1753 return BasePtr;
1754
1755 // A single zero index is a no-op, so check for this and avoid building a GEP
1756 // in that case.
1757 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1758 return BasePtr;
1759
1760 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1761}
1762
1763/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1764/// TargetTy without changing the offset of the pointer.
1765///
1766/// This routine assumes we've already established a properly offset GEP with
1767/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1768/// zero-indices down through type layers until we find one the same as
1769/// TargetTy. If we can't find one with the same type, we at least try to use
1770/// one with the same size. If none of that works, we just produce the GEP as
1771/// indicated by Indices to have the correct offset.
Micah Villmow3574eca2012-10-08 16:38:25 +00001772static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001773 Value *BasePtr, Type *Ty, Type *TargetTy,
1774 SmallVectorImpl<Value *> &Indices,
1775 const Twine &Prefix) {
1776 if (Ty == TargetTy)
1777 return buildGEP(IRB, BasePtr, Indices, Prefix);
1778
1779 // See if we can descend into a struct and locate a field with the correct
1780 // type.
1781 unsigned NumLayers = 0;
1782 Type *ElementTy = Ty;
1783 do {
1784 if (ElementTy->isPointerTy())
1785 break;
1786 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1787 ElementTy = SeqTy->getElementType();
Chandler Carruth020d9d52012-10-17 07:22:16 +00001788 // Note that we use the default address space as this index is over an
1789 // array or a vector, not a pointer.
1790 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth713aa942012-09-14 09:22:59 +00001791 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth2fdb25b2012-10-09 01:58:35 +00001792 if (STy->element_begin() == STy->element_end())
1793 break; // Nothing left to descend into.
Chandler Carruth713aa942012-09-14 09:22:59 +00001794 ElementTy = *STy->element_begin();
1795 Indices.push_back(IRB.getInt32(0));
1796 } else {
1797 break;
1798 }
1799 ++NumLayers;
1800 } while (ElementTy != TargetTy);
1801 if (ElementTy != TargetTy)
1802 Indices.erase(Indices.end() - NumLayers, Indices.end());
1803
1804 return buildGEP(IRB, BasePtr, Indices, Prefix);
1805}
1806
1807/// \brief Recursively compute indices for a natural GEP.
1808///
1809/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1810/// element types adding appropriate indices for the GEP.
Micah Villmow3574eca2012-10-08 16:38:25 +00001811static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001812 Value *Ptr, Type *Ty, APInt &Offset,
1813 Type *TargetTy,
1814 SmallVectorImpl<Value *> &Indices,
1815 const Twine &Prefix) {
1816 if (Offset == 0)
1817 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1818
1819 // We can't recurse through pointer types.
1820 if (Ty->isPointerTy())
1821 return 0;
1822
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001823 // We try to analyze GEPs over vectors here, but note that these GEPs are
1824 // extremely poorly defined currently. The long-term goal is to remove GEPing
1825 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001826 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1827 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1828 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001829 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001830 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001831 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001832 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1833 return 0;
1834 Offset -= NumSkippedElements * ElementSize;
1835 Indices.push_back(IRB.getInt(NumSkippedElements));
1836 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1837 Offset, TargetTy, Indices, Prefix);
1838 }
1839
1840 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1841 Type *ElementTy = ArrTy->getElementType();
1842 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001843 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001844 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1845 return 0;
1846
1847 Offset -= NumSkippedElements * ElementSize;
1848 Indices.push_back(IRB.getInt(NumSkippedElements));
1849 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1850 Indices, Prefix);
1851 }
1852
1853 StructType *STy = dyn_cast<StructType>(Ty);
1854 if (!STy)
1855 return 0;
1856
1857 const StructLayout *SL = TD.getStructLayout(STy);
1858 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001859 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001860 return 0;
1861 unsigned Index = SL->getElementContainingOffset(StructOffset);
1862 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1863 Type *ElementTy = STy->getElementType(Index);
1864 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1865 return 0; // The offset points into alignment padding.
1866
1867 Indices.push_back(IRB.getInt32(Index));
1868 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1869 Indices, Prefix);
1870}
1871
1872/// \brief Get a natural GEP from a base pointer to a particular offset and
1873/// resulting in a particular type.
1874///
1875/// The goal is to produce a "natural" looking GEP that works with the existing
1876/// composite types to arrive at the appropriate offset and element type for
1877/// a pointer. TargetTy is the element type the returned GEP should point-to if
1878/// possible. We recurse by decreasing Offset, adding the appropriate index to
1879/// Indices, and setting Ty to the result subtype.
1880///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001881/// If no natural GEP can be constructed, this function returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00001882static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001883 Value *Ptr, APInt Offset, Type *TargetTy,
1884 SmallVectorImpl<Value *> &Indices,
1885 const Twine &Prefix) {
1886 PointerType *Ty = cast<PointerType>(Ptr->getType());
1887
1888 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1889 // an i8.
1890 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1891 return 0;
1892
1893 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001894 if (!ElementTy->isSized())
1895 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001896 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1897 if (ElementSize == 0)
1898 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001899 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001900
1901 Offset -= NumSkippedElements * ElementSize;
1902 Indices.push_back(IRB.getInt(NumSkippedElements));
1903 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1904 Indices, Prefix);
1905}
1906
1907/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1908/// resulting pointer has PointerTy.
1909///
1910/// This tries very hard to compute a "natural" GEP which arrives at the offset
1911/// and produces the pointer type desired. Where it cannot, it will try to use
1912/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1913/// fails, it will try to use an existing i8* and GEP to the byte offset and
1914/// bitcast to the type.
1915///
1916/// The strategy for finding the more natural GEPs is to peel off layers of the
1917/// pointer, walking back through bit casts and GEPs, searching for a base
1918/// pointer from which we can compute a natural GEP with the desired
1919/// properities. The algorithm tries to fold as many constant indices into
1920/// a single GEP as possible, thus making each GEP more independent of the
1921/// surrounding code.
Micah Villmow3574eca2012-10-08 16:38:25 +00001922static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001923 Value *Ptr, APInt Offset, Type *PointerTy,
1924 const Twine &Prefix) {
1925 // Even though we don't look through PHI nodes, we could be called on an
1926 // instruction in an unreachable block, which may be on a cycle.
1927 SmallPtrSet<Value *, 4> Visited;
1928 Visited.insert(Ptr);
1929 SmallVector<Value *, 4> Indices;
1930
1931 // We may end up computing an offset pointer that has the wrong type. If we
1932 // never are able to compute one directly that has the correct type, we'll
1933 // fall back to it, so keep it around here.
1934 Value *OffsetPtr = 0;
1935
1936 // Remember any i8 pointer we come across to re-use if we need to do a raw
1937 // byte offset.
1938 Value *Int8Ptr = 0;
1939 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1940
1941 Type *TargetTy = PointerTy->getPointerElementType();
1942
1943 do {
1944 // First fold any existing GEPs into the offset.
1945 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1946 APInt GEPOffset(Offset.getBitWidth(), 0);
1947 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1948 break;
1949 Offset += GEPOffset;
1950 Ptr = GEP->getPointerOperand();
1951 if (!Visited.insert(Ptr))
1952 break;
1953 }
1954
1955 // See if we can perform a natural GEP here.
1956 Indices.clear();
1957 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1958 Indices, Prefix)) {
1959 if (P->getType() == PointerTy) {
1960 // Zap any offset pointer that we ended up computing in previous rounds.
1961 if (OffsetPtr && OffsetPtr->use_empty())
1962 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1963 I->eraseFromParent();
1964 return P;
1965 }
1966 if (!OffsetPtr) {
1967 OffsetPtr = P;
1968 }
1969 }
1970
1971 // Stash this pointer if we've found an i8*.
1972 if (Ptr->getType()->isIntegerTy(8)) {
1973 Int8Ptr = Ptr;
1974 Int8PtrOffset = Offset;
1975 }
1976
1977 // Peel off a layer of the pointer and update the offset appropriately.
1978 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1979 Ptr = cast<Operator>(Ptr)->getOperand(0);
1980 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1981 if (GA->mayBeOverridden())
1982 break;
1983 Ptr = GA->getAliasee();
1984 } else {
1985 break;
1986 }
1987 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1988 } while (Visited.insert(Ptr));
1989
1990 if (!OffsetPtr) {
1991 if (!Int8Ptr) {
1992 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1993 Prefix + ".raw_cast");
1994 Int8PtrOffset = Offset;
1995 }
1996
1997 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1998 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1999 Prefix + ".raw_idx");
2000 }
2001 Ptr = OffsetPtr;
2002
2003 // On the off chance we were targeting i8*, guard the bitcast here.
2004 if (Ptr->getType() != PointerTy)
2005 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2006
2007 return Ptr;
2008}
2009
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002010/// \brief Test whether we can convert a value from the old to the new type.
2011///
2012/// This predicate should be used to guard calls to convertValue in order to
2013/// ensure that we only try to convert viable values. The strategy is that we
2014/// will peel off single element struct and array wrappings to get to an
2015/// underlying value, and convert that value.
2016static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
2017 if (OldTy == NewTy)
2018 return true;
2019 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
2020 return false;
2021 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2022 return false;
2023
2024 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2025 if (NewTy->isPointerTy() && OldTy->isPointerTy())
2026 return true;
2027 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
2028 return true;
2029 return false;
2030 }
2031
2032 return true;
2033}
2034
2035/// \brief Generic routine to convert an SSA value to a value of a different
2036/// type.
2037///
2038/// This will try various different casting techniques, such as bitcasts,
2039/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2040/// two types for viability with this routine.
2041static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2042 Type *Ty) {
2043 assert(canConvertValue(DL, V->getType(), Ty) &&
2044 "Value not convertable to type");
2045 if (V->getType() == Ty)
2046 return V;
2047 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2048 return IRB.CreateIntToPtr(V, Ty);
2049 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2050 return IRB.CreatePtrToInt(V, Ty);
2051
2052 return IRB.CreateBitCast(V, Ty);
2053}
2054
Chandler Carruth713aa942012-09-14 09:22:59 +00002055/// \brief Test whether the given alloca partition can be promoted to a vector.
2056///
2057/// This is a quick test to check whether we can rewrite a particular alloca
2058/// partition (and its newly formed alloca) into a vector alloca with only
2059/// whole-vector loads and stores such that it could be promoted to a vector
2060/// SSA value. We only can ensure this for a limited set of operations, and we
2061/// don't want to do the rewrites unless we are confident that the result will
2062/// be promotable, so we have an early test here.
Micah Villmow3574eca2012-10-08 16:38:25 +00002063static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00002064 Type *AllocaTy,
2065 AllocaPartitioning &P,
2066 uint64_t PartitionBeginOffset,
2067 uint64_t PartitionEndOffset,
2068 AllocaPartitioning::const_use_iterator I,
2069 AllocaPartitioning::const_use_iterator E) {
2070 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2071 if (!Ty)
2072 return false;
2073
2074 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2075 uint64_t ElementSize = Ty->getScalarSizeInBits();
2076
2077 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2078 // that aren't byte sized.
2079 if (ElementSize % 8)
2080 return false;
2081 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2082 VecSize /= 8;
2083 ElementSize /= 8;
2084
2085 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002086 if (!I->U)
2087 continue; // Skip dead use.
2088
Chandler Carruth713aa942012-09-14 09:22:59 +00002089 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2090 uint64_t BeginIndex = BeginOffset / ElementSize;
2091 if (BeginIndex * ElementSize != BeginOffset ||
2092 BeginIndex >= Ty->getNumElements())
2093 return false;
2094 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2095 uint64_t EndIndex = EndOffset / ElementSize;
2096 if (EndIndex * ElementSize != EndOffset ||
2097 EndIndex > Ty->getNumElements())
2098 return false;
2099
Chandler Carruth07df7652012-11-21 08:16:30 +00002100 assert(EndIndex > BeginIndex && "Empty vector!");
2101 uint64_t NumElements = EndIndex - BeginIndex;
2102 Type *PartitionTy
2103 = (NumElements == 1) ? Ty->getElementType()
2104 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruth713aa942012-09-14 09:22:59 +00002105
Chandler Carruth77c12702012-10-01 01:49:22 +00002106 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002107 if (MI->isVolatile())
2108 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002109 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002110 const AllocaPartitioning::MemTransferOffsets &MTO
2111 = P.getMemTransferOffsets(*MTI);
2112 if (!MTO.IsSplittable)
2113 return false;
2114 }
Chandler Carruth77c12702012-10-01 01:49:22 +00002115 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002116 // Disable vector promotion when there are loads or stores of an FCA.
2117 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002118 } else if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
2119 if (LI->isVolatile())
2120 return false;
Chandler Carruth07df7652012-11-21 08:16:30 +00002121 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2122 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002123 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
2124 if (SI->isVolatile())
2125 return false;
Chandler Carruth07df7652012-11-21 08:16:30 +00002126 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2127 return false;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002128 } else {
Chandler Carruth713aa942012-09-14 09:22:59 +00002129 return false;
2130 }
2131 }
2132 return true;
2133}
2134
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002135/// \brief Test whether the given alloca partition's integer operations can be
2136/// widened to promotable ones.
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002137///
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002138/// This is a quick test to check whether we can rewrite the integer loads and
2139/// stores to a particular alloca into wider loads and stores and be able to
2140/// promote the resulting alloca.
2141static bool isIntegerWideningViable(const DataLayout &TD,
2142 Type *AllocaTy,
2143 uint64_t AllocBeginOffset,
2144 AllocaPartitioning &P,
2145 AllocaPartitioning::const_use_iterator I,
2146 AllocaPartitioning::const_use_iterator E) {
2147 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
Benjamin Kramer5bded752012-12-01 11:53:32 +00002148 // Don't create integer types larger than the maximum bitwidth.
2149 if (SizeInBits > IntegerType::MAX_INT_BITS)
2150 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002151
2152 // Don't try to handle allocas with bit-padding.
2153 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002154 return false;
2155
Chandler Carrutha2b88162012-10-25 04:37:07 +00002156 // We need to ensure that an integer type with the appropriate bitwidth can
2157 // be converted to the alloca type, whatever that is. We don't want to force
2158 // the alloca itself to have an integer type if there is a more suitable one.
2159 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2160 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2161 !canConvertValue(TD, IntTy, AllocaTy))
2162 return false;
2163
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002164 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2165
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002166 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2167 // Also ensure that the alloca has a covering load or store. We don't want
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002168 // to widen the integer operotains only to fail to promote due to some other
2169 // unsplittable entry (which we may make splittable later).
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002170 bool WholeAllocaOp = false;
2171 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002172 if (!I->U)
2173 continue; // Skip dead use.
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002174
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002175 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2176 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2177
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002178 // We can't reasonably handle cases where the load or store extends past
2179 // the end of the aloca's type and into its padding.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002180 if (RelEnd > Size)
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002181 return false;
2182
Chandler Carruth77c12702012-10-01 01:49:22 +00002183 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002184 if (LI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002185 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002186 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002187 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002188 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2189 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2190 return false;
2191 continue;
2192 }
2193 // Non-integer loads need to be convertible from the alloca type so that
2194 // they are promotable.
2195 if (RelBegin != 0 || RelEnd != Size ||
2196 !canConvertValue(TD, AllocaTy, LI->getType()))
2197 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002198 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002199 Type *ValueTy = SI->getValueOperand()->getType();
2200 if (SI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002201 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002202 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002203 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002204 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2205 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2206 return false;
2207 continue;
2208 }
2209 // Non-integer stores need to be convertible to the alloca type so that
2210 // they are promotable.
2211 if (RelBegin != 0 || RelEnd != Size ||
2212 !canConvertValue(TD, ValueTy, AllocaTy))
2213 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002214 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002215 if (MI->isVolatile())
2216 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002217 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002218 const AllocaPartitioning::MemTransferOffsets &MTO
2219 = P.getMemTransferOffsets(*MTI);
2220 if (!MTO.IsSplittable)
2221 return false;
2222 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002223 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2224 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2225 II->getIntrinsicID() != Intrinsic::lifetime_end)
2226 return false;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002227 } else {
2228 return false;
2229 }
2230 }
2231 return WholeAllocaOp;
2232}
2233
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002234static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2235 IntegerType *Ty, uint64_t Offset,
2236 const Twine &Name) {
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002237 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002238 IntegerType *IntTy = cast<IntegerType>(V->getType());
2239 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2240 "Element extends past full value");
2241 uint64_t ShAmt = 8*Offset;
2242 if (DL.isBigEndian())
2243 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002244 if (ShAmt) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002245 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002246 DEBUG(dbgs() << " shifted: " << *V << "\n");
2247 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002248 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2249 "Cannot extract to a larger integer!");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002250 if (Ty != IntTy) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002251 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002252 DEBUG(dbgs() << " trunced: " << *V << "\n");
2253 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002254 return V;
2255}
2256
2257static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2258 Value *V, uint64_t Offset, const Twine &Name) {
2259 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2260 IntegerType *Ty = cast<IntegerType>(V->getType());
2261 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2262 "Cannot insert a larger integer!");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002263 DEBUG(dbgs() << " start: " << *V << "\n");
2264 if (Ty != IntTy) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002265 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002266 DEBUG(dbgs() << " extended: " << *V << "\n");
2267 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002268 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2269 "Element store outside of alloca store");
2270 uint64_t ShAmt = 8*Offset;
2271 if (DL.isBigEndian())
2272 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002273 if (ShAmt) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002274 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002275 DEBUG(dbgs() << " shifted: " << *V << "\n");
2276 }
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002277
2278 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2279 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2280 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002281 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002282 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002283 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002284 }
2285 return V;
2286}
2287
Chandler Carruth713aa942012-09-14 09:22:59 +00002288namespace {
2289/// \brief Visitor to rewrite instructions using a partition of an alloca to
2290/// use a new alloca.
2291///
2292/// Also implements the rewriting to vector-based accesses when the partition
2293/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2294/// lives here.
2295class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2296 bool> {
2297 // Befriend the base class so it can delegate to private visit methods.
2298 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2299
Micah Villmow3574eca2012-10-08 16:38:25 +00002300 const DataLayout &TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00002301 AllocaPartitioning &P;
2302 SROA &Pass;
2303 AllocaInst &OldAI, &NewAI;
2304 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth520eeae2012-10-13 02:41:05 +00002305 Type *NewAllocaTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00002306
2307 // If we are rewriting an alloca partition which can be written as pure
2308 // vector operations, we stash extra information here. When VecTy is
2309 // non-null, we have some strict guarantees about the rewriten alloca:
2310 // - The new alloca is exactly the size of the vector type here.
2311 // - The accesses all either map to the entire vector or to a single
2312 // element.
2313 // - The set of accessing instructions is only one of those handled above
2314 // in isVectorPromotionViable. Generally these are the same access kinds
2315 // which are promotable via mem2reg.
2316 VectorType *VecTy;
2317 Type *ElementTy;
2318 uint64_t ElementSize;
2319
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002320 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002321 // alloca's integer operations should be widened to this integer type due to
2322 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002323 // integer type will be stored here for easy access during rewriting.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002324 IntegerType *IntTy;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002325
Chandler Carruth713aa942012-09-14 09:22:59 +00002326 // The offset of the partition user currently being rewritten.
2327 uint64_t BeginOffset, EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002328 Use *OldUse;
Chandler Carruth713aa942012-09-14 09:22:59 +00002329 Instruction *OldPtr;
2330
2331 // The name prefix to use when rewriting instructions for this alloca.
2332 std::string NamePrefix;
2333
2334public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002335 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth713aa942012-09-14 09:22:59 +00002336 AllocaPartitioning::iterator PI,
2337 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2338 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2339 : TD(TD), P(P), Pass(Pass),
2340 OldAI(OldAI), NewAI(NewAI),
2341 NewAllocaBeginOffset(NewBeginOffset),
2342 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth520eeae2012-10-13 02:41:05 +00002343 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002344 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002345 BeginOffset(), EndOffset() {
2346 }
2347
2348 /// \brief Visit the users of the alloca partition and rewrite them.
2349 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2350 AllocaPartitioning::const_use_iterator E) {
2351 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2352 NewAllocaBeginOffset, NewAllocaEndOffset,
2353 I, E)) {
2354 ++NumVectorized;
2355 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2356 ElementTy = VecTy->getElementType();
2357 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2358 "Only multiple-of-8 sized vector elements are viable");
2359 ElementSize = VecTy->getScalarSizeInBits() / 8;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002360 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2361 NewAllocaBeginOffset, P, I, E)) {
2362 IntTy = Type::getIntNTy(NewAI.getContext(),
2363 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002364 }
2365 bool CanSROA = true;
2366 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002367 if (!I->U)
2368 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00002369 BeginOffset = I->BeginOffset;
2370 EndOffset = I->EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002371 OldUse = I->U;
2372 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth713aa942012-09-14 09:22:59 +00002373 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth77c12702012-10-01 01:49:22 +00002374 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002375 }
2376 if (VecTy) {
2377 assert(CanSROA);
2378 VecTy = 0;
2379 ElementTy = 0;
2380 ElementSize = 0;
2381 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002382 if (IntTy) {
2383 assert(CanSROA);
2384 IntTy = 0;
2385 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002386 return CanSROA;
2387 }
2388
2389private:
2390 // Every instruction which can end up as a user must have a rewrite rule.
2391 bool visitInstruction(Instruction &I) {
2392 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2393 llvm_unreachable("No rewrite rule for this instruction!");
2394 }
2395
2396 Twine getName(const Twine &Suffix) {
2397 return NamePrefix + Suffix;
2398 }
2399
2400 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2401 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth426c2bf2012-11-01 09:14:31 +00002402 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002403 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2404 }
2405
Chandler Carruthf710fb12012-10-03 08:14:02 +00002406 /// \brief Compute suitable alignment to access an offset into the new alloca.
2407 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth673850a2012-10-01 12:16:54 +00002408 unsigned NewAIAlign = NewAI.getAlignment();
2409 if (!NewAIAlign)
2410 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2411 return MinAlign(NewAIAlign, Offset);
2412 }
Chandler Carruthf710fb12012-10-03 08:14:02 +00002413
2414 /// \brief Compute suitable alignment to access this partition of the new
2415 /// alloca.
2416 unsigned getPartitionAlign() {
2417 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002418 }
2419
Chandler Carruthf710fb12012-10-03 08:14:02 +00002420 /// \brief Compute suitable alignment to access a type at an offset of the
2421 /// new alloca.
2422 ///
2423 /// \returns zero if the type's ABI alignment is a suitable alignment,
2424 /// otherwise returns the maximal suitable alignment.
2425 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2426 unsigned Align = getOffsetAlign(Offset);
2427 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2428 }
2429
2430 /// \brief Compute suitable alignment to access a type at the beginning of
2431 /// this partition of the new alloca.
2432 ///
2433 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2434 unsigned getPartitionTypeAlign(Type *Ty) {
2435 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002436 }
2437
Chandler Carruth07df7652012-11-21 08:16:30 +00002438 unsigned getIndex(uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002439 assert(VecTy && "Can only call getIndex when rewriting a vector");
2440 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2441 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2442 uint32_t Index = RelOffset / ElementSize;
2443 assert(Index * ElementSize == RelOffset);
Chandler Carruth07df7652012-11-21 08:16:30 +00002444 return Index;
Chandler Carruth713aa942012-09-14 09:22:59 +00002445 }
2446
2447 void deleteIfTriviallyDead(Value *V) {
2448 Instruction *I = cast<Instruction>(V);
2449 if (isInstructionTriviallyDead(I))
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002450 Pass.DeadInsts.insert(I);
Chandler Carruth713aa942012-09-14 09:22:59 +00002451 }
2452
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002453 Value *rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2454 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2455 getName(".load"));
Chandler Carruth07df7652012-11-21 08:16:30 +00002456 unsigned BeginIndex = getIndex(BeginOffset);
2457 unsigned EndIndex = getIndex(EndOffset);
2458 assert(EndIndex > BeginIndex && "Empty vector!");
2459 unsigned NumElements = EndIndex - BeginIndex;
2460 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2461 if (NumElements == 1) {
2462 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002463 getName(".extract"));
Chandler Carruth07df7652012-11-21 08:16:30 +00002464 DEBUG(dbgs() << " extract: " << *V << "\n");
2465 } else if (NumElements < VecTy->getNumElements()) {
2466 SmallVector<Constant*, 8> Mask;
2467 Mask.reserve(NumElements);
2468 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2469 Mask.push_back(IRB.getInt32(i));
2470 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2471 ConstantVector::get(Mask),
2472 getName(".extract"));
2473 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00002474 }
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002475 return V;
Chandler Carruth713aa942012-09-14 09:22:59 +00002476 }
2477
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002478 Value *rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002479 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002480 assert(!LI.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002481 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2482 getName(".load"));
2483 V = convertValue(TD, IRB, V, IntTy);
2484 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2485 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002486 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2487 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2488 getName(".extract"));
2489 return V;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002490 }
2491
Chandler Carruth713aa942012-09-14 09:22:59 +00002492 bool visitLoadInst(LoadInst &LI) {
2493 DEBUG(dbgs() << " original: " << LI << "\n");
2494 Value *OldOp = LI.getOperand(0);
2495 assert(OldOp == OldPtr);
2496 IRBuilder<> IRB(&LI);
2497
Chandler Carrutha2b88162012-10-25 04:37:07 +00002498 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002499 bool IsSplitIntLoad = Size < TD.getTypeStoreSize(LI.getType());
Chandler Carruth17679292012-11-20 10:02:19 +00002500
2501 // If this memory access can be shown to *statically* extend outside the
2502 // bounds of the original allocation it's behavior is undefined. Rather
2503 // than trying to transform it, just replace it with undef.
2504 // FIXME: We should do something more clever for functions being
2505 // instrumented by asan.
2506 // FIXME: Eventually, once ASan and friends can flush out bugs here, this
2507 // should be transformed to a load of null making it unreachable.
2508 uint64_t OldAllocSize = TD.getTypeAllocSize(OldAI.getAllocatedType());
2509 if (TD.getTypeStoreSize(LI.getType()) > OldAllocSize) {
2510 LI.replaceAllUsesWith(UndefValue::get(LI.getType()));
2511 Pass.DeadInsts.insert(&LI);
2512 deleteIfTriviallyDead(OldOp);
2513 DEBUG(dbgs() << " to: undef!!\n");
2514 return true;
2515 }
2516
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002517 Type *TargetTy = IsSplitIntLoad ? Type::getIntNTy(LI.getContext(), Size * 8)
2518 : LI.getType();
2519 bool IsPtrAdjusted = false;
2520 Value *V;
2521 if (VecTy) {
2522 V = rewriteVectorizedLoadInst(IRB, LI, OldOp);
2523 } else if (IntTy && LI.getType()->isIntegerTy()) {
2524 V = rewriteIntegerLoad(IRB, LI);
2525 } else if (BeginOffset == NewAllocaBeginOffset &&
2526 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2527 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2528 LI.isVolatile(), getName(".load"));
2529 } else {
2530 Type *LTy = TargetTy->getPointerTo();
2531 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2532 getPartitionTypeAlign(TargetTy),
2533 LI.isVolatile(), getName(".load"));
2534 IsPtrAdjusted = true;
2535 }
2536 V = convertValue(TD, IRB, V, TargetTy);
2537
2538 if (IsSplitIntLoad) {
Chandler Carrutha2b88162012-10-25 04:37:07 +00002539 assert(!LI.isVolatile());
2540 assert(LI.getType()->isIntegerTy() &&
2541 "Only integer type loads and stores are split");
2542 assert(LI.getType()->getIntegerBitWidth() ==
2543 TD.getTypeStoreSizeInBits(LI.getType()) &&
2544 "Non-byte-multiple bit width");
2545 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth70dace32012-10-30 20:52:40 +00002546 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
Chandler Carrutha2b88162012-10-25 04:37:07 +00002547 "Only alloca-wide loads can be split and recomposed");
Chandler Carrutha2b88162012-10-25 04:37:07 +00002548 // Move the insertion point just past the load so that we can refer to it.
2549 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carrutha2b88162012-10-25 04:37:07 +00002550 // Create a placeholder value with the same type as LI to use as the
2551 // basis for the new value. This allows us to replace the uses of LI with
2552 // the computed value, and then replace the placeholder with LI, leaving
2553 // LI only used for this computation.
2554 Value *Placeholder
Jakub Staszak5801ff92012-11-01 01:10:43 +00002555 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carrutha2b88162012-10-25 04:37:07 +00002556 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2557 getName(".insert"));
2558 LI.replaceAllUsesWith(V);
2559 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak5801ff92012-11-01 01:10:43 +00002560 delete Placeholder;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002561 } else {
2562 LI.replaceAllUsesWith(V);
Chandler Carrutha2b88162012-10-25 04:37:07 +00002563 }
2564
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002565 Pass.DeadInsts.insert(&LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002566 deleteIfTriviallyDead(OldOp);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002567 DEBUG(dbgs() << " to: " << *V << "\n");
2568 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth713aa942012-09-14 09:22:59 +00002569 }
2570
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002571 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, Value *V,
2572 StoreInst &SI, Value *OldOp) {
Chandler Carruth07df7652012-11-21 08:16:30 +00002573 unsigned BeginIndex = getIndex(BeginOffset);
2574 unsigned EndIndex = getIndex(EndOffset);
2575 assert(EndIndex > BeginIndex && "Empty vector!");
2576 unsigned NumElements = EndIndex - BeginIndex;
2577 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2578 Type *PartitionTy
2579 = (NumElements == 1) ? ElementTy
2580 : VectorType::get(ElementTy, NumElements);
2581 if (V->getType() != PartitionTy)
2582 V = convertValue(TD, IRB, V, PartitionTy);
2583 if (NumElements < VecTy->getNumElements()) {
2584 // We need to mix in the existing elements.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002585 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2586 getName(".load"));
Chandler Carruth07df7652012-11-21 08:16:30 +00002587 if (NumElements == 1) {
2588 V = IRB.CreateInsertElement(LI, V, IRB.getInt32(BeginIndex),
2589 getName(".insert"));
2590 DEBUG(dbgs() << " insert: " << *V << "\n");
2591 } else {
2592 // When inserting a smaller vector into the larger to store, we first
2593 // use a shuffle vector to widen it with undef elements, and then
2594 // a second shuffle vector to select between the loaded vector and the
2595 // incoming vector.
2596 SmallVector<Constant*, 8> Mask;
2597 Mask.reserve(VecTy->getNumElements());
2598 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2599 if (i >= BeginIndex && i < EndIndex)
2600 Mask.push_back(IRB.getInt32(i - BeginIndex));
2601 else
2602 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2603 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2604 ConstantVector::get(Mask),
2605 getName(".expand"));
2606 DEBUG(dbgs() << " shuffle1: " << *V << "\n");
2607
2608 Mask.clear();
2609 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2610 if (i >= BeginIndex && i < EndIndex)
2611 Mask.push_back(IRB.getInt32(i));
2612 else
2613 Mask.push_back(IRB.getInt32(i + VecTy->getNumElements()));
2614 V = IRB.CreateShuffleVector(V, LI, ConstantVector::get(Mask),
2615 getName("insert"));
2616 DEBUG(dbgs() << " shuffle2: " << *V << "\n");
2617 }
2618 } else {
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002619 V = convertValue(TD, IRB, V, VecTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00002620 }
Chandler Carruth81b001a2012-09-26 10:27:46 +00002621 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002622 Pass.DeadInsts.insert(&SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002623
2624 (void)Store;
2625 DEBUG(dbgs() << " to: " << *Store << "\n");
2626 return true;
2627 }
2628
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002629 bool rewriteIntegerStore(IRBuilder<> &IRB, Value *V, StoreInst &SI) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002630 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002631 assert(!SI.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002632 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2633 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2634 getName(".oldload"));
2635 Old = convertValue(TD, IRB, Old, IntTy);
2636 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2637 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2638 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2639 getName(".insert"));
2640 }
2641 V = convertValue(TD, IRB, V, NewAllocaTy);
2642 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002643 Pass.DeadInsts.insert(&SI);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002644 (void)Store;
2645 DEBUG(dbgs() << " to: " << *Store << "\n");
2646 return true;
2647 }
2648
Chandler Carruth713aa942012-09-14 09:22:59 +00002649 bool visitStoreInst(StoreInst &SI) {
2650 DEBUG(dbgs() << " original: " << SI << "\n");
2651 Value *OldOp = SI.getOperand(1);
2652 assert(OldOp == OldPtr);
2653 IRBuilder<> IRB(&SI);
2654
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002655 Value *V = SI.getValueOperand();
Chandler Carruth520eeae2012-10-13 02:41:05 +00002656
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002657 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2658 // alloca that should be re-examined after promoting this alloca.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002659 if (V->getType()->isPointerTy())
2660 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002661 Pass.PostPromotionWorklist.insert(AI);
2662
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002663 uint64_t Size = EndOffset - BeginOffset;
2664 if (Size < TD.getTypeStoreSize(V->getType())) {
2665 assert(!SI.isVolatile());
2666 assert(V->getType()->isIntegerTy() &&
2667 "Only integer type loads and stores are split");
2668 assert(V->getType()->getIntegerBitWidth() ==
2669 TD.getTypeStoreSizeInBits(V->getType()) &&
2670 "Non-byte-multiple bit width");
2671 assert(V->getType()->getIntegerBitWidth() ==
2672 TD.getTypeSizeInBits(OldAI.getAllocatedType()) &&
2673 "Only alloca-wide stores can be split and recomposed");
2674 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2675 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
2676 getName(".extract"));
Chandler Carruth520eeae2012-10-13 02:41:05 +00002677 }
2678
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002679 if (VecTy)
2680 return rewriteVectorizedStoreInst(IRB, V, SI, OldOp);
2681 if (IntTy && V->getType()->isIntegerTy())
2682 return rewriteIntegerStore(IRB, V, SI);
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002683
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002684 StoreInst *NewSI;
2685 if (BeginOffset == NewAllocaBeginOffset &&
2686 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2687 V = convertValue(TD, IRB, V, NewAllocaTy);
2688 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2689 SI.isVolatile());
2690 } else {
2691 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2692 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2693 getPartitionTypeAlign(V->getType()),
2694 SI.isVolatile());
2695 }
2696 (void)NewSI;
2697 Pass.DeadInsts.insert(&SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002698 deleteIfTriviallyDead(OldOp);
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002699
2700 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2701 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth713aa942012-09-14 09:22:59 +00002702 }
2703
2704 bool visitMemSetInst(MemSetInst &II) {
2705 DEBUG(dbgs() << " original: " << II << "\n");
2706 IRBuilder<> IRB(&II);
2707 assert(II.getRawDest() == OldPtr);
2708
2709 // If the memset has a variable size, it cannot be split, just adjust the
2710 // pointer to the new alloca.
2711 if (!isa<Constant>(II.getLength())) {
2712 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002713 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf710fb12012-10-03 08:14:02 +00002714 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002715
Chandler Carruth713aa942012-09-14 09:22:59 +00002716 deleteIfTriviallyDead(OldPtr);
2717 return false;
2718 }
2719
2720 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002721 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00002722
2723 Type *AllocaTy = NewAI.getAllocatedType();
2724 Type *ScalarTy = AllocaTy->getScalarType();
2725
2726 // If this doesn't map cleanly onto the alloca type, and that type isn't
2727 // a single value type, just emit a memset.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002728 if (!VecTy && !IntTy &&
2729 (BeginOffset != NewAllocaBeginOffset ||
2730 EndOffset != NewAllocaEndOffset ||
2731 !AllocaTy->isSingleValueType() ||
2732 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002733 Type *SizeTy = II.getLength()->getType();
2734 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002735 CallInst *New
2736 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2737 II.getRawDest()->getType()),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002738 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002739 II.isVolatile());
2740 (void)New;
2741 DEBUG(dbgs() << " to: " << *New << "\n");
2742 return false;
2743 }
2744
2745 // If we can represent this as a simple value, we have to build the actual
2746 // value to store, which requires expanding the byte present in memset to
2747 // a sensible representation for the alloca type. This is essentially
2748 // splatting the byte to a sufficiently wide integer, bitcasting to the
2749 // desired scalar type, and splatting it across any desired vector type.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002750 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +00002751 Value *V = II.getValue();
2752 IntegerType *VTy = cast<IntegerType>(V->getType());
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002753 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2754 if (Size*8 > VTy->getBitWidth())
2755 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
Chandler Carruth713aa942012-09-14 09:22:59 +00002756 ConstantExpr::getUDiv(
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002757 Constant::getAllOnesValue(SplatIntTy),
Chandler Carruth713aa942012-09-14 09:22:59 +00002758 ConstantExpr::getZExt(
2759 Constant::getAllOnesValue(V->getType()),
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002760 SplatIntTy)),
Chandler Carruth713aa942012-09-14 09:22:59 +00002761 getName(".isplat"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002762
2763 // If this is an element-wide memset of a vectorizable alloca, insert it.
2764 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2765 EndOffset < NewAllocaEndOffset)) {
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002766 if (V->getType() != ScalarTy)
2767 V = convertValue(TD, IRB, V, ScalarTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002768 StoreInst *Store = IRB.CreateAlignedStore(
2769 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2770 NewAI.getAlignment(),
2771 getName(".load")),
Chandler Carruth07df7652012-11-21 08:16:30 +00002772 V, IRB.getInt32(getIndex(BeginOffset)),
Chandler Carruth713aa942012-09-14 09:22:59 +00002773 getName(".insert")),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002774 &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002775 (void)Store;
2776 DEBUG(dbgs() << " to: " << *Store << "\n");
2777 return true;
2778 }
2779
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002780 // If this is a memset on an alloca where we can widen stores, insert the
2781 // set integer.
2782 if (IntTy && (BeginOffset > NewAllocaBeginOffset ||
2783 EndOffset < NewAllocaEndOffset)) {
2784 assert(!II.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002785 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2786 getName(".oldload"));
2787 Old = convertValue(TD, IRB, Old, IntTy);
2788 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2789 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2790 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002791 }
2792
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002793 if (V->getType() != AllocaTy)
2794 V = convertValue(TD, IRB, V, AllocaTy);
2795
Chandler Carruth81b001a2012-09-26 10:27:46 +00002796 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2797 II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002798 (void)New;
2799 DEBUG(dbgs() << " to: " << *New << "\n");
2800 return !II.isVolatile();
2801 }
2802
2803 bool visitMemTransferInst(MemTransferInst &II) {
2804 // Rewriting of memory transfer instructions can be a bit tricky. We break
2805 // them into two categories: split intrinsics and unsplit intrinsics.
2806
2807 DEBUG(dbgs() << " original: " << II << "\n");
2808 IRBuilder<> IRB(&II);
2809
2810 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2811 bool IsDest = II.getRawDest() == OldPtr;
2812
2813 const AllocaPartitioning::MemTransferOffsets &MTO
2814 = P.getMemTransferOffsets(II);
2815
Chandler Carruth673850a2012-10-01 12:16:54 +00002816 // Compute the relative offset within the transfer.
Chandler Carruth426c2bf2012-11-01 09:14:31 +00002817 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth673850a2012-10-01 12:16:54 +00002818 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2819 : MTO.SourceBegin));
2820
2821 unsigned Align = II.getAlignment();
2822 if (Align > 1)
2823 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002824 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth673850a2012-10-01 12:16:54 +00002825
Chandler Carruth713aa942012-09-14 09:22:59 +00002826 // For unsplit intrinsics, we simply modify the source and destination
2827 // pointers in place. This isn't just an optimization, it is a matter of
2828 // correctness. With unsplit intrinsics we may be dealing with transfers
2829 // within a single alloca before SROA ran, or with transfers that have
2830 // a variable length. We may also be dealing with memmove instead of
2831 // memcpy, and so simply updating the pointers is the necessary for us to
2832 // update both source and dest of a single call.
2833 if (!MTO.IsSplittable) {
2834 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2835 if (IsDest)
2836 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2837 else
2838 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2839
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002840 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth673850a2012-10-01 12:16:54 +00002841 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002842
Chandler Carruth713aa942012-09-14 09:22:59 +00002843 DEBUG(dbgs() << " to: " << II << "\n");
2844 deleteIfTriviallyDead(OldOp);
2845 return false;
2846 }
2847 // For split transfer intrinsics we have an incredibly useful assurance:
2848 // the source and destination do not reside within the same alloca, and at
2849 // least one of them does not escape. This means that we can replace
2850 // memmove with memcpy, and we don't need to worry about all manner of
2851 // downsides to splitting and transforming the operations.
2852
Chandler Carruth713aa942012-09-14 09:22:59 +00002853 // If this doesn't map cleanly onto the alloca type, and that type isn't
2854 // a single value type, just emit a memcpy.
2855 bool EmitMemCpy
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002856 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2857 EndOffset != NewAllocaEndOffset ||
2858 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002859
2860 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2861 // size hasn't been shrunk based on analysis of the viable range, this is
2862 // a no-op.
2863 if (EmitMemCpy && &OldAI == &NewAI) {
2864 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2865 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2866 // Ensure the start lines up.
2867 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002868 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002869
2870 // Rewrite the size as needed.
2871 if (EndOffset != OrigEnd)
2872 II.setLength(ConstantInt::get(II.getLength()->getType(),
2873 EndOffset - BeginOffset));
2874 return false;
2875 }
2876 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002877 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00002878
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002879 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2880 EndOffset == NewAllocaEndOffset;
2881 bool IsVectorElement = VecTy && !IsWholeAlloca;
2882 uint64_t Size = EndOffset - BeginOffset;
2883 IntegerType *SubIntTy
2884 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002885
2886 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2887 : II.getRawDest()->getType();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002888 if (!EmitMemCpy) {
2889 if (IsVectorElement)
Micah Villmowb8bce922012-10-24 17:25:11 +00002890 OtherPtrTy = VecTy->getElementType()->getPointerTo();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002891 else if (IntTy && !IsWholeAlloca)
Micah Villmowb8bce922012-10-24 17:25:11 +00002892 OtherPtrTy = SubIntTy->getPointerTo();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002893 else
2894 OtherPtrTy = NewAI.getType();
2895 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002896
2897 // Compute the other pointer, folding as much as possible to produce
2898 // a single, simple GEP in most cases.
2899 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2900 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2901 getName("." + OtherPtr->getName()));
2902
2903 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2904 // alloca that should be re-examined after rewriting this instruction.
2905 if (AllocaInst *AI
2906 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruthb3dca3f2012-09-26 07:41:40 +00002907 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002908
2909 if (EmitMemCpy) {
2910 Value *OurPtr
2911 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2912 : II.getRawSource()->getType());
2913 Type *SizeTy = II.getLength()->getType();
2914 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2915
2916 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2917 IsDest ? OtherPtr : OurPtr,
Chandler Carruth81b001a2012-09-26 10:27:46 +00002918 Size, Align, II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002919 (void)New;
2920 DEBUG(dbgs() << " to: " << *New << "\n");
2921 return false;
2922 }
2923
Chandler Carruth322e9ba2012-10-03 08:26:28 +00002924 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2925 // is equivalent to 1, but that isn't true if we end up rewriting this as
2926 // a load or store.
2927 if (!Align)
2928 Align = 1;
2929
Chandler Carruth713aa942012-09-14 09:22:59 +00002930 Value *SrcPtr = OtherPtr;
2931 Value *DstPtr = &NewAI;
2932 if (!IsDest)
2933 std::swap(SrcPtr, DstPtr);
2934
2935 Value *Src;
2936 if (IsVectorElement && !IsDest) {
2937 // We have to extract rather than load.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002938 Src = IRB.CreateExtractElement(
2939 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
Chandler Carruth07df7652012-11-21 08:16:30 +00002940 IRB.getInt32(getIndex(BeginOffset)),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002941 getName(".copyextract"));
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002942 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002943 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2944 getName(".load"));
2945 Src = convertValue(TD, IRB, Src, IntTy);
2946 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2947 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2948 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002949 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002950 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2951 getName(".copyload"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002952 }
2953
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002954 if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002955 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2956 getName(".oldload"));
2957 Old = convertValue(TD, IRB, Old, IntTy);
2958 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2959 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2960 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2961 Src = convertValue(TD, IRB, Src, NewAllocaTy);
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002962 }
2963
Chandler Carruth713aa942012-09-14 09:22:59 +00002964 if (IsVectorElement && IsDest) {
2965 // We have to insert into a loaded copy before storing.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002966 Src = IRB.CreateInsertElement(
2967 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
Chandler Carruth07df7652012-11-21 08:16:30 +00002968 Src, IRB.getInt32(getIndex(BeginOffset)),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002969 getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002970 }
2971
Chandler Carruth81b001a2012-09-26 10:27:46 +00002972 StoreInst *Store = cast<StoreInst>(
2973 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2974 (void)Store;
Chandler Carruth713aa942012-09-14 09:22:59 +00002975 DEBUG(dbgs() << " to: " << *Store << "\n");
2976 return !II.isVolatile();
2977 }
2978
2979 bool visitIntrinsicInst(IntrinsicInst &II) {
2980 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2981 II.getIntrinsicID() == Intrinsic::lifetime_end);
2982 DEBUG(dbgs() << " original: " << II << "\n");
2983 IRBuilder<> IRB(&II);
2984 assert(II.getArgOperand(1) == OldPtr);
2985
2986 // Record this instruction for deletion.
Chandler Carruthf5837aa2012-11-20 01:12:50 +00002987 Pass.DeadInsts.insert(&II);
Chandler Carruth713aa942012-09-14 09:22:59 +00002988
2989 ConstantInt *Size
2990 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2991 EndOffset - BeginOffset);
2992 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2993 Value *New;
2994 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2995 New = IRB.CreateLifetimeStart(Ptr, Size);
2996 else
2997 New = IRB.CreateLifetimeEnd(Ptr, Size);
2998
2999 DEBUG(dbgs() << " to: " << *New << "\n");
3000 return true;
3001 }
3002
Chandler Carruth713aa942012-09-14 09:22:59 +00003003 bool visitPHINode(PHINode &PN) {
3004 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003005
Chandler Carruth713aa942012-09-14 09:22:59 +00003006 // We would like to compute a new pointer in only one place, but have it be
3007 // as local as possible to the PHI. To do that, we re-use the location of
3008 // the old pointer, which necessarily must be in the right position to
3009 // dominate the PHI.
3010 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
3011
Chandler Carruth713aa942012-09-14 09:22:59 +00003012 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003013 // Replace the operands which were using the old pointer.
Benjamin Kramer2a132422012-10-20 12:04:57 +00003014 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth713aa942012-09-14 09:22:59 +00003015
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003016 DEBUG(dbgs() << " to: " << PN << "\n");
3017 deleteIfTriviallyDead(OldPtr);
3018 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00003019 }
3020
3021 bool visitSelectInst(SelectInst &SI) {
3022 DEBUG(dbgs() << " original: " << SI << "\n");
3023 IRBuilder<> IRB(&SI);
3024
3025 // Find the operand we need to rewrite here.
3026 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3027 if (IsTrueVal)
3028 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3029 else
3030 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003031
Chandler Carruth713aa942012-09-14 09:22:59 +00003032 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003033 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3034 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00003035 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003036 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00003037 }
3038
3039};
3040}
3041
Chandler Carruthc370acd2012-09-18 12:57:43 +00003042namespace {
3043/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3044///
3045/// This pass aggressively rewrites all aggregate loads and stores on
3046/// a particular pointer (or any pointer derived from it which we can identify)
3047/// with scalar loads and stores.
3048class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3049 // Befriend the base class so it can delegate to private visit methods.
3050 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3051
Micah Villmow3574eca2012-10-08 16:38:25 +00003052 const DataLayout &TD;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003053
3054 /// Queue of pointer uses to analyze and potentially rewrite.
3055 SmallVector<Use *, 8> Queue;
3056
3057 /// Set to prevent us from cycling with phi nodes and loops.
3058 SmallPtrSet<User *, 8> Visited;
3059
3060 /// The current pointer use being rewritten. This is used to dig up the used
3061 /// value (as opposed to the user).
3062 Use *U;
3063
3064public:
Micah Villmow3574eca2012-10-08 16:38:25 +00003065 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003066
3067 /// Rewrite loads and stores through a pointer and all pointers derived from
3068 /// it.
3069 bool rewrite(Instruction &I) {
3070 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3071 enqueueUsers(I);
3072 bool Changed = false;
3073 while (!Queue.empty()) {
3074 U = Queue.pop_back_val();
3075 Changed |= visit(cast<Instruction>(U->getUser()));
3076 }
3077 return Changed;
3078 }
3079
3080private:
3081 /// Enqueue all the users of the given instruction for further processing.
3082 /// This uses a set to de-duplicate users.
3083 void enqueueUsers(Instruction &I) {
3084 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3085 ++UI)
3086 if (Visited.insert(*UI))
3087 Queue.push_back(&UI.getUse());
3088 }
3089
3090 // Conservative default is to not rewrite anything.
3091 bool visitInstruction(Instruction &I) { return false; }
3092
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003093 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003094 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003095 class OpSplitter {
3096 protected:
3097 /// The builder used to form new instructions.
3098 IRBuilder<> IRB;
3099 /// The indices which to be used with insert- or extractvalue to select the
3100 /// appropriate value within the aggregate.
3101 SmallVector<unsigned, 4> Indices;
3102 /// The indices to a GEP instruction which will move Ptr to the correct slot
3103 /// within the aggregate.
3104 SmallVector<Value *, 4> GEPIndices;
3105 /// The base pointer of the original op, used as a base for GEPing the
3106 /// split operations.
3107 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003108
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003109 /// Initialize the splitter with an insertion point, Ptr and start with a
3110 /// single zero GEP index.
3111 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003112 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003113
3114 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003115 /// \brief Generic recursive split emission routine.
3116 ///
3117 /// This method recursively splits an aggregate op (load or store) into
3118 /// scalar or vector ops. It splits recursively until it hits a single value
3119 /// and emits that single value operation via the template argument.
3120 ///
3121 /// The logic of this routine relies on GEPs and insertvalue and
3122 /// extractvalue all operating with the same fundamental index list, merely
3123 /// formatted differently (GEPs need actual values).
3124 ///
3125 /// \param Ty The type being split recursively into smaller ops.
3126 /// \param Agg The aggregate value being built up or stored, depending on
3127 /// whether this is splitting a load or a store respectively.
3128 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3129 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003130 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003131
3132 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3133 unsigned OldSize = Indices.size();
3134 (void)OldSize;
3135 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3136 ++Idx) {
3137 assert(Indices.size() == OldSize && "Did not return to the old size");
3138 Indices.push_back(Idx);
3139 GEPIndices.push_back(IRB.getInt32(Idx));
3140 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3141 GEPIndices.pop_back();
3142 Indices.pop_back();
3143 }
3144 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003145 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00003146
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003147 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3148 unsigned OldSize = Indices.size();
3149 (void)OldSize;
3150 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3151 ++Idx) {
3152 assert(Indices.size() == OldSize && "Did not return to the old size");
3153 Indices.push_back(Idx);
3154 GEPIndices.push_back(IRB.getInt32(Idx));
3155 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3156 GEPIndices.pop_back();
3157 Indices.pop_back();
3158 }
3159 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003160 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003161
3162 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003163 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003164 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003165
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003166 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003167 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003168 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003169
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003170 /// Emit a leaf load of a single value. This is called at the leaves of the
3171 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003172 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003173 assert(Ty->isSingleValueType());
3174 // Load the single value and insert it using the indices.
3175 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3176 Name + ".gep"),
3177 Name + ".load");
3178 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3179 DEBUG(dbgs() << " to: " << *Load << "\n");
3180 }
3181 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003182
3183 bool visitLoadInst(LoadInst &LI) {
3184 assert(LI.getPointerOperand() == *U);
3185 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3186 return false;
3187
3188 // We have an aggregate being loaded, split it apart.
3189 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003190 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00003191 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003192 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003193 LI.replaceAllUsesWith(V);
3194 LI.eraseFromParent();
3195 return true;
3196 }
3197
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003198 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003199 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003200 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003201
3202 /// Emit a leaf store of a single value. This is called at the leaves of the
3203 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003204 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003205 assert(Ty->isSingleValueType());
3206 // Extract the single value and store it using the indices.
3207 Value *Store = IRB.CreateStore(
3208 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3209 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3210 (void)Store;
3211 DEBUG(dbgs() << " to: " << *Store << "\n");
3212 }
3213 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003214
3215 bool visitStoreInst(StoreInst &SI) {
3216 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3217 return false;
3218 Value *V = SI.getValueOperand();
3219 if (V->getType()->isSingleValueType())
3220 return false;
3221
3222 // We have an aggregate being stored, split it apart.
3223 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003224 StoreOpSplitter Splitter(&SI, *U);
3225 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003226 SI.eraseFromParent();
3227 return true;
3228 }
3229
3230 bool visitBitCastInst(BitCastInst &BC) {
3231 enqueueUsers(BC);
3232 return false;
3233 }
3234
3235 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3236 enqueueUsers(GEPI);
3237 return false;
3238 }
3239
3240 bool visitPHINode(PHINode &PN) {
3241 enqueueUsers(PN);
3242 return false;
3243 }
3244
3245 bool visitSelectInst(SelectInst &SI) {
3246 enqueueUsers(SI);
3247 return false;
3248 }
3249};
3250}
3251
Chandler Carruth07525a62012-10-13 10:49:33 +00003252/// \brief Strip aggregate type wrapping.
3253///
3254/// This removes no-op aggregate types wrapping an underlying type. It will
3255/// strip as many layers of types as it can without changing either the type
3256/// size or the allocated size.
3257static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3258 if (Ty->isSingleValueType())
3259 return Ty;
3260
3261 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3262 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3263
3264 Type *InnerTy;
3265 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3266 InnerTy = ArrTy->getElementType();
3267 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3268 const StructLayout *SL = DL.getStructLayout(STy);
3269 unsigned Index = SL->getElementContainingOffset(0);
3270 InnerTy = STy->getElementType(Index);
3271 } else {
3272 return Ty;
3273 }
3274
3275 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3276 TypeSize > DL.getTypeSizeInBits(InnerTy))
3277 return Ty;
3278
3279 return stripAggregateTypeWrapping(DL, InnerTy);
3280}
3281
Chandler Carruth713aa942012-09-14 09:22:59 +00003282/// \brief Try to find a partition of the aggregate type passed in for a given
3283/// offset and size.
3284///
3285/// This recurses through the aggregate type and tries to compute a subtype
3286/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00003287/// of an array, it will even compute a new array type for that sub-section,
3288/// and the same for structs.
3289///
3290/// Note that this routine is very strict and tries to find a partition of the
3291/// type which produces the *exact* right offset and size. It is not forgiving
3292/// when the size or offset cause either end of type-based partition to be off.
3293/// Also, this is a best-effort routine. It is reasonable to give up and not
3294/// return a type if necessary.
Micah Villmow3574eca2012-10-08 16:38:25 +00003295static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth713aa942012-09-14 09:22:59 +00003296 uint64_t Offset, uint64_t Size) {
3297 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruth07525a62012-10-13 10:49:33 +00003298 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carrutha2b88162012-10-25 04:37:07 +00003299 if (Offset > TD.getTypeAllocSize(Ty) ||
3300 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3301 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003302
3303 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3304 // We can't partition pointers...
3305 if (SeqTy->isPointerTy())
3306 return 0;
3307
3308 Type *ElementTy = SeqTy->getElementType();
3309 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3310 uint64_t NumSkippedElements = Offset / ElementSize;
3311 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3312 if (NumSkippedElements >= ArrTy->getNumElements())
3313 return 0;
3314 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3315 if (NumSkippedElements >= VecTy->getNumElements())
3316 return 0;
3317 Offset -= NumSkippedElements * ElementSize;
3318
3319 // First check if we need to recurse.
3320 if (Offset > 0 || Size < ElementSize) {
3321 // Bail if the partition ends in a different array element.
3322 if ((Offset + Size) > ElementSize)
3323 return 0;
3324 // Recurse through the element type trying to peel off offset bytes.
3325 return getTypePartition(TD, ElementTy, Offset, Size);
3326 }
3327 assert(Offset == 0);
3328
3329 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003330 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003331 assert(Size > ElementSize);
3332 uint64_t NumElements = Size / ElementSize;
3333 if (NumElements * ElementSize != Size)
3334 return 0;
3335 return ArrayType::get(ElementTy, NumElements);
3336 }
3337
3338 StructType *STy = dyn_cast<StructType>(Ty);
3339 if (!STy)
3340 return 0;
3341
3342 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003343 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00003344 return 0;
3345 uint64_t EndOffset = Offset + Size;
3346 if (EndOffset > SL->getSizeInBytes())
3347 return 0;
3348
3349 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00003350 Offset -= SL->getElementOffset(Index);
3351
3352 Type *ElementTy = STy->getElementType(Index);
3353 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3354 if (Offset >= ElementSize)
3355 return 0; // The offset points into alignment padding.
3356
3357 // See if any partition must be contained by the element.
3358 if (Offset > 0 || Size < ElementSize) {
3359 if ((Offset + Size) > ElementSize)
3360 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003361 return getTypePartition(TD, ElementTy, Offset, Size);
3362 }
3363 assert(Offset == 0);
3364
3365 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003366 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003367
3368 StructType::element_iterator EI = STy->element_begin() + Index,
3369 EE = STy->element_end();
3370 if (EndOffset < SL->getSizeInBytes()) {
3371 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3372 if (Index == EndIndex)
3373 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00003374
3375 // Don't try to form "natural" types if the elements don't line up with the
3376 // expected size.
3377 // FIXME: We could potentially recurse down through the last element in the
3378 // sub-struct to find a natural end point.
3379 if (SL->getElementOffset(EndIndex) != EndOffset)
3380 return 0;
3381
Chandler Carruth713aa942012-09-14 09:22:59 +00003382 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00003383 EE = STy->element_begin() + EndIndex;
3384 }
3385
3386 // Try to build up a sub-structure.
Benjamin Kramer2a132422012-10-20 12:04:57 +00003387 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth713aa942012-09-14 09:22:59 +00003388 STy->isPacked());
3389 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003390 if (Size != SubSL->getSizeInBytes())
3391 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00003392
Chandler Carruth6b547a22012-09-14 11:08:31 +00003393 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00003394}
3395
3396/// \brief Rewrite an alloca partition's users.
3397///
3398/// This routine drives both of the rewriting goals of the SROA pass. It tries
3399/// to rewrite uses of an alloca partition to be conducive for SSA value
3400/// promotion. If the partition needs a new, more refined alloca, this will
3401/// build that new alloca, preserving as much type information as possible, and
3402/// rewrite the uses of the old alloca to point at the new one and have the
3403/// appropriate new offsets. It also evaluates how successful the rewrite was
3404/// at enabling promotion and if it was successful queues the alloca to be
3405/// promoted.
3406bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3407 AllocaPartitioning &P,
3408 AllocaPartitioning::iterator PI) {
3409 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruthfdb15852012-10-02 18:57:13 +00003410 bool IsLive = false;
3411 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3412 UE = P.use_end(PI);
3413 UI != UE && !IsLive; ++UI)
3414 if (UI->U)
3415 IsLive = true;
3416 if (!IsLive)
Chandler Carruth713aa942012-09-14 09:22:59 +00003417 return false; // No live uses left of this partition.
3418
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003419 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3420 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3421
3422 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3423 DEBUG(dbgs() << " speculating ");
3424 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carrutha346f462012-10-02 17:49:47 +00003425 Speculator.visitUsers(PI);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003426
Chandler Carruth713aa942012-09-14 09:22:59 +00003427 // Try to compute a friendly type for this partition of the alloca. This
3428 // won't always succeed, in which case we fall back to a legal integer type
3429 // or an i8 array of an appropriate size.
3430 Type *AllocaTy = 0;
3431 if (Type *PartitionTy = P.getCommonType(PI))
3432 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3433 AllocaTy = PartitionTy;
3434 if (!AllocaTy)
3435 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3436 PI->BeginOffset, AllocaSize))
3437 AllocaTy = PartitionTy;
3438 if ((!AllocaTy ||
3439 (AllocaTy->isArrayTy() &&
3440 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3441 TD->isLegalInteger(AllocaSize * 8))
3442 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3443 if (!AllocaTy)
3444 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00003445 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00003446
3447 // Check for the case where we're going to rewrite to a new alloca of the
3448 // exact same type as the original, and with the same access offsets. In that
3449 // case, re-use the existing alloca, but still run through the rewriter to
3450 // performe phi and select speculation.
3451 AllocaInst *NewAI;
3452 if (AllocaTy == AI.getAllocatedType()) {
3453 assert(PI->BeginOffset == 0 &&
3454 "Non-zero begin offset but same alloca type");
3455 assert(PI == P.begin() && "Begin offset is zero on later partition");
3456 NewAI = &AI;
3457 } else {
Chandler Carruthb67c9a52012-09-29 10:41:21 +00003458 unsigned Alignment = AI.getAlignment();
3459 if (!Alignment) {
3460 // The minimum alignment which users can rely on when the explicit
3461 // alignment is omitted or zero is that required by the ABI for this
3462 // type.
3463 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3464 }
3465 Alignment = MinAlign(Alignment, PI->BeginOffset);
3466 // If we will get at least this much alignment from the type alone, leave
3467 // the alloca's alignment unconstrained.
3468 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3469 Alignment = 0;
3470 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth713aa942012-09-14 09:22:59 +00003471 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3472 &AI);
3473 ++NumNewAllocas;
3474 }
3475
3476 DEBUG(dbgs() << "Rewriting alloca partition "
3477 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3478 << *NewAI << "\n");
3479
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003480 // Track the high watermark of the post-promotion worklist. We will reset it
3481 // to this point if the alloca is not in fact scheduled for promotion.
3482 unsigned PPWOldSize = PostPromotionWorklist.size();
3483
Chandler Carruth713aa942012-09-14 09:22:59 +00003484 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3485 PI->BeginOffset, PI->EndOffset);
3486 DEBUG(dbgs() << " rewriting ");
3487 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003488 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3489 if (Promotable) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003490 DEBUG(dbgs() << " and queuing for promotion\n");
3491 PromotableAllocas.push_back(NewAI);
3492 } else if (NewAI != &AI) {
3493 // If we can't promote the alloca, iterate on it to check for new
3494 // refinements exposed by splitting the current alloca. Don't iterate on an
3495 // alloca which didn't actually change and didn't get promoted.
3496 Worklist.insert(NewAI);
3497 }
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003498
3499 // Drop any post-promotion work items if promotion didn't happen.
3500 if (!Promotable)
3501 while (PostPromotionWorklist.size() > PPWOldSize)
3502 PostPromotionWorklist.pop_back();
3503
Chandler Carruth713aa942012-09-14 09:22:59 +00003504 return true;
3505}
3506
3507/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3508bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3509 bool Changed = false;
3510 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3511 ++PI)
3512 Changed |= rewriteAllocaPartition(AI, P, PI);
3513
3514 return Changed;
3515}
3516
3517/// \brief Analyze an alloca for SROA.
3518///
3519/// This analyzes the alloca to ensure we can reason about it, builds
3520/// a partitioning of the alloca, and then hands it off to be split and
3521/// rewritten as needed.
3522bool SROA::runOnAlloca(AllocaInst &AI) {
3523 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3524 ++NumAllocasAnalyzed;
3525
3526 // Special case dead allocas, as they're trivial.
3527 if (AI.use_empty()) {
3528 AI.eraseFromParent();
3529 return true;
3530 }
3531
3532 // Skip alloca forms that this analysis can't handle.
3533 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3534 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3535 return false;
3536
Chandler Carruthc370acd2012-09-18 12:57:43 +00003537 bool Changed = false;
3538
3539 // First, split any FCA loads and stores touching this alloca to promote
3540 // better splitting and promotion opportunities.
3541 AggLoadStoreRewriter AggRewriter(*TD);
3542 Changed |= AggRewriter.rewrite(AI);
3543
Chandler Carruth713aa942012-09-14 09:22:59 +00003544 // Build the partition set using a recursive instruction-visiting builder.
3545 AllocaPartitioning P(*TD, AI);
3546 DEBUG(P.print(dbgs()));
3547 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003548 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003549
Chandler Carruth713aa942012-09-14 09:22:59 +00003550 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003551 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3552 DE = P.dead_user_end();
3553 DI != DE; ++DI) {
3554 Changed = true;
3555 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003556 DeadInsts.insert(*DI);
Chandler Carruth713aa942012-09-14 09:22:59 +00003557 }
3558 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3559 DE = P.dead_op_end();
3560 DO != DE; ++DO) {
3561 Value *OldV = **DO;
3562 // Clobber the use with an undef value.
3563 **DO = UndefValue::get(OldV->getType());
3564 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3565 if (isInstructionTriviallyDead(OldI)) {
3566 Changed = true;
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003567 DeadInsts.insert(OldI);
Chandler Carruth713aa942012-09-14 09:22:59 +00003568 }
3569 }
3570
Chandler Carruthfca3f402012-10-05 01:29:09 +00003571 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3572 if (P.begin() == P.end())
3573 return Changed;
3574
Chandler Carruth713aa942012-09-14 09:22:59 +00003575 return splitAlloca(AI, P) || Changed;
3576}
3577
Chandler Carruth8615cd22012-09-14 10:26:38 +00003578/// \brief Delete the dead instructions accumulated in this run.
3579///
3580/// Recursively deletes the dead instructions we've accumulated. This is done
3581/// at the very end to maximize locality of the recursive delete and to
3582/// minimize the problems of invalidated instruction pointers as such pointers
3583/// are used heavily in the intermediate stages of the algorithm.
3584///
3585/// We also record the alloca instructions deleted here so that they aren't
3586/// subsequently handed to mem2reg to promote.
3587void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003588 while (!DeadInsts.empty()) {
3589 Instruction *I = DeadInsts.pop_back_val();
3590 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3591
Chandler Carrutha2b88162012-10-25 04:37:07 +00003592 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3593
Chandler Carruth713aa942012-09-14 09:22:59 +00003594 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3595 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3596 // Zero out the operand and see if it becomes trivially dead.
3597 *OI = 0;
3598 if (isInstructionTriviallyDead(U))
Chandler Carruthf5837aa2012-11-20 01:12:50 +00003599 DeadInsts.insert(U);
Chandler Carruth713aa942012-09-14 09:22:59 +00003600 }
3601
3602 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3603 DeletedAllocas.insert(AI);
3604
3605 ++NumDeleted;
3606 I->eraseFromParent();
3607 }
3608}
3609
Chandler Carruth1c8db502012-09-15 11:43:14 +00003610/// \brief Promote the allocas, using the best available technique.
3611///
3612/// This attempts to promote whatever allocas have been identified as viable in
3613/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3614/// If there is a domtree available, we attempt to promote using the full power
3615/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3616/// based on the SSAUpdater utilities. This function returns whether any
3617/// promotion occured.
3618bool SROA::promoteAllocas(Function &F) {
3619 if (PromotableAllocas.empty())
3620 return false;
3621
3622 NumPromoted += PromotableAllocas.size();
3623
3624 if (DT && !ForceSSAUpdater) {
3625 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3626 PromoteMemToReg(PromotableAllocas, *DT);
3627 PromotableAllocas.clear();
3628 return true;
3629 }
3630
3631 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3632 SSAUpdater SSA;
3633 DIBuilder DIB(*F.getParent());
3634 SmallVector<Instruction*, 64> Insts;
3635
3636 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3637 AllocaInst *AI = PromotableAllocas[Idx];
3638 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3639 UI != UE;) {
3640 Instruction *I = cast<Instruction>(*UI++);
3641 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3642 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3643 // leading to them) here. Eventually it should use them to optimize the
3644 // scalar values produced.
3645 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3646 assert(onlyUsedByLifetimeMarkers(I) &&
3647 "Found a bitcast used outside of a lifetime marker.");
3648 while (!I->use_empty())
3649 cast<Instruction>(*I->use_begin())->eraseFromParent();
3650 I->eraseFromParent();
3651 continue;
3652 }
3653 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3654 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3655 II->getIntrinsicID() == Intrinsic::lifetime_end);
3656 II->eraseFromParent();
3657 continue;
3658 }
3659
3660 Insts.push_back(I);
3661 }
3662 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3663 Insts.clear();
3664 }
3665
3666 PromotableAllocas.clear();
3667 return true;
3668}
3669
Chandler Carruth713aa942012-09-14 09:22:59 +00003670namespace {
3671 /// \brief A predicate to test whether an alloca belongs to a set.
3672 class IsAllocaInSet {
3673 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3674 const SetType &Set;
3675
3676 public:
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003677 typedef AllocaInst *argument_type;
3678
Chandler Carruth713aa942012-09-14 09:22:59 +00003679 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003680 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth713aa942012-09-14 09:22:59 +00003681 };
3682}
3683
3684bool SROA::runOnFunction(Function &F) {
3685 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3686 C = &F.getContext();
Micah Villmow3574eca2012-10-08 16:38:25 +00003687 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003688 if (!TD) {
3689 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3690 return false;
3691 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003692 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003693
3694 BasicBlock &EntryBB = F.getEntryBlock();
3695 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3696 I != E; ++I)
3697 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3698 Worklist.insert(AI);
3699
3700 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003701 // A set of deleted alloca instruction pointers which should be removed from
3702 // the list of promotable allocas.
3703 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3704
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003705 do {
3706 while (!Worklist.empty()) {
3707 Changed |= runOnAlloca(*Worklist.pop_back_val());
3708 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth5c5b3cf2012-10-02 22:46:45 +00003709
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003710 // Remove the deleted allocas from various lists so that we don't try to
3711 // continue processing them.
3712 if (!DeletedAllocas.empty()) {
3713 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3714 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3715 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3716 PromotableAllocas.end(),
3717 IsAllocaInSet(DeletedAllocas)),
3718 PromotableAllocas.end());
3719 DeletedAllocas.clear();
3720 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003721 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003722
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003723 Changed |= promoteAllocas(F);
3724
3725 Worklist = PostPromotionWorklist;
3726 PostPromotionWorklist.clear();
3727 } while (!Worklist.empty());
Chandler Carruth713aa942012-09-14 09:22:59 +00003728
3729 return Changed;
3730}
3731
3732void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003733 if (RequiresDomTree)
3734 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003735 AU.setPreservesCFG();
3736}