blob: 929f1b5c07a8897880ff70bb3a0d8867552712b3 [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"
28#include "llvm/Constants.h"
29#include "llvm/DIBuilder.h"
30#include "llvm/DebugInfo.h"
31#include "llvm/DerivedTypes.h"
32#include "llvm/Function.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000033#include "llvm/IRBuilder.h"
34#include "llvm/Instructions.h"
35#include "llvm/IntrinsicInst.h"
36#include "llvm/LLVMContext.h"
37#include "llvm/Module.h"
38#include "llvm/Operator.h"
39#include "llvm/Pass.h"
40#include "llvm/ADT/SetVector.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000044#include "llvm/Analysis/Dominators.h"
45#include "llvm/Analysis/Loads.h"
46#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1c8db502012-09-15 11:43:14 +000047#include "llvm/Support/CommandLine.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000048#include "llvm/Support/Debug.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000054#include "llvm/DataLayout.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
Benjamin Kramerd0807692012-09-14 13:08:09 +0000337#ifndef NDEBUG
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;
Micah Villmow2c39b152012-10-15 16:24:29 +0000447 unsigned int AS = GEPI.getPointerAddressSpace();
Chandler Carruth713aa942012-09-14 09:22:59 +0000448 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
449 GTI != GTE; ++GTI) {
450 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
451 if (!OpC)
452 return false;
453 if (OpC->isZero())
454 continue;
455
456 // Handle a struct index, which adds its field offset to the pointer.
457 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
458 unsigned ElementIdx = OpC->getZExtValue();
459 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth02e92a02012-09-23 11:43:14 +0000460 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
461 // Check that we can continue to model this GEP in a signed 64-bit offset.
462 if (ElementOffset > INT64_MAX ||
463 (GEPOffset >= 0 &&
464 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
465 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
466 << "what can be represented in an int64_t!\n"
467 << " alloca: " << P.AI << "\n");
468 return false;
469 }
470 if (GEPOffset < 0)
471 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
472 else
473 GEPOffset += ElementOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000474 continue;
475 }
476
Micah Villmow2c39b152012-10-15 16:24:29 +0000477 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits(AS));
Chandler Carruth02e92a02012-09-23 11:43:14 +0000478 Index *= APInt(Index.getBitWidth(),
479 TD.getTypeAllocSize(GTI.getIndexedType()));
480 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
481 /*isSigned*/true);
482 // Check if the result can be stored in our int64_t offset.
483 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
484 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
485 << "what can be represented in an int64_t!\n"
486 << " alloca: " << P.AI << "\n");
487 return false;
488 }
489
490 GEPOffset = Index.getSExtValue();
Chandler Carruth713aa942012-09-14 09:22:59 +0000491 }
492 return true;
493 }
494
495 Value *foldSelectInst(SelectInst &SI) {
496 // If the condition being selected on is a constant or the same value is
497 // being selected between, fold the select. Yes this does (rarely) happen
498 // early on.
499 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
500 return SI.getOperand(1+CI->isZero());
501 if (SI.getOperand(1) == SI.getOperand(2)) {
502 assert(*U == SI.getOperand(1));
503 return SI.getOperand(1);
504 }
505 return 0;
506 }
507};
508
509/// \brief Builder for the alloca partitioning.
510///
511/// This class builds an alloca partitioning by recursively visiting the uses
512/// of an alloca and splitting the partitions for each load and store at each
513/// offset.
514class AllocaPartitioning::PartitionBuilder
515 : public BuilderBase<PartitionBuilder, bool> {
516 friend class InstVisitor<PartitionBuilder, bool>;
517
518 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
519
520public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000521 PartitionBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000522 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000523
524 /// \brief Run the builder over the allocation.
525 bool operator()() {
526 // Note that we have to re-evaluate size on each trip through the loop as
527 // the queue grows at the tail.
528 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
529 U = Queue[Idx].U;
530 Offset = Queue[Idx].Offset;
531 if (!visit(cast<Instruction>(U->getUser())))
532 return false;
533 }
534 return true;
535 }
536
537private:
538 bool markAsEscaping(Instruction &I) {
539 P.PointerEscapingInstr = &I;
540 return false;
541 }
542
Chandler Carruth02e92a02012-09-23 11:43:14 +0000543 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000544 bool IsSplittable = false) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000545 // Completely skip uses which have a zero size or don't overlap the
546 // allocation.
547 if (Size == 0 ||
548 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000549 (Offset < 0 && (uint64_t)-Offset >= Size)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000550 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
551 << " which starts past the end of the " << AllocSize
552 << " byte alloca:\n"
553 << " alloca: " << P.AI << "\n"
554 << " use: " << I << "\n");
555 return;
556 }
557
Chandler Carruth02e92a02012-09-23 11:43:14 +0000558 // Clamp the start to the beginning of the allocation.
559 if (Offset < 0) {
560 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
561 << " to start at the beginning of the alloca:\n"
562 << " alloca: " << P.AI << "\n"
563 << " use: " << I << "\n");
564 Size -= (uint64_t)-Offset;
565 Offset = 0;
566 }
567
568 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
569
570 // Clamp the end offset to the end of the allocation. Note that this is
571 // formulated to handle even the case where "BeginOffset + Size" overflows.
572 assert(AllocSize >= BeginOffset); // Established above.
573 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000574 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
575 << " to remain within the " << AllocSize << " byte alloca:\n"
576 << " alloca: " << P.AI << "\n"
577 << " use: " << I << "\n");
578 EndOffset = AllocSize;
579 }
580
Chandler Carruth713aa942012-09-14 09:22:59 +0000581 Partition New(BeginOffset, EndOffset, IsSplittable);
582 P.Partitions.push_back(New);
583 }
584
Chandler Carruth02e92a02012-09-23 11:43:14 +0000585 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000586 uint64_t Size = TD.getTypeStoreSize(Ty);
587
588 // If this memory access can be shown to *statically* extend outside the
589 // bounds of of the allocation, it's behavior is undefined, so simply
590 // ignore it. Note that this is more strict than the generic clamping
591 // behavior of insertUse. We also try to handle cases which might run the
592 // risk of overflow.
593 // FIXME: We should instead consider the pointer to have escaped if this
594 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000595 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
596 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000597 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
598 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
599 << " which extends past the end of the " << AllocSize
600 << " byte alloca:\n"
601 << " alloca: " << P.AI << "\n"
602 << " use: " << I << "\n");
603 return true;
604 }
605
Chandler Carruth63392ea2012-09-16 19:39:50 +0000606 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000607 return true;
608 }
609
610 bool visitBitCastInst(BitCastInst &BC) {
611 enqueueUsers(BC, Offset);
612 return true;
613 }
614
615 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000616 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000617 if (!computeConstantGEPOffset(GEPI, GEPOffset))
618 return markAsEscaping(GEPI);
619
620 enqueueUsers(GEPI, GEPOffset);
621 return true;
622 }
623
624 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000625 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
626 "All simple FCA loads should have been pre-split");
Chandler Carruth63392ea2012-09-16 19:39:50 +0000627 return handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000628 }
629
630 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000631 Value *ValOp = SI.getValueOperand();
632 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000633 return markAsEscaping(SI);
634
Chandler Carruthc370acd2012-09-18 12:57:43 +0000635 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
636 "All simple FCA stores should have been pre-split");
637 return handleLoadOrStore(ValOp->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000638 }
639
640
641 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000642 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000643 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000644 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
645 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000646 return true;
647 }
648
649 bool visitMemTransferInst(MemTransferInst &II) {
650 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
651 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
652 if (!Size)
653 // Zero-length mem transfer intrinsics can be ignored entirely.
654 return true;
655
656 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
657
658 // Only intrinsics with a constant length can be split.
659 Offsets.IsSplittable = Length;
660
Chandler Carruthfca3f402012-10-05 01:29:09 +0000661 if (*U == II.getRawDest()) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000662 Offsets.DestBegin = Offset;
663 Offsets.DestEnd = Offset + Size;
664 }
Chandler Carruthfca3f402012-10-05 01:29:09 +0000665 if (*U == II.getRawSource()) {
666 Offsets.SourceBegin = Offset;
667 Offsets.SourceEnd = Offset + Size;
668 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000669
Chandler Carruthfca3f402012-10-05 01:29:09 +0000670 // If we have set up end offsets for both the source and the destination,
671 // we have found both sides of this transfer pointing at the same alloca.
672 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
673 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
674 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth713aa942012-09-14 09:22:59 +0000675
Chandler Carruthfca3f402012-10-05 01:29:09 +0000676 // Check if the begin offsets match and this is a non-volatile transfer.
677 // In that case, we can completely elide the transfer.
678 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
679 P.Partitions[PrevIdx].kill();
680 return true;
681 }
682
683 // Otherwise we have an offset transfer within the same alloca. We can't
684 // split those.
685 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
686 } else if (SeenBothEnds) {
687 // Handle the case where this exact use provides both ends of the
688 // operation.
689 assert(II.getRawDest() == II.getRawSource());
690
691 // For non-volatile transfers this is a no-op.
692 if (!II.isVolatile())
693 return true;
694
695 // Otherwise just suppress splitting.
Chandler Carruth713aa942012-09-14 09:22:59 +0000696 Offsets.IsSplittable = false;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000697 }
698
699
700 // Insert the use now that we've fixed up the splittable nature.
701 insertUse(II, Offset, Size, Offsets.IsSplittable);
702
703 // Setup the mapping from intrinsic to partition of we've not seen both
704 // ends of this transfer.
705 if (!SeenBothEnds) {
706 unsigned NewIdx = P.Partitions.size() - 1;
707 bool Inserted
708 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
709 assert(Inserted &&
710 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi0559d312012-10-05 13:56:23 +0000711 (void)Inserted;
Chandler Carruth713aa942012-09-14 09:22:59 +0000712 }
713
714 return true;
715 }
716
717 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000718 // FIXME: What about debug instrinsics? This matches old behavior, but
719 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000720 bool visitIntrinsicInst(IntrinsicInst &II) {
721 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
722 II.getIntrinsicID() == Intrinsic::lifetime_end) {
723 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
724 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000725 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000726 return true;
727 }
728
729 return markAsEscaping(II);
730 }
731
732 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
733 // We consider any PHI or select that results in a direct load or store of
734 // the same offset to be a viable use for partitioning purposes. These uses
735 // are considered unsplittable and the size is the maximum loaded or stored
736 // size.
737 SmallPtrSet<Instruction *, 4> Visited;
738 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
739 Visited.insert(Root);
740 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000741 // If there are no loads or stores, the access is dead. We mark that as
742 // a size zero access.
743 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000744 do {
745 Instruction *I, *UsedI;
746 llvm::tie(UsedI, I) = Uses.pop_back_val();
747
748 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
749 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
750 continue;
751 }
752 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
753 Value *Op = SI->getOperand(0);
754 if (Op == UsedI)
755 return SI;
756 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
757 continue;
758 }
759
760 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
761 if (!GEP->hasAllZeroIndices())
762 return GEP;
763 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
764 !isa<SelectInst>(I)) {
765 return I;
766 }
767
768 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
769 ++UI)
770 if (Visited.insert(cast<Instruction>(*UI)))
771 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
772 } while (!Uses.empty());
773
774 return 0;
775 }
776
777 bool visitPHINode(PHINode &PN) {
778 // See if we already have computed info on this node.
779 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
780 if (PHIInfo.first) {
781 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000782 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000783 return true;
784 }
785
786 // Check for an unsafe use of the PHI node.
787 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
788 return markAsEscaping(*EscapingI);
789
Chandler Carruth63392ea2012-09-16 19:39:50 +0000790 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000791 return true;
792 }
793
794 bool visitSelectInst(SelectInst &SI) {
795 if (Value *Result = foldSelectInst(SI)) {
796 if (Result == *U)
797 // If the result of the constant fold will be the pointer, recurse
798 // through the select as if we had RAUW'ed it.
799 enqueueUsers(SI, Offset);
800
801 return true;
802 }
803
804 // See if we already have computed info on this node.
805 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
806 if (SelectInfo.first) {
807 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000808 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000809 return true;
810 }
811
812 // Check for an unsafe use of the PHI node.
813 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
814 return markAsEscaping(*EscapingI);
815
Chandler Carruth63392ea2012-09-16 19:39:50 +0000816 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000817 return true;
818 }
819
820 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
821 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
822};
823
824
825/// \brief Use adder for the alloca partitioning.
826///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000827/// This class adds the uses of an alloca to all of the partitions which they
828/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000829/// walk of the partitions, but the number of steps remains bounded by the
830/// total result instruction size:
831/// - The number of partitions is a result of the number unsplittable
832/// instructions using the alloca.
833/// - The number of users of each partition is at worst the total number of
834/// splittable instructions using the alloca.
835/// Thus we will produce N * M instructions in the end, where N are the number
836/// of unsplittable uses and M are the number of splittable. This visitor does
837/// the exact same number of updates to the partitioning.
838///
839/// In the more common case, this visitor will leverage the fact that the
840/// partition space is pre-sorted, and do a logarithmic search for the
841/// partition needed, making the total visit a classical ((N + M) * log(N))
842/// complexity operation.
843class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
844 friend class InstVisitor<UseBuilder>;
845
846 /// \brief Set to de-duplicate dead instructions found in the use walk.
847 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
848
849public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000850 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000851 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000852
853 /// \brief Run the builder over the allocation.
854 void operator()() {
855 // Note that we have to re-evaluate size on each trip through the loop as
856 // the queue grows at the tail.
857 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
858 U = Queue[Idx].U;
859 Offset = Queue[Idx].Offset;
860 this->visit(cast<Instruction>(U->getUser()));
861 }
862 }
863
864private:
865 void markAsDead(Instruction &I) {
866 if (VisitedDeadInsts.insert(&I))
867 P.DeadUsers.push_back(&I);
868 }
869
Chandler Carruth02e92a02012-09-23 11:43:14 +0000870 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000871 // If the use has a zero size or extends outside of the allocation, record
872 // it as a dead use for elimination later.
873 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000874 (Offset < 0 && (uint64_t)-Offset >= Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000875 return markAsDead(User);
876
Chandler Carruth02e92a02012-09-23 11:43:14 +0000877 // Clamp the start to the beginning of the allocation.
878 if (Offset < 0) {
879 Size -= (uint64_t)-Offset;
880 Offset = 0;
881 }
882
883 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
884
885 // Clamp the end offset to the end of the allocation. Note that this is
886 // formulated to handle even the case where "BeginOffset + Size" overflows.
887 assert(AllocSize >= BeginOffset); // Established above.
888 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000889 EndOffset = AllocSize;
890
891 // NB: This only works if we have zero overlapping partitions.
892 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
893 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
894 B = llvm::prior(B);
895 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
896 ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000897 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
898 std::min(I->EndOffset, EndOffset), U);
899 P.use_push_back(I, NewPU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000900 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth77c12702012-10-01 01:49:22 +0000901 P.PHIOrSelectOpMap[U]
Chandler Carruth713aa942012-09-14 09:22:59 +0000902 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
903 }
904 }
905
Chandler Carruth02e92a02012-09-23 11:43:14 +0000906 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000907 uint64_t Size = TD.getTypeStoreSize(Ty);
908
909 // If this memory access can be shown to *statically* extend outside the
910 // bounds of of the allocation, it's behavior is undefined, so simply
911 // ignore it. Note that this is more strict than the generic clamping
912 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000913 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
914 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000915 return markAsDead(I);
916
Chandler Carruth63392ea2012-09-16 19:39:50 +0000917 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000918 }
919
920 void visitBitCastInst(BitCastInst &BC) {
921 if (BC.use_empty())
922 return markAsDead(BC);
923
924 enqueueUsers(BC, Offset);
925 }
926
927 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
928 if (GEPI.use_empty())
929 return markAsDead(GEPI);
930
Chandler Carruth02e92a02012-09-23 11:43:14 +0000931 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000932 if (!computeConstantGEPOffset(GEPI, GEPOffset))
933 llvm_unreachable("Unable to compute constant offset for use");
934
935 enqueueUsers(GEPI, GEPOffset);
936 }
937
938 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000939 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000940 }
941
942 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000943 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000944 }
945
946 void visitMemSetInst(MemSetInst &II) {
947 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000948 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
949 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000950 }
951
952 void visitMemTransferInst(MemTransferInst &II) {
953 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000954 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000955 if (!Size)
956 return markAsDead(II);
957
958 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
959 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
960 Offsets.DestBegin == Offsets.SourceBegin)
961 return markAsDead(II); // Skip identity transfers without side-effects.
962
Chandler Carruth63392ea2012-09-16 19:39:50 +0000963 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000964 }
965
966 void visitIntrinsicInst(IntrinsicInst &II) {
967 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
968 II.getIntrinsicID() == Intrinsic::lifetime_end);
969
970 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000971 insertUse(II, Offset,
972 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000973 }
974
Chandler Carruth63392ea2012-09-16 19:39:50 +0000975 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000976 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
977
978 // For PHI and select operands outside the alloca, we can't nuke the entire
979 // phi or select -- the other side might still be relevant, so we special
980 // case them here and use a separate structure to track the operands
981 // themselves which should be replaced with undef.
982 if (Offset >= AllocSize) {
983 P.DeadOperands.push_back(U);
984 return;
985 }
986
Chandler Carruth63392ea2012-09-16 19:39:50 +0000987 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000988 }
989 void visitPHINode(PHINode &PN) {
990 if (PN.use_empty())
991 return markAsDead(PN);
992
Chandler Carruth63392ea2012-09-16 19:39:50 +0000993 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000994 }
995 void visitSelectInst(SelectInst &SI) {
996 if (SI.use_empty())
997 return markAsDead(SI);
998
999 if (Value *Result = foldSelectInst(SI)) {
1000 if (Result == *U)
1001 // If the result of the constant fold will be the pointer, recurse
1002 // through the select as if we had RAUW'ed it.
1003 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +00001004 else
1005 // Otherwise the operand to the select is dead, and we can replace it
1006 // with undef.
1007 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +00001008
1009 return;
1010 }
1011
Chandler Carruth63392ea2012-09-16 19:39:50 +00001012 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00001013 }
1014
1015 /// \brief Unreachable, we've already visited the alloca once.
1016 void visitInstruction(Instruction &I) {
1017 llvm_unreachable("Unhandled instruction in use builder.");
1018 }
1019};
1020
1021void AllocaPartitioning::splitAndMergePartitions() {
1022 size_t NumDeadPartitions = 0;
1023
1024 // Track the range of splittable partitions that we pass when accumulating
1025 // overlapping unsplittable partitions.
1026 uint64_t SplitEndOffset = 0ull;
1027
1028 Partition New(0ull, 0ull, false);
1029
1030 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1031 ++j;
1032
1033 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1034 assert(New.BeginOffset == New.EndOffset);
1035 New = Partitions[i];
1036 } else {
1037 assert(New.IsSplittable);
1038 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1039 }
1040 assert(New.BeginOffset != New.EndOffset);
1041
1042 // Scan the overlapping partitions.
1043 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1044 // If the new partition we are forming is splittable, stop at the first
1045 // unsplittable partition.
1046 if (New.IsSplittable && !Partitions[j].IsSplittable)
1047 break;
1048
1049 // Grow the new partition to include any equally splittable range. 'j' is
1050 // always equally splittable when New is splittable, but when New is not
1051 // splittable, we may subsume some (or part of some) splitable partition
1052 // without growing the new one.
1053 if (New.IsSplittable == Partitions[j].IsSplittable) {
1054 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1055 } else {
1056 assert(!New.IsSplittable);
1057 assert(Partitions[j].IsSplittable);
1058 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1059 }
1060
Chandler Carruthfca3f402012-10-05 01:29:09 +00001061 Partitions[j].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001062 ++NumDeadPartitions;
1063 ++j;
1064 }
1065
1066 // If the new partition is splittable, chop off the end as soon as the
1067 // unsplittable subsequent partition starts and ensure we eventually cover
1068 // the splittable area.
1069 if (j != e && New.IsSplittable) {
1070 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1071 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1072 }
1073
1074 // Add the new partition if it differs from the original one and is
1075 // non-empty. We can end up with an empty partition here if it was
1076 // splittable but there is an unsplittable one that starts at the same
1077 // offset.
1078 if (New != Partitions[i]) {
1079 if (New.BeginOffset != New.EndOffset)
1080 Partitions.push_back(New);
1081 // Mark the old one for removal.
Chandler Carruthfca3f402012-10-05 01:29:09 +00001082 Partitions[i].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001083 ++NumDeadPartitions;
1084 }
1085
1086 New.BeginOffset = New.EndOffset;
1087 if (!New.IsSplittable) {
1088 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1089 if (j != e && !Partitions[j].IsSplittable)
1090 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1091 New.IsSplittable = true;
1092 // If there is a trailing splittable partition which won't be fused into
1093 // the next splittable partition go ahead and add it onto the partitions
1094 // list.
1095 if (New.BeginOffset < New.EndOffset &&
1096 (j == e || !Partitions[j].IsSplittable ||
1097 New.EndOffset < Partitions[j].BeginOffset)) {
1098 Partitions.push_back(New);
1099 New.BeginOffset = New.EndOffset = 0ull;
1100 }
1101 }
1102 }
1103
1104 // Re-sort the partitions now that they have been split and merged into
1105 // disjoint set of partitions. Also remove any of the dead partitions we've
1106 // replaced in the process.
1107 std::sort(Partitions.begin(), Partitions.end());
1108 if (NumDeadPartitions) {
Chandler Carruthfca3f402012-10-05 01:29:09 +00001109 assert(Partitions.back().isDead());
Chandler Carruth713aa942012-09-14 09:22:59 +00001110 assert((ptrdiff_t)NumDeadPartitions ==
1111 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1112 }
1113 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1114}
1115
Micah Villmow3574eca2012-10-08 16:38:25 +00001116AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001117 :
1118#ifndef NDEBUG
1119 AI(AI),
1120#endif
1121 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001122 PartitionBuilder PB(TD, AI, *this);
1123 if (!PB())
1124 return;
1125
Chandler Carruthfca3f402012-10-05 01:29:09 +00001126 // Sort the uses. This arranges for the offsets to be in ascending order,
1127 // and the sizes to be in descending order.
1128 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth713aa942012-09-14 09:22:59 +00001129
Chandler Carruthfca3f402012-10-05 01:29:09 +00001130 // Remove any partitions from the back which are marked as dead.
1131 while (!Partitions.empty() && Partitions.back().isDead())
1132 Partitions.pop_back();
1133
1134 if (Partitions.size() > 1) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001135 // Intersect splittability for all partitions with equal offsets and sizes.
1136 // Then remove all but the first so that we have a sequence of non-equal but
1137 // potentially overlapping partitions.
1138 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1139 I = J) {
1140 ++J;
1141 while (J != E && *I == *J) {
1142 I->IsSplittable &= J->IsSplittable;
1143 ++J;
1144 }
1145 }
1146 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1147 Partitions.end());
1148
1149 // Split splittable and merge unsplittable partitions into a disjoint set
1150 // of partitions over the used space of the allocation.
1151 splitAndMergePartitions();
1152 }
1153
1154 // Now build up the user lists for each of these disjoint partitions by
1155 // re-walking the recursive users of the alloca.
1156 Uses.resize(Partitions.size());
1157 UseBuilder UB(TD, AI, *this);
1158 UB();
Chandler Carruth713aa942012-09-14 09:22:59 +00001159}
1160
1161Type *AllocaPartitioning::getCommonType(iterator I) const {
1162 Type *Ty = 0;
1163 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001164 if (!UI->U)
1165 continue; // Skip dead uses.
Chandler Carruth77c12702012-10-01 01:49:22 +00001166 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth713aa942012-09-14 09:22:59 +00001167 continue;
1168 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001169 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001170
1171 Type *UserTy = 0;
Chandler Carruth77c12702012-10-01 01:49:22 +00001172 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001173 UserTy = LI->getType();
Chandler Carruth77c12702012-10-01 01:49:22 +00001174 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001175 UserTy = SI->getValueOperand()->getType();
Chandler Carruth713aa942012-09-14 09:22:59 +00001176 }
1177
1178 if (Ty && Ty != UserTy)
1179 return 0;
1180
1181 Ty = UserTy;
1182 }
1183 return Ty;
1184}
1185
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001186#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1187
Chandler Carruth713aa942012-09-14 09:22:59 +00001188void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1189 StringRef Indent) const {
1190 OS << Indent << "partition #" << (I - begin())
1191 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1192 << (I->IsSplittable ? " (splittable)" : "")
1193 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1194 << "\n";
1195}
1196
1197void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1198 StringRef Indent) const {
1199 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1200 UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001201 if (!UI->U)
1202 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00001203 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth77c12702012-10-01 01:49:22 +00001204 << "used by: " << *UI->U->getUser() << "\n";
1205 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001206 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1207 bool IsDest;
1208 if (!MTO.IsSplittable)
1209 IsDest = UI->BeginOffset == MTO.DestBegin;
1210 else
1211 IsDest = MTO.DestBegin != 0u;
1212 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1213 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1214 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1215 }
1216 }
1217}
1218
1219void AllocaPartitioning::print(raw_ostream &OS) const {
1220 if (PointerEscapingInstr) {
1221 OS << "No partitioning for alloca: " << AI << "\n"
1222 << " A pointer to this alloca escaped by:\n"
1223 << " " << *PointerEscapingInstr << "\n";
1224 return;
1225 }
1226
1227 OS << "Partitioning of alloca: " << AI << "\n";
1228 unsigned Num = 0;
1229 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1230 print(OS, I);
1231 printUsers(OS, I);
1232 }
1233}
1234
1235void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1236void AllocaPartitioning::dump() const { print(dbgs()); }
1237
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001238#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1239
Chandler Carruth713aa942012-09-14 09:22:59 +00001240
1241namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001242/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1243///
1244/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1245/// the loads and stores of an alloca instruction, as well as updating its
1246/// debug information. This is used when a domtree is unavailable and thus
1247/// mem2reg in its full form can't be used to handle promotion of allocas to
1248/// scalar values.
1249class AllocaPromoter : public LoadAndStorePromoter {
1250 AllocaInst &AI;
1251 DIBuilder &DIB;
1252
1253 SmallVector<DbgDeclareInst *, 4> DDIs;
1254 SmallVector<DbgValueInst *, 4> DVIs;
1255
1256public:
1257 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1258 AllocaInst &AI, DIBuilder &DIB)
1259 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1260
1261 void run(const SmallVectorImpl<Instruction*> &Insts) {
1262 // Remember which alloca we're promoting (for isInstInList).
1263 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1264 for (Value::use_iterator UI = DebugNode->use_begin(),
1265 UE = DebugNode->use_end();
1266 UI != UE; ++UI)
1267 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1268 DDIs.push_back(DDI);
1269 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1270 DVIs.push_back(DVI);
1271 }
1272
1273 LoadAndStorePromoter::run(Insts);
1274 AI.eraseFromParent();
1275 while (!DDIs.empty())
1276 DDIs.pop_back_val()->eraseFromParent();
1277 while (!DVIs.empty())
1278 DVIs.pop_back_val()->eraseFromParent();
1279 }
1280
1281 virtual bool isInstInList(Instruction *I,
1282 const SmallVectorImpl<Instruction*> &Insts) const {
1283 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1284 return LI->getOperand(0) == &AI;
1285 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1286 }
1287
1288 virtual void updateDebugInfo(Instruction *Inst) const {
1289 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1290 E = DDIs.end(); I != E; ++I) {
1291 DbgDeclareInst *DDI = *I;
1292 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1293 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1294 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1295 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1296 }
1297 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1298 E = DVIs.end(); I != E; ++I) {
1299 DbgValueInst *DVI = *I;
1300 Value *Arg = NULL;
1301 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1302 // If an argument is zero extended then use argument directly. The ZExt
1303 // may be zapped by an optimization pass in future.
1304 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1305 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1306 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1307 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1308 if (!Arg)
1309 Arg = SI->getOperand(0);
1310 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1311 Arg = LI->getOperand(0);
1312 } else {
1313 continue;
1314 }
1315 Instruction *DbgVal =
1316 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1317 Inst);
1318 DbgVal->setDebugLoc(DVI->getDebugLoc());
1319 }
1320 }
1321};
1322} // end anon namespace
1323
1324
1325namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001326/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1327///
1328/// This pass takes allocations which can be completely analyzed (that is, they
1329/// don't escape) and tries to turn them into scalar SSA values. There are
1330/// a few steps to this process.
1331///
1332/// 1) It takes allocations of aggregates and analyzes the ways in which they
1333/// are used to try to split them into smaller allocations, ideally of
1334/// a single scalar data type. It will split up memcpy and memset accesses
1335/// as necessary and try to isolate invidual scalar accesses.
1336/// 2) It will transform accesses into forms which are suitable for SSA value
1337/// promotion. This can be replacing a memset with a scalar store of an
1338/// integer value, or it can involve speculating operations on a PHI or
1339/// select to be a PHI or select of the results.
1340/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1341/// onto insert and extract operations on a vector value, and convert them to
1342/// this form. By doing so, it will enable promotion of vector aggregates to
1343/// SSA vector values.
1344class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001345 const bool RequiresDomTree;
1346
Chandler Carruth713aa942012-09-14 09:22:59 +00001347 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +00001348 const DataLayout *TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00001349 DominatorTree *DT;
1350
1351 /// \brief Worklist of alloca instructions to simplify.
1352 ///
1353 /// Each alloca in the function is added to this. Each new alloca formed gets
1354 /// added to it as well to recursively simplify unless that alloca can be
1355 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1356 /// the one being actively rewritten, we add it back onto the list if not
1357 /// already present to ensure it is re-visited.
1358 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1359
1360 /// \brief A collection of instructions to delete.
1361 /// We try to batch deletions to simplify code and make things a bit more
1362 /// efficient.
1363 SmallVector<Instruction *, 8> DeadInsts;
1364
1365 /// \brief A set to prevent repeatedly marking an instruction split into many
1366 /// uses as dead. Only used to guard insertion into DeadInsts.
1367 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1368
Chandler Carruthb2d98c22012-10-04 12:33:50 +00001369 /// \brief Post-promotion worklist.
1370 ///
1371 /// Sometimes we discover an alloca which has a high probability of becoming
1372 /// viable for SROA after a round of promotion takes place. In those cases,
1373 /// the alloca is enqueued here for re-processing.
1374 ///
1375 /// Note that we have to be very careful to clear allocas out of this list in
1376 /// the event they are deleted.
1377 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1378
Chandler Carruth713aa942012-09-14 09:22:59 +00001379 /// \brief A collection of alloca instructions we can directly promote.
1380 std::vector<AllocaInst *> PromotableAllocas;
1381
1382public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001383 SROA(bool RequiresDomTree = true)
1384 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1385 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001386 initializeSROAPass(*PassRegistry::getPassRegistry());
1387 }
1388 bool runOnFunction(Function &F);
1389 void getAnalysisUsage(AnalysisUsage &AU) const;
1390
1391 const char *getPassName() const { return "SROA"; }
1392 static char ID;
1393
1394private:
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001395 friend class PHIOrSelectSpeculator;
Chandler Carruth713aa942012-09-14 09:22:59 +00001396 friend class AllocaPartitionRewriter;
1397 friend class AllocaPartitionVectorRewriter;
1398
1399 bool rewriteAllocaPartition(AllocaInst &AI,
1400 AllocaPartitioning &P,
1401 AllocaPartitioning::iterator PI);
1402 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1403 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001404 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001405 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001406};
1407}
1408
1409char SROA::ID = 0;
1410
Chandler Carruth1c8db502012-09-15 11:43:14 +00001411FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1412 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001413}
1414
1415INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1416 false, false)
1417INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1418INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1419 false, false)
1420
Chandler Carruth0e9da582012-10-05 01:29:06 +00001421namespace {
1422/// \brief Visitor to speculate PHIs and Selects where possible.
1423class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1424 // Befriend the base class so it can delegate to private visit methods.
1425 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1426
Micah Villmow3574eca2012-10-08 16:38:25 +00001427 const DataLayout &TD;
Chandler Carruth0e9da582012-10-05 01:29:06 +00001428 AllocaPartitioning &P;
1429 SROA &Pass;
1430
1431public:
Micah Villmow3574eca2012-10-08 16:38:25 +00001432 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth0e9da582012-10-05 01:29:06 +00001433 : TD(TD), P(P), Pass(Pass) {}
1434
1435 /// \brief Visit the users of an alloca partition and rewrite them.
1436 void visitUsers(AllocaPartitioning::const_iterator PI) {
1437 // Note that we need to use an index here as the underlying vector of uses
1438 // may be grown during speculation. However, we never need to re-visit the
1439 // new uses, and so we can use the initial size bound.
1440 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1441 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1442 if (!PU.U)
1443 continue; // Skip dead use.
1444
1445 visit(cast<Instruction>(PU.U->getUser()));
1446 }
1447 }
1448
1449private:
1450 // By default, skip this instruction.
1451 void visitInstruction(Instruction &I) {}
1452
1453 /// PHI instructions that use an alloca and are subsequently loaded can be
1454 /// rewritten to load both input pointers in the pred blocks and then PHI the
1455 /// results, allowing the load of the alloca to be promoted.
1456 /// From this:
1457 /// %P2 = phi [i32* %Alloca, i32* %Other]
1458 /// %V = load i32* %P2
1459 /// to:
1460 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1461 /// ...
1462 /// %V2 = load i32* %Other
1463 /// ...
1464 /// %V = phi [i32 %V1, i32 %V2]
1465 ///
1466 /// We can do this to a select if its only uses are loads and if the operands
1467 /// to the select can be loaded unconditionally.
1468 ///
1469 /// FIXME: This should be hoisted into a generic utility, likely in
1470 /// Transforms/Util/Local.h
1471 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1472 // For now, we can only do this promotion if the load is in the same block
1473 // as the PHI, and if there are no stores between the phi and load.
1474 // TODO: Allow recursive phi users.
1475 // TODO: Allow stores.
1476 BasicBlock *BB = PN.getParent();
1477 unsigned MaxAlign = 0;
1478 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1479 UI != UE; ++UI) {
1480 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1481 if (LI == 0 || !LI->isSimple()) return false;
1482
1483 // For now we only allow loads in the same block as the PHI. This is
1484 // a common case that happens when instcombine merges two loads through
1485 // a PHI.
1486 if (LI->getParent() != BB) return false;
1487
1488 // Ensure that there are no instructions between the PHI and the load that
1489 // could store.
1490 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1491 if (BBI->mayWriteToMemory())
1492 return false;
1493
1494 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1495 Loads.push_back(LI);
1496 }
1497
1498 // We can only transform this if it is safe to push the loads into the
1499 // predecessor blocks. The only thing to watch out for is that we can't put
1500 // a possibly trapping load in the predecessor if it is a critical edge.
1501 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1502 ++Idx) {
1503 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1504 Value *InVal = PN.getIncomingValue(Idx);
1505
1506 // If the value is produced by the terminator of the predecessor (an
1507 // invoke) or it has side-effects, there is no valid place to put a load
1508 // in the predecessor.
1509 if (TI == InVal || TI->mayHaveSideEffects())
1510 return false;
1511
1512 // If the predecessor has a single successor, then the edge isn't
1513 // critical.
1514 if (TI->getNumSuccessors() == 1)
1515 continue;
1516
1517 // If this pointer is always safe to load, or if we can prove that there
1518 // is already a load in the block, then we can move the load to the pred
1519 // block.
1520 if (InVal->isDereferenceablePointer() ||
1521 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1522 continue;
1523
1524 return false;
1525 }
1526
1527 return true;
1528 }
1529
1530 void visitPHINode(PHINode &PN) {
1531 DEBUG(dbgs() << " original: " << PN << "\n");
1532
1533 SmallVector<LoadInst *, 4> Loads;
1534 if (!isSafePHIToSpeculate(PN, Loads))
1535 return;
1536
1537 assert(!Loads.empty());
1538
1539 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1540 IRBuilder<> PHIBuilder(&PN);
1541 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1542 PN.getName() + ".sroa.speculated");
1543
1544 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1545 // matter which one we get and if any differ, it doesn't matter.
1546 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1547 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1548 unsigned Align = SomeLoad->getAlignment();
1549
1550 // Rewrite all loads of the PN to use the new PHI.
1551 do {
1552 LoadInst *LI = Loads.pop_back_val();
1553 LI->replaceAllUsesWith(NewPN);
1554 Pass.DeadInsts.push_back(LI);
1555 } while (!Loads.empty());
1556
1557 // Inject loads into all of the pred blocks.
1558 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1559 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1560 TerminatorInst *TI = Pred->getTerminator();
1561 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1562 Value *InVal = PN.getIncomingValue(Idx);
1563 IRBuilder<> PredBuilder(TI);
1564
1565 LoadInst *Load
1566 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1567 Pred->getName()));
1568 ++NumLoadsSpeculated;
1569 Load->setAlignment(Align);
1570 if (TBAATag)
1571 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1572 NewPN->addIncoming(Load, Pred);
1573
1574 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1575 if (!Ptr)
1576 // No uses to rewrite.
1577 continue;
1578
1579 // Try to lookup and rewrite any partition uses corresponding to this phi
1580 // input.
1581 AllocaPartitioning::iterator PI
1582 = P.findPartitionForPHIOrSelectOperand(InUse);
1583 if (PI == P.end())
1584 continue;
1585
1586 // Replace the Use in the PartitionUse for this operand with the Use
1587 // inside the load.
1588 AllocaPartitioning::use_iterator UI
1589 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1590 assert(isa<PHINode>(*UI->U->getUser()));
1591 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1592 }
1593 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1594 }
1595
1596 /// Select instructions that use an alloca and are subsequently loaded can be
1597 /// rewritten to load both input pointers and then select between the result,
1598 /// allowing the load of the alloca to be promoted.
1599 /// From this:
1600 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1601 /// %V = load i32* %P2
1602 /// to:
1603 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1604 /// %V2 = load i32* %Other
1605 /// %V = select i1 %cond, i32 %V1, i32 %V2
1606 ///
1607 /// We can do this to a select if its only uses are loads and if the operand
1608 /// to the select can be loaded unconditionally.
1609 bool isSafeSelectToSpeculate(SelectInst &SI,
1610 SmallVectorImpl<LoadInst *> &Loads) {
1611 Value *TValue = SI.getTrueValue();
1612 Value *FValue = SI.getFalseValue();
1613 bool TDerefable = TValue->isDereferenceablePointer();
1614 bool FDerefable = FValue->isDereferenceablePointer();
1615
1616 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1617 UI != UE; ++UI) {
1618 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1619 if (LI == 0 || !LI->isSimple()) return false;
1620
1621 // Both operands to the select need to be dereferencable, either
1622 // absolutely (e.g. allocas) or at this point because we can see other
1623 // accesses to it.
1624 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1625 LI->getAlignment(), &TD))
1626 return false;
1627 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1628 LI->getAlignment(), &TD))
1629 return false;
1630 Loads.push_back(LI);
1631 }
1632
1633 return true;
1634 }
1635
1636 void visitSelectInst(SelectInst &SI) {
1637 DEBUG(dbgs() << " original: " << SI << "\n");
1638 IRBuilder<> IRB(&SI);
1639
1640 // If the select isn't safe to speculate, just use simple logic to emit it.
1641 SmallVector<LoadInst *, 4> Loads;
1642 if (!isSafeSelectToSpeculate(SI, Loads))
1643 return;
1644
1645 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1646 AllocaPartitioning::iterator PIs[2];
1647 AllocaPartitioning::PartitionUse PUs[2];
1648 for (unsigned i = 0, e = 2; i != e; ++i) {
1649 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1650 if (PIs[i] != P.end()) {
1651 // If the pointer is within the partitioning, remove the select from
1652 // its uses. We'll add in the new loads below.
1653 AllocaPartitioning::use_iterator UI
1654 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1655 PUs[i] = *UI;
1656 // Clear out the use here so that the offsets into the use list remain
1657 // stable but this use is ignored when rewriting.
1658 UI->U = 0;
1659 }
1660 }
1661
1662 Value *TV = SI.getTrueValue();
1663 Value *FV = SI.getFalseValue();
1664 // Replace the loads of the select with a select of two loads.
1665 while (!Loads.empty()) {
1666 LoadInst *LI = Loads.pop_back_val();
1667
1668 IRB.SetInsertPoint(LI);
1669 LoadInst *TL =
1670 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1671 LoadInst *FL =
1672 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1673 NumLoadsSpeculated += 2;
1674
1675 // Transfer alignment and TBAA info if present.
1676 TL->setAlignment(LI->getAlignment());
1677 FL->setAlignment(LI->getAlignment());
1678 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1679 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1680 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1681 }
1682
1683 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1684 LI->getName() + ".sroa.speculated");
1685
1686 LoadInst *Loads[2] = { TL, FL };
1687 for (unsigned i = 0, e = 2; i != e; ++i) {
1688 if (PIs[i] != P.end()) {
1689 Use *LoadUse = &Loads[i]->getOperandUse(0);
1690 assert(PUs[i].U->get() == LoadUse->get());
1691 PUs[i].U = LoadUse;
1692 P.use_push_back(PIs[i], PUs[i]);
1693 }
1694 }
1695
1696 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1697 LI->replaceAllUsesWith(V);
1698 Pass.DeadInsts.push_back(LI);
1699 }
1700 }
1701};
1702}
1703
Chandler Carruth713aa942012-09-14 09:22:59 +00001704/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1705///
1706/// If the provided GEP is all-constant, the total byte offset formed by the
1707/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1708/// operands, the function returns false and the value of Offset is unmodified.
Micah Villmow3574eca2012-10-08 16:38:25 +00001709static bool accumulateGEPOffsets(const DataLayout &TD, GEPOperator &GEP,
Chandler Carruth713aa942012-09-14 09:22:59 +00001710 APInt &Offset) {
1711 APInt GEPOffset(Offset.getBitWidth(), 0);
1712 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1713 GTI != GTE; ++GTI) {
1714 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1715 if (!OpC)
1716 return false;
1717 if (OpC->isZero()) continue;
1718
1719 // Handle a struct index, which adds its field offset to the pointer.
1720 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1721 unsigned ElementIdx = OpC->getZExtValue();
1722 const StructLayout *SL = TD.getStructLayout(STy);
1723 GEPOffset += APInt(Offset.getBitWidth(),
1724 SL->getElementOffset(ElementIdx));
1725 continue;
1726 }
1727
1728 APInt TypeSize(Offset.getBitWidth(),
1729 TD.getTypeAllocSize(GTI.getIndexedType()));
1730 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1731 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1732 "vector element size is not a multiple of 8, cannot GEP over it");
1733 TypeSize = VTy->getScalarSizeInBits() / 8;
1734 }
1735
1736 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1737 }
1738 Offset = GEPOffset;
1739 return true;
1740}
1741
1742/// \brief Build a GEP out of a base pointer and indices.
1743///
1744/// This will return the BasePtr if that is valid, or build a new GEP
1745/// instruction using the IRBuilder if GEP-ing is needed.
1746static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1747 SmallVectorImpl<Value *> &Indices,
1748 const Twine &Prefix) {
1749 if (Indices.empty())
1750 return BasePtr;
1751
1752 // A single zero index is a no-op, so check for this and avoid building a GEP
1753 // in that case.
1754 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1755 return BasePtr;
1756
1757 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1758}
1759
1760/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1761/// TargetTy without changing the offset of the pointer.
1762///
1763/// This routine assumes we've already established a properly offset GEP with
1764/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1765/// zero-indices down through type layers until we find one the same as
1766/// TargetTy. If we can't find one with the same type, we at least try to use
1767/// one with the same size. If none of that works, we just produce the GEP as
1768/// indicated by Indices to have the correct offset.
Micah Villmow3574eca2012-10-08 16:38:25 +00001769static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001770 Value *BasePtr, Type *Ty, Type *TargetTy,
1771 SmallVectorImpl<Value *> &Indices,
1772 const Twine &Prefix) {
1773 if (Ty == TargetTy)
1774 return buildGEP(IRB, BasePtr, Indices, Prefix);
1775
1776 // See if we can descend into a struct and locate a field with the correct
1777 // type.
1778 unsigned NumLayers = 0;
1779 Type *ElementTy = Ty;
1780 do {
1781 if (ElementTy->isPointerTy())
1782 break;
1783 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1784 ElementTy = SeqTy->getElementType();
Chandler Carruth020d9d52012-10-17 07:22:16 +00001785 // Note that we use the default address space as this index is over an
1786 // array or a vector, not a pointer.
1787 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth713aa942012-09-14 09:22:59 +00001788 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth2fdb25b2012-10-09 01:58:35 +00001789 if (STy->element_begin() == STy->element_end())
1790 break; // Nothing left to descend into.
Chandler Carruth713aa942012-09-14 09:22:59 +00001791 ElementTy = *STy->element_begin();
1792 Indices.push_back(IRB.getInt32(0));
1793 } else {
1794 break;
1795 }
1796 ++NumLayers;
1797 } while (ElementTy != TargetTy);
1798 if (ElementTy != TargetTy)
1799 Indices.erase(Indices.end() - NumLayers, Indices.end());
1800
1801 return buildGEP(IRB, BasePtr, Indices, Prefix);
1802}
1803
1804/// \brief Recursively compute indices for a natural GEP.
1805///
1806/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1807/// element types adding appropriate indices for the GEP.
Micah Villmow3574eca2012-10-08 16:38:25 +00001808static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001809 Value *Ptr, Type *Ty, APInt &Offset,
1810 Type *TargetTy,
1811 SmallVectorImpl<Value *> &Indices,
1812 const Twine &Prefix) {
1813 if (Offset == 0)
1814 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1815
1816 // We can't recurse through pointer types.
1817 if (Ty->isPointerTy())
1818 return 0;
1819
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001820 // We try to analyze GEPs over vectors here, but note that these GEPs are
1821 // extremely poorly defined currently. The long-term goal is to remove GEPing
1822 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001823 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1824 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1825 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001826 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001827 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001828 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001829 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1830 return 0;
1831 Offset -= NumSkippedElements * ElementSize;
1832 Indices.push_back(IRB.getInt(NumSkippedElements));
1833 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1834 Offset, TargetTy, Indices, Prefix);
1835 }
1836
1837 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1838 Type *ElementTy = ArrTy->getElementType();
1839 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001840 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001841 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1842 return 0;
1843
1844 Offset -= NumSkippedElements * ElementSize;
1845 Indices.push_back(IRB.getInt(NumSkippedElements));
1846 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1847 Indices, Prefix);
1848 }
1849
1850 StructType *STy = dyn_cast<StructType>(Ty);
1851 if (!STy)
1852 return 0;
1853
1854 const StructLayout *SL = TD.getStructLayout(STy);
1855 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001856 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001857 return 0;
1858 unsigned Index = SL->getElementContainingOffset(StructOffset);
1859 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1860 Type *ElementTy = STy->getElementType(Index);
1861 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1862 return 0; // The offset points into alignment padding.
1863
1864 Indices.push_back(IRB.getInt32(Index));
1865 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1866 Indices, Prefix);
1867}
1868
1869/// \brief Get a natural GEP from a base pointer to a particular offset and
1870/// resulting in a particular type.
1871///
1872/// The goal is to produce a "natural" looking GEP that works with the existing
1873/// composite types to arrive at the appropriate offset and element type for
1874/// a pointer. TargetTy is the element type the returned GEP should point-to if
1875/// possible. We recurse by decreasing Offset, adding the appropriate index to
1876/// Indices, and setting Ty to the result subtype.
1877///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001878/// If no natural GEP can be constructed, this function returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00001879static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001880 Value *Ptr, APInt Offset, Type *TargetTy,
1881 SmallVectorImpl<Value *> &Indices,
1882 const Twine &Prefix) {
1883 PointerType *Ty = cast<PointerType>(Ptr->getType());
1884
1885 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1886 // an i8.
1887 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1888 return 0;
1889
1890 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001891 if (!ElementTy->isSized())
1892 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001893 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1894 if (ElementSize == 0)
1895 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001896 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001897
1898 Offset -= NumSkippedElements * ElementSize;
1899 Indices.push_back(IRB.getInt(NumSkippedElements));
1900 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1901 Indices, Prefix);
1902}
1903
1904/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1905/// resulting pointer has PointerTy.
1906///
1907/// This tries very hard to compute a "natural" GEP which arrives at the offset
1908/// and produces the pointer type desired. Where it cannot, it will try to use
1909/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1910/// fails, it will try to use an existing i8* and GEP to the byte offset and
1911/// bitcast to the type.
1912///
1913/// The strategy for finding the more natural GEPs is to peel off layers of the
1914/// pointer, walking back through bit casts and GEPs, searching for a base
1915/// pointer from which we can compute a natural GEP with the desired
1916/// properities. The algorithm tries to fold as many constant indices into
1917/// a single GEP as possible, thus making each GEP more independent of the
1918/// surrounding code.
Micah Villmow3574eca2012-10-08 16:38:25 +00001919static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001920 Value *Ptr, APInt Offset, Type *PointerTy,
1921 const Twine &Prefix) {
1922 // Even though we don't look through PHI nodes, we could be called on an
1923 // instruction in an unreachable block, which may be on a cycle.
1924 SmallPtrSet<Value *, 4> Visited;
1925 Visited.insert(Ptr);
1926 SmallVector<Value *, 4> Indices;
1927
1928 // We may end up computing an offset pointer that has the wrong type. If we
1929 // never are able to compute one directly that has the correct type, we'll
1930 // fall back to it, so keep it around here.
1931 Value *OffsetPtr = 0;
1932
1933 // Remember any i8 pointer we come across to re-use if we need to do a raw
1934 // byte offset.
1935 Value *Int8Ptr = 0;
1936 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1937
1938 Type *TargetTy = PointerTy->getPointerElementType();
1939
1940 do {
1941 // First fold any existing GEPs into the offset.
1942 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1943 APInt GEPOffset(Offset.getBitWidth(), 0);
1944 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1945 break;
1946 Offset += GEPOffset;
1947 Ptr = GEP->getPointerOperand();
1948 if (!Visited.insert(Ptr))
1949 break;
1950 }
1951
1952 // See if we can perform a natural GEP here.
1953 Indices.clear();
1954 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1955 Indices, Prefix)) {
1956 if (P->getType() == PointerTy) {
1957 // Zap any offset pointer that we ended up computing in previous rounds.
1958 if (OffsetPtr && OffsetPtr->use_empty())
1959 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1960 I->eraseFromParent();
1961 return P;
1962 }
1963 if (!OffsetPtr) {
1964 OffsetPtr = P;
1965 }
1966 }
1967
1968 // Stash this pointer if we've found an i8*.
1969 if (Ptr->getType()->isIntegerTy(8)) {
1970 Int8Ptr = Ptr;
1971 Int8PtrOffset = Offset;
1972 }
1973
1974 // Peel off a layer of the pointer and update the offset appropriately.
1975 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1976 Ptr = cast<Operator>(Ptr)->getOperand(0);
1977 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1978 if (GA->mayBeOverridden())
1979 break;
1980 Ptr = GA->getAliasee();
1981 } else {
1982 break;
1983 }
1984 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1985 } while (Visited.insert(Ptr));
1986
1987 if (!OffsetPtr) {
1988 if (!Int8Ptr) {
1989 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1990 Prefix + ".raw_cast");
1991 Int8PtrOffset = Offset;
1992 }
1993
1994 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1995 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1996 Prefix + ".raw_idx");
1997 }
1998 Ptr = OffsetPtr;
1999
2000 // On the off chance we were targeting i8*, guard the bitcast here.
2001 if (Ptr->getType() != PointerTy)
2002 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2003
2004 return Ptr;
2005}
2006
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002007/// \brief Test whether we can convert a value from the old to the new type.
2008///
2009/// This predicate should be used to guard calls to convertValue in order to
2010/// ensure that we only try to convert viable values. The strategy is that we
2011/// will peel off single element struct and array wrappings to get to an
2012/// underlying value, and convert that value.
2013static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
2014 if (OldTy == NewTy)
2015 return true;
2016 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
2017 return false;
2018 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2019 return false;
2020
2021 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2022 if (NewTy->isPointerTy() && OldTy->isPointerTy())
2023 return true;
2024 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
2025 return true;
2026 return false;
2027 }
2028
2029 return true;
2030}
2031
2032/// \brief Generic routine to convert an SSA value to a value of a different
2033/// type.
2034///
2035/// This will try various different casting techniques, such as bitcasts,
2036/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2037/// two types for viability with this routine.
2038static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2039 Type *Ty) {
2040 assert(canConvertValue(DL, V->getType(), Ty) &&
2041 "Value not convertable to type");
2042 if (V->getType() == Ty)
2043 return V;
2044 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2045 return IRB.CreateIntToPtr(V, Ty);
2046 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2047 return IRB.CreatePtrToInt(V, Ty);
2048
2049 return IRB.CreateBitCast(V, Ty);
2050}
2051
Chandler Carruth713aa942012-09-14 09:22:59 +00002052/// \brief Test whether the given alloca partition can be promoted to a vector.
2053///
2054/// This is a quick test to check whether we can rewrite a particular alloca
2055/// partition (and its newly formed alloca) into a vector alloca with only
2056/// whole-vector loads and stores such that it could be promoted to a vector
2057/// SSA value. We only can ensure this for a limited set of operations, and we
2058/// don't want to do the rewrites unless we are confident that the result will
2059/// be promotable, so we have an early test here.
Micah Villmow3574eca2012-10-08 16:38:25 +00002060static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00002061 Type *AllocaTy,
2062 AllocaPartitioning &P,
2063 uint64_t PartitionBeginOffset,
2064 uint64_t PartitionEndOffset,
2065 AllocaPartitioning::const_use_iterator I,
2066 AllocaPartitioning::const_use_iterator E) {
2067 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2068 if (!Ty)
2069 return false;
2070
2071 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2072 uint64_t ElementSize = Ty->getScalarSizeInBits();
2073
2074 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2075 // that aren't byte sized.
2076 if (ElementSize % 8)
2077 return false;
2078 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2079 VecSize /= 8;
2080 ElementSize /= 8;
2081
2082 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002083 if (!I->U)
2084 continue; // Skip dead use.
2085
Chandler Carruth713aa942012-09-14 09:22:59 +00002086 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2087 uint64_t BeginIndex = BeginOffset / ElementSize;
2088 if (BeginIndex * ElementSize != BeginOffset ||
2089 BeginIndex >= Ty->getNumElements())
2090 return false;
2091 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2092 uint64_t EndIndex = EndOffset / ElementSize;
2093 if (EndIndex * ElementSize != EndOffset ||
2094 EndIndex > Ty->getNumElements())
2095 return false;
2096
2097 // FIXME: We should build shuffle vector instructions to handle
2098 // non-element-sized accesses.
2099 if ((EndOffset - BeginOffset) != ElementSize &&
2100 (EndOffset - BeginOffset) != VecSize)
2101 return false;
2102
Chandler Carruth77c12702012-10-01 01:49:22 +00002103 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002104 if (MI->isVolatile())
2105 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002106 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002107 const AllocaPartitioning::MemTransferOffsets &MTO
2108 = P.getMemTransferOffsets(*MTI);
2109 if (!MTO.IsSplittable)
2110 return false;
2111 }
Chandler Carruth77c12702012-10-01 01:49:22 +00002112 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002113 // Disable vector promotion when there are loads or stores of an FCA.
2114 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002115 } else if (!isa<LoadInst>(I->U->getUser()) &&
2116 !isa<StoreInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002117 return false;
2118 }
2119 }
2120 return true;
2121}
2122
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002123/// \brief Test whether the given alloca partition's integer operations can be
2124/// widened to promotable ones.
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002125///
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002126/// This is a quick test to check whether we can rewrite the integer loads and
2127/// stores to a particular alloca into wider loads and stores and be able to
2128/// promote the resulting alloca.
2129static bool isIntegerWideningViable(const DataLayout &TD,
2130 Type *AllocaTy,
2131 uint64_t AllocBeginOffset,
2132 AllocaPartitioning &P,
2133 AllocaPartitioning::const_use_iterator I,
2134 AllocaPartitioning::const_use_iterator E) {
2135 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
2136
2137 // Don't try to handle allocas with bit-padding.
2138 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002139 return false;
2140
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002141 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2142
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002143 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2144 // Also ensure that the alloca has a covering load or store. We don't want
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002145 // to widen the integer operotains only to fail to promote due to some other
2146 // unsplittable entry (which we may make splittable later).
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002147 bool WholeAllocaOp = false;
2148 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002149 if (!I->U)
2150 continue; // Skip dead use.
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002151
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002152 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2153 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2154
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002155 // We can't reasonably handle cases where the load or store extends past
2156 // the end of the aloca's type and into its padding.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002157 if (RelEnd > Size)
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002158 return false;
2159
Chandler Carruth77c12702012-10-01 01:49:22 +00002160 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002161 if (LI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002162 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002163 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002164 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002165 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2166 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2167 return false;
2168 continue;
2169 }
2170 // Non-integer loads need to be convertible from the alloca type so that
2171 // they are promotable.
2172 if (RelBegin != 0 || RelEnd != Size ||
2173 !canConvertValue(TD, AllocaTy, LI->getType()))
2174 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002175 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002176 Type *ValueTy = SI->getValueOperand()->getType();
2177 if (SI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002178 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002179 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002180 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002181 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2182 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2183 return false;
2184 continue;
2185 }
2186 // Non-integer stores need to be convertible to the alloca type so that
2187 // they are promotable.
2188 if (RelBegin != 0 || RelEnd != Size ||
2189 !canConvertValue(TD, ValueTy, AllocaTy))
2190 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002191 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002192 if (MI->isVolatile())
2193 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002194 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002195 const AllocaPartitioning::MemTransferOffsets &MTO
2196 = P.getMemTransferOffsets(*MTI);
2197 if (!MTO.IsSplittable)
2198 return false;
2199 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002200 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2201 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2202 II->getIntrinsicID() != Intrinsic::lifetime_end)
2203 return false;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002204 } else {
2205 return false;
2206 }
2207 }
2208 return WholeAllocaOp;
2209}
2210
Chandler Carruth713aa942012-09-14 09:22:59 +00002211namespace {
2212/// \brief Visitor to rewrite instructions using a partition of an alloca to
2213/// use a new alloca.
2214///
2215/// Also implements the rewriting to vector-based accesses when the partition
2216/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2217/// lives here.
2218class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2219 bool> {
2220 // Befriend the base class so it can delegate to private visit methods.
2221 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2222
Micah Villmow3574eca2012-10-08 16:38:25 +00002223 const DataLayout &TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00002224 AllocaPartitioning &P;
2225 SROA &Pass;
2226 AllocaInst &OldAI, &NewAI;
2227 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth520eeae2012-10-13 02:41:05 +00002228 Type *NewAllocaTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00002229
2230 // If we are rewriting an alloca partition which can be written as pure
2231 // vector operations, we stash extra information here. When VecTy is
2232 // non-null, we have some strict guarantees about the rewriten alloca:
2233 // - The new alloca is exactly the size of the vector type here.
2234 // - The accesses all either map to the entire vector or to a single
2235 // element.
2236 // - The set of accessing instructions is only one of those handled above
2237 // in isVectorPromotionViable. Generally these are the same access kinds
2238 // which are promotable via mem2reg.
2239 VectorType *VecTy;
2240 Type *ElementTy;
2241 uint64_t ElementSize;
2242
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002243 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002244 // alloca's integer operations should be widened to this integer type due to
2245 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002246 // integer type will be stored here for easy access during rewriting.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002247 IntegerType *IntTy;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002248
Chandler Carruth713aa942012-09-14 09:22:59 +00002249 // The offset of the partition user currently being rewritten.
2250 uint64_t BeginOffset, EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002251 Use *OldUse;
Chandler Carruth713aa942012-09-14 09:22:59 +00002252 Instruction *OldPtr;
2253
2254 // The name prefix to use when rewriting instructions for this alloca.
2255 std::string NamePrefix;
2256
2257public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002258 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth713aa942012-09-14 09:22:59 +00002259 AllocaPartitioning::iterator PI,
2260 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2261 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2262 : TD(TD), P(P), Pass(Pass),
2263 OldAI(OldAI), NewAI(NewAI),
2264 NewAllocaBeginOffset(NewBeginOffset),
2265 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth520eeae2012-10-13 02:41:05 +00002266 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002267 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002268 BeginOffset(), EndOffset() {
2269 }
2270
2271 /// \brief Visit the users of the alloca partition and rewrite them.
2272 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2273 AllocaPartitioning::const_use_iterator E) {
2274 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2275 NewAllocaBeginOffset, NewAllocaEndOffset,
2276 I, E)) {
2277 ++NumVectorized;
2278 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2279 ElementTy = VecTy->getElementType();
2280 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2281 "Only multiple-of-8 sized vector elements are viable");
2282 ElementSize = VecTy->getScalarSizeInBits() / 8;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002283 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2284 NewAllocaBeginOffset, P, I, E)) {
2285 IntTy = Type::getIntNTy(NewAI.getContext(),
2286 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002287 }
2288 bool CanSROA = true;
2289 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002290 if (!I->U)
2291 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00002292 BeginOffset = I->BeginOffset;
2293 EndOffset = I->EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002294 OldUse = I->U;
2295 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth713aa942012-09-14 09:22:59 +00002296 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth77c12702012-10-01 01:49:22 +00002297 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002298 }
2299 if (VecTy) {
2300 assert(CanSROA);
2301 VecTy = 0;
2302 ElementTy = 0;
2303 ElementSize = 0;
2304 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002305 if (IntTy) {
2306 assert(CanSROA);
2307 IntTy = 0;
2308 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002309 return CanSROA;
2310 }
2311
2312private:
2313 // Every instruction which can end up as a user must have a rewrite rule.
2314 bool visitInstruction(Instruction &I) {
2315 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2316 llvm_unreachable("No rewrite rule for this instruction!");
2317 }
2318
2319 Twine getName(const Twine &Suffix) {
2320 return NamePrefix + Suffix;
2321 }
2322
2323 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2324 assert(BeginOffset >= NewAllocaBeginOffset);
Micah Villmow2c39b152012-10-15 16:24:29 +00002325 unsigned AS = cast<PointerType>(PointerTy)->getAddressSpace();
2326 APInt Offset(TD.getPointerSizeInBits(AS), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002327 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2328 }
2329
Chandler Carruthf710fb12012-10-03 08:14:02 +00002330 /// \brief Compute suitable alignment to access an offset into the new alloca.
2331 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth673850a2012-10-01 12:16:54 +00002332 unsigned NewAIAlign = NewAI.getAlignment();
2333 if (!NewAIAlign)
2334 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2335 return MinAlign(NewAIAlign, Offset);
2336 }
Chandler Carruthf710fb12012-10-03 08:14:02 +00002337
2338 /// \brief Compute suitable alignment to access this partition of the new
2339 /// alloca.
2340 unsigned getPartitionAlign() {
2341 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002342 }
2343
Chandler Carruthf710fb12012-10-03 08:14:02 +00002344 /// \brief Compute suitable alignment to access a type at an offset of the
2345 /// new alloca.
2346 ///
2347 /// \returns zero if the type's ABI alignment is a suitable alignment,
2348 /// otherwise returns the maximal suitable alignment.
2349 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2350 unsigned Align = getOffsetAlign(Offset);
2351 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2352 }
2353
2354 /// \brief Compute suitable alignment to access a type at the beginning of
2355 /// this partition of the new alloca.
2356 ///
2357 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2358 unsigned getPartitionTypeAlign(Type *Ty) {
2359 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002360 }
2361
Chandler Carruth713aa942012-09-14 09:22:59 +00002362 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
2363 assert(VecTy && "Can only call getIndex when rewriting a vector");
2364 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2365 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2366 uint32_t Index = RelOffset / ElementSize;
2367 assert(Index * ElementSize == RelOffset);
2368 return IRB.getInt32(Index);
2369 }
2370
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002371 Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy,
2372 uint64_t Offset) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002373 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth81b001a2012-09-26 10:27:46 +00002374 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2375 getName(".load"));
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002376 V = convertValue(TD, IRB, V, IntTy);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002377 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2378 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002379 assert(TD.getTypeStoreSize(TargetTy) + RelOffset <=
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002380 TD.getTypeStoreSize(IntTy) &&
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002381 "Element load outside of alloca store");
2382 uint64_t ShAmt = 8*RelOffset;
2383 if (TD.isBigEndian())
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002384 ShAmt = 8*(TD.getTypeStoreSize(IntTy) -
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002385 TD.getTypeStoreSize(TargetTy) - RelOffset);
2386 if (ShAmt)
2387 V = IRB.CreateLShr(V, ShAmt, getName(".shift"));
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002388 assert(TargetTy->getBitWidth() <= IntTy->getBitWidth() &&
2389 "Cannot extract to a larger integer!");
2390 if (TargetTy != IntTy)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002391 V = IRB.CreateTrunc(V, TargetTy, getName(".trunc"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002392 return V;
2393 }
2394
2395 StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) {
2396 IntegerType *Ty = cast<IntegerType>(V->getType());
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002397 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002398 "Cannot insert a larger integer!");
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002399 if (Ty != IntTy)
2400 V = IRB.CreateZExt(V, IntTy, getName(".ext"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002401 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2402 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002403 assert(TD.getTypeStoreSize(Ty) + RelOffset <=
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002404 TD.getTypeStoreSize(IntTy) &&
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002405 "Element store outside of alloca store");
2406 uint64_t ShAmt = 8*RelOffset;
2407 if (TD.isBigEndian())
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002408 ShAmt = 8*(TD.getTypeStoreSize(IntTy) - TD.getTypeStoreSize(Ty)
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002409 - RelOffset);
2410 if (ShAmt)
2411 V = IRB.CreateShl(V, ShAmt, getName(".shift"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002412
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002413 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2414 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2415 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2416 getName(".oldload"));
2417 Old = convertValue(TD, IRB, Old, IntTy);
2418 Old = IRB.CreateAnd(Old, Mask, getName(".mask"));
2419 V = IRB.CreateOr(Old, V, getName(".insert"));
2420 }
2421 V = convertValue(TD, IRB, V, NewAllocaTy);
2422 return IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002423 }
2424
Chandler Carruth713aa942012-09-14 09:22:59 +00002425 void deleteIfTriviallyDead(Value *V) {
2426 Instruction *I = cast<Instruction>(V);
2427 if (isInstructionTriviallyDead(I))
2428 Pass.DeadInsts.push_back(I);
2429 }
2430
Chandler Carruth713aa942012-09-14 09:22:59 +00002431 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2432 Value *Result;
2433 if (LI.getType() == VecTy->getElementType() ||
2434 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002435 Result = IRB.CreateExtractElement(
2436 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2437 getIndex(IRB, BeginOffset), getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002438 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002439 Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2440 getName(".load"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002441 }
2442 if (Result->getType() != LI.getType())
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002443 Result = convertValue(TD, IRB, Result, LI.getType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002444 LI.replaceAllUsesWith(Result);
2445 Pass.DeadInsts.push_back(&LI);
2446
2447 DEBUG(dbgs() << " to: " << *Result << "\n");
2448 return true;
2449 }
2450
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002451 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2452 assert(!LI.isVolatile());
2453 Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()),
2454 BeginOffset);
2455 LI.replaceAllUsesWith(Result);
2456 Pass.DeadInsts.push_back(&LI);
2457 DEBUG(dbgs() << " to: " << *Result << "\n");
2458 return true;
2459 }
2460
Chandler Carruth713aa942012-09-14 09:22:59 +00002461 bool visitLoadInst(LoadInst &LI) {
2462 DEBUG(dbgs() << " original: " << LI << "\n");
2463 Value *OldOp = LI.getOperand(0);
2464 assert(OldOp == OldPtr);
2465 IRBuilder<> IRB(&LI);
2466
2467 if (VecTy)
2468 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002469 if (IntTy && LI.getType()->isIntegerTy())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002470 return rewriteIntegerLoad(IRB, LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002471
Chandler Carruth520eeae2012-10-13 02:41:05 +00002472 if (BeginOffset == NewAllocaBeginOffset &&
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002473 canConvertValue(TD, NewAllocaTy, LI.getType())) {
Chandler Carruth520eeae2012-10-13 02:41:05 +00002474 Value *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2475 LI.isVolatile(), getName(".load"));
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002476 Value *NewV = convertValue(TD, IRB, NewLI, LI.getType());
Chandler Carruth520eeae2012-10-13 02:41:05 +00002477 LI.replaceAllUsesWith(NewV);
2478 Pass.DeadInsts.push_back(&LI);
2479
2480 DEBUG(dbgs() << " to: " << *NewLI << "\n");
2481 return !LI.isVolatile();
2482 }
2483
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002484 assert(!IntTy && "Invalid load found with int-op widening enabled");
2485
Chandler Carruth713aa942012-09-14 09:22:59 +00002486 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2487 LI.getPointerOperand()->getType());
2488 LI.setOperand(0, NewPtr);
Chandler Carruthf710fb12012-10-03 08:14:02 +00002489 LI.setAlignment(getPartitionTypeAlign(LI.getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002490 DEBUG(dbgs() << " to: " << LI << "\n");
2491
2492 deleteIfTriviallyDead(OldOp);
2493 return NewPtr == &NewAI && !LI.isVolatile();
2494 }
2495
2496 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
2497 Value *OldOp) {
2498 Value *V = SI.getValueOperand();
2499 if (V->getType() == ElementTy ||
2500 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2501 if (V->getType() != ElementTy)
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002502 V = convertValue(TD, IRB, V, ElementTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002503 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2504 getName(".load"));
2505 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002506 getName(".insert"));
2507 } else if (V->getType() != VecTy) {
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002508 V = convertValue(TD, IRB, V, VecTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00002509 }
Chandler Carruth81b001a2012-09-26 10:27:46 +00002510 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002511 Pass.DeadInsts.push_back(&SI);
2512
2513 (void)Store;
2514 DEBUG(dbgs() << " to: " << *Store << "\n");
2515 return true;
2516 }
2517
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002518 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
2519 assert(!SI.isVolatile());
2520 StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset);
2521 Pass.DeadInsts.push_back(&SI);
2522 (void)Store;
2523 DEBUG(dbgs() << " to: " << *Store << "\n");
2524 return true;
2525 }
2526
Chandler Carruth713aa942012-09-14 09:22:59 +00002527 bool visitStoreInst(StoreInst &SI) {
2528 DEBUG(dbgs() << " original: " << SI << "\n");
2529 Value *OldOp = SI.getOperand(1);
2530 assert(OldOp == OldPtr);
2531 IRBuilder<> IRB(&SI);
2532
2533 if (VecTy)
2534 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
Chandler Carruth520eeae2012-10-13 02:41:05 +00002535 Type *ValueTy = SI.getValueOperand()->getType();
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002536 if (IntTy && ValueTy->isIntegerTy())
2537 return rewriteIntegerStore(IRB, SI);
Chandler Carruth520eeae2012-10-13 02:41:05 +00002538
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002539 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2540 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth520eeae2012-10-13 02:41:05 +00002541 if (ValueTy->isPointerTy())
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002542 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI.getValueOperand()
2543 ->stripInBoundsOffsets()))
2544 Pass.PostPromotionWorklist.insert(AI);
2545
Chandler Carruth520eeae2012-10-13 02:41:05 +00002546 if (BeginOffset == NewAllocaBeginOffset &&
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002547 canConvertValue(TD, ValueTy, NewAllocaTy)) {
2548 Value *NewV = convertValue(TD, IRB, SI.getValueOperand(), NewAllocaTy);
Chandler Carruth520eeae2012-10-13 02:41:05 +00002549 StoreInst *NewSI = IRB.CreateAlignedStore(NewV, &NewAI, NewAI.getAlignment(),
2550 SI.isVolatile());
Chandler Carruthc2fcf1a62012-10-13 05:09:27 +00002551 (void)NewSI;
Chandler Carruth520eeae2012-10-13 02:41:05 +00002552 Pass.DeadInsts.push_back(&SI);
2553
2554 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2555 return !SI.isVolatile();
2556 }
2557
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002558 assert(!IntTy && "Invalid store found with int-op widening enabled");
2559
Chandler Carruth713aa942012-09-14 09:22:59 +00002560 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2561 SI.getPointerOperand()->getType());
2562 SI.setOperand(1, NewPtr);
Chandler Carruthf710fb12012-10-03 08:14:02 +00002563 SI.setAlignment(getPartitionTypeAlign(SI.getValueOperand()->getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002564 DEBUG(dbgs() << " to: " << SI << "\n");
2565
2566 deleteIfTriviallyDead(OldOp);
2567 return NewPtr == &NewAI && !SI.isVolatile();
2568 }
2569
2570 bool visitMemSetInst(MemSetInst &II) {
2571 DEBUG(dbgs() << " original: " << II << "\n");
2572 IRBuilder<> IRB(&II);
2573 assert(II.getRawDest() == OldPtr);
2574
2575 // If the memset has a variable size, it cannot be split, just adjust the
2576 // pointer to the new alloca.
2577 if (!isa<Constant>(II.getLength())) {
2578 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002579 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf710fb12012-10-03 08:14:02 +00002580 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002581
Chandler Carruth713aa942012-09-14 09:22:59 +00002582 deleteIfTriviallyDead(OldPtr);
2583 return false;
2584 }
2585
2586 // Record this instruction for deletion.
2587 if (Pass.DeadSplitInsts.insert(&II))
2588 Pass.DeadInsts.push_back(&II);
2589
2590 Type *AllocaTy = NewAI.getAllocatedType();
2591 Type *ScalarTy = AllocaTy->getScalarType();
2592
2593 // If this doesn't map cleanly onto the alloca type, and that type isn't
2594 // a single value type, just emit a memset.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002595 if (!VecTy && !IntTy &&
2596 (BeginOffset != NewAllocaBeginOffset ||
2597 EndOffset != NewAllocaEndOffset ||
2598 !AllocaTy->isSingleValueType() ||
2599 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002600 Type *SizeTy = II.getLength()->getType();
2601 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002602 CallInst *New
2603 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2604 II.getRawDest()->getType()),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002605 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002606 II.isVolatile());
2607 (void)New;
2608 DEBUG(dbgs() << " to: " << *New << "\n");
2609 return false;
2610 }
2611
2612 // If we can represent this as a simple value, we have to build the actual
2613 // value to store, which requires expanding the byte present in memset to
2614 // a sensible representation for the alloca type. This is essentially
2615 // splatting the byte to a sufficiently wide integer, bitcasting to the
2616 // desired scalar type, and splatting it across any desired vector type.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002617 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +00002618 Value *V = II.getValue();
2619 IntegerType *VTy = cast<IntegerType>(V->getType());
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002620 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2621 if (Size*8 > VTy->getBitWidth())
2622 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
Chandler Carruth713aa942012-09-14 09:22:59 +00002623 ConstantExpr::getUDiv(
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002624 Constant::getAllOnesValue(SplatIntTy),
Chandler Carruth713aa942012-09-14 09:22:59 +00002625 ConstantExpr::getZExt(
2626 Constant::getAllOnesValue(V->getType()),
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002627 SplatIntTy)),
Chandler Carruth713aa942012-09-14 09:22:59 +00002628 getName(".isplat"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002629
2630 // If this is an element-wide memset of a vectorizable alloca, insert it.
2631 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2632 EndOffset < NewAllocaEndOffset)) {
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002633 if (V->getType() != ScalarTy)
2634 V = convertValue(TD, IRB, V, ScalarTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002635 StoreInst *Store = IRB.CreateAlignedStore(
2636 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2637 NewAI.getAlignment(),
2638 getName(".load")),
2639 V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002640 getName(".insert")),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002641 &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002642 (void)Store;
2643 DEBUG(dbgs() << " to: " << *Store << "\n");
2644 return true;
2645 }
2646
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002647 // If this is a memset on an alloca where we can widen stores, insert the
2648 // set integer.
2649 if (IntTy && (BeginOffset > NewAllocaBeginOffset ||
2650 EndOffset < NewAllocaEndOffset)) {
2651 assert(!II.isVolatile());
2652 StoreInst *Store = insertInteger(IRB, V, BeginOffset);
2653 (void)Store;
2654 DEBUG(dbgs() << " to: " << *Store << "\n");
2655 return true;
Chandler Carruth713aa942012-09-14 09:22:59 +00002656 }
2657
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002658 if (V->getType() != AllocaTy)
2659 V = convertValue(TD, IRB, V, AllocaTy);
2660
Chandler Carruth81b001a2012-09-26 10:27:46 +00002661 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2662 II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002663 (void)New;
2664 DEBUG(dbgs() << " to: " << *New << "\n");
2665 return !II.isVolatile();
2666 }
2667
2668 bool visitMemTransferInst(MemTransferInst &II) {
2669 // Rewriting of memory transfer instructions can be a bit tricky. We break
2670 // them into two categories: split intrinsics and unsplit intrinsics.
2671
2672 DEBUG(dbgs() << " original: " << II << "\n");
2673 IRBuilder<> IRB(&II);
2674
2675 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2676 bool IsDest = II.getRawDest() == OldPtr;
2677
2678 const AllocaPartitioning::MemTransferOffsets &MTO
2679 = P.getMemTransferOffsets(II);
2680
Micah Villmow2c39b152012-10-15 16:24:29 +00002681 assert(OldPtr->getType()->isPointerTy() && "Must be a pointer type!");
2682 unsigned AS = cast<PointerType>(OldPtr->getType())->getAddressSpace();
Chandler Carruth673850a2012-10-01 12:16:54 +00002683 // Compute the relative offset within the transfer.
Micah Villmow2c39b152012-10-15 16:24:29 +00002684 unsigned IntPtrWidth = TD.getPointerSizeInBits(AS);
Chandler Carruth673850a2012-10-01 12:16:54 +00002685 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2686 : MTO.SourceBegin));
2687
2688 unsigned Align = II.getAlignment();
2689 if (Align > 1)
2690 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002691 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth673850a2012-10-01 12:16:54 +00002692
Chandler Carruth713aa942012-09-14 09:22:59 +00002693 // For unsplit intrinsics, we simply modify the source and destination
2694 // pointers in place. This isn't just an optimization, it is a matter of
2695 // correctness. With unsplit intrinsics we may be dealing with transfers
2696 // within a single alloca before SROA ran, or with transfers that have
2697 // a variable length. We may also be dealing with memmove instead of
2698 // memcpy, and so simply updating the pointers is the necessary for us to
2699 // update both source and dest of a single call.
2700 if (!MTO.IsSplittable) {
2701 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2702 if (IsDest)
2703 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2704 else
2705 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2706
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002707 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth673850a2012-10-01 12:16:54 +00002708 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002709
Chandler Carruth713aa942012-09-14 09:22:59 +00002710 DEBUG(dbgs() << " to: " << II << "\n");
2711 deleteIfTriviallyDead(OldOp);
2712 return false;
2713 }
2714 // For split transfer intrinsics we have an incredibly useful assurance:
2715 // the source and destination do not reside within the same alloca, and at
2716 // least one of them does not escape. This means that we can replace
2717 // memmove with memcpy, and we don't need to worry about all manner of
2718 // downsides to splitting and transforming the operations.
2719
Chandler Carruth713aa942012-09-14 09:22:59 +00002720 // If this doesn't map cleanly onto the alloca type, and that type isn't
2721 // a single value type, just emit a memcpy.
2722 bool EmitMemCpy
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002723 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2724 EndOffset != NewAllocaEndOffset ||
2725 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002726
2727 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2728 // size hasn't been shrunk based on analysis of the viable range, this is
2729 // a no-op.
2730 if (EmitMemCpy && &OldAI == &NewAI) {
2731 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2732 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2733 // Ensure the start lines up.
2734 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002735 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002736
2737 // Rewrite the size as needed.
2738 if (EndOffset != OrigEnd)
2739 II.setLength(ConstantInt::get(II.getLength()->getType(),
2740 EndOffset - BeginOffset));
2741 return false;
2742 }
2743 // Record this instruction for deletion.
2744 if (Pass.DeadSplitInsts.insert(&II))
2745 Pass.DeadInsts.push_back(&II);
2746
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002747 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2748 EndOffset == NewAllocaEndOffset;
2749 bool IsVectorElement = VecTy && !IsWholeAlloca;
2750 uint64_t Size = EndOffset - BeginOffset;
2751 IntegerType *SubIntTy
2752 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002753
2754 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2755 : II.getRawDest()->getType();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002756 if (!EmitMemCpy) {
2757 if (IsVectorElement)
2758 OtherPtrTy = VecTy->getElementType()->getPointerTo();
2759 else if (IntTy && !IsWholeAlloca)
2760 OtherPtrTy = SubIntTy->getPointerTo();
2761 else
2762 OtherPtrTy = NewAI.getType();
2763 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002764
2765 // Compute the other pointer, folding as much as possible to produce
2766 // a single, simple GEP in most cases.
2767 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2768 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2769 getName("." + OtherPtr->getName()));
2770
2771 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2772 // alloca that should be re-examined after rewriting this instruction.
2773 if (AllocaInst *AI
2774 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruthb3dca3f2012-09-26 07:41:40 +00002775 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002776
2777 if (EmitMemCpy) {
2778 Value *OurPtr
2779 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2780 : II.getRawSource()->getType());
2781 Type *SizeTy = II.getLength()->getType();
2782 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2783
2784 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2785 IsDest ? OtherPtr : OurPtr,
Chandler Carruth81b001a2012-09-26 10:27:46 +00002786 Size, Align, II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002787 (void)New;
2788 DEBUG(dbgs() << " to: " << *New << "\n");
2789 return false;
2790 }
2791
Chandler Carruth322e9ba2012-10-03 08:26:28 +00002792 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2793 // is equivalent to 1, but that isn't true if we end up rewriting this as
2794 // a load or store.
2795 if (!Align)
2796 Align = 1;
2797
Chandler Carruth713aa942012-09-14 09:22:59 +00002798 Value *SrcPtr = OtherPtr;
2799 Value *DstPtr = &NewAI;
2800 if (!IsDest)
2801 std::swap(SrcPtr, DstPtr);
2802
2803 Value *Src;
2804 if (IsVectorElement && !IsDest) {
2805 // We have to extract rather than load.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002806 Src = IRB.CreateExtractElement(
2807 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2808 getIndex(IRB, BeginOffset),
2809 getName(".copyextract"));
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002810 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2811 Src = extractInteger(IRB, SubIntTy, BeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002812 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002813 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2814 getName(".copyload"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002815 }
2816
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002817 if (IntTy && !IsWholeAlloca && IsDest) {
2818 StoreInst *Store = insertInteger(IRB, Src, BeginOffset);
2819 (void)Store;
2820 DEBUG(dbgs() << " to: " << *Store << "\n");
2821 return true;
2822 }
2823
Chandler Carruth713aa942012-09-14 09:22:59 +00002824 if (IsVectorElement && IsDest) {
2825 // We have to insert into a loaded copy before storing.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002826 Src = IRB.CreateInsertElement(
2827 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2828 Src, getIndex(IRB, BeginOffset),
2829 getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002830 }
2831
Chandler Carruth81b001a2012-09-26 10:27:46 +00002832 StoreInst *Store = cast<StoreInst>(
2833 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2834 (void)Store;
Chandler Carruth713aa942012-09-14 09:22:59 +00002835 DEBUG(dbgs() << " to: " << *Store << "\n");
2836 return !II.isVolatile();
2837 }
2838
2839 bool visitIntrinsicInst(IntrinsicInst &II) {
2840 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2841 II.getIntrinsicID() == Intrinsic::lifetime_end);
2842 DEBUG(dbgs() << " original: " << II << "\n");
2843 IRBuilder<> IRB(&II);
2844 assert(II.getArgOperand(1) == OldPtr);
2845
2846 // Record this instruction for deletion.
2847 if (Pass.DeadSplitInsts.insert(&II))
2848 Pass.DeadInsts.push_back(&II);
2849
2850 ConstantInt *Size
2851 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2852 EndOffset - BeginOffset);
2853 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2854 Value *New;
2855 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2856 New = IRB.CreateLifetimeStart(Ptr, Size);
2857 else
2858 New = IRB.CreateLifetimeEnd(Ptr, Size);
2859
2860 DEBUG(dbgs() << " to: " << *New << "\n");
2861 return true;
2862 }
2863
Chandler Carruth713aa942012-09-14 09:22:59 +00002864 bool visitPHINode(PHINode &PN) {
2865 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002866
Chandler Carruth713aa942012-09-14 09:22:59 +00002867 // We would like to compute a new pointer in only one place, but have it be
2868 // as local as possible to the PHI. To do that, we re-use the location of
2869 // the old pointer, which necessarily must be in the right position to
2870 // dominate the PHI.
2871 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2872
Chandler Carruth713aa942012-09-14 09:22:59 +00002873 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002874 // Replace the operands which were using the old pointer.
2875 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2876 for (; OI != OE; ++OI)
2877 if (*OI == OldPtr)
2878 *OI = NewPtr;
Chandler Carruth713aa942012-09-14 09:22:59 +00002879
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002880 DEBUG(dbgs() << " to: " << PN << "\n");
2881 deleteIfTriviallyDead(OldPtr);
2882 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002883 }
2884
2885 bool visitSelectInst(SelectInst &SI) {
2886 DEBUG(dbgs() << " original: " << SI << "\n");
2887 IRBuilder<> IRB(&SI);
2888
2889 // Find the operand we need to rewrite here.
2890 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2891 if (IsTrueVal)
2892 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2893 else
2894 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002895
Chandler Carruth713aa942012-09-14 09:22:59 +00002896 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002897 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2898 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00002899 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002900 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002901 }
2902
2903};
2904}
2905
Chandler Carruthc370acd2012-09-18 12:57:43 +00002906namespace {
2907/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2908///
2909/// This pass aggressively rewrites all aggregate loads and stores on
2910/// a particular pointer (or any pointer derived from it which we can identify)
2911/// with scalar loads and stores.
2912class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2913 // Befriend the base class so it can delegate to private visit methods.
2914 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2915
Micah Villmow3574eca2012-10-08 16:38:25 +00002916 const DataLayout &TD;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002917
2918 /// Queue of pointer uses to analyze and potentially rewrite.
2919 SmallVector<Use *, 8> Queue;
2920
2921 /// Set to prevent us from cycling with phi nodes and loops.
2922 SmallPtrSet<User *, 8> Visited;
2923
2924 /// The current pointer use being rewritten. This is used to dig up the used
2925 /// value (as opposed to the user).
2926 Use *U;
2927
2928public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002929 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00002930
2931 /// Rewrite loads and stores through a pointer and all pointers derived from
2932 /// it.
2933 bool rewrite(Instruction &I) {
2934 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2935 enqueueUsers(I);
2936 bool Changed = false;
2937 while (!Queue.empty()) {
2938 U = Queue.pop_back_val();
2939 Changed |= visit(cast<Instruction>(U->getUser()));
2940 }
2941 return Changed;
2942 }
2943
2944private:
2945 /// Enqueue all the users of the given instruction for further processing.
2946 /// This uses a set to de-duplicate users.
2947 void enqueueUsers(Instruction &I) {
2948 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2949 ++UI)
2950 if (Visited.insert(*UI))
2951 Queue.push_back(&UI.getUse());
2952 }
2953
2954 // Conservative default is to not rewrite anything.
2955 bool visitInstruction(Instruction &I) { return false; }
2956
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002957 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002958 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002959 class OpSplitter {
2960 protected:
2961 /// The builder used to form new instructions.
2962 IRBuilder<> IRB;
2963 /// The indices which to be used with insert- or extractvalue to select the
2964 /// appropriate value within the aggregate.
2965 SmallVector<unsigned, 4> Indices;
2966 /// The indices to a GEP instruction which will move Ptr to the correct slot
2967 /// within the aggregate.
2968 SmallVector<Value *, 4> GEPIndices;
2969 /// The base pointer of the original op, used as a base for GEPing the
2970 /// split operations.
2971 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002972
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002973 /// Initialize the splitter with an insertion point, Ptr and start with a
2974 /// single zero GEP index.
2975 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002976 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002977
2978 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002979 /// \brief Generic recursive split emission routine.
2980 ///
2981 /// This method recursively splits an aggregate op (load or store) into
2982 /// scalar or vector ops. It splits recursively until it hits a single value
2983 /// and emits that single value operation via the template argument.
2984 ///
2985 /// The logic of this routine relies on GEPs and insertvalue and
2986 /// extractvalue all operating with the same fundamental index list, merely
2987 /// formatted differently (GEPs need actual values).
2988 ///
2989 /// \param Ty The type being split recursively into smaller ops.
2990 /// \param Agg The aggregate value being built up or stored, depending on
2991 /// whether this is splitting a load or a store respectively.
2992 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2993 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002994 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002995
2996 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2997 unsigned OldSize = Indices.size();
2998 (void)OldSize;
2999 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3000 ++Idx) {
3001 assert(Indices.size() == OldSize && "Did not return to the old size");
3002 Indices.push_back(Idx);
3003 GEPIndices.push_back(IRB.getInt32(Idx));
3004 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3005 GEPIndices.pop_back();
3006 Indices.pop_back();
3007 }
3008 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003009 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00003010
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003011 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3012 unsigned OldSize = Indices.size();
3013 (void)OldSize;
3014 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3015 ++Idx) {
3016 assert(Indices.size() == OldSize && "Did not return to the old size");
3017 Indices.push_back(Idx);
3018 GEPIndices.push_back(IRB.getInt32(Idx));
3019 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3020 GEPIndices.pop_back();
3021 Indices.pop_back();
3022 }
3023 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003024 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003025
3026 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003027 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003028 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003029
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003030 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003031 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003032 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003033
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003034 /// Emit a leaf load of a single value. This is called at the leaves of the
3035 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003036 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003037 assert(Ty->isSingleValueType());
3038 // Load the single value and insert it using the indices.
3039 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3040 Name + ".gep"),
3041 Name + ".load");
3042 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3043 DEBUG(dbgs() << " to: " << *Load << "\n");
3044 }
3045 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003046
3047 bool visitLoadInst(LoadInst &LI) {
3048 assert(LI.getPointerOperand() == *U);
3049 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3050 return false;
3051
3052 // We have an aggregate being loaded, split it apart.
3053 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003054 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00003055 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003056 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003057 LI.replaceAllUsesWith(V);
3058 LI.eraseFromParent();
3059 return true;
3060 }
3061
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003062 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003063 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003064 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003065
3066 /// Emit a leaf store of a single value. This is called at the leaves of the
3067 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003068 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003069 assert(Ty->isSingleValueType());
3070 // Extract the single value and store it using the indices.
3071 Value *Store = IRB.CreateStore(
3072 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3073 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3074 (void)Store;
3075 DEBUG(dbgs() << " to: " << *Store << "\n");
3076 }
3077 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003078
3079 bool visitStoreInst(StoreInst &SI) {
3080 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3081 return false;
3082 Value *V = SI.getValueOperand();
3083 if (V->getType()->isSingleValueType())
3084 return false;
3085
3086 // We have an aggregate being stored, split it apart.
3087 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003088 StoreOpSplitter Splitter(&SI, *U);
3089 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003090 SI.eraseFromParent();
3091 return true;
3092 }
3093
3094 bool visitBitCastInst(BitCastInst &BC) {
3095 enqueueUsers(BC);
3096 return false;
3097 }
3098
3099 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3100 enqueueUsers(GEPI);
3101 return false;
3102 }
3103
3104 bool visitPHINode(PHINode &PN) {
3105 enqueueUsers(PN);
3106 return false;
3107 }
3108
3109 bool visitSelectInst(SelectInst &SI) {
3110 enqueueUsers(SI);
3111 return false;
3112 }
3113};
3114}
3115
Chandler Carruth07525a62012-10-13 10:49:33 +00003116/// \brief Strip aggregate type wrapping.
3117///
3118/// This removes no-op aggregate types wrapping an underlying type. It will
3119/// strip as many layers of types as it can without changing either the type
3120/// size or the allocated size.
3121static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3122 if (Ty->isSingleValueType())
3123 return Ty;
3124
3125 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3126 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3127
3128 Type *InnerTy;
3129 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3130 InnerTy = ArrTy->getElementType();
3131 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3132 const StructLayout *SL = DL.getStructLayout(STy);
3133 unsigned Index = SL->getElementContainingOffset(0);
3134 InnerTy = STy->getElementType(Index);
3135 } else {
3136 return Ty;
3137 }
3138
3139 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3140 TypeSize > DL.getTypeSizeInBits(InnerTy))
3141 return Ty;
3142
3143 return stripAggregateTypeWrapping(DL, InnerTy);
3144}
3145
Chandler Carruth713aa942012-09-14 09:22:59 +00003146/// \brief Try to find a partition of the aggregate type passed in for a given
3147/// offset and size.
3148///
3149/// This recurses through the aggregate type and tries to compute a subtype
3150/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00003151/// of an array, it will even compute a new array type for that sub-section,
3152/// and the same for structs.
3153///
3154/// Note that this routine is very strict and tries to find a partition of the
3155/// type which produces the *exact* right offset and size. It is not forgiving
3156/// when the size or offset cause either end of type-based partition to be off.
3157/// Also, this is a best-effort routine. It is reasonable to give up and not
3158/// return a type if necessary.
Micah Villmow3574eca2012-10-08 16:38:25 +00003159static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth713aa942012-09-14 09:22:59 +00003160 uint64_t Offset, uint64_t Size) {
3161 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruth07525a62012-10-13 10:49:33 +00003162 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carruth713aa942012-09-14 09:22:59 +00003163
3164 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3165 // We can't partition pointers...
3166 if (SeqTy->isPointerTy())
3167 return 0;
3168
3169 Type *ElementTy = SeqTy->getElementType();
3170 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3171 uint64_t NumSkippedElements = Offset / ElementSize;
3172 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3173 if (NumSkippedElements >= ArrTy->getNumElements())
3174 return 0;
3175 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3176 if (NumSkippedElements >= VecTy->getNumElements())
3177 return 0;
3178 Offset -= NumSkippedElements * ElementSize;
3179
3180 // First check if we need to recurse.
3181 if (Offset > 0 || Size < ElementSize) {
3182 // Bail if the partition ends in a different array element.
3183 if ((Offset + Size) > ElementSize)
3184 return 0;
3185 // Recurse through the element type trying to peel off offset bytes.
3186 return getTypePartition(TD, ElementTy, Offset, Size);
3187 }
3188 assert(Offset == 0);
3189
3190 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003191 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003192 assert(Size > ElementSize);
3193 uint64_t NumElements = Size / ElementSize;
3194 if (NumElements * ElementSize != Size)
3195 return 0;
3196 return ArrayType::get(ElementTy, NumElements);
3197 }
3198
3199 StructType *STy = dyn_cast<StructType>(Ty);
3200 if (!STy)
3201 return 0;
3202
3203 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003204 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00003205 return 0;
3206 uint64_t EndOffset = Offset + Size;
3207 if (EndOffset > SL->getSizeInBytes())
3208 return 0;
3209
3210 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00003211 Offset -= SL->getElementOffset(Index);
3212
3213 Type *ElementTy = STy->getElementType(Index);
3214 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3215 if (Offset >= ElementSize)
3216 return 0; // The offset points into alignment padding.
3217
3218 // See if any partition must be contained by the element.
3219 if (Offset > 0 || Size < ElementSize) {
3220 if ((Offset + Size) > ElementSize)
3221 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003222 return getTypePartition(TD, ElementTy, Offset, Size);
3223 }
3224 assert(Offset == 0);
3225
3226 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003227 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003228
3229 StructType::element_iterator EI = STy->element_begin() + Index,
3230 EE = STy->element_end();
3231 if (EndOffset < SL->getSizeInBytes()) {
3232 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3233 if (Index == EndIndex)
3234 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00003235
3236 // Don't try to form "natural" types if the elements don't line up with the
3237 // expected size.
3238 // FIXME: We could potentially recurse down through the last element in the
3239 // sub-struct to find a natural end point.
3240 if (SL->getElementOffset(EndIndex) != EndOffset)
3241 return 0;
3242
Chandler Carruth713aa942012-09-14 09:22:59 +00003243 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00003244 EE = STy->element_begin() + EndIndex;
3245 }
3246
3247 // Try to build up a sub-structure.
3248 SmallVector<Type *, 4> ElementTys;
3249 do {
3250 ElementTys.push_back(*EI++);
3251 } while (EI != EE);
3252 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
3253 STy->isPacked());
3254 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003255 if (Size != SubSL->getSizeInBytes())
3256 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00003257
Chandler Carruth6b547a22012-09-14 11:08:31 +00003258 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00003259}
3260
3261/// \brief Rewrite an alloca partition's users.
3262///
3263/// This routine drives both of the rewriting goals of the SROA pass. It tries
3264/// to rewrite uses of an alloca partition to be conducive for SSA value
3265/// promotion. If the partition needs a new, more refined alloca, this will
3266/// build that new alloca, preserving as much type information as possible, and
3267/// rewrite the uses of the old alloca to point at the new one and have the
3268/// appropriate new offsets. It also evaluates how successful the rewrite was
3269/// at enabling promotion and if it was successful queues the alloca to be
3270/// promoted.
3271bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3272 AllocaPartitioning &P,
3273 AllocaPartitioning::iterator PI) {
3274 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruthfdb15852012-10-02 18:57:13 +00003275 bool IsLive = false;
3276 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3277 UE = P.use_end(PI);
3278 UI != UE && !IsLive; ++UI)
3279 if (UI->U)
3280 IsLive = true;
3281 if (!IsLive)
Chandler Carruth713aa942012-09-14 09:22:59 +00003282 return false; // No live uses left of this partition.
3283
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003284 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3285 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3286
3287 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3288 DEBUG(dbgs() << " speculating ");
3289 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carrutha346f462012-10-02 17:49:47 +00003290 Speculator.visitUsers(PI);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003291
Chandler Carruth713aa942012-09-14 09:22:59 +00003292 // Try to compute a friendly type for this partition of the alloca. This
3293 // won't always succeed, in which case we fall back to a legal integer type
3294 // or an i8 array of an appropriate size.
3295 Type *AllocaTy = 0;
3296 if (Type *PartitionTy = P.getCommonType(PI))
3297 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3298 AllocaTy = PartitionTy;
3299 if (!AllocaTy)
3300 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3301 PI->BeginOffset, AllocaSize))
3302 AllocaTy = PartitionTy;
3303 if ((!AllocaTy ||
3304 (AllocaTy->isArrayTy() &&
3305 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3306 TD->isLegalInteger(AllocaSize * 8))
3307 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3308 if (!AllocaTy)
3309 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00003310 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00003311
3312 // Check for the case where we're going to rewrite to a new alloca of the
3313 // exact same type as the original, and with the same access offsets. In that
3314 // case, re-use the existing alloca, but still run through the rewriter to
3315 // performe phi and select speculation.
3316 AllocaInst *NewAI;
3317 if (AllocaTy == AI.getAllocatedType()) {
3318 assert(PI->BeginOffset == 0 &&
3319 "Non-zero begin offset but same alloca type");
3320 assert(PI == P.begin() && "Begin offset is zero on later partition");
3321 NewAI = &AI;
3322 } else {
Chandler Carruthb67c9a52012-09-29 10:41:21 +00003323 unsigned Alignment = AI.getAlignment();
3324 if (!Alignment) {
3325 // The minimum alignment which users can rely on when the explicit
3326 // alignment is omitted or zero is that required by the ABI for this
3327 // type.
3328 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3329 }
3330 Alignment = MinAlign(Alignment, PI->BeginOffset);
3331 // If we will get at least this much alignment from the type alone, leave
3332 // the alloca's alignment unconstrained.
3333 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3334 Alignment = 0;
3335 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth713aa942012-09-14 09:22:59 +00003336 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3337 &AI);
3338 ++NumNewAllocas;
3339 }
3340
3341 DEBUG(dbgs() << "Rewriting alloca partition "
3342 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3343 << *NewAI << "\n");
3344
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003345 // Track the high watermark of the post-promotion worklist. We will reset it
3346 // to this point if the alloca is not in fact scheduled for promotion.
3347 unsigned PPWOldSize = PostPromotionWorklist.size();
3348
Chandler Carruth713aa942012-09-14 09:22:59 +00003349 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3350 PI->BeginOffset, PI->EndOffset);
3351 DEBUG(dbgs() << " rewriting ");
3352 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003353 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3354 if (Promotable) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003355 DEBUG(dbgs() << " and queuing for promotion\n");
3356 PromotableAllocas.push_back(NewAI);
3357 } else if (NewAI != &AI) {
3358 // If we can't promote the alloca, iterate on it to check for new
3359 // refinements exposed by splitting the current alloca. Don't iterate on an
3360 // alloca which didn't actually change and didn't get promoted.
3361 Worklist.insert(NewAI);
3362 }
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003363
3364 // Drop any post-promotion work items if promotion didn't happen.
3365 if (!Promotable)
3366 while (PostPromotionWorklist.size() > PPWOldSize)
3367 PostPromotionWorklist.pop_back();
3368
Chandler Carruth713aa942012-09-14 09:22:59 +00003369 return true;
3370}
3371
3372/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3373bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3374 bool Changed = false;
3375 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3376 ++PI)
3377 Changed |= rewriteAllocaPartition(AI, P, PI);
3378
3379 return Changed;
3380}
3381
3382/// \brief Analyze an alloca for SROA.
3383///
3384/// This analyzes the alloca to ensure we can reason about it, builds
3385/// a partitioning of the alloca, and then hands it off to be split and
3386/// rewritten as needed.
3387bool SROA::runOnAlloca(AllocaInst &AI) {
3388 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3389 ++NumAllocasAnalyzed;
3390
3391 // Special case dead allocas, as they're trivial.
3392 if (AI.use_empty()) {
3393 AI.eraseFromParent();
3394 return true;
3395 }
3396
3397 // Skip alloca forms that this analysis can't handle.
3398 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3399 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3400 return false;
3401
Chandler Carruthc370acd2012-09-18 12:57:43 +00003402 bool Changed = false;
3403
3404 // First, split any FCA loads and stores touching this alloca to promote
3405 // better splitting and promotion opportunities.
3406 AggLoadStoreRewriter AggRewriter(*TD);
3407 Changed |= AggRewriter.rewrite(AI);
3408
Chandler Carruth713aa942012-09-14 09:22:59 +00003409 // Build the partition set using a recursive instruction-visiting builder.
3410 AllocaPartitioning P(*TD, AI);
3411 DEBUG(P.print(dbgs()));
3412 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003413 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003414
Chandler Carruth713aa942012-09-14 09:22:59 +00003415 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003416 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3417 DE = P.dead_user_end();
3418 DI != DE; ++DI) {
3419 Changed = true;
3420 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3421 DeadInsts.push_back(*DI);
3422 }
3423 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3424 DE = P.dead_op_end();
3425 DO != DE; ++DO) {
3426 Value *OldV = **DO;
3427 // Clobber the use with an undef value.
3428 **DO = UndefValue::get(OldV->getType());
3429 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3430 if (isInstructionTriviallyDead(OldI)) {
3431 Changed = true;
3432 DeadInsts.push_back(OldI);
3433 }
3434 }
3435
Chandler Carruthfca3f402012-10-05 01:29:09 +00003436 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3437 if (P.begin() == P.end())
3438 return Changed;
3439
Chandler Carruth713aa942012-09-14 09:22:59 +00003440 return splitAlloca(AI, P) || Changed;
3441}
3442
Chandler Carruth8615cd22012-09-14 10:26:38 +00003443/// \brief Delete the dead instructions accumulated in this run.
3444///
3445/// Recursively deletes the dead instructions we've accumulated. This is done
3446/// at the very end to maximize locality of the recursive delete and to
3447/// minimize the problems of invalidated instruction pointers as such pointers
3448/// are used heavily in the intermediate stages of the algorithm.
3449///
3450/// We also record the alloca instructions deleted here so that they aren't
3451/// subsequently handed to mem2reg to promote.
3452void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003453 DeadSplitInsts.clear();
3454 while (!DeadInsts.empty()) {
3455 Instruction *I = DeadInsts.pop_back_val();
3456 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3457
3458 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3459 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3460 // Zero out the operand and see if it becomes trivially dead.
3461 *OI = 0;
3462 if (isInstructionTriviallyDead(U))
3463 DeadInsts.push_back(U);
3464 }
3465
3466 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3467 DeletedAllocas.insert(AI);
3468
3469 ++NumDeleted;
3470 I->eraseFromParent();
3471 }
3472}
3473
Chandler Carruth1c8db502012-09-15 11:43:14 +00003474/// \brief Promote the allocas, using the best available technique.
3475///
3476/// This attempts to promote whatever allocas have been identified as viable in
3477/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3478/// If there is a domtree available, we attempt to promote using the full power
3479/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3480/// based on the SSAUpdater utilities. This function returns whether any
3481/// promotion occured.
3482bool SROA::promoteAllocas(Function &F) {
3483 if (PromotableAllocas.empty())
3484 return false;
3485
3486 NumPromoted += PromotableAllocas.size();
3487
3488 if (DT && !ForceSSAUpdater) {
3489 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3490 PromoteMemToReg(PromotableAllocas, *DT);
3491 PromotableAllocas.clear();
3492 return true;
3493 }
3494
3495 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3496 SSAUpdater SSA;
3497 DIBuilder DIB(*F.getParent());
3498 SmallVector<Instruction*, 64> Insts;
3499
3500 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3501 AllocaInst *AI = PromotableAllocas[Idx];
3502 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3503 UI != UE;) {
3504 Instruction *I = cast<Instruction>(*UI++);
3505 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3506 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3507 // leading to them) here. Eventually it should use them to optimize the
3508 // scalar values produced.
3509 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3510 assert(onlyUsedByLifetimeMarkers(I) &&
3511 "Found a bitcast used outside of a lifetime marker.");
3512 while (!I->use_empty())
3513 cast<Instruction>(*I->use_begin())->eraseFromParent();
3514 I->eraseFromParent();
3515 continue;
3516 }
3517 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3518 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3519 II->getIntrinsicID() == Intrinsic::lifetime_end);
3520 II->eraseFromParent();
3521 continue;
3522 }
3523
3524 Insts.push_back(I);
3525 }
3526 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3527 Insts.clear();
3528 }
3529
3530 PromotableAllocas.clear();
3531 return true;
3532}
3533
Chandler Carruth713aa942012-09-14 09:22:59 +00003534namespace {
3535 /// \brief A predicate to test whether an alloca belongs to a set.
3536 class IsAllocaInSet {
3537 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3538 const SetType &Set;
3539
3540 public:
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003541 typedef AllocaInst *argument_type;
3542
Chandler Carruth713aa942012-09-14 09:22:59 +00003543 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003544 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth713aa942012-09-14 09:22:59 +00003545 };
3546}
3547
3548bool SROA::runOnFunction(Function &F) {
3549 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3550 C = &F.getContext();
Micah Villmow3574eca2012-10-08 16:38:25 +00003551 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003552 if (!TD) {
3553 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3554 return false;
3555 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003556 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003557
3558 BasicBlock &EntryBB = F.getEntryBlock();
3559 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3560 I != E; ++I)
3561 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3562 Worklist.insert(AI);
3563
3564 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003565 // A set of deleted alloca instruction pointers which should be removed from
3566 // the list of promotable allocas.
3567 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3568
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003569 do {
3570 while (!Worklist.empty()) {
3571 Changed |= runOnAlloca(*Worklist.pop_back_val());
3572 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth5c5b3cf2012-10-02 22:46:45 +00003573
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003574 // Remove the deleted allocas from various lists so that we don't try to
3575 // continue processing them.
3576 if (!DeletedAllocas.empty()) {
3577 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3578 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3579 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3580 PromotableAllocas.end(),
3581 IsAllocaInSet(DeletedAllocas)),
3582 PromotableAllocas.end());
3583 DeletedAllocas.clear();
3584 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003585 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003586
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003587 Changed |= promoteAllocas(F);
3588
3589 Worklist = PostPromotionWorklist;
3590 PostPromotionWorklist.clear();
3591 } while (!Worklist.empty());
Chandler Carruth713aa942012-09-14 09:22:59 +00003592
3593 return Changed;
3594}
3595
3596void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003597 if (RequiresDomTree)
3598 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003599 AU.setPreservesCFG();
3600}