blob: 428aa8a472daa3cb32cfa4a7e19a8a8524062ef8 [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 Carrutha2b88162012-10-25 04:37:07 +0000585 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset,
586 bool IsVolatile) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000587 uint64_t Size = TD.getTypeStoreSize(Ty);
588
589 // If this memory access can be shown to *statically* extend outside the
590 // bounds of of the allocation, it's behavior is undefined, so simply
591 // ignore it. Note that this is more strict than the generic clamping
592 // behavior of insertUse. We also try to handle cases which might run the
593 // risk of overflow.
594 // FIXME: We should instead consider the pointer to have escaped if this
595 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000596 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
597 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000598 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
599 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
600 << " which extends past the end of the " << AllocSize
601 << " byte alloca:\n"
602 << " alloca: " << P.AI << "\n"
603 << " use: " << I << "\n");
604 return true;
605 }
606
Chandler Carrutha2b88162012-10-25 04:37:07 +0000607 // We allow splitting of loads and stores where the type is an integer type
608 // and which cover the entire alloca. Such integer loads and stores
609 // often require decomposition into fine grained loads and stores.
610 bool IsSplittable = false;
611 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
612 IsSplittable = !IsVolatile && ITy->getBitWidth() == AllocSize*8;
613
614 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth713aa942012-09-14 09:22:59 +0000615 return true;
616 }
617
618 bool visitBitCastInst(BitCastInst &BC) {
619 enqueueUsers(BC, Offset);
620 return true;
621 }
622
623 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000624 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000625 if (!computeConstantGEPOffset(GEPI, GEPOffset))
626 return markAsEscaping(GEPI);
627
628 enqueueUsers(GEPI, GEPOffset);
629 return true;
630 }
631
632 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000633 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
634 "All simple FCA loads should have been pre-split");
Chandler Carrutha2b88162012-10-25 04:37:07 +0000635 return handleLoadOrStore(LI.getType(), LI, Offset, LI.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +0000636 }
637
638 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000639 Value *ValOp = SI.getValueOperand();
640 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000641 return markAsEscaping(SI);
642
Chandler Carruthc370acd2012-09-18 12:57:43 +0000643 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
644 "All simple FCA stores should have been pre-split");
Chandler Carrutha2b88162012-10-25 04:37:07 +0000645 return handleLoadOrStore(ValOp->getType(), SI, Offset, SI.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +0000646 }
647
648
649 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000650 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000651 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000652 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
653 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000654 return true;
655 }
656
657 bool visitMemTransferInst(MemTransferInst &II) {
658 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
659 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
660 if (!Size)
661 // Zero-length mem transfer intrinsics can be ignored entirely.
662 return true;
663
664 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
665
666 // Only intrinsics with a constant length can be split.
667 Offsets.IsSplittable = Length;
668
Chandler Carruthfca3f402012-10-05 01:29:09 +0000669 if (*U == II.getRawDest()) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000670 Offsets.DestBegin = Offset;
671 Offsets.DestEnd = Offset + Size;
672 }
Chandler Carruthfca3f402012-10-05 01:29:09 +0000673 if (*U == II.getRawSource()) {
674 Offsets.SourceBegin = Offset;
675 Offsets.SourceEnd = Offset + Size;
676 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000677
Chandler Carruthfca3f402012-10-05 01:29:09 +0000678 // If we have set up end offsets for both the source and the destination,
679 // we have found both sides of this transfer pointing at the same alloca.
680 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
681 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
682 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth713aa942012-09-14 09:22:59 +0000683
Chandler Carruthfca3f402012-10-05 01:29:09 +0000684 // Check if the begin offsets match and this is a non-volatile transfer.
685 // In that case, we can completely elide the transfer.
686 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
687 P.Partitions[PrevIdx].kill();
688 return true;
689 }
690
691 // Otherwise we have an offset transfer within the same alloca. We can't
692 // split those.
693 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
694 } else if (SeenBothEnds) {
695 // Handle the case where this exact use provides both ends of the
696 // operation.
697 assert(II.getRawDest() == II.getRawSource());
698
699 // For non-volatile transfers this is a no-op.
700 if (!II.isVolatile())
701 return true;
702
703 // Otherwise just suppress splitting.
Chandler Carruth713aa942012-09-14 09:22:59 +0000704 Offsets.IsSplittable = false;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000705 }
706
707
708 // Insert the use now that we've fixed up the splittable nature.
709 insertUse(II, Offset, Size, Offsets.IsSplittable);
710
711 // Setup the mapping from intrinsic to partition of we've not seen both
712 // ends of this transfer.
713 if (!SeenBothEnds) {
714 unsigned NewIdx = P.Partitions.size() - 1;
715 bool Inserted
716 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
717 assert(Inserted &&
718 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi0559d312012-10-05 13:56:23 +0000719 (void)Inserted;
Chandler Carruth713aa942012-09-14 09:22:59 +0000720 }
721
722 return true;
723 }
724
725 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000726 // FIXME: What about debug instrinsics? This matches old behavior, but
727 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000728 bool visitIntrinsicInst(IntrinsicInst &II) {
729 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
730 II.getIntrinsicID() == Intrinsic::lifetime_end) {
731 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
732 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000733 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000734 return true;
735 }
736
737 return markAsEscaping(II);
738 }
739
740 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
741 // We consider any PHI or select that results in a direct load or store of
742 // the same offset to be a viable use for partitioning purposes. These uses
743 // are considered unsplittable and the size is the maximum loaded or stored
744 // size.
745 SmallPtrSet<Instruction *, 4> Visited;
746 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
747 Visited.insert(Root);
748 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000749 // If there are no loads or stores, the access is dead. We mark that as
750 // a size zero access.
751 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000752 do {
753 Instruction *I, *UsedI;
754 llvm::tie(UsedI, I) = Uses.pop_back_val();
755
756 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
757 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
758 continue;
759 }
760 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
761 Value *Op = SI->getOperand(0);
762 if (Op == UsedI)
763 return SI;
764 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
765 continue;
766 }
767
768 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
769 if (!GEP->hasAllZeroIndices())
770 return GEP;
771 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
772 !isa<SelectInst>(I)) {
773 return I;
774 }
775
776 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
777 ++UI)
778 if (Visited.insert(cast<Instruction>(*UI)))
779 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
780 } while (!Uses.empty());
781
782 return 0;
783 }
784
785 bool visitPHINode(PHINode &PN) {
786 // See if we already have computed info on this node.
787 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
788 if (PHIInfo.first) {
789 PHIInfo.second = true;
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 // Check for an unsafe use of the PHI node.
795 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
796 return markAsEscaping(*EscapingI);
797
Chandler Carruth63392ea2012-09-16 19:39:50 +0000798 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000799 return true;
800 }
801
802 bool visitSelectInst(SelectInst &SI) {
803 if (Value *Result = foldSelectInst(SI)) {
804 if (Result == *U)
805 // If the result of the constant fold will be the pointer, recurse
806 // through the select as if we had RAUW'ed it.
807 enqueueUsers(SI, Offset);
808
809 return true;
810 }
811
812 // See if we already have computed info on this node.
813 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
814 if (SelectInfo.first) {
815 SelectInfo.second = true;
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 // Check for an unsafe use of the PHI node.
821 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
822 return markAsEscaping(*EscapingI);
823
Chandler Carruth63392ea2012-09-16 19:39:50 +0000824 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000825 return true;
826 }
827
828 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
829 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
830};
831
832
833/// \brief Use adder for the alloca partitioning.
834///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000835/// This class adds the uses of an alloca to all of the partitions which they
836/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000837/// walk of the partitions, but the number of steps remains bounded by the
838/// total result instruction size:
839/// - The number of partitions is a result of the number unsplittable
840/// instructions using the alloca.
841/// - The number of users of each partition is at worst the total number of
842/// splittable instructions using the alloca.
843/// Thus we will produce N * M instructions in the end, where N are the number
844/// of unsplittable uses and M are the number of splittable. This visitor does
845/// the exact same number of updates to the partitioning.
846///
847/// In the more common case, this visitor will leverage the fact that the
848/// partition space is pre-sorted, and do a logarithmic search for the
849/// partition needed, making the total visit a classical ((N + M) * log(N))
850/// complexity operation.
851class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
852 friend class InstVisitor<UseBuilder>;
853
854 /// \brief Set to de-duplicate dead instructions found in the use walk.
855 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
856
857public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000858 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000859 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000860
861 /// \brief Run the builder over the allocation.
862 void operator()() {
863 // Note that we have to re-evaluate size on each trip through the loop as
864 // the queue grows at the tail.
865 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
866 U = Queue[Idx].U;
867 Offset = Queue[Idx].Offset;
868 this->visit(cast<Instruction>(U->getUser()));
869 }
870 }
871
872private:
873 void markAsDead(Instruction &I) {
874 if (VisitedDeadInsts.insert(&I))
875 P.DeadUsers.push_back(&I);
876 }
877
Chandler Carruth02e92a02012-09-23 11:43:14 +0000878 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000879 // If the use has a zero size or extends outside of the allocation, record
880 // it as a dead use for elimination later.
881 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000882 (Offset < 0 && (uint64_t)-Offset >= Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000883 return markAsDead(User);
884
Chandler Carruth02e92a02012-09-23 11:43:14 +0000885 // Clamp the start to the beginning of the allocation.
886 if (Offset < 0) {
887 Size -= (uint64_t)-Offset;
888 Offset = 0;
889 }
890
891 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
892
893 // Clamp the end offset to the end of the allocation. Note that this is
894 // formulated to handle even the case where "BeginOffset + Size" overflows.
895 assert(AllocSize >= BeginOffset); // Established above.
896 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000897 EndOffset = AllocSize;
898
899 // NB: This only works if we have zero overlapping partitions.
900 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
901 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
902 B = llvm::prior(B);
903 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
904 ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000905 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
906 std::min(I->EndOffset, EndOffset), U);
907 P.use_push_back(I, NewPU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000908 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth77c12702012-10-01 01:49:22 +0000909 P.PHIOrSelectOpMap[U]
Chandler Carruth713aa942012-09-14 09:22:59 +0000910 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
911 }
912 }
913
Chandler Carruth02e92a02012-09-23 11:43:14 +0000914 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000915 uint64_t Size = TD.getTypeStoreSize(Ty);
916
917 // If this memory access can be shown to *statically* extend outside the
918 // bounds of of the allocation, it's behavior is undefined, so simply
919 // ignore it. Note that this is more strict than the generic clamping
920 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000921 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
922 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000923 return markAsDead(I);
924
Chandler Carruth63392ea2012-09-16 19:39:50 +0000925 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000926 }
927
928 void visitBitCastInst(BitCastInst &BC) {
929 if (BC.use_empty())
930 return markAsDead(BC);
931
932 enqueueUsers(BC, Offset);
933 }
934
935 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
936 if (GEPI.use_empty())
937 return markAsDead(GEPI);
938
Chandler Carruth02e92a02012-09-23 11:43:14 +0000939 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000940 if (!computeConstantGEPOffset(GEPI, GEPOffset))
941 llvm_unreachable("Unable to compute constant offset for use");
942
943 enqueueUsers(GEPI, GEPOffset);
944 }
945
946 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000947 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000948 }
949
950 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000951 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000952 }
953
954 void visitMemSetInst(MemSetInst &II) {
955 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000956 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
957 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000958 }
959
960 void visitMemTransferInst(MemTransferInst &II) {
961 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000962 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
Chandler Carruthfca3f402012-10-05 01:29:09 +0000963 if (!Size)
964 return markAsDead(II);
965
966 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
967 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
968 Offsets.DestBegin == Offsets.SourceBegin)
969 return markAsDead(II); // Skip identity transfers without side-effects.
970
Chandler Carruth63392ea2012-09-16 19:39:50 +0000971 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000972 }
973
974 void visitIntrinsicInst(IntrinsicInst &II) {
975 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
976 II.getIntrinsicID() == Intrinsic::lifetime_end);
977
978 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000979 insertUse(II, Offset,
980 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000981 }
982
Chandler Carruth63392ea2012-09-16 19:39:50 +0000983 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000984 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
985
986 // For PHI and select operands outside the alloca, we can't nuke the entire
987 // phi or select -- the other side might still be relevant, so we special
988 // case them here and use a separate structure to track the operands
989 // themselves which should be replaced with undef.
990 if (Offset >= AllocSize) {
991 P.DeadOperands.push_back(U);
992 return;
993 }
994
Chandler Carruth63392ea2012-09-16 19:39:50 +0000995 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000996 }
997 void visitPHINode(PHINode &PN) {
998 if (PN.use_empty())
999 return markAsDead(PN);
1000
Chandler Carruth63392ea2012-09-16 19:39:50 +00001001 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00001002 }
1003 void visitSelectInst(SelectInst &SI) {
1004 if (SI.use_empty())
1005 return markAsDead(SI);
1006
1007 if (Value *Result = foldSelectInst(SI)) {
1008 if (Result == *U)
1009 // If the result of the constant fold will be the pointer, recurse
1010 // through the select as if we had RAUW'ed it.
1011 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +00001012 else
1013 // Otherwise the operand to the select is dead, and we can replace it
1014 // with undef.
1015 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +00001016
1017 return;
1018 }
1019
Chandler Carruth63392ea2012-09-16 19:39:50 +00001020 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00001021 }
1022
1023 /// \brief Unreachable, we've already visited the alloca once.
1024 void visitInstruction(Instruction &I) {
1025 llvm_unreachable("Unhandled instruction in use builder.");
1026 }
1027};
1028
1029void AllocaPartitioning::splitAndMergePartitions() {
1030 size_t NumDeadPartitions = 0;
1031
1032 // Track the range of splittable partitions that we pass when accumulating
1033 // overlapping unsplittable partitions.
1034 uint64_t SplitEndOffset = 0ull;
1035
1036 Partition New(0ull, 0ull, false);
1037
1038 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1039 ++j;
1040
1041 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1042 assert(New.BeginOffset == New.EndOffset);
1043 New = Partitions[i];
1044 } else {
1045 assert(New.IsSplittable);
1046 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1047 }
1048 assert(New.BeginOffset != New.EndOffset);
1049
1050 // Scan the overlapping partitions.
1051 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1052 // If the new partition we are forming is splittable, stop at the first
1053 // unsplittable partition.
1054 if (New.IsSplittable && !Partitions[j].IsSplittable)
1055 break;
1056
1057 // Grow the new partition to include any equally splittable range. 'j' is
1058 // always equally splittable when New is splittable, but when New is not
1059 // splittable, we may subsume some (or part of some) splitable partition
1060 // without growing the new one.
1061 if (New.IsSplittable == Partitions[j].IsSplittable) {
1062 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1063 } else {
1064 assert(!New.IsSplittable);
1065 assert(Partitions[j].IsSplittable);
1066 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1067 }
1068
Chandler Carruthfca3f402012-10-05 01:29:09 +00001069 Partitions[j].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001070 ++NumDeadPartitions;
1071 ++j;
1072 }
1073
1074 // If the new partition is splittable, chop off the end as soon as the
1075 // unsplittable subsequent partition starts and ensure we eventually cover
1076 // the splittable area.
1077 if (j != e && New.IsSplittable) {
1078 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1079 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1080 }
1081
1082 // Add the new partition if it differs from the original one and is
1083 // non-empty. We can end up with an empty partition here if it was
1084 // splittable but there is an unsplittable one that starts at the same
1085 // offset.
1086 if (New != Partitions[i]) {
1087 if (New.BeginOffset != New.EndOffset)
1088 Partitions.push_back(New);
1089 // Mark the old one for removal.
Chandler Carruthfca3f402012-10-05 01:29:09 +00001090 Partitions[i].kill();
Chandler Carruth713aa942012-09-14 09:22:59 +00001091 ++NumDeadPartitions;
1092 }
1093
1094 New.BeginOffset = New.EndOffset;
1095 if (!New.IsSplittable) {
1096 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1097 if (j != e && !Partitions[j].IsSplittable)
1098 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1099 New.IsSplittable = true;
1100 // If there is a trailing splittable partition which won't be fused into
1101 // the next splittable partition go ahead and add it onto the partitions
1102 // list.
1103 if (New.BeginOffset < New.EndOffset &&
1104 (j == e || !Partitions[j].IsSplittable ||
1105 New.EndOffset < Partitions[j].BeginOffset)) {
1106 Partitions.push_back(New);
1107 New.BeginOffset = New.EndOffset = 0ull;
1108 }
1109 }
1110 }
1111
1112 // Re-sort the partitions now that they have been split and merged into
1113 // disjoint set of partitions. Also remove any of the dead partitions we've
1114 // replaced in the process.
1115 std::sort(Partitions.begin(), Partitions.end());
1116 if (NumDeadPartitions) {
Chandler Carruthfca3f402012-10-05 01:29:09 +00001117 assert(Partitions.back().isDead());
Chandler Carruth713aa942012-09-14 09:22:59 +00001118 assert((ptrdiff_t)NumDeadPartitions ==
1119 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1120 }
1121 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1122}
1123
Micah Villmow3574eca2012-10-08 16:38:25 +00001124AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001125 :
1126#ifndef NDEBUG
1127 AI(AI),
1128#endif
1129 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001130 PartitionBuilder PB(TD, AI, *this);
1131 if (!PB())
1132 return;
1133
Chandler Carruthfca3f402012-10-05 01:29:09 +00001134 // Sort the uses. This arranges for the offsets to be in ascending order,
1135 // and the sizes to be in descending order.
1136 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth713aa942012-09-14 09:22:59 +00001137
Chandler Carruthfca3f402012-10-05 01:29:09 +00001138 // Remove any partitions from the back which are marked as dead.
1139 while (!Partitions.empty() && Partitions.back().isDead())
1140 Partitions.pop_back();
1141
1142 if (Partitions.size() > 1) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001143 // Intersect splittability for all partitions with equal offsets and sizes.
1144 // Then remove all but the first so that we have a sequence of non-equal but
1145 // potentially overlapping partitions.
1146 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1147 I = J) {
1148 ++J;
1149 while (J != E && *I == *J) {
1150 I->IsSplittable &= J->IsSplittable;
1151 ++J;
1152 }
1153 }
1154 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1155 Partitions.end());
1156
1157 // Split splittable and merge unsplittable partitions into a disjoint set
1158 // of partitions over the used space of the allocation.
1159 splitAndMergePartitions();
1160 }
1161
1162 // Now build up the user lists for each of these disjoint partitions by
1163 // re-walking the recursive users of the alloca.
1164 Uses.resize(Partitions.size());
1165 UseBuilder UB(TD, AI, *this);
1166 UB();
Chandler Carruth713aa942012-09-14 09:22:59 +00001167}
1168
1169Type *AllocaPartitioning::getCommonType(iterator I) const {
1170 Type *Ty = 0;
1171 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001172 if (!UI->U)
1173 continue; // Skip dead uses.
Chandler Carruth77c12702012-10-01 01:49:22 +00001174 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth713aa942012-09-14 09:22:59 +00001175 continue;
1176 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001177 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001178
1179 Type *UserTy = 0;
Chandler Carruth77c12702012-10-01 01:49:22 +00001180 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001181 UserTy = LI->getType();
Chandler Carruth77c12702012-10-01 01:49:22 +00001182 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001183 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha2b88162012-10-25 04:37:07 +00001184 } else {
1185 return 0; // Bail if we have weird uses.
1186 }
1187
1188 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1189 // If the type is larger than the partition, skip it. We only encounter
1190 // this for split integer operations where we want to use the type of the
1191 // entity causing the split.
1192 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1193 continue;
1194
1195 // If we have found an integer type use covering the alloca, use that
1196 // regardless of the other types, as integers are often used for a "bucket
1197 // of bits" type.
1198 return ITy;
Chandler Carruth713aa942012-09-14 09:22:59 +00001199 }
1200
1201 if (Ty && Ty != UserTy)
1202 return 0;
1203
1204 Ty = UserTy;
1205 }
1206 return Ty;
1207}
1208
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001209#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1210
Chandler Carruth713aa942012-09-14 09:22:59 +00001211void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1212 StringRef Indent) const {
1213 OS << Indent << "partition #" << (I - begin())
1214 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1215 << (I->IsSplittable ? " (splittable)" : "")
1216 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1217 << "\n";
1218}
1219
1220void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1221 StringRef Indent) const {
1222 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1223 UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001224 if (!UI->U)
1225 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00001226 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth77c12702012-10-01 01:49:22 +00001227 << "used by: " << *UI->U->getUser() << "\n";
1228 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001229 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1230 bool IsDest;
1231 if (!MTO.IsSplittable)
1232 IsDest = UI->BeginOffset == MTO.DestBegin;
1233 else
1234 IsDest = MTO.DestBegin != 0u;
1235 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1236 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1237 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1238 }
1239 }
1240}
1241
1242void AllocaPartitioning::print(raw_ostream &OS) const {
1243 if (PointerEscapingInstr) {
1244 OS << "No partitioning for alloca: " << AI << "\n"
1245 << " A pointer to this alloca escaped by:\n"
1246 << " " << *PointerEscapingInstr << "\n";
1247 return;
1248 }
1249
1250 OS << "Partitioning of alloca: " << AI << "\n";
1251 unsigned Num = 0;
1252 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1253 print(OS, I);
1254 printUsers(OS, I);
1255 }
1256}
1257
1258void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1259void AllocaPartitioning::dump() const { print(dbgs()); }
1260
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001261#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1262
Chandler Carruth713aa942012-09-14 09:22:59 +00001263
1264namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001265/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1266///
1267/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1268/// the loads and stores of an alloca instruction, as well as updating its
1269/// debug information. This is used when a domtree is unavailable and thus
1270/// mem2reg in its full form can't be used to handle promotion of allocas to
1271/// scalar values.
1272class AllocaPromoter : public LoadAndStorePromoter {
1273 AllocaInst &AI;
1274 DIBuilder &DIB;
1275
1276 SmallVector<DbgDeclareInst *, 4> DDIs;
1277 SmallVector<DbgValueInst *, 4> DVIs;
1278
1279public:
1280 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1281 AllocaInst &AI, DIBuilder &DIB)
1282 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1283
1284 void run(const SmallVectorImpl<Instruction*> &Insts) {
1285 // Remember which alloca we're promoting (for isInstInList).
1286 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1287 for (Value::use_iterator UI = DebugNode->use_begin(),
1288 UE = DebugNode->use_end();
1289 UI != UE; ++UI)
1290 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1291 DDIs.push_back(DDI);
1292 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1293 DVIs.push_back(DVI);
1294 }
1295
1296 LoadAndStorePromoter::run(Insts);
1297 AI.eraseFromParent();
1298 while (!DDIs.empty())
1299 DDIs.pop_back_val()->eraseFromParent();
1300 while (!DVIs.empty())
1301 DVIs.pop_back_val()->eraseFromParent();
1302 }
1303
1304 virtual bool isInstInList(Instruction *I,
1305 const SmallVectorImpl<Instruction*> &Insts) const {
1306 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1307 return LI->getOperand(0) == &AI;
1308 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1309 }
1310
1311 virtual void updateDebugInfo(Instruction *Inst) const {
1312 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1313 E = DDIs.end(); I != E; ++I) {
1314 DbgDeclareInst *DDI = *I;
1315 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1316 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1317 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1318 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1319 }
1320 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1321 E = DVIs.end(); I != E; ++I) {
1322 DbgValueInst *DVI = *I;
1323 Value *Arg = NULL;
1324 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1325 // If an argument is zero extended then use argument directly. The ZExt
1326 // may be zapped by an optimization pass in future.
1327 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1328 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1329 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1330 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1331 if (!Arg)
1332 Arg = SI->getOperand(0);
1333 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1334 Arg = LI->getOperand(0);
1335 } else {
1336 continue;
1337 }
1338 Instruction *DbgVal =
1339 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1340 Inst);
1341 DbgVal->setDebugLoc(DVI->getDebugLoc());
1342 }
1343 }
1344};
1345} // end anon namespace
1346
1347
1348namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001349/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1350///
1351/// This pass takes allocations which can be completely analyzed (that is, they
1352/// don't escape) and tries to turn them into scalar SSA values. There are
1353/// a few steps to this process.
1354///
1355/// 1) It takes allocations of aggregates and analyzes the ways in which they
1356/// are used to try to split them into smaller allocations, ideally of
1357/// a single scalar data type. It will split up memcpy and memset accesses
1358/// as necessary and try to isolate invidual scalar accesses.
1359/// 2) It will transform accesses into forms which are suitable for SSA value
1360/// promotion. This can be replacing a memset with a scalar store of an
1361/// integer value, or it can involve speculating operations on a PHI or
1362/// select to be a PHI or select of the results.
1363/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1364/// onto insert and extract operations on a vector value, and convert them to
1365/// this form. By doing so, it will enable promotion of vector aggregates to
1366/// SSA vector values.
1367class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001368 const bool RequiresDomTree;
1369
Chandler Carruth713aa942012-09-14 09:22:59 +00001370 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +00001371 const DataLayout *TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00001372 DominatorTree *DT;
1373
1374 /// \brief Worklist of alloca instructions to simplify.
1375 ///
1376 /// Each alloca in the function is added to this. Each new alloca formed gets
1377 /// added to it as well to recursively simplify unless that alloca can be
1378 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1379 /// the one being actively rewritten, we add it back onto the list if not
1380 /// already present to ensure it is re-visited.
1381 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1382
1383 /// \brief A collection of instructions to delete.
1384 /// We try to batch deletions to simplify code and make things a bit more
1385 /// efficient.
1386 SmallVector<Instruction *, 8> DeadInsts;
1387
1388 /// \brief A set to prevent repeatedly marking an instruction split into many
1389 /// uses as dead. Only used to guard insertion into DeadInsts.
1390 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1391
Chandler Carruthb2d98c22012-10-04 12:33:50 +00001392 /// \brief Post-promotion worklist.
1393 ///
1394 /// Sometimes we discover an alloca which has a high probability of becoming
1395 /// viable for SROA after a round of promotion takes place. In those cases,
1396 /// the alloca is enqueued here for re-processing.
1397 ///
1398 /// Note that we have to be very careful to clear allocas out of this list in
1399 /// the event they are deleted.
1400 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1401
Chandler Carruth713aa942012-09-14 09:22:59 +00001402 /// \brief A collection of alloca instructions we can directly promote.
1403 std::vector<AllocaInst *> PromotableAllocas;
1404
1405public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001406 SROA(bool RequiresDomTree = true)
1407 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1408 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001409 initializeSROAPass(*PassRegistry::getPassRegistry());
1410 }
1411 bool runOnFunction(Function &F);
1412 void getAnalysisUsage(AnalysisUsage &AU) const;
1413
1414 const char *getPassName() const { return "SROA"; }
1415 static char ID;
1416
1417private:
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001418 friend class PHIOrSelectSpeculator;
Chandler Carruth713aa942012-09-14 09:22:59 +00001419 friend class AllocaPartitionRewriter;
1420 friend class AllocaPartitionVectorRewriter;
1421
1422 bool rewriteAllocaPartition(AllocaInst &AI,
1423 AllocaPartitioning &P,
1424 AllocaPartitioning::iterator PI);
1425 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1426 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001427 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001428 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001429};
1430}
1431
1432char SROA::ID = 0;
1433
Chandler Carruth1c8db502012-09-15 11:43:14 +00001434FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1435 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001436}
1437
1438INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1439 false, false)
1440INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1441INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1442 false, false)
1443
Chandler Carruth0e9da582012-10-05 01:29:06 +00001444namespace {
1445/// \brief Visitor to speculate PHIs and Selects where possible.
1446class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1447 // Befriend the base class so it can delegate to private visit methods.
1448 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1449
Micah Villmow3574eca2012-10-08 16:38:25 +00001450 const DataLayout &TD;
Chandler Carruth0e9da582012-10-05 01:29:06 +00001451 AllocaPartitioning &P;
1452 SROA &Pass;
1453
1454public:
Micah Villmow3574eca2012-10-08 16:38:25 +00001455 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth0e9da582012-10-05 01:29:06 +00001456 : TD(TD), P(P), Pass(Pass) {}
1457
1458 /// \brief Visit the users of an alloca partition and rewrite them.
1459 void visitUsers(AllocaPartitioning::const_iterator PI) {
1460 // Note that we need to use an index here as the underlying vector of uses
1461 // may be grown during speculation. However, we never need to re-visit the
1462 // new uses, and so we can use the initial size bound.
1463 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1464 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1465 if (!PU.U)
1466 continue; // Skip dead use.
1467
1468 visit(cast<Instruction>(PU.U->getUser()));
1469 }
1470 }
1471
1472private:
1473 // By default, skip this instruction.
1474 void visitInstruction(Instruction &I) {}
1475
1476 /// PHI instructions that use an alloca and are subsequently loaded can be
1477 /// rewritten to load both input pointers in the pred blocks and then PHI the
1478 /// results, allowing the load of the alloca to be promoted.
1479 /// From this:
1480 /// %P2 = phi [i32* %Alloca, i32* %Other]
1481 /// %V = load i32* %P2
1482 /// to:
1483 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1484 /// ...
1485 /// %V2 = load i32* %Other
1486 /// ...
1487 /// %V = phi [i32 %V1, i32 %V2]
1488 ///
1489 /// We can do this to a select if its only uses are loads and if the operands
1490 /// to the select can be loaded unconditionally.
1491 ///
1492 /// FIXME: This should be hoisted into a generic utility, likely in
1493 /// Transforms/Util/Local.h
1494 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1495 // For now, we can only do this promotion if the load is in the same block
1496 // as the PHI, and if there are no stores between the phi and load.
1497 // TODO: Allow recursive phi users.
1498 // TODO: Allow stores.
1499 BasicBlock *BB = PN.getParent();
1500 unsigned MaxAlign = 0;
1501 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1502 UI != UE; ++UI) {
1503 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1504 if (LI == 0 || !LI->isSimple()) return false;
1505
1506 // For now we only allow loads in the same block as the PHI. This is
1507 // a common case that happens when instcombine merges two loads through
1508 // a PHI.
1509 if (LI->getParent() != BB) return false;
1510
1511 // Ensure that there are no instructions between the PHI and the load that
1512 // could store.
1513 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1514 if (BBI->mayWriteToMemory())
1515 return false;
1516
1517 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1518 Loads.push_back(LI);
1519 }
1520
1521 // We can only transform this if it is safe to push the loads into the
1522 // predecessor blocks. The only thing to watch out for is that we can't put
1523 // a possibly trapping load in the predecessor if it is a critical edge.
1524 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1525 ++Idx) {
1526 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1527 Value *InVal = PN.getIncomingValue(Idx);
1528
1529 // If the value is produced by the terminator of the predecessor (an
1530 // invoke) or it has side-effects, there is no valid place to put a load
1531 // in the predecessor.
1532 if (TI == InVal || TI->mayHaveSideEffects())
1533 return false;
1534
1535 // If the predecessor has a single successor, then the edge isn't
1536 // critical.
1537 if (TI->getNumSuccessors() == 1)
1538 continue;
1539
1540 // If this pointer is always safe to load, or if we can prove that there
1541 // is already a load in the block, then we can move the load to the pred
1542 // block.
1543 if (InVal->isDereferenceablePointer() ||
1544 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1545 continue;
1546
1547 return false;
1548 }
1549
1550 return true;
1551 }
1552
1553 void visitPHINode(PHINode &PN) {
1554 DEBUG(dbgs() << " original: " << PN << "\n");
1555
1556 SmallVector<LoadInst *, 4> Loads;
1557 if (!isSafePHIToSpeculate(PN, Loads))
1558 return;
1559
1560 assert(!Loads.empty());
1561
1562 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1563 IRBuilder<> PHIBuilder(&PN);
1564 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1565 PN.getName() + ".sroa.speculated");
1566
1567 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1568 // matter which one we get and if any differ, it doesn't matter.
1569 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1570 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1571 unsigned Align = SomeLoad->getAlignment();
1572
1573 // Rewrite all loads of the PN to use the new PHI.
1574 do {
1575 LoadInst *LI = Loads.pop_back_val();
1576 LI->replaceAllUsesWith(NewPN);
1577 Pass.DeadInsts.push_back(LI);
1578 } while (!Loads.empty());
1579
1580 // Inject loads into all of the pred blocks.
1581 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1582 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1583 TerminatorInst *TI = Pred->getTerminator();
1584 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1585 Value *InVal = PN.getIncomingValue(Idx);
1586 IRBuilder<> PredBuilder(TI);
1587
1588 LoadInst *Load
1589 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1590 Pred->getName()));
1591 ++NumLoadsSpeculated;
1592 Load->setAlignment(Align);
1593 if (TBAATag)
1594 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1595 NewPN->addIncoming(Load, Pred);
1596
1597 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1598 if (!Ptr)
1599 // No uses to rewrite.
1600 continue;
1601
1602 // Try to lookup and rewrite any partition uses corresponding to this phi
1603 // input.
1604 AllocaPartitioning::iterator PI
1605 = P.findPartitionForPHIOrSelectOperand(InUse);
1606 if (PI == P.end())
1607 continue;
1608
1609 // Replace the Use in the PartitionUse for this operand with the Use
1610 // inside the load.
1611 AllocaPartitioning::use_iterator UI
1612 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1613 assert(isa<PHINode>(*UI->U->getUser()));
1614 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1615 }
1616 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1617 }
1618
1619 /// Select instructions that use an alloca and are subsequently loaded can be
1620 /// rewritten to load both input pointers and then select between the result,
1621 /// allowing the load of the alloca to be promoted.
1622 /// From this:
1623 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1624 /// %V = load i32* %P2
1625 /// to:
1626 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1627 /// %V2 = load i32* %Other
1628 /// %V = select i1 %cond, i32 %V1, i32 %V2
1629 ///
1630 /// We can do this to a select if its only uses are loads and if the operand
1631 /// to the select can be loaded unconditionally.
1632 bool isSafeSelectToSpeculate(SelectInst &SI,
1633 SmallVectorImpl<LoadInst *> &Loads) {
1634 Value *TValue = SI.getTrueValue();
1635 Value *FValue = SI.getFalseValue();
1636 bool TDerefable = TValue->isDereferenceablePointer();
1637 bool FDerefable = FValue->isDereferenceablePointer();
1638
1639 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1640 UI != UE; ++UI) {
1641 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1642 if (LI == 0 || !LI->isSimple()) return false;
1643
1644 // Both operands to the select need to be dereferencable, either
1645 // absolutely (e.g. allocas) or at this point because we can see other
1646 // accesses to it.
1647 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1648 LI->getAlignment(), &TD))
1649 return false;
1650 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1651 LI->getAlignment(), &TD))
1652 return false;
1653 Loads.push_back(LI);
1654 }
1655
1656 return true;
1657 }
1658
1659 void visitSelectInst(SelectInst &SI) {
1660 DEBUG(dbgs() << " original: " << SI << "\n");
1661 IRBuilder<> IRB(&SI);
1662
1663 // If the select isn't safe to speculate, just use simple logic to emit it.
1664 SmallVector<LoadInst *, 4> Loads;
1665 if (!isSafeSelectToSpeculate(SI, Loads))
1666 return;
1667
1668 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1669 AllocaPartitioning::iterator PIs[2];
1670 AllocaPartitioning::PartitionUse PUs[2];
1671 for (unsigned i = 0, e = 2; i != e; ++i) {
1672 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1673 if (PIs[i] != P.end()) {
1674 // If the pointer is within the partitioning, remove the select from
1675 // its uses. We'll add in the new loads below.
1676 AllocaPartitioning::use_iterator UI
1677 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1678 PUs[i] = *UI;
1679 // Clear out the use here so that the offsets into the use list remain
1680 // stable but this use is ignored when rewriting.
1681 UI->U = 0;
1682 }
1683 }
1684
1685 Value *TV = SI.getTrueValue();
1686 Value *FV = SI.getFalseValue();
1687 // Replace the loads of the select with a select of two loads.
1688 while (!Loads.empty()) {
1689 LoadInst *LI = Loads.pop_back_val();
1690
1691 IRB.SetInsertPoint(LI);
1692 LoadInst *TL =
1693 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1694 LoadInst *FL =
1695 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1696 NumLoadsSpeculated += 2;
1697
1698 // Transfer alignment and TBAA info if present.
1699 TL->setAlignment(LI->getAlignment());
1700 FL->setAlignment(LI->getAlignment());
1701 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1702 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1703 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1704 }
1705
1706 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1707 LI->getName() + ".sroa.speculated");
1708
1709 LoadInst *Loads[2] = { TL, FL };
1710 for (unsigned i = 0, e = 2; i != e; ++i) {
1711 if (PIs[i] != P.end()) {
1712 Use *LoadUse = &Loads[i]->getOperandUse(0);
1713 assert(PUs[i].U->get() == LoadUse->get());
1714 PUs[i].U = LoadUse;
1715 P.use_push_back(PIs[i], PUs[i]);
1716 }
1717 }
1718
1719 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1720 LI->replaceAllUsesWith(V);
1721 Pass.DeadInsts.push_back(LI);
1722 }
1723 }
1724};
1725}
1726
Chandler Carruth713aa942012-09-14 09:22:59 +00001727/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1728///
1729/// If the provided GEP is all-constant, the total byte offset formed by the
1730/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1731/// operands, the function returns false and the value of Offset is unmodified.
Micah Villmow3574eca2012-10-08 16:38:25 +00001732static bool accumulateGEPOffsets(const DataLayout &TD, GEPOperator &GEP,
Chandler Carruth713aa942012-09-14 09:22:59 +00001733 APInt &Offset) {
1734 APInt GEPOffset(Offset.getBitWidth(), 0);
1735 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1736 GTI != GTE; ++GTI) {
1737 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1738 if (!OpC)
1739 return false;
1740 if (OpC->isZero()) continue;
1741
1742 // Handle a struct index, which adds its field offset to the pointer.
1743 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1744 unsigned ElementIdx = OpC->getZExtValue();
1745 const StructLayout *SL = TD.getStructLayout(STy);
1746 GEPOffset += APInt(Offset.getBitWidth(),
1747 SL->getElementOffset(ElementIdx));
1748 continue;
1749 }
1750
1751 APInt TypeSize(Offset.getBitWidth(),
1752 TD.getTypeAllocSize(GTI.getIndexedType()));
1753 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1754 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1755 "vector element size is not a multiple of 8, cannot GEP over it");
1756 TypeSize = VTy->getScalarSizeInBits() / 8;
1757 }
1758
1759 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1760 }
1761 Offset = GEPOffset;
1762 return true;
1763}
1764
1765/// \brief Build a GEP out of a base pointer and indices.
1766///
1767/// This will return the BasePtr if that is valid, or build a new GEP
1768/// instruction using the IRBuilder if GEP-ing is needed.
1769static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1770 SmallVectorImpl<Value *> &Indices,
1771 const Twine &Prefix) {
1772 if (Indices.empty())
1773 return BasePtr;
1774
1775 // A single zero index is a no-op, so check for this and avoid building a GEP
1776 // in that case.
1777 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1778 return BasePtr;
1779
1780 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1781}
1782
1783/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1784/// TargetTy without changing the offset of the pointer.
1785///
1786/// This routine assumes we've already established a properly offset GEP with
1787/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1788/// zero-indices down through type layers until we find one the same as
1789/// TargetTy. If we can't find one with the same type, we at least try to use
1790/// one with the same size. If none of that works, we just produce the GEP as
1791/// indicated by Indices to have the correct offset.
Micah Villmow3574eca2012-10-08 16:38:25 +00001792static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001793 Value *BasePtr, Type *Ty, Type *TargetTy,
1794 SmallVectorImpl<Value *> &Indices,
1795 const Twine &Prefix) {
1796 if (Ty == TargetTy)
1797 return buildGEP(IRB, BasePtr, Indices, Prefix);
1798
1799 // See if we can descend into a struct and locate a field with the correct
1800 // type.
1801 unsigned NumLayers = 0;
1802 Type *ElementTy = Ty;
1803 do {
1804 if (ElementTy->isPointerTy())
1805 break;
1806 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1807 ElementTy = SeqTy->getElementType();
Chandler Carruth020d9d52012-10-17 07:22:16 +00001808 // Note that we use the default address space as this index is over an
1809 // array or a vector, not a pointer.
1810 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth713aa942012-09-14 09:22:59 +00001811 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth2fdb25b2012-10-09 01:58:35 +00001812 if (STy->element_begin() == STy->element_end())
1813 break; // Nothing left to descend into.
Chandler Carruth713aa942012-09-14 09:22:59 +00001814 ElementTy = *STy->element_begin();
1815 Indices.push_back(IRB.getInt32(0));
1816 } else {
1817 break;
1818 }
1819 ++NumLayers;
1820 } while (ElementTy != TargetTy);
1821 if (ElementTy != TargetTy)
1822 Indices.erase(Indices.end() - NumLayers, Indices.end());
1823
1824 return buildGEP(IRB, BasePtr, Indices, Prefix);
1825}
1826
1827/// \brief Recursively compute indices for a natural GEP.
1828///
1829/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1830/// element types adding appropriate indices for the GEP.
Micah Villmow3574eca2012-10-08 16:38:25 +00001831static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001832 Value *Ptr, Type *Ty, APInt &Offset,
1833 Type *TargetTy,
1834 SmallVectorImpl<Value *> &Indices,
1835 const Twine &Prefix) {
1836 if (Offset == 0)
1837 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1838
1839 // We can't recurse through pointer types.
1840 if (Ty->isPointerTy())
1841 return 0;
1842
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001843 // We try to analyze GEPs over vectors here, but note that these GEPs are
1844 // extremely poorly defined currently. The long-term goal is to remove GEPing
1845 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001846 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1847 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1848 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001849 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001850 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001851 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001852 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1853 return 0;
1854 Offset -= NumSkippedElements * ElementSize;
1855 Indices.push_back(IRB.getInt(NumSkippedElements));
1856 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1857 Offset, TargetTy, Indices, Prefix);
1858 }
1859
1860 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1861 Type *ElementTy = ArrTy->getElementType();
1862 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001863 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001864 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1865 return 0;
1866
1867 Offset -= NumSkippedElements * ElementSize;
1868 Indices.push_back(IRB.getInt(NumSkippedElements));
1869 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1870 Indices, Prefix);
1871 }
1872
1873 StructType *STy = dyn_cast<StructType>(Ty);
1874 if (!STy)
1875 return 0;
1876
1877 const StructLayout *SL = TD.getStructLayout(STy);
1878 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001879 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001880 return 0;
1881 unsigned Index = SL->getElementContainingOffset(StructOffset);
1882 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1883 Type *ElementTy = STy->getElementType(Index);
1884 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1885 return 0; // The offset points into alignment padding.
1886
1887 Indices.push_back(IRB.getInt32(Index));
1888 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1889 Indices, Prefix);
1890}
1891
1892/// \brief Get a natural GEP from a base pointer to a particular offset and
1893/// resulting in a particular type.
1894///
1895/// The goal is to produce a "natural" looking GEP that works with the existing
1896/// composite types to arrive at the appropriate offset and element type for
1897/// a pointer. TargetTy is the element type the returned GEP should point-to if
1898/// possible. We recurse by decreasing Offset, adding the appropriate index to
1899/// Indices, and setting Ty to the result subtype.
1900///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001901/// If no natural GEP can be constructed, this function returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00001902static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001903 Value *Ptr, APInt Offset, Type *TargetTy,
1904 SmallVectorImpl<Value *> &Indices,
1905 const Twine &Prefix) {
1906 PointerType *Ty = cast<PointerType>(Ptr->getType());
1907
1908 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1909 // an i8.
1910 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1911 return 0;
1912
1913 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001914 if (!ElementTy->isSized())
1915 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001916 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1917 if (ElementSize == 0)
1918 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth02bf98a2012-10-17 09:23:48 +00001919 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00001920
1921 Offset -= NumSkippedElements * ElementSize;
1922 Indices.push_back(IRB.getInt(NumSkippedElements));
1923 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1924 Indices, Prefix);
1925}
1926
1927/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1928/// resulting pointer has PointerTy.
1929///
1930/// This tries very hard to compute a "natural" GEP which arrives at the offset
1931/// and produces the pointer type desired. Where it cannot, it will try to use
1932/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1933/// fails, it will try to use an existing i8* and GEP to the byte offset and
1934/// bitcast to the type.
1935///
1936/// The strategy for finding the more natural GEPs is to peel off layers of the
1937/// pointer, walking back through bit casts and GEPs, searching for a base
1938/// pointer from which we can compute a natural GEP with the desired
1939/// properities. The algorithm tries to fold as many constant indices into
1940/// a single GEP as possible, thus making each GEP more independent of the
1941/// surrounding code.
Micah Villmow3574eca2012-10-08 16:38:25 +00001942static Value *getAdjustedPtr(IRBuilder<> &IRB, const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00001943 Value *Ptr, APInt Offset, Type *PointerTy,
1944 const Twine &Prefix) {
1945 // Even though we don't look through PHI nodes, we could be called on an
1946 // instruction in an unreachable block, which may be on a cycle.
1947 SmallPtrSet<Value *, 4> Visited;
1948 Visited.insert(Ptr);
1949 SmallVector<Value *, 4> Indices;
1950
1951 // We may end up computing an offset pointer that has the wrong type. If we
1952 // never are able to compute one directly that has the correct type, we'll
1953 // fall back to it, so keep it around here.
1954 Value *OffsetPtr = 0;
1955
1956 // Remember any i8 pointer we come across to re-use if we need to do a raw
1957 // byte offset.
1958 Value *Int8Ptr = 0;
1959 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1960
1961 Type *TargetTy = PointerTy->getPointerElementType();
1962
1963 do {
1964 // First fold any existing GEPs into the offset.
1965 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1966 APInt GEPOffset(Offset.getBitWidth(), 0);
1967 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1968 break;
1969 Offset += GEPOffset;
1970 Ptr = GEP->getPointerOperand();
1971 if (!Visited.insert(Ptr))
1972 break;
1973 }
1974
1975 // See if we can perform a natural GEP here.
1976 Indices.clear();
1977 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1978 Indices, Prefix)) {
1979 if (P->getType() == PointerTy) {
1980 // Zap any offset pointer that we ended up computing in previous rounds.
1981 if (OffsetPtr && OffsetPtr->use_empty())
1982 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1983 I->eraseFromParent();
1984 return P;
1985 }
1986 if (!OffsetPtr) {
1987 OffsetPtr = P;
1988 }
1989 }
1990
1991 // Stash this pointer if we've found an i8*.
1992 if (Ptr->getType()->isIntegerTy(8)) {
1993 Int8Ptr = Ptr;
1994 Int8PtrOffset = Offset;
1995 }
1996
1997 // Peel off a layer of the pointer and update the offset appropriately.
1998 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1999 Ptr = cast<Operator>(Ptr)->getOperand(0);
2000 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2001 if (GA->mayBeOverridden())
2002 break;
2003 Ptr = GA->getAliasee();
2004 } else {
2005 break;
2006 }
2007 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
2008 } while (Visited.insert(Ptr));
2009
2010 if (!OffsetPtr) {
2011 if (!Int8Ptr) {
2012 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
2013 Prefix + ".raw_cast");
2014 Int8PtrOffset = Offset;
2015 }
2016
2017 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
2018 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
2019 Prefix + ".raw_idx");
2020 }
2021 Ptr = OffsetPtr;
2022
2023 // On the off chance we were targeting i8*, guard the bitcast here.
2024 if (Ptr->getType() != PointerTy)
2025 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
2026
2027 return Ptr;
2028}
2029
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002030/// \brief Test whether we can convert a value from the old to the new type.
2031///
2032/// This predicate should be used to guard calls to convertValue in order to
2033/// ensure that we only try to convert viable values. The strategy is that we
2034/// will peel off single element struct and array wrappings to get to an
2035/// underlying value, and convert that value.
2036static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
2037 if (OldTy == NewTy)
2038 return true;
2039 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
2040 return false;
2041 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
2042 return false;
2043
2044 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
2045 if (NewTy->isPointerTy() && OldTy->isPointerTy())
2046 return true;
2047 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
2048 return true;
2049 return false;
2050 }
2051
2052 return true;
2053}
2054
2055/// \brief Generic routine to convert an SSA value to a value of a different
2056/// type.
2057///
2058/// This will try various different casting techniques, such as bitcasts,
2059/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2060/// two types for viability with this routine.
2061static Value *convertValue(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2062 Type *Ty) {
2063 assert(canConvertValue(DL, V->getType(), Ty) &&
2064 "Value not convertable to type");
2065 if (V->getType() == Ty)
2066 return V;
2067 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2068 return IRB.CreateIntToPtr(V, Ty);
2069 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2070 return IRB.CreatePtrToInt(V, Ty);
2071
2072 return IRB.CreateBitCast(V, Ty);
2073}
2074
Chandler Carruth713aa942012-09-14 09:22:59 +00002075/// \brief Test whether the given alloca partition can be promoted to a vector.
2076///
2077/// This is a quick test to check whether we can rewrite a particular alloca
2078/// partition (and its newly formed alloca) into a vector alloca with only
2079/// whole-vector loads and stores such that it could be promoted to a vector
2080/// SSA value. We only can ensure this for a limited set of operations, and we
2081/// don't want to do the rewrites unless we are confident that the result will
2082/// be promotable, so we have an early test here.
Micah Villmow3574eca2012-10-08 16:38:25 +00002083static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth713aa942012-09-14 09:22:59 +00002084 Type *AllocaTy,
2085 AllocaPartitioning &P,
2086 uint64_t PartitionBeginOffset,
2087 uint64_t PartitionEndOffset,
2088 AllocaPartitioning::const_use_iterator I,
2089 AllocaPartitioning::const_use_iterator E) {
2090 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2091 if (!Ty)
2092 return false;
2093
2094 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
2095 uint64_t ElementSize = Ty->getScalarSizeInBits();
2096
2097 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2098 // that aren't byte sized.
2099 if (ElementSize % 8)
2100 return false;
2101 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
2102 VecSize /= 8;
2103 ElementSize /= 8;
2104
2105 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002106 if (!I->U)
2107 continue; // Skip dead use.
2108
Chandler Carruth713aa942012-09-14 09:22:59 +00002109 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2110 uint64_t BeginIndex = BeginOffset / ElementSize;
2111 if (BeginIndex * ElementSize != BeginOffset ||
2112 BeginIndex >= Ty->getNumElements())
2113 return false;
2114 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2115 uint64_t EndIndex = EndOffset / ElementSize;
2116 if (EndIndex * ElementSize != EndOffset ||
2117 EndIndex > Ty->getNumElements())
2118 return false;
2119
2120 // FIXME: We should build shuffle vector instructions to handle
2121 // non-element-sized accesses.
2122 if ((EndOffset - BeginOffset) != ElementSize &&
2123 (EndOffset - BeginOffset) != VecSize)
2124 return false;
2125
Chandler Carruth77c12702012-10-01 01:49:22 +00002126 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002127 if (MI->isVolatile())
2128 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002129 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002130 const AllocaPartitioning::MemTransferOffsets &MTO
2131 = P.getMemTransferOffsets(*MTI);
2132 if (!MTO.IsSplittable)
2133 return false;
2134 }
Chandler Carruth77c12702012-10-01 01:49:22 +00002135 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002136 // Disable vector promotion when there are loads or stores of an FCA.
2137 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002138 } else if (!isa<LoadInst>(I->U->getUser()) &&
2139 !isa<StoreInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002140 return false;
2141 }
2142 }
2143 return true;
2144}
2145
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002146/// \brief Test whether the given alloca partition's integer operations can be
2147/// widened to promotable ones.
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002148///
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002149/// This is a quick test to check whether we can rewrite the integer loads and
2150/// stores to a particular alloca into wider loads and stores and be able to
2151/// promote the resulting alloca.
2152static bool isIntegerWideningViable(const DataLayout &TD,
2153 Type *AllocaTy,
2154 uint64_t AllocBeginOffset,
2155 AllocaPartitioning &P,
2156 AllocaPartitioning::const_use_iterator I,
2157 AllocaPartitioning::const_use_iterator E) {
2158 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
2159
2160 // Don't try to handle allocas with bit-padding.
2161 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002162 return false;
2163
Chandler Carrutha2b88162012-10-25 04:37:07 +00002164 // We need to ensure that an integer type with the appropriate bitwidth can
2165 // be converted to the alloca type, whatever that is. We don't want to force
2166 // the alloca itself to have an integer type if there is a more suitable one.
2167 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2168 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2169 !canConvertValue(TD, IntTy, AllocaTy))
2170 return false;
2171
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002172 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2173
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002174 // Check the uses to ensure the uses are (likely) promoteable integer uses.
2175 // Also ensure that the alloca has a covering load or store. We don't want
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002176 // to widen the integer operotains only to fail to promote due to some other
2177 // unsplittable entry (which we may make splittable later).
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002178 bool WholeAllocaOp = false;
2179 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002180 if (!I->U)
2181 continue; // Skip dead use.
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002182
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002183 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2184 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2185
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002186 // We can't reasonably handle cases where the load or store extends past
2187 // the end of the aloca's type and into its padding.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002188 if (RelEnd > Size)
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002189 return false;
2190
Chandler Carruth77c12702012-10-01 01:49:22 +00002191 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002192 if (LI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002193 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002194 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002195 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002196 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2197 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2198 return false;
2199 continue;
2200 }
2201 // Non-integer loads need to be convertible from the alloca type so that
2202 // they are promotable.
2203 if (RelBegin != 0 || RelEnd != Size ||
2204 !canConvertValue(TD, AllocaTy, LI->getType()))
2205 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002206 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002207 Type *ValueTy = SI->getValueOperand()->getType();
2208 if (SI->isVolatile())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002209 return false;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002210 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002211 WholeAllocaOp = true;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002212 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2213 if (ITy->getBitWidth() < TD.getTypeStoreSize(ITy))
2214 return false;
2215 continue;
2216 }
2217 // Non-integer stores need to be convertible to the alloca type so that
2218 // they are promotable.
2219 if (RelBegin != 0 || RelEnd != Size ||
2220 !canConvertValue(TD, ValueTy, AllocaTy))
2221 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002222 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002223 if (MI->isVolatile())
2224 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00002225 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002226 const AllocaPartitioning::MemTransferOffsets &MTO
2227 = P.getMemTransferOffsets(*MTI);
2228 if (!MTO.IsSplittable)
2229 return false;
2230 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002231 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->U->getUser())) {
2232 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2233 II->getIntrinsicID() != Intrinsic::lifetime_end)
2234 return false;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002235 } else {
2236 return false;
2237 }
2238 }
2239 return WholeAllocaOp;
2240}
2241
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002242static Value *extractInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *V,
2243 IntegerType *Ty, uint64_t Offset,
2244 const Twine &Name) {
2245 IntegerType *IntTy = cast<IntegerType>(V->getType());
2246 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2247 "Element extends past full value");
2248 uint64_t ShAmt = 8*Offset;
2249 if (DL.isBigEndian())
2250 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2251 if (ShAmt)
2252 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2253 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2254 "Cannot extract to a larger integer!");
2255 if (Ty != IntTy)
2256 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2257 return V;
2258}
2259
2260static Value *insertInteger(const DataLayout &DL, IRBuilder<> &IRB, Value *Old,
2261 Value *V, uint64_t Offset, const Twine &Name) {
2262 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2263 IntegerType *Ty = cast<IntegerType>(V->getType());
2264 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2265 "Cannot insert a larger integer!");
2266 if (Ty != IntTy)
2267 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2268 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2269 "Element store outside of alloca store");
2270 uint64_t ShAmt = 8*Offset;
2271 if (DL.isBigEndian())
2272 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2273 if (ShAmt)
2274 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2275
2276 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2277 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2278 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2279 V = IRB.CreateOr(Old, V, Name + ".insert");
2280 }
2281 return V;
2282}
2283
Chandler Carruth713aa942012-09-14 09:22:59 +00002284namespace {
2285/// \brief Visitor to rewrite instructions using a partition of an alloca to
2286/// use a new alloca.
2287///
2288/// Also implements the rewriting to vector-based accesses when the partition
2289/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2290/// lives here.
2291class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2292 bool> {
2293 // Befriend the base class so it can delegate to private visit methods.
2294 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2295
Micah Villmow3574eca2012-10-08 16:38:25 +00002296 const DataLayout &TD;
Chandler Carruth713aa942012-09-14 09:22:59 +00002297 AllocaPartitioning &P;
2298 SROA &Pass;
2299 AllocaInst &OldAI, &NewAI;
2300 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth520eeae2012-10-13 02:41:05 +00002301 Type *NewAllocaTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00002302
2303 // If we are rewriting an alloca partition which can be written as pure
2304 // vector operations, we stash extra information here. When VecTy is
2305 // non-null, we have some strict guarantees about the rewriten alloca:
2306 // - The new alloca is exactly the size of the vector type here.
2307 // - The accesses all either map to the entire vector or to a single
2308 // element.
2309 // - The set of accessing instructions is only one of those handled above
2310 // in isVectorPromotionViable. Generally these are the same access kinds
2311 // which are promotable via mem2reg.
2312 VectorType *VecTy;
2313 Type *ElementTy;
2314 uint64_t ElementSize;
2315
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002316 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002317 // alloca's integer operations should be widened to this integer type due to
2318 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002319 // integer type will be stored here for easy access during rewriting.
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002320 IntegerType *IntTy;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002321
Chandler Carruth713aa942012-09-14 09:22:59 +00002322 // The offset of the partition user currently being rewritten.
2323 uint64_t BeginOffset, EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002324 Use *OldUse;
Chandler Carruth713aa942012-09-14 09:22:59 +00002325 Instruction *OldPtr;
2326
2327 // The name prefix to use when rewriting instructions for this alloca.
2328 std::string NamePrefix;
2329
2330public:
Micah Villmow3574eca2012-10-08 16:38:25 +00002331 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth713aa942012-09-14 09:22:59 +00002332 AllocaPartitioning::iterator PI,
2333 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2334 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2335 : TD(TD), P(P), Pass(Pass),
2336 OldAI(OldAI), NewAI(NewAI),
2337 NewAllocaBeginOffset(NewBeginOffset),
2338 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth520eeae2012-10-13 02:41:05 +00002339 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002340 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002341 BeginOffset(), EndOffset() {
2342 }
2343
2344 /// \brief Visit the users of the alloca partition and rewrite them.
2345 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2346 AllocaPartitioning::const_use_iterator E) {
2347 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2348 NewAllocaBeginOffset, NewAllocaEndOffset,
2349 I, E)) {
2350 ++NumVectorized;
2351 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2352 ElementTy = VecTy->getElementType();
2353 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2354 "Only multiple-of-8 sized vector elements are viable");
2355 ElementSize = VecTy->getScalarSizeInBits() / 8;
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002356 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2357 NewAllocaBeginOffset, P, I, E)) {
2358 IntTy = Type::getIntNTy(NewAI.getContext(),
2359 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002360 }
2361 bool CanSROA = true;
2362 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002363 if (!I->U)
2364 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00002365 BeginOffset = I->BeginOffset;
2366 EndOffset = I->EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002367 OldUse = I->U;
2368 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth713aa942012-09-14 09:22:59 +00002369 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth77c12702012-10-01 01:49:22 +00002370 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002371 }
2372 if (VecTy) {
2373 assert(CanSROA);
2374 VecTy = 0;
2375 ElementTy = 0;
2376 ElementSize = 0;
2377 }
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002378 if (IntTy) {
2379 assert(CanSROA);
2380 IntTy = 0;
2381 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002382 return CanSROA;
2383 }
2384
2385private:
2386 // Every instruction which can end up as a user must have a rewrite rule.
2387 bool visitInstruction(Instruction &I) {
2388 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2389 llvm_unreachable("No rewrite rule for this instruction!");
2390 }
2391
2392 Twine getName(const Twine &Suffix) {
2393 return NamePrefix + Suffix;
2394 }
2395
2396 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2397 assert(BeginOffset >= NewAllocaBeginOffset);
Micah Villmowb52fb872012-10-24 18:36:13 +00002398 assert(PointerTy->isPointerTy() &&
2399 "Type must be pointer type!");
2400 APInt Offset(TD.getTypeSizeInBits(PointerTy), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002401 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2402 }
2403
Chandler Carruthf710fb12012-10-03 08:14:02 +00002404 /// \brief Compute suitable alignment to access an offset into the new alloca.
2405 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth673850a2012-10-01 12:16:54 +00002406 unsigned NewAIAlign = NewAI.getAlignment();
2407 if (!NewAIAlign)
2408 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2409 return MinAlign(NewAIAlign, Offset);
2410 }
Chandler Carruthf710fb12012-10-03 08:14:02 +00002411
2412 /// \brief Compute suitable alignment to access this partition of the new
2413 /// alloca.
2414 unsigned getPartitionAlign() {
2415 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002416 }
2417
Chandler Carruthf710fb12012-10-03 08:14:02 +00002418 /// \brief Compute suitable alignment to access a type at an offset of the
2419 /// new alloca.
2420 ///
2421 /// \returns zero if the type's ABI alignment is a suitable alignment,
2422 /// otherwise returns the maximal suitable alignment.
2423 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2424 unsigned Align = getOffsetAlign(Offset);
2425 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2426 }
2427
2428 /// \brief Compute suitable alignment to access a type at the beginning of
2429 /// this partition of the new alloca.
2430 ///
2431 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2432 unsigned getPartitionTypeAlign(Type *Ty) {
2433 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002434 }
2435
Chandler Carruth713aa942012-09-14 09:22:59 +00002436 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
2437 assert(VecTy && "Can only call getIndex when rewriting a vector");
2438 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2439 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2440 uint32_t Index = RelOffset / ElementSize;
2441 assert(Index * ElementSize == RelOffset);
2442 return IRB.getInt32(Index);
2443 }
2444
2445 void deleteIfTriviallyDead(Value *V) {
2446 Instruction *I = cast<Instruction>(V);
2447 if (isInstructionTriviallyDead(I))
2448 Pass.DeadInsts.push_back(I);
2449 }
2450
Chandler Carruth713aa942012-09-14 09:22:59 +00002451 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2452 Value *Result;
2453 if (LI.getType() == VecTy->getElementType() ||
2454 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002455 Result = IRB.CreateExtractElement(
2456 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2457 getIndex(IRB, BeginOffset), getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002458 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002459 Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2460 getName(".load"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002461 }
2462 if (Result->getType() != LI.getType())
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002463 Result = convertValue(TD, IRB, Result, LI.getType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002464 LI.replaceAllUsesWith(Result);
2465 Pass.DeadInsts.push_back(&LI);
2466
2467 DEBUG(dbgs() << " to: " << *Result << "\n");
2468 return true;
2469 }
2470
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002471 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002472 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002473 assert(!LI.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002474 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2475 getName(".load"));
2476 V = convertValue(TD, IRB, V, IntTy);
2477 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2478 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2479 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
2480 getName(".extract"));
2481 LI.replaceAllUsesWith(V);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002482 Pass.DeadInsts.push_back(&LI);
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002483 DEBUG(dbgs() << " to: " << *V << "\n");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002484 return true;
2485 }
2486
Chandler Carruth713aa942012-09-14 09:22:59 +00002487 bool visitLoadInst(LoadInst &LI) {
2488 DEBUG(dbgs() << " original: " << LI << "\n");
2489 Value *OldOp = LI.getOperand(0);
2490 assert(OldOp == OldPtr);
2491 IRBuilder<> IRB(&LI);
2492
Chandler Carrutha2b88162012-10-25 04:37:07 +00002493 uint64_t Size = EndOffset - BeginOffset;
2494 if (Size < TD.getTypeStoreSize(LI.getType())) {
2495 assert(!LI.isVolatile());
2496 assert(LI.getType()->isIntegerTy() &&
2497 "Only integer type loads and stores are split");
2498 assert(LI.getType()->getIntegerBitWidth() ==
2499 TD.getTypeStoreSizeInBits(LI.getType()) &&
2500 "Non-byte-multiple bit width");
2501 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth70dace32012-10-30 20:52:40 +00002502 TD.getTypeAllocSizeInBits(OldAI.getAllocatedType()) &&
Chandler Carrutha2b88162012-10-25 04:37:07 +00002503 "Only alloca-wide loads can be split and recomposed");
2504 IntegerType *NarrowTy = Type::getIntNTy(LI.getContext(), Size * 8);
2505 bool IsConvertable = (BeginOffset - NewAllocaBeginOffset == 0) &&
2506 canConvertValue(TD, NewAllocaTy, NarrowTy);
2507 Value *V;
2508 // Move the insertion point just past the load so that we can refer to it.
2509 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
2510 if (IsConvertable)
2511 V = convertValue(TD, IRB,
2512 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2513 getName(".load")),
2514 NarrowTy);
2515 else
2516 V = IRB.CreateAlignedLoad(
2517 getAdjustedAllocaPtr(IRB, NarrowTy->getPointerTo()),
2518 getPartitionTypeAlign(NarrowTy), getName(".load"));
2519 // Create a placeholder value with the same type as LI to use as the
2520 // basis for the new value. This allows us to replace the uses of LI with
2521 // the computed value, and then replace the placeholder with LI, leaving
2522 // LI only used for this computation.
2523 Value *Placeholder
Jakub Staszak5801ff92012-11-01 01:10:43 +00002524 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carrutha2b88162012-10-25 04:37:07 +00002525 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
2526 getName(".insert"));
2527 LI.replaceAllUsesWith(V);
2528 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak5801ff92012-11-01 01:10:43 +00002529 delete Placeholder;
Chandler Carrutha2b88162012-10-25 04:37:07 +00002530 if (Pass.DeadSplitInsts.insert(&LI))
2531 Pass.DeadInsts.push_back(&LI);
2532 DEBUG(dbgs() << " to: " << *V << "\n");
2533 return IsConvertable;
2534 }
2535
Chandler Carruth70dace32012-10-30 20:52:40 +00002536 if (VecTy)
2537 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002538 if (IntTy && LI.getType()->isIntegerTy())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002539 return rewriteIntegerLoad(IRB, LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002540
Chandler Carruth520eeae2012-10-13 02:41:05 +00002541 if (BeginOffset == NewAllocaBeginOffset &&
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002542 canConvertValue(TD, NewAllocaTy, LI.getType())) {
Chandler Carruth520eeae2012-10-13 02:41:05 +00002543 Value *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2544 LI.isVolatile(), getName(".load"));
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002545 Value *NewV = convertValue(TD, IRB, NewLI, LI.getType());
Chandler Carruth520eeae2012-10-13 02:41:05 +00002546 LI.replaceAllUsesWith(NewV);
2547 Pass.DeadInsts.push_back(&LI);
2548
2549 DEBUG(dbgs() << " to: " << *NewLI << "\n");
2550 return !LI.isVolatile();
2551 }
2552
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002553 assert(!IntTy && "Invalid load found with int-op widening enabled");
2554
Chandler Carruth713aa942012-09-14 09:22:59 +00002555 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2556 LI.getPointerOperand()->getType());
2557 LI.setOperand(0, NewPtr);
Chandler Carruthf710fb12012-10-03 08:14:02 +00002558 LI.setAlignment(getPartitionTypeAlign(LI.getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002559 DEBUG(dbgs() << " to: " << LI << "\n");
2560
2561 deleteIfTriviallyDead(OldOp);
2562 return NewPtr == &NewAI && !LI.isVolatile();
2563 }
2564
2565 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
2566 Value *OldOp) {
2567 Value *V = SI.getValueOperand();
2568 if (V->getType() == ElementTy ||
2569 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2570 if (V->getType() != ElementTy)
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002571 V = convertValue(TD, IRB, V, ElementTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002572 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2573 getName(".load"));
2574 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002575 getName(".insert"));
2576 } else if (V->getType() != VecTy) {
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002577 V = convertValue(TD, IRB, V, VecTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00002578 }
Chandler Carruth81b001a2012-09-26 10:27:46 +00002579 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002580 Pass.DeadInsts.push_back(&SI);
2581
2582 (void)Store;
2583 DEBUG(dbgs() << " to: " << *Store << "\n");
2584 return true;
2585 }
2586
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002587 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002588 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002589 assert(!SI.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002590 Value *V = SI.getValueOperand();
2591 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2592 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2593 getName(".oldload"));
2594 Old = convertValue(TD, IRB, Old, IntTy);
2595 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2596 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2597 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
2598 getName(".insert"));
2599 }
2600 V = convertValue(TD, IRB, V, NewAllocaTy);
2601 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002602 Pass.DeadInsts.push_back(&SI);
2603 (void)Store;
2604 DEBUG(dbgs() << " to: " << *Store << "\n");
2605 return true;
2606 }
2607
Chandler Carruth713aa942012-09-14 09:22:59 +00002608 bool visitStoreInst(StoreInst &SI) {
2609 DEBUG(dbgs() << " original: " << SI << "\n");
2610 Value *OldOp = SI.getOperand(1);
2611 assert(OldOp == OldPtr);
2612 IRBuilder<> IRB(&SI);
2613
2614 if (VecTy)
2615 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
Chandler Carruth520eeae2012-10-13 02:41:05 +00002616 Type *ValueTy = SI.getValueOperand()->getType();
Chandler Carrutha2b88162012-10-25 04:37:07 +00002617
2618 uint64_t Size = EndOffset - BeginOffset;
2619 if (Size < TD.getTypeStoreSize(ValueTy)) {
2620 assert(!SI.isVolatile());
2621 assert(ValueTy->isIntegerTy() &&
2622 "Only integer type loads and stores are split");
2623 assert(ValueTy->getIntegerBitWidth() ==
2624 TD.getTypeStoreSizeInBits(ValueTy) &&
2625 "Non-byte-multiple bit width");
2626 assert(ValueTy->getIntegerBitWidth() ==
2627 TD.getTypeSizeInBits(OldAI.getAllocatedType()) &&
2628 "Only alloca-wide stores can be split and recomposed");
2629 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2630 Value *V = extractInteger(TD, IRB, SI.getValueOperand(), NarrowTy,
2631 BeginOffset, getName(".extract"));
2632 StoreInst *NewSI;
2633 bool IsConvertable = (BeginOffset - NewAllocaBeginOffset == 0) &&
2634 canConvertValue(TD, NarrowTy, NewAllocaTy);
2635 if (IsConvertable)
2636 NewSI = IRB.CreateAlignedStore(convertValue(TD, IRB, V, NewAllocaTy),
2637 &NewAI, NewAI.getAlignment());
2638 else
2639 NewSI = IRB.CreateAlignedStore(
2640 V, getAdjustedAllocaPtr(IRB, NarrowTy->getPointerTo()),
2641 getPartitionTypeAlign(NarrowTy));
2642 (void)NewSI;
2643 if (Pass.DeadSplitInsts.insert(&SI))
2644 Pass.DeadInsts.push_back(&SI);
2645
2646 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2647 return IsConvertable;
2648 }
2649
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002650 if (IntTy && ValueTy->isIntegerTy())
2651 return rewriteIntegerStore(IRB, SI);
Chandler Carruth520eeae2012-10-13 02:41:05 +00002652
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002653 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2654 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth520eeae2012-10-13 02:41:05 +00002655 if (ValueTy->isPointerTy())
Chandler Carruthb2d98c22012-10-04 12:33:50 +00002656 if (AllocaInst *AI = dyn_cast<AllocaInst>(SI.getValueOperand()
2657 ->stripInBoundsOffsets()))
2658 Pass.PostPromotionWorklist.insert(AI);
2659
Chandler Carruth520eeae2012-10-13 02:41:05 +00002660 if (BeginOffset == NewAllocaBeginOffset &&
Chandler Carruth11cb6ba2012-10-15 08:40:22 +00002661 canConvertValue(TD, ValueTy, NewAllocaTy)) {
2662 Value *NewV = convertValue(TD, IRB, SI.getValueOperand(), NewAllocaTy);
Chandler Carruth520eeae2012-10-13 02:41:05 +00002663 StoreInst *NewSI = IRB.CreateAlignedStore(NewV, &NewAI, NewAI.getAlignment(),
2664 SI.isVolatile());
Chandler Carruthc2fcf1a62012-10-13 05:09:27 +00002665 (void)NewSI;
Chandler Carruth520eeae2012-10-13 02:41:05 +00002666 Pass.DeadInsts.push_back(&SI);
2667
2668 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2669 return !SI.isVolatile();
2670 }
2671
Chandler Carruth81ff90d2012-10-15 08:40:30 +00002672 assert(!IntTy && "Invalid store found with int-op widening enabled");
2673
Chandler Carruth713aa942012-09-14 09:22:59 +00002674 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2675 SI.getPointerOperand()->getType());
2676 SI.setOperand(1, NewPtr);
Chandler Carruthf710fb12012-10-03 08:14:02 +00002677 SI.setAlignment(getPartitionTypeAlign(SI.getValueOperand()->getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002678 DEBUG(dbgs() << " to: " << SI << "\n");
2679
2680 deleteIfTriviallyDead(OldOp);
2681 return NewPtr == &NewAI && !SI.isVolatile();
2682 }
2683
2684 bool visitMemSetInst(MemSetInst &II) {
2685 DEBUG(dbgs() << " original: " << II << "\n");
2686 IRBuilder<> IRB(&II);
2687 assert(II.getRawDest() == OldPtr);
2688
2689 // If the memset has a variable size, it cannot be split, just adjust the
2690 // pointer to the new alloca.
2691 if (!isa<Constant>(II.getLength())) {
2692 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002693 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf710fb12012-10-03 08:14:02 +00002694 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002695
Chandler Carruth713aa942012-09-14 09:22:59 +00002696 deleteIfTriviallyDead(OldPtr);
2697 return false;
2698 }
2699
2700 // Record this instruction for deletion.
2701 if (Pass.DeadSplitInsts.insert(&II))
2702 Pass.DeadInsts.push_back(&II);
2703
2704 Type *AllocaTy = NewAI.getAllocatedType();
2705 Type *ScalarTy = AllocaTy->getScalarType();
2706
2707 // If this doesn't map cleanly onto the alloca type, and that type isn't
2708 // a single value type, just emit a memset.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002709 if (!VecTy && !IntTy &&
2710 (BeginOffset != NewAllocaBeginOffset ||
2711 EndOffset != NewAllocaEndOffset ||
2712 !AllocaTy->isSingleValueType() ||
2713 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002714 Type *SizeTy = II.getLength()->getType();
2715 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002716 CallInst *New
2717 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2718 II.getRawDest()->getType()),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002719 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002720 II.isVolatile());
2721 (void)New;
2722 DEBUG(dbgs() << " to: " << *New << "\n");
2723 return false;
2724 }
2725
2726 // If we can represent this as a simple value, we have to build the actual
2727 // value to store, which requires expanding the byte present in memset to
2728 // a sensible representation for the alloca type. This is essentially
2729 // splatting the byte to a sufficiently wide integer, bitcasting to the
2730 // desired scalar type, and splatting it across any desired vector type.
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002731 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +00002732 Value *V = II.getValue();
2733 IntegerType *VTy = cast<IntegerType>(V->getType());
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002734 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
2735 if (Size*8 > VTy->getBitWidth())
2736 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, getName(".zext")),
Chandler Carruth713aa942012-09-14 09:22:59 +00002737 ConstantExpr::getUDiv(
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002738 Constant::getAllOnesValue(SplatIntTy),
Chandler Carruth713aa942012-09-14 09:22:59 +00002739 ConstantExpr::getZExt(
2740 Constant::getAllOnesValue(V->getType()),
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002741 SplatIntTy)),
Chandler Carruth713aa942012-09-14 09:22:59 +00002742 getName(".isplat"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002743
2744 // If this is an element-wide memset of a vectorizable alloca, insert it.
2745 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2746 EndOffset < NewAllocaEndOffset)) {
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002747 if (V->getType() != ScalarTy)
2748 V = convertValue(TD, IRB, V, ScalarTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002749 StoreInst *Store = IRB.CreateAlignedStore(
2750 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2751 NewAI.getAlignment(),
2752 getName(".load")),
2753 V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002754 getName(".insert")),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002755 &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002756 (void)Store;
2757 DEBUG(dbgs() << " to: " << *Store << "\n");
2758 return true;
2759 }
2760
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002761 // If this is a memset on an alloca where we can widen stores, insert the
2762 // set integer.
2763 if (IntTy && (BeginOffset > NewAllocaBeginOffset ||
2764 EndOffset < NewAllocaEndOffset)) {
2765 assert(!II.isVolatile());
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002766 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2767 getName(".oldload"));
2768 Old = convertValue(TD, IRB, Old, IntTy);
2769 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2770 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2771 V = insertInteger(TD, IRB, Old, V, Offset, getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002772 }
2773
Chandler Carruth94fc64c2012-10-15 10:24:40 +00002774 if (V->getType() != AllocaTy)
2775 V = convertValue(TD, IRB, V, AllocaTy);
2776
Chandler Carruth81b001a2012-09-26 10:27:46 +00002777 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2778 II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002779 (void)New;
2780 DEBUG(dbgs() << " to: " << *New << "\n");
2781 return !II.isVolatile();
2782 }
2783
2784 bool visitMemTransferInst(MemTransferInst &II) {
2785 // Rewriting of memory transfer instructions can be a bit tricky. We break
2786 // them into two categories: split intrinsics and unsplit intrinsics.
2787
2788 DEBUG(dbgs() << " original: " << II << "\n");
2789 IRBuilder<> IRB(&II);
2790
2791 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2792 bool IsDest = II.getRawDest() == OldPtr;
2793
2794 const AllocaPartitioning::MemTransferOffsets &MTO
2795 = P.getMemTransferOffsets(II);
2796
Micah Villmow2c39b152012-10-15 16:24:29 +00002797 assert(OldPtr->getType()->isPointerTy() && "Must be a pointer type!");
Chandler Carruth673850a2012-10-01 12:16:54 +00002798 // Compute the relative offset within the transfer.
Micah Villmowb52fb872012-10-24 18:36:13 +00002799 unsigned IntPtrWidth = TD.getTypeSizeInBits(OldPtr->getType());
Chandler Carruth673850a2012-10-01 12:16:54 +00002800 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2801 : MTO.SourceBegin));
2802
2803 unsigned Align = II.getAlignment();
2804 if (Align > 1)
2805 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002806 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth673850a2012-10-01 12:16:54 +00002807
Chandler Carruth713aa942012-09-14 09:22:59 +00002808 // For unsplit intrinsics, we simply modify the source and destination
2809 // pointers in place. This isn't just an optimization, it is a matter of
2810 // correctness. With unsplit intrinsics we may be dealing with transfers
2811 // within a single alloca before SROA ran, or with transfers that have
2812 // a variable length. We may also be dealing with memmove instead of
2813 // memcpy, and so simply updating the pointers is the necessary for us to
2814 // update both source and dest of a single call.
2815 if (!MTO.IsSplittable) {
2816 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2817 if (IsDest)
2818 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2819 else
2820 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2821
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002822 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth673850a2012-10-01 12:16:54 +00002823 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002824
Chandler Carruth713aa942012-09-14 09:22:59 +00002825 DEBUG(dbgs() << " to: " << II << "\n");
2826 deleteIfTriviallyDead(OldOp);
2827 return false;
2828 }
2829 // For split transfer intrinsics we have an incredibly useful assurance:
2830 // the source and destination do not reside within the same alloca, and at
2831 // least one of them does not escape. This means that we can replace
2832 // memmove with memcpy, and we don't need to worry about all manner of
2833 // downsides to splitting and transforming the operations.
2834
Chandler Carruth713aa942012-09-14 09:22:59 +00002835 // If this doesn't map cleanly onto the alloca type, and that type isn't
2836 // a single value type, just emit a memcpy.
2837 bool EmitMemCpy
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002838 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2839 EndOffset != NewAllocaEndOffset ||
2840 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002841
2842 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2843 // size hasn't been shrunk based on analysis of the viable range, this is
2844 // a no-op.
2845 if (EmitMemCpy && &OldAI == &NewAI) {
2846 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2847 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2848 // Ensure the start lines up.
2849 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002850 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002851
2852 // Rewrite the size as needed.
2853 if (EndOffset != OrigEnd)
2854 II.setLength(ConstantInt::get(II.getLength()->getType(),
2855 EndOffset - BeginOffset));
2856 return false;
2857 }
2858 // Record this instruction for deletion.
2859 if (Pass.DeadSplitInsts.insert(&II))
2860 Pass.DeadInsts.push_back(&II);
2861
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002862 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2863 EndOffset == NewAllocaEndOffset;
2864 bool IsVectorElement = VecTy && !IsWholeAlloca;
2865 uint64_t Size = EndOffset - BeginOffset;
2866 IntegerType *SubIntTy
2867 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002868
2869 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2870 : II.getRawDest()->getType();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002871 if (!EmitMemCpy) {
2872 if (IsVectorElement)
Micah Villmowb8bce922012-10-24 17:25:11 +00002873 OtherPtrTy = VecTy->getElementType()->getPointerTo();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002874 else if (IntTy && !IsWholeAlloca)
Micah Villmowb8bce922012-10-24 17:25:11 +00002875 OtherPtrTy = SubIntTy->getPointerTo();
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002876 else
2877 OtherPtrTy = NewAI.getType();
2878 }
Chandler Carruth713aa942012-09-14 09:22:59 +00002879
2880 // Compute the other pointer, folding as much as possible to produce
2881 // a single, simple GEP in most cases.
2882 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2883 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2884 getName("." + OtherPtr->getName()));
2885
2886 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2887 // alloca that should be re-examined after rewriting this instruction.
2888 if (AllocaInst *AI
2889 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruthb3dca3f2012-09-26 07:41:40 +00002890 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002891
2892 if (EmitMemCpy) {
2893 Value *OurPtr
2894 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2895 : II.getRawSource()->getType());
2896 Type *SizeTy = II.getLength()->getType();
2897 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2898
2899 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2900 IsDest ? OtherPtr : OurPtr,
Chandler Carruth81b001a2012-09-26 10:27:46 +00002901 Size, Align, II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002902 (void)New;
2903 DEBUG(dbgs() << " to: " << *New << "\n");
2904 return false;
2905 }
2906
Chandler Carruth322e9ba2012-10-03 08:26:28 +00002907 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2908 // is equivalent to 1, but that isn't true if we end up rewriting this as
2909 // a load or store.
2910 if (!Align)
2911 Align = 1;
2912
Chandler Carruth713aa942012-09-14 09:22:59 +00002913 Value *SrcPtr = OtherPtr;
2914 Value *DstPtr = &NewAI;
2915 if (!IsDest)
2916 std::swap(SrcPtr, DstPtr);
2917
2918 Value *Src;
2919 if (IsVectorElement && !IsDest) {
2920 // We have to extract rather than load.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002921 Src = IRB.CreateExtractElement(
2922 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2923 getIndex(IRB, BeginOffset),
2924 getName(".copyextract"));
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002925 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002926 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2927 getName(".load"));
2928 Src = convertValue(TD, IRB, Src, IntTy);
2929 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2930 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2931 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002932 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002933 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2934 getName(".copyload"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002935 }
2936
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002937 if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth2360b7a2012-10-18 09:56:08 +00002938 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2939 getName(".oldload"));
2940 Old = convertValue(TD, IRB, Old, IntTy);
2941 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2942 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2943 Src = insertInteger(TD, IRB, Old, Src, Offset, getName(".insert"));
2944 Src = convertValue(TD, IRB, Src, NewAllocaTy);
Chandler Carruthd2cd73f2012-10-15 10:24:43 +00002945 }
2946
Chandler Carruth713aa942012-09-14 09:22:59 +00002947 if (IsVectorElement && IsDest) {
2948 // We have to insert into a loaded copy before storing.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002949 Src = IRB.CreateInsertElement(
2950 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2951 Src, getIndex(IRB, BeginOffset),
2952 getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002953 }
2954
Chandler Carruth81b001a2012-09-26 10:27:46 +00002955 StoreInst *Store = cast<StoreInst>(
2956 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2957 (void)Store;
Chandler Carruth713aa942012-09-14 09:22:59 +00002958 DEBUG(dbgs() << " to: " << *Store << "\n");
2959 return !II.isVolatile();
2960 }
2961
2962 bool visitIntrinsicInst(IntrinsicInst &II) {
2963 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2964 II.getIntrinsicID() == Intrinsic::lifetime_end);
2965 DEBUG(dbgs() << " original: " << II << "\n");
2966 IRBuilder<> IRB(&II);
2967 assert(II.getArgOperand(1) == OldPtr);
2968
2969 // Record this instruction for deletion.
2970 if (Pass.DeadSplitInsts.insert(&II))
2971 Pass.DeadInsts.push_back(&II);
2972
2973 ConstantInt *Size
2974 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2975 EndOffset - BeginOffset);
2976 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2977 Value *New;
2978 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2979 New = IRB.CreateLifetimeStart(Ptr, Size);
2980 else
2981 New = IRB.CreateLifetimeEnd(Ptr, Size);
2982
2983 DEBUG(dbgs() << " to: " << *New << "\n");
2984 return true;
2985 }
2986
Chandler Carruth713aa942012-09-14 09:22:59 +00002987 bool visitPHINode(PHINode &PN) {
2988 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002989
Chandler Carruth713aa942012-09-14 09:22:59 +00002990 // We would like to compute a new pointer in only one place, but have it be
2991 // as local as possible to the PHI. To do that, we re-use the location of
2992 // the old pointer, which necessarily must be in the right position to
2993 // dominate the PHI.
2994 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2995
Chandler Carruth713aa942012-09-14 09:22:59 +00002996 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002997 // Replace the operands which were using the old pointer.
Benjamin Kramer2a132422012-10-20 12:04:57 +00002998 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth713aa942012-09-14 09:22:59 +00002999
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003000 DEBUG(dbgs() << " to: " << PN << "\n");
3001 deleteIfTriviallyDead(OldPtr);
3002 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00003003 }
3004
3005 bool visitSelectInst(SelectInst &SI) {
3006 DEBUG(dbgs() << " original: " << SI << "\n");
3007 IRBuilder<> IRB(&SI);
3008
3009 // Find the operand we need to rewrite here.
3010 bool IsTrueVal = SI.getTrueValue() == OldPtr;
3011 if (IsTrueVal)
3012 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
3013 else
3014 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003015
Chandler Carruth713aa942012-09-14 09:22:59 +00003016 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003017 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
3018 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00003019 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003020 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00003021 }
3022
3023};
3024}
3025
Chandler Carruthc370acd2012-09-18 12:57:43 +00003026namespace {
3027/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3028///
3029/// This pass aggressively rewrites all aggregate loads and stores on
3030/// a particular pointer (or any pointer derived from it which we can identify)
3031/// with scalar loads and stores.
3032class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3033 // Befriend the base class so it can delegate to private visit methods.
3034 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3035
Micah Villmow3574eca2012-10-08 16:38:25 +00003036 const DataLayout &TD;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003037
3038 /// Queue of pointer uses to analyze and potentially rewrite.
3039 SmallVector<Use *, 8> Queue;
3040
3041 /// Set to prevent us from cycling with phi nodes and loops.
3042 SmallPtrSet<User *, 8> Visited;
3043
3044 /// The current pointer use being rewritten. This is used to dig up the used
3045 /// value (as opposed to the user).
3046 Use *U;
3047
3048public:
Micah Villmow3574eca2012-10-08 16:38:25 +00003049 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003050
3051 /// Rewrite loads and stores through a pointer and all pointers derived from
3052 /// it.
3053 bool rewrite(Instruction &I) {
3054 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3055 enqueueUsers(I);
3056 bool Changed = false;
3057 while (!Queue.empty()) {
3058 U = Queue.pop_back_val();
3059 Changed |= visit(cast<Instruction>(U->getUser()));
3060 }
3061 return Changed;
3062 }
3063
3064private:
3065 /// Enqueue all the users of the given instruction for further processing.
3066 /// This uses a set to de-duplicate users.
3067 void enqueueUsers(Instruction &I) {
3068 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3069 ++UI)
3070 if (Visited.insert(*UI))
3071 Queue.push_back(&UI.getUse());
3072 }
3073
3074 // Conservative default is to not rewrite anything.
3075 bool visitInstruction(Instruction &I) { return false; }
3076
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003077 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003078 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003079 class OpSplitter {
3080 protected:
3081 /// The builder used to form new instructions.
3082 IRBuilder<> IRB;
3083 /// The indices which to be used with insert- or extractvalue to select the
3084 /// appropriate value within the aggregate.
3085 SmallVector<unsigned, 4> Indices;
3086 /// The indices to a GEP instruction which will move Ptr to the correct slot
3087 /// within the aggregate.
3088 SmallVector<Value *, 4> GEPIndices;
3089 /// The base pointer of the original op, used as a base for GEPing the
3090 /// split operations.
3091 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003092
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003093 /// Initialize the splitter with an insertion point, Ptr and start with a
3094 /// single zero GEP index.
3095 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003096 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003097
3098 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003099 /// \brief Generic recursive split emission routine.
3100 ///
3101 /// This method recursively splits an aggregate op (load or store) into
3102 /// scalar or vector ops. It splits recursively until it hits a single value
3103 /// and emits that single value operation via the template argument.
3104 ///
3105 /// The logic of this routine relies on GEPs and insertvalue and
3106 /// extractvalue all operating with the same fundamental index list, merely
3107 /// formatted differently (GEPs need actual values).
3108 ///
3109 /// \param Ty The type being split recursively into smaller ops.
3110 /// \param Agg The aggregate value being built up or stored, depending on
3111 /// whether this is splitting a load or a store respectively.
3112 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3113 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003114 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003115
3116 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3117 unsigned OldSize = Indices.size();
3118 (void)OldSize;
3119 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3120 ++Idx) {
3121 assert(Indices.size() == OldSize && "Did not return to the old size");
3122 Indices.push_back(Idx);
3123 GEPIndices.push_back(IRB.getInt32(Idx));
3124 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3125 GEPIndices.pop_back();
3126 Indices.pop_back();
3127 }
3128 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003129 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00003130
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003131 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3132 unsigned OldSize = Indices.size();
3133 (void)OldSize;
3134 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3135 ++Idx) {
3136 assert(Indices.size() == OldSize && "Did not return to the old size");
3137 Indices.push_back(Idx);
3138 GEPIndices.push_back(IRB.getInt32(Idx));
3139 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3140 GEPIndices.pop_back();
3141 Indices.pop_back();
3142 }
3143 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00003144 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003145
3146 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003147 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003148 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003149
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003150 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003151 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003152 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00003153
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003154 /// Emit a leaf load of a single value. This is called at the leaves of the
3155 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003156 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003157 assert(Ty->isSingleValueType());
3158 // Load the single value and insert it using the indices.
3159 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
3160 Name + ".gep"),
3161 Name + ".load");
3162 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3163 DEBUG(dbgs() << " to: " << *Load << "\n");
3164 }
3165 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003166
3167 bool visitLoadInst(LoadInst &LI) {
3168 assert(LI.getPointerOperand() == *U);
3169 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3170 return false;
3171
3172 // We have an aggregate being loaded, split it apart.
3173 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003174 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00003175 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003176 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003177 LI.replaceAllUsesWith(V);
3178 LI.eraseFromParent();
3179 return true;
3180 }
3181
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003182 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003183 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00003184 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003185
3186 /// Emit a leaf store of a single value. This is called at the leaves of the
3187 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00003188 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003189 assert(Ty->isSingleValueType());
3190 // Extract the single value and store it using the indices.
3191 Value *Store = IRB.CreateStore(
3192 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3193 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3194 (void)Store;
3195 DEBUG(dbgs() << " to: " << *Store << "\n");
3196 }
3197 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00003198
3199 bool visitStoreInst(StoreInst &SI) {
3200 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3201 return false;
3202 Value *V = SI.getValueOperand();
3203 if (V->getType()->isSingleValueType())
3204 return false;
3205
3206 // We have an aggregate being stored, split it apart.
3207 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00003208 StoreOpSplitter Splitter(&SI, *U);
3209 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00003210 SI.eraseFromParent();
3211 return true;
3212 }
3213
3214 bool visitBitCastInst(BitCastInst &BC) {
3215 enqueueUsers(BC);
3216 return false;
3217 }
3218
3219 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3220 enqueueUsers(GEPI);
3221 return false;
3222 }
3223
3224 bool visitPHINode(PHINode &PN) {
3225 enqueueUsers(PN);
3226 return false;
3227 }
3228
3229 bool visitSelectInst(SelectInst &SI) {
3230 enqueueUsers(SI);
3231 return false;
3232 }
3233};
3234}
3235
Chandler Carruth07525a62012-10-13 10:49:33 +00003236/// \brief Strip aggregate type wrapping.
3237///
3238/// This removes no-op aggregate types wrapping an underlying type. It will
3239/// strip as many layers of types as it can without changing either the type
3240/// size or the allocated size.
3241static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3242 if (Ty->isSingleValueType())
3243 return Ty;
3244
3245 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3246 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3247
3248 Type *InnerTy;
3249 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3250 InnerTy = ArrTy->getElementType();
3251 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3252 const StructLayout *SL = DL.getStructLayout(STy);
3253 unsigned Index = SL->getElementContainingOffset(0);
3254 InnerTy = STy->getElementType(Index);
3255 } else {
3256 return Ty;
3257 }
3258
3259 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3260 TypeSize > DL.getTypeSizeInBits(InnerTy))
3261 return Ty;
3262
3263 return stripAggregateTypeWrapping(DL, InnerTy);
3264}
3265
Chandler Carruth713aa942012-09-14 09:22:59 +00003266/// \brief Try to find a partition of the aggregate type passed in for a given
3267/// offset and size.
3268///
3269/// This recurses through the aggregate type and tries to compute a subtype
3270/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00003271/// of an array, it will even compute a new array type for that sub-section,
3272/// and the same for structs.
3273///
3274/// Note that this routine is very strict and tries to find a partition of the
3275/// type which produces the *exact* right offset and size. It is not forgiving
3276/// when the size or offset cause either end of type-based partition to be off.
3277/// Also, this is a best-effort routine. It is reasonable to give up and not
3278/// return a type if necessary.
Micah Villmow3574eca2012-10-08 16:38:25 +00003279static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth713aa942012-09-14 09:22:59 +00003280 uint64_t Offset, uint64_t Size) {
3281 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruth07525a62012-10-13 10:49:33 +00003282 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carrutha2b88162012-10-25 04:37:07 +00003283 if (Offset > TD.getTypeAllocSize(Ty) ||
3284 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3285 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003286
3287 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3288 // We can't partition pointers...
3289 if (SeqTy->isPointerTy())
3290 return 0;
3291
3292 Type *ElementTy = SeqTy->getElementType();
3293 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3294 uint64_t NumSkippedElements = Offset / ElementSize;
3295 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
3296 if (NumSkippedElements >= ArrTy->getNumElements())
3297 return 0;
3298 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
3299 if (NumSkippedElements >= VecTy->getNumElements())
3300 return 0;
3301 Offset -= NumSkippedElements * ElementSize;
3302
3303 // First check if we need to recurse.
3304 if (Offset > 0 || Size < ElementSize) {
3305 // Bail if the partition ends in a different array element.
3306 if ((Offset + Size) > ElementSize)
3307 return 0;
3308 // Recurse through the element type trying to peel off offset bytes.
3309 return getTypePartition(TD, ElementTy, Offset, Size);
3310 }
3311 assert(Offset == 0);
3312
3313 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003314 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003315 assert(Size > ElementSize);
3316 uint64_t NumElements = Size / ElementSize;
3317 if (NumElements * ElementSize != Size)
3318 return 0;
3319 return ArrayType::get(ElementTy, NumElements);
3320 }
3321
3322 StructType *STy = dyn_cast<StructType>(Ty);
3323 if (!STy)
3324 return 0;
3325
3326 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003327 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00003328 return 0;
3329 uint64_t EndOffset = Offset + Size;
3330 if (EndOffset > SL->getSizeInBytes())
3331 return 0;
3332
3333 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00003334 Offset -= SL->getElementOffset(Index);
3335
3336 Type *ElementTy = STy->getElementType(Index);
3337 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3338 if (Offset >= ElementSize)
3339 return 0; // The offset points into alignment padding.
3340
3341 // See if any partition must be contained by the element.
3342 if (Offset > 0 || Size < ElementSize) {
3343 if ((Offset + Size) > ElementSize)
3344 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00003345 return getTypePartition(TD, ElementTy, Offset, Size);
3346 }
3347 assert(Offset == 0);
3348
3349 if (Size == ElementSize)
Chandler Carruth07525a62012-10-13 10:49:33 +00003350 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth713aa942012-09-14 09:22:59 +00003351
3352 StructType::element_iterator EI = STy->element_begin() + Index,
3353 EE = STy->element_end();
3354 if (EndOffset < SL->getSizeInBytes()) {
3355 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3356 if (Index == EndIndex)
3357 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00003358
3359 // Don't try to form "natural" types if the elements don't line up with the
3360 // expected size.
3361 // FIXME: We could potentially recurse down through the last element in the
3362 // sub-struct to find a natural end point.
3363 if (SL->getElementOffset(EndIndex) != EndOffset)
3364 return 0;
3365
Chandler Carruth713aa942012-09-14 09:22:59 +00003366 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00003367 EE = STy->element_begin() + EndIndex;
3368 }
3369
3370 // Try to build up a sub-structure.
Benjamin Kramer2a132422012-10-20 12:04:57 +00003371 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth713aa942012-09-14 09:22:59 +00003372 STy->isPacked());
3373 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003374 if (Size != SubSL->getSizeInBytes())
3375 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00003376
Chandler Carruth6b547a22012-09-14 11:08:31 +00003377 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00003378}
3379
3380/// \brief Rewrite an alloca partition's users.
3381///
3382/// This routine drives both of the rewriting goals of the SROA pass. It tries
3383/// to rewrite uses of an alloca partition to be conducive for SSA value
3384/// promotion. If the partition needs a new, more refined alloca, this will
3385/// build that new alloca, preserving as much type information as possible, and
3386/// rewrite the uses of the old alloca to point at the new one and have the
3387/// appropriate new offsets. It also evaluates how successful the rewrite was
3388/// at enabling promotion and if it was successful queues the alloca to be
3389/// promoted.
3390bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3391 AllocaPartitioning &P,
3392 AllocaPartitioning::iterator PI) {
3393 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruthfdb15852012-10-02 18:57:13 +00003394 bool IsLive = false;
3395 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3396 UE = P.use_end(PI);
3397 UI != UE && !IsLive; ++UI)
3398 if (UI->U)
3399 IsLive = true;
3400 if (!IsLive)
Chandler Carruth713aa942012-09-14 09:22:59 +00003401 return false; // No live uses left of this partition.
3402
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003403 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3404 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3405
3406 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3407 DEBUG(dbgs() << " speculating ");
3408 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carrutha346f462012-10-02 17:49:47 +00003409 Speculator.visitUsers(PI);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003410
Chandler Carruth713aa942012-09-14 09:22:59 +00003411 // Try to compute a friendly type for this partition of the alloca. This
3412 // won't always succeed, in which case we fall back to a legal integer type
3413 // or an i8 array of an appropriate size.
3414 Type *AllocaTy = 0;
3415 if (Type *PartitionTy = P.getCommonType(PI))
3416 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3417 AllocaTy = PartitionTy;
3418 if (!AllocaTy)
3419 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3420 PI->BeginOffset, AllocaSize))
3421 AllocaTy = PartitionTy;
3422 if ((!AllocaTy ||
3423 (AllocaTy->isArrayTy() &&
3424 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3425 TD->isLegalInteger(AllocaSize * 8))
3426 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3427 if (!AllocaTy)
3428 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00003429 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00003430
3431 // Check for the case where we're going to rewrite to a new alloca of the
3432 // exact same type as the original, and with the same access offsets. In that
3433 // case, re-use the existing alloca, but still run through the rewriter to
3434 // performe phi and select speculation.
3435 AllocaInst *NewAI;
3436 if (AllocaTy == AI.getAllocatedType()) {
3437 assert(PI->BeginOffset == 0 &&
3438 "Non-zero begin offset but same alloca type");
3439 assert(PI == P.begin() && "Begin offset is zero on later partition");
3440 NewAI = &AI;
3441 } else {
Chandler Carruthb67c9a52012-09-29 10:41:21 +00003442 unsigned Alignment = AI.getAlignment();
3443 if (!Alignment) {
3444 // The minimum alignment which users can rely on when the explicit
3445 // alignment is omitted or zero is that required by the ABI for this
3446 // type.
3447 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3448 }
3449 Alignment = MinAlign(Alignment, PI->BeginOffset);
3450 // If we will get at least this much alignment from the type alone, leave
3451 // the alloca's alignment unconstrained.
3452 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3453 Alignment = 0;
3454 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth713aa942012-09-14 09:22:59 +00003455 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3456 &AI);
3457 ++NumNewAllocas;
3458 }
3459
3460 DEBUG(dbgs() << "Rewriting alloca partition "
3461 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3462 << *NewAI << "\n");
3463
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003464 // Track the high watermark of the post-promotion worklist. We will reset it
3465 // to this point if the alloca is not in fact scheduled for promotion.
3466 unsigned PPWOldSize = PostPromotionWorklist.size();
3467
Chandler Carruth713aa942012-09-14 09:22:59 +00003468 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3469 PI->BeginOffset, PI->EndOffset);
3470 DEBUG(dbgs() << " rewriting ");
3471 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003472 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3473 if (Promotable) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003474 DEBUG(dbgs() << " and queuing for promotion\n");
3475 PromotableAllocas.push_back(NewAI);
3476 } else if (NewAI != &AI) {
3477 // If we can't promote the alloca, iterate on it to check for new
3478 // refinements exposed by splitting the current alloca. Don't iterate on an
3479 // alloca which didn't actually change and didn't get promoted.
3480 Worklist.insert(NewAI);
3481 }
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003482
3483 // Drop any post-promotion work items if promotion didn't happen.
3484 if (!Promotable)
3485 while (PostPromotionWorklist.size() > PPWOldSize)
3486 PostPromotionWorklist.pop_back();
3487
Chandler Carruth713aa942012-09-14 09:22:59 +00003488 return true;
3489}
3490
3491/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3492bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3493 bool Changed = false;
3494 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3495 ++PI)
3496 Changed |= rewriteAllocaPartition(AI, P, PI);
3497
3498 return Changed;
3499}
3500
3501/// \brief Analyze an alloca for SROA.
3502///
3503/// This analyzes the alloca to ensure we can reason about it, builds
3504/// a partitioning of the alloca, and then hands it off to be split and
3505/// rewritten as needed.
3506bool SROA::runOnAlloca(AllocaInst &AI) {
3507 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3508 ++NumAllocasAnalyzed;
3509
3510 // Special case dead allocas, as they're trivial.
3511 if (AI.use_empty()) {
3512 AI.eraseFromParent();
3513 return true;
3514 }
3515
3516 // Skip alloca forms that this analysis can't handle.
3517 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3518 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3519 return false;
3520
Chandler Carruthc370acd2012-09-18 12:57:43 +00003521 bool Changed = false;
3522
3523 // First, split any FCA loads and stores touching this alloca to promote
3524 // better splitting and promotion opportunities.
3525 AggLoadStoreRewriter AggRewriter(*TD);
3526 Changed |= AggRewriter.rewrite(AI);
3527
Chandler Carruth713aa942012-09-14 09:22:59 +00003528 // Build the partition set using a recursive instruction-visiting builder.
3529 AllocaPartitioning P(*TD, AI);
3530 DEBUG(P.print(dbgs()));
3531 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003532 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003533
Chandler Carruth713aa942012-09-14 09:22:59 +00003534 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003535 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3536 DE = P.dead_user_end();
3537 DI != DE; ++DI) {
3538 Changed = true;
3539 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3540 DeadInsts.push_back(*DI);
3541 }
3542 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3543 DE = P.dead_op_end();
3544 DO != DE; ++DO) {
3545 Value *OldV = **DO;
3546 // Clobber the use with an undef value.
3547 **DO = UndefValue::get(OldV->getType());
3548 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3549 if (isInstructionTriviallyDead(OldI)) {
3550 Changed = true;
3551 DeadInsts.push_back(OldI);
3552 }
3553 }
3554
Chandler Carruthfca3f402012-10-05 01:29:09 +00003555 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3556 if (P.begin() == P.end())
3557 return Changed;
3558
Chandler Carruth713aa942012-09-14 09:22:59 +00003559 return splitAlloca(AI, P) || Changed;
3560}
3561
Chandler Carruth8615cd22012-09-14 10:26:38 +00003562/// \brief Delete the dead instructions accumulated in this run.
3563///
3564/// Recursively deletes the dead instructions we've accumulated. This is done
3565/// at the very end to maximize locality of the recursive delete and to
3566/// minimize the problems of invalidated instruction pointers as such pointers
3567/// are used heavily in the intermediate stages of the algorithm.
3568///
3569/// We also record the alloca instructions deleted here so that they aren't
3570/// subsequently handed to mem2reg to promote.
3571void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003572 DeadSplitInsts.clear();
3573 while (!DeadInsts.empty()) {
3574 Instruction *I = DeadInsts.pop_back_val();
3575 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3576
Chandler Carrutha2b88162012-10-25 04:37:07 +00003577 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3578
Chandler Carruth713aa942012-09-14 09:22:59 +00003579 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3580 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3581 // Zero out the operand and see if it becomes trivially dead.
3582 *OI = 0;
3583 if (isInstructionTriviallyDead(U))
3584 DeadInsts.push_back(U);
3585 }
3586
3587 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3588 DeletedAllocas.insert(AI);
3589
3590 ++NumDeleted;
3591 I->eraseFromParent();
3592 }
3593}
3594
Chandler Carruth1c8db502012-09-15 11:43:14 +00003595/// \brief Promote the allocas, using the best available technique.
3596///
3597/// This attempts to promote whatever allocas have been identified as viable in
3598/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3599/// If there is a domtree available, we attempt to promote using the full power
3600/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3601/// based on the SSAUpdater utilities. This function returns whether any
3602/// promotion occured.
3603bool SROA::promoteAllocas(Function &F) {
3604 if (PromotableAllocas.empty())
3605 return false;
3606
3607 NumPromoted += PromotableAllocas.size();
3608
3609 if (DT && !ForceSSAUpdater) {
3610 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3611 PromoteMemToReg(PromotableAllocas, *DT);
3612 PromotableAllocas.clear();
3613 return true;
3614 }
3615
3616 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3617 SSAUpdater SSA;
3618 DIBuilder DIB(*F.getParent());
3619 SmallVector<Instruction*, 64> Insts;
3620
3621 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3622 AllocaInst *AI = PromotableAllocas[Idx];
3623 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3624 UI != UE;) {
3625 Instruction *I = cast<Instruction>(*UI++);
3626 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3627 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3628 // leading to them) here. Eventually it should use them to optimize the
3629 // scalar values produced.
3630 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3631 assert(onlyUsedByLifetimeMarkers(I) &&
3632 "Found a bitcast used outside of a lifetime marker.");
3633 while (!I->use_empty())
3634 cast<Instruction>(*I->use_begin())->eraseFromParent();
3635 I->eraseFromParent();
3636 continue;
3637 }
3638 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3639 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3640 II->getIntrinsicID() == Intrinsic::lifetime_end);
3641 II->eraseFromParent();
3642 continue;
3643 }
3644
3645 Insts.push_back(I);
3646 }
3647 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3648 Insts.clear();
3649 }
3650
3651 PromotableAllocas.clear();
3652 return true;
3653}
3654
Chandler Carruth713aa942012-09-14 09:22:59 +00003655namespace {
3656 /// \brief A predicate to test whether an alloca belongs to a set.
3657 class IsAllocaInSet {
3658 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3659 const SetType &Set;
3660
3661 public:
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003662 typedef AllocaInst *argument_type;
3663
Chandler Carruth713aa942012-09-14 09:22:59 +00003664 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003665 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth713aa942012-09-14 09:22:59 +00003666 };
3667}
3668
3669bool SROA::runOnFunction(Function &F) {
3670 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3671 C = &F.getContext();
Micah Villmow3574eca2012-10-08 16:38:25 +00003672 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003673 if (!TD) {
3674 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3675 return false;
3676 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003677 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003678
3679 BasicBlock &EntryBB = F.getEntryBlock();
3680 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3681 I != E; ++I)
3682 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3683 Worklist.insert(AI);
3684
3685 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003686 // A set of deleted alloca instruction pointers which should be removed from
3687 // the list of promotable allocas.
3688 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3689
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003690 do {
3691 while (!Worklist.empty()) {
3692 Changed |= runOnAlloca(*Worklist.pop_back_val());
3693 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth5c5b3cf2012-10-02 22:46:45 +00003694
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003695 // Remove the deleted allocas from various lists so that we don't try to
3696 // continue processing them.
3697 if (!DeletedAllocas.empty()) {
3698 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3699 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3700 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3701 PromotableAllocas.end(),
3702 IsAllocaInSet(DeletedAllocas)),
3703 PromotableAllocas.end());
3704 DeletedAllocas.clear();
3705 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003706 }
Chandler Carruth713aa942012-09-14 09:22:59 +00003707
Chandler Carruthb2d98c22012-10-04 12:33:50 +00003708 Changed |= promoteAllocas(F);
3709
3710 Worklist = PostPromotionWorklist;
3711 PostPromotionWorklist.clear();
3712 } while (!Worklist.empty());
Chandler Carruth713aa942012-09-14 09:22:59 +00003713
3714 return Changed;
3715}
3716
3717void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003718 if (RequiresDomTree)
3719 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003720 AU.setPreservesCFG();
3721}