blob: 11b8d2e0215af13452a412bee2532d43a98001d8 [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"
54#include "llvm/Target/TargetData.h"
55#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/PromoteMemToReg.h"
57#include "llvm/Transforms/Utils/SSAUpdater.h"
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 ///
136 /// FIXME: At some point we should consider loads and stores of FCAs to be
137 /// splittable and eagerly split them into scalar values.
138 bool IsSplittable;
139
140 Partition() : ByteRange(), IsSplittable() {}
141 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
142 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
143 };
144
145 /// \brief A particular use of a partition of the alloca.
146 ///
147 /// This structure is used to associate uses of a partition with it. They
148 /// mark the range of bytes which are referenced by a particular instruction,
149 /// and includes a handle to the user itself and the pointer value in use.
150 /// The bounds of these uses are determined by intersecting the bounds of the
151 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000152 /// intentionally overlap between various uses of the same partition.
Chandler Carruth713aa942012-09-14 09:22:59 +0000153 struct PartitionUse : public ByteRange {
Chandler Carruth77c12702012-10-01 01:49:22 +0000154 /// \brief The use in question. Provides access to both user and used value.
Chandler Carruthfdb15852012-10-02 18:57:13 +0000155 ///
156 /// Note that this may be null if the partition use is *dead*, that is, it
157 /// should be ignored.
158 Use *U;
Chandler Carruth713aa942012-09-14 09:22:59 +0000159
Chandler Carruth77c12702012-10-01 01:49:22 +0000160 PartitionUse() : ByteRange(), U() {}
161 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
162 : ByteRange(BeginOffset, EndOffset), U(U) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000163 };
164
165 /// \brief Construct a partitioning of a particular alloca.
166 ///
167 /// Construction does most of the work for partitioning the alloca. This
168 /// performs the necessary walks of users and builds a partitioning from it.
169 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
170
171 /// \brief Test whether a pointer to the allocation escapes our analysis.
172 ///
173 /// If this is true, the partitioning is never fully built and should be
174 /// ignored.
175 bool isEscaped() const { return PointerEscapingInstr; }
176
177 /// \brief Support for iterating over the partitions.
178 /// @{
179 typedef SmallVectorImpl<Partition>::iterator iterator;
180 iterator begin() { return Partitions.begin(); }
181 iterator end() { return Partitions.end(); }
182
183 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
184 const_iterator begin() const { return Partitions.begin(); }
185 const_iterator end() const { return Partitions.end(); }
186 /// @}
187
188 /// \brief Support for iterating over and manipulating a particular
189 /// partition's uses.
190 ///
191 /// The iteration support provided for uses is more limited, but also
192 /// includes some manipulation routines to support rewriting the uses of
193 /// partitions during SROA.
194 /// @{
195 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
196 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
197 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
198 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
199 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth713aa942012-09-14 09:22:59 +0000200
201 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
202 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
203 const_use_iterator use_begin(const_iterator I) const {
204 return Uses[I - begin()].begin();
205 }
206 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
207 const_use_iterator use_end(const_iterator I) const {
208 return Uses[I - begin()].end();
209 }
Chandler Carrutha346f462012-10-02 17:49:47 +0000210
211 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
212 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
213 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
214 return Uses[PIdx][UIdx];
215 }
216 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
217 return Uses[I - begin()][UIdx];
218 }
219
220 void use_push_back(unsigned Idx, const PartitionUse &PU) {
221 Uses[Idx].push_back(PU);
222 }
223 void use_push_back(const_iterator I, const PartitionUse &PU) {
224 Uses[I - begin()].push_back(PU);
225 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000226 /// @}
227
228 /// \brief Allow iterating the dead users for this alloca.
229 ///
230 /// These are instructions which will never actually use the alloca as they
231 /// are outside the allocated range. They are safe to replace with undef and
232 /// delete.
233 /// @{
234 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
235 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
236 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
237 /// @}
238
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000239 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000240 ///
241 /// These are operands which have cannot actually be used to refer to the
242 /// alloca as they are outside its range and the user doesn't correct for
243 /// that. These mostly consist of PHI node inputs and the like which we just
244 /// need to replace with undef.
245 /// @{
246 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
247 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
248 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
249 /// @}
250
251 /// \brief MemTransferInst auxiliary data.
252 /// This struct provides some auxiliary data about memory transfer
253 /// intrinsics such as memcpy and memmove. These intrinsics can use two
254 /// different ranges within the same alloca, and provide other challenges to
255 /// correctly represent. We stash extra data to help us untangle this
256 /// after the partitioning is complete.
257 struct MemTransferOffsets {
258 uint64_t DestBegin, DestEnd;
259 uint64_t SourceBegin, SourceEnd;
260 bool IsSplittable;
261 };
262 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
263 return MemTransferInstData.lookup(&II);
264 }
265
266 /// \brief Map from a PHI or select operand back to a partition.
267 ///
268 /// When manipulating PHI nodes or selects, they can use more than one
269 /// partition of an alloca. We store a special mapping to allow finding the
270 /// partition referenced by each of these operands, if any.
Chandler Carruth77c12702012-10-01 01:49:22 +0000271 iterator findPartitionForPHIOrSelectOperand(Use *U) {
272 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
273 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000274 if (MapIt == PHIOrSelectOpMap.end())
275 return end();
276
277 return begin() + MapIt->second.first;
278 }
279
280 /// \brief Map from a PHI or select operand back to the specific use of
281 /// a partition.
282 ///
283 /// Similar to mapping these operands back to the partitions, this maps
284 /// directly to the use structure of that partition.
Chandler Carruth77c12702012-10-01 01:49:22 +0000285 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
286 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
287 = PHIOrSelectOpMap.find(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000288 assert(MapIt != PHIOrSelectOpMap.end());
289 return Uses[MapIt->second.first].begin() + MapIt->second.second;
290 }
291
292 /// \brief Compute a common type among the uses of a particular partition.
293 ///
294 /// This routines walks all of the uses of a particular partition and tries
295 /// to find a common type between them. Untyped operations such as memset and
296 /// memcpy are ignored.
297 Type *getCommonType(iterator I) const;
298
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000299#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000300 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
301 void printUsers(raw_ostream &OS, const_iterator I,
302 StringRef Indent = " ") const;
303 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000304 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
305 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000306#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000307
308private:
309 template <typename DerivedT, typename RetT = void> class BuilderBase;
310 class PartitionBuilder;
311 friend class AllocaPartitioning::PartitionBuilder;
312 class UseBuilder;
313 friend class AllocaPartitioning::UseBuilder;
314
Benjamin Kramerd0807692012-09-14 13:08:09 +0000315#ifndef NDEBUG
Chandler Carruth713aa942012-09-14 09:22:59 +0000316 /// \brief Handle to alloca instruction to simplify method interfaces.
317 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000318#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000319
320 /// \brief The instruction responsible for this alloca having no partitioning.
321 ///
322 /// When an instruction (potentially) escapes the pointer to the alloca, we
323 /// store a pointer to that here and abort trying to partition the alloca.
324 /// This will be null if the alloca is partitioned successfully.
325 Instruction *PointerEscapingInstr;
326
327 /// \brief The partitions of the alloca.
328 ///
329 /// We store a vector of the partitions over the alloca here. This vector is
330 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000331 /// the Partition inner class for more details. Initially (during
332 /// construction) there are overlaps, but we form a disjoint sequence of
333 /// partitions while finishing construction and a fully constructed object is
334 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000335 SmallVector<Partition, 8> Partitions;
336
337 /// \brief The uses of the partitions.
338 ///
339 /// This is essentially a mapping from each partition to a list of uses of
340 /// that partition. The mapping is done with a Uses vector that has the exact
341 /// same number of entries as the partition vector. Each entry is itself
342 /// a vector of the uses.
343 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
344
345 /// \brief Instructions which will become dead if we rewrite the alloca.
346 ///
347 /// Note that these are not separated by partition. This is because we expect
348 /// a partitioned alloca to be completely rewritten or not rewritten at all.
349 /// If rewritten, all these instructions can simply be removed and replaced
350 /// with undef as they come from outside of the allocated space.
351 SmallVector<Instruction *, 8> DeadUsers;
352
353 /// \brief Operands which will become dead if we rewrite the alloca.
354 ///
355 /// These are operands that in their particular use can be replaced with
356 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
357 /// to PHI nodes and the like. They aren't entirely dead (there might be
358 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
359 /// want to swap this particular input for undef to simplify the use lists of
360 /// the alloca.
361 SmallVector<Use *, 8> DeadOperands;
362
363 /// \brief The underlying storage for auxiliary memcpy and memset info.
364 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
365
366 /// \brief A side datastructure used when building up the partitions and uses.
367 ///
368 /// This mapping is only really used during the initial building of the
369 /// partitioning so that we can retain information about PHI and select nodes
370 /// processed.
371 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
372
373 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth77c12702012-10-01 01:49:22 +0000374 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth713aa942012-09-14 09:22:59 +0000375
376 /// \brief A utility routine called from the constructor.
377 ///
378 /// This does what it says on the tin. It is the key of the alloca partition
379 /// splitting and merging. After it is called we have the desired disjoint
380 /// collection of partitions.
381 void splitAndMergePartitions();
382};
383}
384
385template <typename DerivedT, typename RetT>
386class AllocaPartitioning::BuilderBase
387 : public InstVisitor<DerivedT, RetT> {
388public:
389 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
390 : TD(TD),
391 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
392 P(P) {
393 enqueueUsers(AI, 0);
394 }
395
396protected:
397 const TargetData &TD;
398 const uint64_t AllocSize;
399 AllocaPartitioning &P;
400
Chandler Carruth77c12702012-10-01 01:49:22 +0000401 SmallPtrSet<Use *, 8> VisitedUses;
402
Chandler Carruth713aa942012-09-14 09:22:59 +0000403 struct OffsetUse {
404 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000405 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000406 };
407 SmallVector<OffsetUse, 8> Queue;
408
409 // The active offset and use while visiting.
410 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000411 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000412
Chandler Carruth02e92a02012-09-23 11:43:14 +0000413 void enqueueUsers(Instruction &I, int64_t UserOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000414 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
415 UI != UE; ++UI) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000416 if (VisitedUses.insert(&UI.getUse())) {
417 OffsetUse OU = { &UI.getUse(), UserOffset };
418 Queue.push_back(OU);
419 }
Chandler Carruth713aa942012-09-14 09:22:59 +0000420 }
421 }
422
Chandler Carruth02e92a02012-09-23 11:43:14 +0000423 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000424 GEPOffset = Offset;
425 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
426 GTI != GTE; ++GTI) {
427 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
428 if (!OpC)
429 return false;
430 if (OpC->isZero())
431 continue;
432
433 // Handle a struct index, which adds its field offset to the pointer.
434 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
435 unsigned ElementIdx = OpC->getZExtValue();
436 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth02e92a02012-09-23 11:43:14 +0000437 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
438 // Check that we can continue to model this GEP in a signed 64-bit offset.
439 if (ElementOffset > INT64_MAX ||
440 (GEPOffset >= 0 &&
441 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
442 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
443 << "what can be represented in an int64_t!\n"
444 << " alloca: " << P.AI << "\n");
445 return false;
446 }
447 if (GEPOffset < 0)
448 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
449 else
450 GEPOffset += ElementOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000451 continue;
452 }
453
Chandler Carruth02e92a02012-09-23 11:43:14 +0000454 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
455 Index *= APInt(Index.getBitWidth(),
456 TD.getTypeAllocSize(GTI.getIndexedType()));
457 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
458 /*isSigned*/true);
459 // Check if the result can be stored in our int64_t offset.
460 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
461 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
462 << "what can be represented in an int64_t!\n"
463 << " alloca: " << P.AI << "\n");
464 return false;
465 }
466
467 GEPOffset = Index.getSExtValue();
Chandler Carruth713aa942012-09-14 09:22:59 +0000468 }
469 return true;
470 }
471
472 Value *foldSelectInst(SelectInst &SI) {
473 // If the condition being selected on is a constant or the same value is
474 // being selected between, fold the select. Yes this does (rarely) happen
475 // early on.
476 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
477 return SI.getOperand(1+CI->isZero());
478 if (SI.getOperand(1) == SI.getOperand(2)) {
479 assert(*U == SI.getOperand(1));
480 return SI.getOperand(1);
481 }
482 return 0;
483 }
484};
485
486/// \brief Builder for the alloca partitioning.
487///
488/// This class builds an alloca partitioning by recursively visiting the uses
489/// of an alloca and splitting the partitions for each load and store at each
490/// offset.
491class AllocaPartitioning::PartitionBuilder
492 : public BuilderBase<PartitionBuilder, bool> {
493 friend class InstVisitor<PartitionBuilder, bool>;
494
495 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
496
497public:
498 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000499 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000500
501 /// \brief Run the builder over the allocation.
502 bool operator()() {
503 // Note that we have to re-evaluate size on each trip through the loop as
504 // the queue grows at the tail.
505 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
506 U = Queue[Idx].U;
507 Offset = Queue[Idx].Offset;
508 if (!visit(cast<Instruction>(U->getUser())))
509 return false;
510 }
511 return true;
512 }
513
514private:
515 bool markAsEscaping(Instruction &I) {
516 P.PointerEscapingInstr = &I;
517 return false;
518 }
519
Chandler Carruth02e92a02012-09-23 11:43:14 +0000520 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000521 bool IsSplittable = false) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000522 // Completely skip uses which have a zero size or don't overlap the
523 // allocation.
524 if (Size == 0 ||
525 (Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000526 (Offset < 0 && (uint64_t)-Offset >= Size)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000527 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
528 << " which starts past the end of the " << AllocSize
529 << " byte alloca:\n"
530 << " alloca: " << P.AI << "\n"
531 << " use: " << I << "\n");
532 return;
533 }
534
Chandler Carruth02e92a02012-09-23 11:43:14 +0000535 // Clamp the start to the beginning of the allocation.
536 if (Offset < 0) {
537 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
538 << " to start at the beginning of the alloca:\n"
539 << " alloca: " << P.AI << "\n"
540 << " use: " << I << "\n");
541 Size -= (uint64_t)-Offset;
542 Offset = 0;
543 }
544
545 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
546
547 // Clamp the end offset to the end of the allocation. Note that this is
548 // formulated to handle even the case where "BeginOffset + Size" overflows.
549 assert(AllocSize >= BeginOffset); // Established above.
550 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000551 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
552 << " to remain within the " << AllocSize << " byte alloca:\n"
553 << " alloca: " << P.AI << "\n"
554 << " use: " << I << "\n");
555 EndOffset = AllocSize;
556 }
557
558 // See if we can just add a user onto the last slot currently occupied.
559 if (!P.Partitions.empty() &&
560 P.Partitions.back().BeginOffset == BeginOffset &&
561 P.Partitions.back().EndOffset == EndOffset) {
562 P.Partitions.back().IsSplittable &= IsSplittable;
563 return;
564 }
565
566 Partition New(BeginOffset, EndOffset, IsSplittable);
567 P.Partitions.push_back(New);
568 }
569
Chandler Carruth02e92a02012-09-23 11:43:14 +0000570 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000571 uint64_t Size = TD.getTypeStoreSize(Ty);
572
573 // If this memory access can be shown to *statically* extend outside the
574 // bounds of of the allocation, it's behavior is undefined, so simply
575 // ignore it. Note that this is more strict than the generic clamping
576 // behavior of insertUse. We also try to handle cases which might run the
577 // risk of overflow.
578 // FIXME: We should instead consider the pointer to have escaped if this
579 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000580 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
581 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000582 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
583 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
584 << " which extends past the end of the " << AllocSize
585 << " byte alloca:\n"
586 << " alloca: " << P.AI << "\n"
587 << " use: " << I << "\n");
588 return true;
589 }
590
Chandler Carruth63392ea2012-09-16 19:39:50 +0000591 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000592 return true;
593 }
594
595 bool visitBitCastInst(BitCastInst &BC) {
596 enqueueUsers(BC, Offset);
597 return true;
598 }
599
600 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000601 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000602 if (!computeConstantGEPOffset(GEPI, GEPOffset))
603 return markAsEscaping(GEPI);
604
605 enqueueUsers(GEPI, GEPOffset);
606 return true;
607 }
608
609 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000610 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
611 "All simple FCA loads should have been pre-split");
Chandler Carruth63392ea2012-09-16 19:39:50 +0000612 return handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000613 }
614
615 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000616 Value *ValOp = SI.getValueOperand();
617 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000618 return markAsEscaping(SI);
619
Chandler Carruthc370acd2012-09-18 12:57:43 +0000620 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
621 "All simple FCA stores should have been pre-split");
622 return handleLoadOrStore(ValOp->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000623 }
624
625
626 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000627 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000628 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000629 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
630 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000631 return true;
632 }
633
634 bool visitMemTransferInst(MemTransferInst &II) {
635 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
636 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
637 if (!Size)
638 // Zero-length mem transfer intrinsics can be ignored entirely.
639 return true;
640
641 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
642
643 // Only intrinsics with a constant length can be split.
644 Offsets.IsSplittable = Length;
645
646 if (*U != II.getRawDest()) {
647 assert(*U == II.getRawSource());
648 Offsets.SourceBegin = Offset;
649 Offsets.SourceEnd = Offset + Size;
650 } else {
651 Offsets.DestBegin = Offset;
652 Offsets.DestEnd = Offset + Size;
653 }
654
Chandler Carruth63392ea2012-09-16 19:39:50 +0000655 insertUse(II, Offset, Size, Offsets.IsSplittable);
Chandler Carruth713aa942012-09-14 09:22:59 +0000656 unsigned NewIdx = P.Partitions.size() - 1;
657
658 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
659 bool Inserted = false;
660 llvm::tie(PMI, Inserted)
661 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
Chandler Carruthb3dca3f2012-09-26 07:41:40 +0000662 if (Offsets.IsSplittable &&
663 (!Inserted || II.getRawSource() == II.getRawDest())) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000664 // We've found a memory transfer intrinsic which refers to the alloca as
Chandler Carruthb3dca3f2012-09-26 07:41:40 +0000665 // both a source and dest. This is detected either by direct equality of
666 // the operand values, or when we visit the intrinsic twice due to two
667 // different chains of values leading to it. We refuse to split these to
668 // simplify splitting logic. If possible, SROA will still split them into
669 // separate allocas and then re-analyze.
Chandler Carruth713aa942012-09-14 09:22:59 +0000670 Offsets.IsSplittable = false;
671 P.Partitions[PMI->second].IsSplittable = false;
672 P.Partitions[NewIdx].IsSplittable = false;
673 }
674
675 return true;
676 }
677
678 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000679 // FIXME: What about debug instrinsics? This matches old behavior, but
680 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000681 bool visitIntrinsicInst(IntrinsicInst &II) {
682 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
683 II.getIntrinsicID() == Intrinsic::lifetime_end) {
684 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
685 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000686 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000687 return true;
688 }
689
690 return markAsEscaping(II);
691 }
692
693 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
694 // We consider any PHI or select that results in a direct load or store of
695 // the same offset to be a viable use for partitioning purposes. These uses
696 // are considered unsplittable and the size is the maximum loaded or stored
697 // size.
698 SmallPtrSet<Instruction *, 4> Visited;
699 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
700 Visited.insert(Root);
701 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruthc3034632012-09-25 10:03:40 +0000702 // If there are no loads or stores, the access is dead. We mark that as
703 // a size zero access.
704 Size = 0;
Chandler Carruth713aa942012-09-14 09:22:59 +0000705 do {
706 Instruction *I, *UsedI;
707 llvm::tie(UsedI, I) = Uses.pop_back_val();
708
709 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
710 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
711 continue;
712 }
713 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
714 Value *Op = SI->getOperand(0);
715 if (Op == UsedI)
716 return SI;
717 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
718 continue;
719 }
720
721 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
722 if (!GEP->hasAllZeroIndices())
723 return GEP;
724 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
725 !isa<SelectInst>(I)) {
726 return I;
727 }
728
729 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
730 ++UI)
731 if (Visited.insert(cast<Instruction>(*UI)))
732 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
733 } while (!Uses.empty());
734
735 return 0;
736 }
737
738 bool visitPHINode(PHINode &PN) {
739 // See if we already have computed info on this node.
740 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
741 if (PHIInfo.first) {
742 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000743 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000744 return true;
745 }
746
747 // Check for an unsafe use of the PHI node.
748 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
749 return markAsEscaping(*EscapingI);
750
Chandler Carruth63392ea2012-09-16 19:39:50 +0000751 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000752 return true;
753 }
754
755 bool visitSelectInst(SelectInst &SI) {
756 if (Value *Result = foldSelectInst(SI)) {
757 if (Result == *U)
758 // If the result of the constant fold will be the pointer, recurse
759 // through the select as if we had RAUW'ed it.
760 enqueueUsers(SI, Offset);
761
762 return true;
763 }
764
765 // See if we already have computed info on this node.
766 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
767 if (SelectInfo.first) {
768 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000769 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000770 return true;
771 }
772
773 // Check for an unsafe use of the PHI node.
774 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
775 return markAsEscaping(*EscapingI);
776
Chandler Carruth63392ea2012-09-16 19:39:50 +0000777 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000778 return true;
779 }
780
781 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
782 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
783};
784
785
786/// \brief Use adder for the alloca partitioning.
787///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000788/// This class adds the uses of an alloca to all of the partitions which they
789/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000790/// walk of the partitions, but the number of steps remains bounded by the
791/// total result instruction size:
792/// - The number of partitions is a result of the number unsplittable
793/// instructions using the alloca.
794/// - The number of users of each partition is at worst the total number of
795/// splittable instructions using the alloca.
796/// Thus we will produce N * M instructions in the end, where N are the number
797/// of unsplittable uses and M are the number of splittable. This visitor does
798/// the exact same number of updates to the partitioning.
799///
800/// In the more common case, this visitor will leverage the fact that the
801/// partition space is pre-sorted, and do a logarithmic search for the
802/// partition needed, making the total visit a classical ((N + M) * log(N))
803/// complexity operation.
804class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
805 friend class InstVisitor<UseBuilder>;
806
807 /// \brief Set to de-duplicate dead instructions found in the use walk.
808 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
809
810public:
811 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000812 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000813
814 /// \brief Run the builder over the allocation.
815 void operator()() {
816 // Note that we have to re-evaluate size on each trip through the loop as
817 // the queue grows at the tail.
818 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
819 U = Queue[Idx].U;
820 Offset = Queue[Idx].Offset;
821 this->visit(cast<Instruction>(U->getUser()));
822 }
823 }
824
825private:
826 void markAsDead(Instruction &I) {
827 if (VisitedDeadInsts.insert(&I))
828 P.DeadUsers.push_back(&I);
829 }
830
Chandler Carruth02e92a02012-09-23 11:43:14 +0000831 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruthc3034632012-09-25 10:03:40 +0000832 // If the use has a zero size or extends outside of the allocation, record
833 // it as a dead use for elimination later.
834 if (Size == 0 || (uint64_t)Offset >= AllocSize ||
Chandler Carruth02e92a02012-09-23 11:43:14 +0000835 (Offset < 0 && (uint64_t)-Offset >= Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000836 return markAsDead(User);
837
Chandler Carruth02e92a02012-09-23 11:43:14 +0000838 // Clamp the start to the beginning of the allocation.
839 if (Offset < 0) {
840 Size -= (uint64_t)-Offset;
841 Offset = 0;
842 }
843
844 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
845
846 // Clamp the end offset to the end of the allocation. Note that this is
847 // formulated to handle even the case where "BeginOffset + Size" overflows.
848 assert(AllocSize >= BeginOffset); // Established above.
849 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000850 EndOffset = AllocSize;
851
852 // NB: This only works if we have zero overlapping partitions.
853 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
854 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
855 B = llvm::prior(B);
856 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
857 ++I) {
Chandler Carruth77c12702012-10-01 01:49:22 +0000858 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
859 std::min(I->EndOffset, EndOffset), U);
860 P.use_push_back(I, NewPU);
Chandler Carruth713aa942012-09-14 09:22:59 +0000861 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth77c12702012-10-01 01:49:22 +0000862 P.PHIOrSelectOpMap[U]
Chandler Carruth713aa942012-09-14 09:22:59 +0000863 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
864 }
865 }
866
Chandler Carruth02e92a02012-09-23 11:43:14 +0000867 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000868 uint64_t Size = TD.getTypeStoreSize(Ty);
869
870 // If this memory access can be shown to *statically* extend outside the
871 // bounds of of the allocation, it's behavior is undefined, so simply
872 // ignore it. Note that this is more strict than the generic clamping
873 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000874 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
875 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000876 return markAsDead(I);
877
Chandler Carruth63392ea2012-09-16 19:39:50 +0000878 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000879 }
880
881 void visitBitCastInst(BitCastInst &BC) {
882 if (BC.use_empty())
883 return markAsDead(BC);
884
885 enqueueUsers(BC, Offset);
886 }
887
888 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
889 if (GEPI.use_empty())
890 return markAsDead(GEPI);
891
Chandler Carruth02e92a02012-09-23 11:43:14 +0000892 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000893 if (!computeConstantGEPOffset(GEPI, GEPOffset))
894 llvm_unreachable("Unable to compute constant offset for use");
895
896 enqueueUsers(GEPI, GEPOffset);
897 }
898
899 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000900 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000901 }
902
903 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000904 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000905 }
906
907 void visitMemSetInst(MemSetInst &II) {
908 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000909 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
910 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000911 }
912
913 void visitMemTransferInst(MemTransferInst &II) {
914 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000915 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
916 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000917 }
918
919 void visitIntrinsicInst(IntrinsicInst &II) {
920 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
921 II.getIntrinsicID() == Intrinsic::lifetime_end);
922
923 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000924 insertUse(II, Offset,
925 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000926 }
927
Chandler Carruth63392ea2012-09-16 19:39:50 +0000928 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000929 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
930
931 // For PHI and select operands outside the alloca, we can't nuke the entire
932 // phi or select -- the other side might still be relevant, so we special
933 // case them here and use a separate structure to track the operands
934 // themselves which should be replaced with undef.
935 if (Offset >= AllocSize) {
936 P.DeadOperands.push_back(U);
937 return;
938 }
939
Chandler Carruth63392ea2012-09-16 19:39:50 +0000940 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000941 }
942 void visitPHINode(PHINode &PN) {
943 if (PN.use_empty())
944 return markAsDead(PN);
945
Chandler Carruth63392ea2012-09-16 19:39:50 +0000946 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000947 }
948 void visitSelectInst(SelectInst &SI) {
949 if (SI.use_empty())
950 return markAsDead(SI);
951
952 if (Value *Result = foldSelectInst(SI)) {
953 if (Result == *U)
954 // If the result of the constant fold will be the pointer, recurse
955 // through the select as if we had RAUW'ed it.
956 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +0000957 else
958 // Otherwise the operand to the select is dead, and we can replace it
959 // with undef.
960 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000961
962 return;
963 }
964
Chandler Carruth63392ea2012-09-16 19:39:50 +0000965 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000966 }
967
968 /// \brief Unreachable, we've already visited the alloca once.
969 void visitInstruction(Instruction &I) {
970 llvm_unreachable("Unhandled instruction in use builder.");
971 }
972};
973
974void AllocaPartitioning::splitAndMergePartitions() {
975 size_t NumDeadPartitions = 0;
976
977 // Track the range of splittable partitions that we pass when accumulating
978 // overlapping unsplittable partitions.
979 uint64_t SplitEndOffset = 0ull;
980
981 Partition New(0ull, 0ull, false);
982
983 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
984 ++j;
985
986 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
987 assert(New.BeginOffset == New.EndOffset);
988 New = Partitions[i];
989 } else {
990 assert(New.IsSplittable);
991 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
992 }
993 assert(New.BeginOffset != New.EndOffset);
994
995 // Scan the overlapping partitions.
996 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
997 // If the new partition we are forming is splittable, stop at the first
998 // unsplittable partition.
999 if (New.IsSplittable && !Partitions[j].IsSplittable)
1000 break;
1001
1002 // Grow the new partition to include any equally splittable range. 'j' is
1003 // always equally splittable when New is splittable, but when New is not
1004 // splittable, we may subsume some (or part of some) splitable partition
1005 // without growing the new one.
1006 if (New.IsSplittable == Partitions[j].IsSplittable) {
1007 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1008 } else {
1009 assert(!New.IsSplittable);
1010 assert(Partitions[j].IsSplittable);
1011 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1012 }
1013
1014 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
1015 ++NumDeadPartitions;
1016 ++j;
1017 }
1018
1019 // If the new partition is splittable, chop off the end as soon as the
1020 // unsplittable subsequent partition starts and ensure we eventually cover
1021 // the splittable area.
1022 if (j != e && New.IsSplittable) {
1023 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1024 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1025 }
1026
1027 // Add the new partition if it differs from the original one and is
1028 // non-empty. We can end up with an empty partition here if it was
1029 // splittable but there is an unsplittable one that starts at the same
1030 // offset.
1031 if (New != Partitions[i]) {
1032 if (New.BeginOffset != New.EndOffset)
1033 Partitions.push_back(New);
1034 // Mark the old one for removal.
1035 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
1036 ++NumDeadPartitions;
1037 }
1038
1039 New.BeginOffset = New.EndOffset;
1040 if (!New.IsSplittable) {
1041 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1042 if (j != e && !Partitions[j].IsSplittable)
1043 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1044 New.IsSplittable = true;
1045 // If there is a trailing splittable partition which won't be fused into
1046 // the next splittable partition go ahead and add it onto the partitions
1047 // list.
1048 if (New.BeginOffset < New.EndOffset &&
1049 (j == e || !Partitions[j].IsSplittable ||
1050 New.EndOffset < Partitions[j].BeginOffset)) {
1051 Partitions.push_back(New);
1052 New.BeginOffset = New.EndOffset = 0ull;
1053 }
1054 }
1055 }
1056
1057 // Re-sort the partitions now that they have been split and merged into
1058 // disjoint set of partitions. Also remove any of the dead partitions we've
1059 // replaced in the process.
1060 std::sort(Partitions.begin(), Partitions.end());
1061 if (NumDeadPartitions) {
1062 assert(Partitions.back().BeginOffset == UINT64_MAX);
1063 assert(Partitions.back().EndOffset == UINT64_MAX);
1064 assert((ptrdiff_t)NumDeadPartitions ==
1065 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1066 }
1067 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1068}
1069
1070AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001071 :
1072#ifndef NDEBUG
1073 AI(AI),
1074#endif
1075 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001076 PartitionBuilder PB(TD, AI, *this);
1077 if (!PB())
1078 return;
1079
1080 if (Partitions.size() > 1) {
1081 // Sort the uses. This arranges for the offsets to be in ascending order,
1082 // and the sizes to be in descending order.
1083 std::sort(Partitions.begin(), Partitions.end());
1084
1085 // Intersect splittability for all partitions with equal offsets and sizes.
1086 // Then remove all but the first so that we have a sequence of non-equal but
1087 // potentially overlapping partitions.
1088 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1089 I = J) {
1090 ++J;
1091 while (J != E && *I == *J) {
1092 I->IsSplittable &= J->IsSplittable;
1093 ++J;
1094 }
1095 }
1096 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1097 Partitions.end());
1098
1099 // Split splittable and merge unsplittable partitions into a disjoint set
1100 // of partitions over the used space of the allocation.
1101 splitAndMergePartitions();
1102 }
1103
1104 // Now build up the user lists for each of these disjoint partitions by
1105 // re-walking the recursive users of the alloca.
1106 Uses.resize(Partitions.size());
1107 UseBuilder UB(TD, AI, *this);
1108 UB();
Chandler Carruth713aa942012-09-14 09:22:59 +00001109}
1110
1111Type *AllocaPartitioning::getCommonType(iterator I) const {
1112 Type *Ty = 0;
1113 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001114 if (!UI->U)
1115 continue; // Skip dead uses.
Chandler Carruth77c12702012-10-01 01:49:22 +00001116 if (isa<IntrinsicInst>(*UI->U->getUser()))
Chandler Carruth713aa942012-09-14 09:22:59 +00001117 continue;
1118 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001119 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001120
1121 Type *UserTy = 0;
Chandler Carruth77c12702012-10-01 01:49:22 +00001122 if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001123 UserTy = LI->getType();
Chandler Carruth77c12702012-10-01 01:49:22 +00001124 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001125 UserTy = SI->getValueOperand()->getType();
Chandler Carruth713aa942012-09-14 09:22:59 +00001126 }
1127
1128 if (Ty && Ty != UserTy)
1129 return 0;
1130
1131 Ty = UserTy;
1132 }
1133 return Ty;
1134}
1135
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001136#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1137
Chandler Carruth713aa942012-09-14 09:22:59 +00001138void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1139 StringRef Indent) const {
1140 OS << Indent << "partition #" << (I - begin())
1141 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1142 << (I->IsSplittable ? " (splittable)" : "")
1143 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1144 << "\n";
1145}
1146
1147void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1148 StringRef Indent) const {
1149 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1150 UI != UE; ++UI) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001151 if (!UI->U)
1152 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00001153 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carruth77c12702012-10-01 01:49:22 +00001154 << "used by: " << *UI->U->getUser() << "\n";
1155 if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001156 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1157 bool IsDest;
1158 if (!MTO.IsSplittable)
1159 IsDest = UI->BeginOffset == MTO.DestBegin;
1160 else
1161 IsDest = MTO.DestBegin != 0u;
1162 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1163 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1164 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1165 }
1166 }
1167}
1168
1169void AllocaPartitioning::print(raw_ostream &OS) const {
1170 if (PointerEscapingInstr) {
1171 OS << "No partitioning for alloca: " << AI << "\n"
1172 << " A pointer to this alloca escaped by:\n"
1173 << " " << *PointerEscapingInstr << "\n";
1174 return;
1175 }
1176
1177 OS << "Partitioning of alloca: " << AI << "\n";
1178 unsigned Num = 0;
1179 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1180 print(OS, I);
1181 printUsers(OS, I);
1182 }
1183}
1184
1185void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1186void AllocaPartitioning::dump() const { print(dbgs()); }
1187
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001188#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1189
Chandler Carruth713aa942012-09-14 09:22:59 +00001190
1191namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001192/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1193///
1194/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1195/// the loads and stores of an alloca instruction, as well as updating its
1196/// debug information. This is used when a domtree is unavailable and thus
1197/// mem2reg in its full form can't be used to handle promotion of allocas to
1198/// scalar values.
1199class AllocaPromoter : public LoadAndStorePromoter {
1200 AllocaInst &AI;
1201 DIBuilder &DIB;
1202
1203 SmallVector<DbgDeclareInst *, 4> DDIs;
1204 SmallVector<DbgValueInst *, 4> DVIs;
1205
1206public:
1207 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1208 AllocaInst &AI, DIBuilder &DIB)
1209 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1210
1211 void run(const SmallVectorImpl<Instruction*> &Insts) {
1212 // Remember which alloca we're promoting (for isInstInList).
1213 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1214 for (Value::use_iterator UI = DebugNode->use_begin(),
1215 UE = DebugNode->use_end();
1216 UI != UE; ++UI)
1217 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1218 DDIs.push_back(DDI);
1219 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1220 DVIs.push_back(DVI);
1221 }
1222
1223 LoadAndStorePromoter::run(Insts);
1224 AI.eraseFromParent();
1225 while (!DDIs.empty())
1226 DDIs.pop_back_val()->eraseFromParent();
1227 while (!DVIs.empty())
1228 DVIs.pop_back_val()->eraseFromParent();
1229 }
1230
1231 virtual bool isInstInList(Instruction *I,
1232 const SmallVectorImpl<Instruction*> &Insts) const {
1233 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1234 return LI->getOperand(0) == &AI;
1235 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1236 }
1237
1238 virtual void updateDebugInfo(Instruction *Inst) const {
1239 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1240 E = DDIs.end(); I != E; ++I) {
1241 DbgDeclareInst *DDI = *I;
1242 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1243 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1244 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1245 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1246 }
1247 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1248 E = DVIs.end(); I != E; ++I) {
1249 DbgValueInst *DVI = *I;
1250 Value *Arg = NULL;
1251 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1252 // If an argument is zero extended then use argument directly. The ZExt
1253 // may be zapped by an optimization pass in future.
1254 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1255 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1256 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1257 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1258 if (!Arg)
1259 Arg = SI->getOperand(0);
1260 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1261 Arg = LI->getOperand(0);
1262 } else {
1263 continue;
1264 }
1265 Instruction *DbgVal =
1266 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1267 Inst);
1268 DbgVal->setDebugLoc(DVI->getDebugLoc());
1269 }
1270 }
1271};
1272} // end anon namespace
1273
1274
1275namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001276/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1277///
1278/// This pass takes allocations which can be completely analyzed (that is, they
1279/// don't escape) and tries to turn them into scalar SSA values. There are
1280/// a few steps to this process.
1281///
1282/// 1) It takes allocations of aggregates and analyzes the ways in which they
1283/// are used to try to split them into smaller allocations, ideally of
1284/// a single scalar data type. It will split up memcpy and memset accesses
1285/// as necessary and try to isolate invidual scalar accesses.
1286/// 2) It will transform accesses into forms which are suitable for SSA value
1287/// promotion. This can be replacing a memset with a scalar store of an
1288/// integer value, or it can involve speculating operations on a PHI or
1289/// select to be a PHI or select of the results.
1290/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1291/// onto insert and extract operations on a vector value, and convert them to
1292/// this form. By doing so, it will enable promotion of vector aggregates to
1293/// SSA vector values.
1294class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001295 const bool RequiresDomTree;
1296
Chandler Carruth713aa942012-09-14 09:22:59 +00001297 LLVMContext *C;
1298 const TargetData *TD;
1299 DominatorTree *DT;
1300
1301 /// \brief Worklist of alloca instructions to simplify.
1302 ///
1303 /// Each alloca in the function is added to this. Each new alloca formed gets
1304 /// added to it as well to recursively simplify unless that alloca can be
1305 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1306 /// the one being actively rewritten, we add it back onto the list if not
1307 /// already present to ensure it is re-visited.
1308 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1309
1310 /// \brief A collection of instructions to delete.
1311 /// We try to batch deletions to simplify code and make things a bit more
1312 /// efficient.
1313 SmallVector<Instruction *, 8> DeadInsts;
1314
1315 /// \brief A set to prevent repeatedly marking an instruction split into many
1316 /// uses as dead. Only used to guard insertion into DeadInsts.
1317 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1318
Chandler Carruth713aa942012-09-14 09:22:59 +00001319 /// \brief A collection of alloca instructions we can directly promote.
1320 std::vector<AllocaInst *> PromotableAllocas;
1321
1322public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001323 SROA(bool RequiresDomTree = true)
1324 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1325 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001326 initializeSROAPass(*PassRegistry::getPassRegistry());
1327 }
1328 bool runOnFunction(Function &F);
1329 void getAnalysisUsage(AnalysisUsage &AU) const;
1330
1331 const char *getPassName() const { return "SROA"; }
1332 static char ID;
1333
1334private:
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001335 friend class PHIOrSelectSpeculator;
Chandler Carruth713aa942012-09-14 09:22:59 +00001336 friend class AllocaPartitionRewriter;
1337 friend class AllocaPartitionVectorRewriter;
1338
1339 bool rewriteAllocaPartition(AllocaInst &AI,
1340 AllocaPartitioning &P,
1341 AllocaPartitioning::iterator PI);
1342 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1343 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001344 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001345 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001346};
1347}
1348
1349char SROA::ID = 0;
1350
Chandler Carruth1c8db502012-09-15 11:43:14 +00001351FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1352 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001353}
1354
1355INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1356 false, false)
1357INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1358INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1359 false, false)
1360
1361/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1362///
1363/// If the provided GEP is all-constant, the total byte offset formed by the
1364/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1365/// operands, the function returns false and the value of Offset is unmodified.
1366static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1367 APInt &Offset) {
1368 APInt GEPOffset(Offset.getBitWidth(), 0);
1369 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1370 GTI != GTE; ++GTI) {
1371 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1372 if (!OpC)
1373 return false;
1374 if (OpC->isZero()) continue;
1375
1376 // Handle a struct index, which adds its field offset to the pointer.
1377 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1378 unsigned ElementIdx = OpC->getZExtValue();
1379 const StructLayout *SL = TD.getStructLayout(STy);
1380 GEPOffset += APInt(Offset.getBitWidth(),
1381 SL->getElementOffset(ElementIdx));
1382 continue;
1383 }
1384
1385 APInt TypeSize(Offset.getBitWidth(),
1386 TD.getTypeAllocSize(GTI.getIndexedType()));
1387 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1388 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1389 "vector element size is not a multiple of 8, cannot GEP over it");
1390 TypeSize = VTy->getScalarSizeInBits() / 8;
1391 }
1392
1393 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1394 }
1395 Offset = GEPOffset;
1396 return true;
1397}
1398
1399/// \brief Build a GEP out of a base pointer and indices.
1400///
1401/// This will return the BasePtr if that is valid, or build a new GEP
1402/// instruction using the IRBuilder if GEP-ing is needed.
1403static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1404 SmallVectorImpl<Value *> &Indices,
1405 const Twine &Prefix) {
1406 if (Indices.empty())
1407 return BasePtr;
1408
1409 // A single zero index is a no-op, so check for this and avoid building a GEP
1410 // in that case.
1411 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1412 return BasePtr;
1413
1414 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1415}
1416
1417/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1418/// TargetTy without changing the offset of the pointer.
1419///
1420/// This routine assumes we've already established a properly offset GEP with
1421/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1422/// zero-indices down through type layers until we find one the same as
1423/// TargetTy. If we can't find one with the same type, we at least try to use
1424/// one with the same size. If none of that works, we just produce the GEP as
1425/// indicated by Indices to have the correct offset.
1426static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1427 Value *BasePtr, Type *Ty, Type *TargetTy,
1428 SmallVectorImpl<Value *> &Indices,
1429 const Twine &Prefix) {
1430 if (Ty == TargetTy)
1431 return buildGEP(IRB, BasePtr, Indices, Prefix);
1432
1433 // See if we can descend into a struct and locate a field with the correct
1434 // type.
1435 unsigned NumLayers = 0;
1436 Type *ElementTy = Ty;
1437 do {
1438 if (ElementTy->isPointerTy())
1439 break;
1440 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1441 ElementTy = SeqTy->getElementType();
1442 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1443 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1444 ElementTy = *STy->element_begin();
1445 Indices.push_back(IRB.getInt32(0));
1446 } else {
1447 break;
1448 }
1449 ++NumLayers;
1450 } while (ElementTy != TargetTy);
1451 if (ElementTy != TargetTy)
1452 Indices.erase(Indices.end() - NumLayers, Indices.end());
1453
1454 return buildGEP(IRB, BasePtr, Indices, Prefix);
1455}
1456
1457/// \brief Recursively compute indices for a natural GEP.
1458///
1459/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1460/// element types adding appropriate indices for the GEP.
1461static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1462 Value *Ptr, Type *Ty, APInt &Offset,
1463 Type *TargetTy,
1464 SmallVectorImpl<Value *> &Indices,
1465 const Twine &Prefix) {
1466 if (Offset == 0)
1467 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1468
1469 // We can't recurse through pointer types.
1470 if (Ty->isPointerTy())
1471 return 0;
1472
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001473 // We try to analyze GEPs over vectors here, but note that these GEPs are
1474 // extremely poorly defined currently. The long-term goal is to remove GEPing
1475 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001476 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1477 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1478 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001479 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001480 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1481 APInt NumSkippedElements = Offset.udiv(ElementSize);
1482 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1483 return 0;
1484 Offset -= NumSkippedElements * ElementSize;
1485 Indices.push_back(IRB.getInt(NumSkippedElements));
1486 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1487 Offset, TargetTy, Indices, Prefix);
1488 }
1489
1490 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1491 Type *ElementTy = ArrTy->getElementType();
1492 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1493 APInt NumSkippedElements = Offset.udiv(ElementSize);
1494 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1495 return 0;
1496
1497 Offset -= NumSkippedElements * ElementSize;
1498 Indices.push_back(IRB.getInt(NumSkippedElements));
1499 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1500 Indices, Prefix);
1501 }
1502
1503 StructType *STy = dyn_cast<StructType>(Ty);
1504 if (!STy)
1505 return 0;
1506
1507 const StructLayout *SL = TD.getStructLayout(STy);
1508 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001509 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001510 return 0;
1511 unsigned Index = SL->getElementContainingOffset(StructOffset);
1512 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1513 Type *ElementTy = STy->getElementType(Index);
1514 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1515 return 0; // The offset points into alignment padding.
1516
1517 Indices.push_back(IRB.getInt32(Index));
1518 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1519 Indices, Prefix);
1520}
1521
1522/// \brief Get a natural GEP from a base pointer to a particular offset and
1523/// resulting in a particular type.
1524///
1525/// The goal is to produce a "natural" looking GEP that works with the existing
1526/// composite types to arrive at the appropriate offset and element type for
1527/// a pointer. TargetTy is the element type the returned GEP should point-to if
1528/// possible. We recurse by decreasing Offset, adding the appropriate index to
1529/// Indices, and setting Ty to the result subtype.
1530///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001531/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth713aa942012-09-14 09:22:59 +00001532static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1533 Value *Ptr, APInt Offset, Type *TargetTy,
1534 SmallVectorImpl<Value *> &Indices,
1535 const Twine &Prefix) {
1536 PointerType *Ty = cast<PointerType>(Ptr->getType());
1537
1538 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1539 // an i8.
1540 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1541 return 0;
1542
1543 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001544 if (!ElementTy->isSized())
1545 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001546 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1547 if (ElementSize == 0)
1548 return 0; // Zero-length arrays can't help us build a natural GEP.
1549 APInt NumSkippedElements = Offset.udiv(ElementSize);
1550
1551 Offset -= NumSkippedElements * ElementSize;
1552 Indices.push_back(IRB.getInt(NumSkippedElements));
1553 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1554 Indices, Prefix);
1555}
1556
1557/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1558/// resulting pointer has PointerTy.
1559///
1560/// This tries very hard to compute a "natural" GEP which arrives at the offset
1561/// and produces the pointer type desired. Where it cannot, it will try to use
1562/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1563/// fails, it will try to use an existing i8* and GEP to the byte offset and
1564/// bitcast to the type.
1565///
1566/// The strategy for finding the more natural GEPs is to peel off layers of the
1567/// pointer, walking back through bit casts and GEPs, searching for a base
1568/// pointer from which we can compute a natural GEP with the desired
1569/// properities. The algorithm tries to fold as many constant indices into
1570/// a single GEP as possible, thus making each GEP more independent of the
1571/// surrounding code.
1572static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1573 Value *Ptr, APInt Offset, Type *PointerTy,
1574 const Twine &Prefix) {
1575 // Even though we don't look through PHI nodes, we could be called on an
1576 // instruction in an unreachable block, which may be on a cycle.
1577 SmallPtrSet<Value *, 4> Visited;
1578 Visited.insert(Ptr);
1579 SmallVector<Value *, 4> Indices;
1580
1581 // We may end up computing an offset pointer that has the wrong type. If we
1582 // never are able to compute one directly that has the correct type, we'll
1583 // fall back to it, so keep it around here.
1584 Value *OffsetPtr = 0;
1585
1586 // Remember any i8 pointer we come across to re-use if we need to do a raw
1587 // byte offset.
1588 Value *Int8Ptr = 0;
1589 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1590
1591 Type *TargetTy = PointerTy->getPointerElementType();
1592
1593 do {
1594 // First fold any existing GEPs into the offset.
1595 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1596 APInt GEPOffset(Offset.getBitWidth(), 0);
1597 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1598 break;
1599 Offset += GEPOffset;
1600 Ptr = GEP->getPointerOperand();
1601 if (!Visited.insert(Ptr))
1602 break;
1603 }
1604
1605 // See if we can perform a natural GEP here.
1606 Indices.clear();
1607 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1608 Indices, Prefix)) {
1609 if (P->getType() == PointerTy) {
1610 // Zap any offset pointer that we ended up computing in previous rounds.
1611 if (OffsetPtr && OffsetPtr->use_empty())
1612 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1613 I->eraseFromParent();
1614 return P;
1615 }
1616 if (!OffsetPtr) {
1617 OffsetPtr = P;
1618 }
1619 }
1620
1621 // Stash this pointer if we've found an i8*.
1622 if (Ptr->getType()->isIntegerTy(8)) {
1623 Int8Ptr = Ptr;
1624 Int8PtrOffset = Offset;
1625 }
1626
1627 // Peel off a layer of the pointer and update the offset appropriately.
1628 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1629 Ptr = cast<Operator>(Ptr)->getOperand(0);
1630 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1631 if (GA->mayBeOverridden())
1632 break;
1633 Ptr = GA->getAliasee();
1634 } else {
1635 break;
1636 }
1637 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1638 } while (Visited.insert(Ptr));
1639
1640 if (!OffsetPtr) {
1641 if (!Int8Ptr) {
1642 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1643 Prefix + ".raw_cast");
1644 Int8PtrOffset = Offset;
1645 }
1646
1647 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1648 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1649 Prefix + ".raw_idx");
1650 }
1651 Ptr = OffsetPtr;
1652
1653 // On the off chance we were targeting i8*, guard the bitcast here.
1654 if (Ptr->getType() != PointerTy)
1655 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1656
1657 return Ptr;
1658}
1659
1660/// \brief Test whether the given alloca partition can be promoted to a vector.
1661///
1662/// This is a quick test to check whether we can rewrite a particular alloca
1663/// partition (and its newly formed alloca) into a vector alloca with only
1664/// whole-vector loads and stores such that it could be promoted to a vector
1665/// SSA value. We only can ensure this for a limited set of operations, and we
1666/// don't want to do the rewrites unless we are confident that the result will
1667/// be promotable, so we have an early test here.
1668static bool isVectorPromotionViable(const TargetData &TD,
1669 Type *AllocaTy,
1670 AllocaPartitioning &P,
1671 uint64_t PartitionBeginOffset,
1672 uint64_t PartitionEndOffset,
1673 AllocaPartitioning::const_use_iterator I,
1674 AllocaPartitioning::const_use_iterator E) {
1675 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1676 if (!Ty)
1677 return false;
1678
1679 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1680 uint64_t ElementSize = Ty->getScalarSizeInBits();
1681
1682 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1683 // that aren't byte sized.
1684 if (ElementSize % 8)
1685 return false;
1686 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1687 VecSize /= 8;
1688 ElementSize /= 8;
1689
1690 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001691 if (!I->U)
1692 continue; // Skip dead use.
1693
Chandler Carruth713aa942012-09-14 09:22:59 +00001694 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1695 uint64_t BeginIndex = BeginOffset / ElementSize;
1696 if (BeginIndex * ElementSize != BeginOffset ||
1697 BeginIndex >= Ty->getNumElements())
1698 return false;
1699 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1700 uint64_t EndIndex = EndOffset / ElementSize;
1701 if (EndIndex * ElementSize != EndOffset ||
1702 EndIndex > Ty->getNumElements())
1703 return false;
1704
1705 // FIXME: We should build shuffle vector instructions to handle
1706 // non-element-sized accesses.
1707 if ((EndOffset - BeginOffset) != ElementSize &&
1708 (EndOffset - BeginOffset) != VecSize)
1709 return false;
1710
Chandler Carruth77c12702012-10-01 01:49:22 +00001711 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001712 if (MI->isVolatile())
1713 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00001714 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001715 const AllocaPartitioning::MemTransferOffsets &MTO
1716 = P.getMemTransferOffsets(*MTI);
1717 if (!MTO.IsSplittable)
1718 return false;
1719 }
Chandler Carruth77c12702012-10-01 01:49:22 +00001720 } else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001721 // Disable vector promotion when there are loads or stores of an FCA.
1722 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00001723 } else if (!isa<LoadInst>(I->U->getUser()) &&
1724 !isa<StoreInst>(I->U->getUser())) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001725 return false;
1726 }
1727 }
1728 return true;
1729}
1730
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001731/// \brief Test whether the given alloca partition can be promoted to an int.
1732///
1733/// This is a quick test to check whether we can rewrite a particular alloca
1734/// partition (and its newly formed alloca) into an integer alloca suitable for
1735/// promotion to an SSA value. We only can ensure this for a limited set of
1736/// operations, and we don't want to do the rewrites unless we are confident
1737/// that the result will be promotable, so we have an early test here.
1738static bool isIntegerPromotionViable(const TargetData &TD,
1739 Type *AllocaTy,
Chandler Carruthaa3cb332012-10-04 10:39:28 +00001740 uint64_t AllocBeginOffset,
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001741 AllocaPartitioning &P,
1742 AllocaPartitioning::const_use_iterator I,
1743 AllocaPartitioning::const_use_iterator E) {
1744 IntegerType *Ty = dyn_cast<IntegerType>(AllocaTy);
Chandler Carruthaa3cb332012-10-04 10:39:28 +00001745 if (!Ty || 8*TD.getTypeStoreSize(Ty) != Ty->getBitWidth())
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001746 return false;
1747
1748 // Check the uses to ensure the uses are (likely) promoteable integer uses.
1749 // Also ensure that the alloca has a covering load or store. We don't want
1750 // promote because of some other unsplittable entry (which we may make
1751 // splittable later) and lose the ability to promote each element access.
1752 bool WholeAllocaOp = false;
1753 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00001754 if (!I->U)
1755 continue; // Skip dead use.
Chandler Carruthaa3cb332012-10-04 10:39:28 +00001756
1757 // We can't reasonably handle cases where the load or store extends past
1758 // the end of the aloca's type and into its padding.
1759 if ((I->EndOffset - AllocBeginOffset) > TD.getTypeStoreSize(Ty))
1760 return false;
1761
Chandler Carruth77c12702012-10-01 01:49:22 +00001762 if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001763 if (LI->isVolatile() || !LI->getType()->isIntegerTy())
1764 return false;
1765 if (LI->getType() == Ty)
1766 WholeAllocaOp = true;
Chandler Carruth77c12702012-10-01 01:49:22 +00001767 } else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001768 if (SI->isVolatile() || !SI->getValueOperand()->getType()->isIntegerTy())
1769 return false;
1770 if (SI->getValueOperand()->getType() == Ty)
1771 WholeAllocaOp = true;
Chandler Carruth77c12702012-10-01 01:49:22 +00001772 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001773 if (MI->isVolatile())
1774 return false;
Chandler Carruth77c12702012-10-01 01:49:22 +00001775 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00001776 const AllocaPartitioning::MemTransferOffsets &MTO
1777 = P.getMemTransferOffsets(*MTI);
1778 if (!MTO.IsSplittable)
1779 return false;
1780 }
1781 } else {
1782 return false;
1783 }
1784 }
1785 return WholeAllocaOp;
1786}
1787
Chandler Carruth713aa942012-09-14 09:22:59 +00001788namespace {
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001789/// \brief Visitor to speculate PHIs and Selects where possible.
1790class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1791 // Befriend the base class so it can delegate to private visit methods.
1792 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1793
1794 const TargetData &TD;
1795 AllocaPartitioning &P;
1796 SROA &Pass;
1797
1798public:
1799 PHIOrSelectSpeculator(const TargetData &TD, AllocaPartitioning &P, SROA &Pass)
1800 : TD(TD), P(P), Pass(Pass) {}
1801
Chandler Carrutha346f462012-10-02 17:49:47 +00001802 /// \brief Visit the users of an alloca partition and rewrite them.
1803 void visitUsers(AllocaPartitioning::const_iterator PI) {
1804 // Note that we need to use an index here as the underlying vector of uses
1805 // may be grown during speculation. However, we never need to re-visit the
1806 // new uses, and so we can use the initial size bound.
Chandler Carruthfdb15852012-10-02 18:57:13 +00001807 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
1808 const AllocaPartitioning::PartitionUse &PU = P.getUse(PI, Idx);
1809 if (!PU.U)
1810 continue; // Skip dead use.
1811
1812 visit(cast<Instruction>(PU.U->getUser()));
1813 }
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001814 }
1815
1816private:
1817 // By default, skip this instruction.
1818 void visitInstruction(Instruction &I) {}
1819
1820 /// PHI instructions that use an alloca and are subsequently loaded can be
1821 /// rewritten to load both input pointers in the pred blocks and then PHI the
1822 /// results, allowing the load of the alloca to be promoted.
1823 /// From this:
1824 /// %P2 = phi [i32* %Alloca, i32* %Other]
1825 /// %V = load i32* %P2
1826 /// to:
1827 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1828 /// ...
1829 /// %V2 = load i32* %Other
1830 /// ...
1831 /// %V = phi [i32 %V1, i32 %V2]
1832 ///
Chandler Carruthc7a4ca72012-10-01 12:24:42 +00001833 /// We can do this to a select if its only uses are loads and if the operands
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00001834 /// to the select can be loaded unconditionally.
1835 ///
1836 /// FIXME: This should be hoisted into a generic utility, likely in
1837 /// Transforms/Util/Local.h
1838 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1839 // For now, we can only do this promotion if the load is in the same block
1840 // as the PHI, and if there are no stores between the phi and load.
1841 // TODO: Allow recursive phi users.
1842 // TODO: Allow stores.
1843 BasicBlock *BB = PN.getParent();
1844 unsigned MaxAlign = 0;
1845 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1846 UI != UE; ++UI) {
1847 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1848 if (LI == 0 || !LI->isSimple()) return false;
1849
1850 // For now we only allow loads in the same block as the PHI. This is
1851 // a common case that happens when instcombine merges two loads through
1852 // a PHI.
1853 if (LI->getParent() != BB) return false;
1854
1855 // Ensure that there are no instructions between the PHI and the load that
1856 // could store.
1857 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1858 if (BBI->mayWriteToMemory())
1859 return false;
1860
1861 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1862 Loads.push_back(LI);
1863 }
1864
1865 // We can only transform this if it is safe to push the loads into the
1866 // predecessor blocks. The only thing to watch out for is that we can't put
1867 // a possibly trapping load in the predecessor if it is a critical edge.
1868 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
1869 ++Idx) {
1870 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1871 Value *InVal = PN.getIncomingValue(Idx);
1872
1873 // If the value is produced by the terminator of the predecessor (an
1874 // invoke) or it has side-effects, there is no valid place to put a load
1875 // in the predecessor.
1876 if (TI == InVal || TI->mayHaveSideEffects())
1877 return false;
1878
1879 // If the predecessor has a single successor, then the edge isn't
1880 // critical.
1881 if (TI->getNumSuccessors() == 1)
1882 continue;
1883
1884 // If this pointer is always safe to load, or if we can prove that there
1885 // is already a load in the block, then we can move the load to the pred
1886 // block.
1887 if (InVal->isDereferenceablePointer() ||
1888 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1889 continue;
1890
1891 return false;
1892 }
1893
1894 return true;
1895 }
1896
1897 void visitPHINode(PHINode &PN) {
1898 DEBUG(dbgs() << " original: " << PN << "\n");
1899
1900 SmallVector<LoadInst *, 4> Loads;
1901 if (!isSafePHIToSpeculate(PN, Loads))
1902 return;
1903
1904 assert(!Loads.empty());
1905
1906 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1907 IRBuilder<> PHIBuilder(&PN);
1908 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1909 PN.getName() + ".sroa.speculated");
1910
1911 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
1912 // matter which one we get and if any differ, it doesn't matter.
1913 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1914 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1915 unsigned Align = SomeLoad->getAlignment();
1916
1917 // Rewrite all loads of the PN to use the new PHI.
1918 do {
1919 LoadInst *LI = Loads.pop_back_val();
1920 LI->replaceAllUsesWith(NewPN);
1921 Pass.DeadInsts.push_back(LI);
1922 } while (!Loads.empty());
1923
1924 // Inject loads into all of the pred blocks.
1925 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1926 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1927 TerminatorInst *TI = Pred->getTerminator();
1928 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1929 Value *InVal = PN.getIncomingValue(Idx);
1930 IRBuilder<> PredBuilder(TI);
1931
1932 LoadInst *Load
1933 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1934 Pred->getName()));
1935 ++NumLoadsSpeculated;
1936 Load->setAlignment(Align);
1937 if (TBAATag)
1938 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1939 NewPN->addIncoming(Load, Pred);
1940
1941 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1942 if (!Ptr)
1943 // No uses to rewrite.
1944 continue;
1945
1946 // Try to lookup and rewrite any partition uses corresponding to this phi
1947 // input.
1948 AllocaPartitioning::iterator PI
1949 = P.findPartitionForPHIOrSelectOperand(InUse);
1950 if (PI == P.end())
1951 continue;
1952
1953 // Replace the Use in the PartitionUse for this operand with the Use
1954 // inside the load.
1955 AllocaPartitioning::use_iterator UI
1956 = P.findPartitionUseForPHIOrSelectOperand(InUse);
1957 assert(isa<PHINode>(*UI->U->getUser()));
1958 UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
1959 }
1960 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1961 }
1962
1963 /// Select instructions that use an alloca and are subsequently loaded can be
1964 /// rewritten to load both input pointers and then select between the result,
1965 /// allowing the load of the alloca to be promoted.
1966 /// From this:
1967 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1968 /// %V = load i32* %P2
1969 /// to:
1970 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1971 /// %V2 = load i32* %Other
1972 /// %V = select i1 %cond, i32 %V1, i32 %V2
1973 ///
1974 /// We can do this to a select if its only uses are loads and if the operand
1975 /// to the select can be loaded unconditionally.
1976 bool isSafeSelectToSpeculate(SelectInst &SI,
1977 SmallVectorImpl<LoadInst *> &Loads) {
1978 Value *TValue = SI.getTrueValue();
1979 Value *FValue = SI.getFalseValue();
1980 bool TDerefable = TValue->isDereferenceablePointer();
1981 bool FDerefable = FValue->isDereferenceablePointer();
1982
1983 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1984 UI != UE; ++UI) {
1985 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1986 if (LI == 0 || !LI->isSimple()) return false;
1987
1988 // Both operands to the select need to be dereferencable, either
1989 // absolutely (e.g. allocas) or at this point because we can see other
1990 // accesses to it.
1991 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1992 LI->getAlignment(), &TD))
1993 return false;
1994 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1995 LI->getAlignment(), &TD))
1996 return false;
1997 Loads.push_back(LI);
1998 }
1999
2000 return true;
2001 }
2002
2003 void visitSelectInst(SelectInst &SI) {
2004 DEBUG(dbgs() << " original: " << SI << "\n");
2005 IRBuilder<> IRB(&SI);
2006
2007 // If the select isn't safe to speculate, just use simple logic to emit it.
2008 SmallVector<LoadInst *, 4> Loads;
2009 if (!isSafeSelectToSpeculate(SI, Loads))
2010 return;
2011
2012 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
2013 AllocaPartitioning::iterator PIs[2];
2014 AllocaPartitioning::PartitionUse PUs[2];
2015 for (unsigned i = 0, e = 2; i != e; ++i) {
2016 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
2017 if (PIs[i] != P.end()) {
2018 // If the pointer is within the partitioning, remove the select from
2019 // its uses. We'll add in the new loads below.
2020 AllocaPartitioning::use_iterator UI
2021 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
2022 PUs[i] = *UI;
Chandler Carruthfdb15852012-10-02 18:57:13 +00002023 // Clear out the use here so that the offsets into the use list remain
2024 // stable but this use is ignored when rewriting.
2025 UI->U = 0;
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002026 }
2027 }
2028
2029 Value *TV = SI.getTrueValue();
2030 Value *FV = SI.getFalseValue();
2031 // Replace the loads of the select with a select of two loads.
2032 while (!Loads.empty()) {
2033 LoadInst *LI = Loads.pop_back_val();
2034
2035 IRB.SetInsertPoint(LI);
2036 LoadInst *TL =
2037 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
2038 LoadInst *FL =
2039 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
2040 NumLoadsSpeculated += 2;
2041
2042 // Transfer alignment and TBAA info if present.
2043 TL->setAlignment(LI->getAlignment());
2044 FL->setAlignment(LI->getAlignment());
2045 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2046 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2047 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2048 }
2049
2050 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
2051 LI->getName() + ".sroa.speculated");
2052
2053 LoadInst *Loads[2] = { TL, FL };
2054 for (unsigned i = 0, e = 2; i != e; ++i) {
2055 if (PIs[i] != P.end()) {
2056 Use *LoadUse = &Loads[i]->getOperandUse(0);
2057 assert(PUs[i].U->get() == LoadUse->get());
2058 PUs[i].U = LoadUse;
2059 P.use_push_back(PIs[i], PUs[i]);
2060 }
2061 }
2062
2063 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2064 LI->replaceAllUsesWith(V);
2065 Pass.DeadInsts.push_back(LI);
2066 }
2067 }
2068};
2069
Chandler Carruth713aa942012-09-14 09:22:59 +00002070/// \brief Visitor to rewrite instructions using a partition of an alloca to
2071/// use a new alloca.
2072///
2073/// Also implements the rewriting to vector-based accesses when the partition
2074/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2075/// lives here.
2076class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2077 bool> {
2078 // Befriend the base class so it can delegate to private visit methods.
2079 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2080
2081 const TargetData &TD;
2082 AllocaPartitioning &P;
2083 SROA &Pass;
2084 AllocaInst &OldAI, &NewAI;
2085 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2086
2087 // If we are rewriting an alloca partition which can be written as pure
2088 // vector operations, we stash extra information here. When VecTy is
2089 // non-null, we have some strict guarantees about the rewriten alloca:
2090 // - The new alloca is exactly the size of the vector type here.
2091 // - The accesses all either map to the entire vector or to a single
2092 // element.
2093 // - The set of accessing instructions is only one of those handled above
2094 // in isVectorPromotionViable. Generally these are the same access kinds
2095 // which are promotable via mem2reg.
2096 VectorType *VecTy;
2097 Type *ElementTy;
2098 uint64_t ElementSize;
2099
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002100 // This is a convenience and flag variable that will be null unless the new
2101 // alloca has a promotion-targeted integer type due to passing
2102 // isIntegerPromotionViable above. If it is non-null does, the desired
2103 // integer type will be stored here for easy access during rewriting.
2104 IntegerType *IntPromotionTy;
2105
Chandler Carruth713aa942012-09-14 09:22:59 +00002106 // The offset of the partition user currently being rewritten.
2107 uint64_t BeginOffset, EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002108 Use *OldUse;
Chandler Carruth713aa942012-09-14 09:22:59 +00002109 Instruction *OldPtr;
2110
2111 // The name prefix to use when rewriting instructions for this alloca.
2112 std::string NamePrefix;
2113
2114public:
2115 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
2116 AllocaPartitioning::iterator PI,
2117 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2118 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2119 : TD(TD), P(P), Pass(Pass),
2120 OldAI(OldAI), NewAI(NewAI),
2121 NewAllocaBeginOffset(NewBeginOffset),
2122 NewAllocaEndOffset(NewEndOffset),
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002123 VecTy(), ElementTy(), ElementSize(), IntPromotionTy(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002124 BeginOffset(), EndOffset() {
2125 }
2126
2127 /// \brief Visit the users of the alloca partition and rewrite them.
2128 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2129 AllocaPartitioning::const_use_iterator E) {
2130 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2131 NewAllocaBeginOffset, NewAllocaEndOffset,
2132 I, E)) {
2133 ++NumVectorized;
2134 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2135 ElementTy = VecTy->getElementType();
2136 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
2137 "Only multiple-of-8 sized vector elements are viable");
2138 ElementSize = VecTy->getScalarSizeInBits() / 8;
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002139 } else if (isIntegerPromotionViable(TD, NewAI.getAllocatedType(),
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002140 NewAllocaBeginOffset, P, I, E)) {
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002141 IntPromotionTy = cast<IntegerType>(NewAI.getAllocatedType());
Chandler Carruth713aa942012-09-14 09:22:59 +00002142 }
2143 bool CanSROA = true;
2144 for (; I != E; ++I) {
Chandler Carruthfdb15852012-10-02 18:57:13 +00002145 if (!I->U)
2146 continue; // Skip dead uses.
Chandler Carruth713aa942012-09-14 09:22:59 +00002147 BeginOffset = I->BeginOffset;
2148 EndOffset = I->EndOffset;
Chandler Carruth77c12702012-10-01 01:49:22 +00002149 OldUse = I->U;
2150 OldPtr = cast<Instruction>(I->U->get());
Chandler Carruth713aa942012-09-14 09:22:59 +00002151 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
Chandler Carruth77c12702012-10-01 01:49:22 +00002152 CanSROA &= visit(cast<Instruction>(I->U->getUser()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002153 }
2154 if (VecTy) {
2155 assert(CanSROA);
2156 VecTy = 0;
2157 ElementTy = 0;
2158 ElementSize = 0;
2159 }
2160 return CanSROA;
2161 }
2162
2163private:
2164 // Every instruction which can end up as a user must have a rewrite rule.
2165 bool visitInstruction(Instruction &I) {
2166 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2167 llvm_unreachable("No rewrite rule for this instruction!");
2168 }
2169
2170 Twine getName(const Twine &Suffix) {
2171 return NamePrefix + Suffix;
2172 }
2173
2174 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
2175 assert(BeginOffset >= NewAllocaBeginOffset);
2176 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
2177 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
2178 }
2179
Chandler Carruthf710fb12012-10-03 08:14:02 +00002180 /// \brief Compute suitable alignment to access an offset into the new alloca.
2181 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth673850a2012-10-01 12:16:54 +00002182 unsigned NewAIAlign = NewAI.getAlignment();
2183 if (!NewAIAlign)
2184 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2185 return MinAlign(NewAIAlign, Offset);
2186 }
Chandler Carruthf710fb12012-10-03 08:14:02 +00002187
2188 /// \brief Compute suitable alignment to access this partition of the new
2189 /// alloca.
2190 unsigned getPartitionAlign() {
2191 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002192 }
2193
Chandler Carruthf710fb12012-10-03 08:14:02 +00002194 /// \brief Compute suitable alignment to access a type at an offset of the
2195 /// new alloca.
2196 ///
2197 /// \returns zero if the type's ABI alignment is a suitable alignment,
2198 /// otherwise returns the maximal suitable alignment.
2199 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2200 unsigned Align = getOffsetAlign(Offset);
2201 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2202 }
2203
2204 /// \brief Compute suitable alignment to access a type at the beginning of
2205 /// this partition of the new alloca.
2206 ///
2207 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2208 unsigned getPartitionTypeAlign(Type *Ty) {
2209 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth673850a2012-10-01 12:16:54 +00002210 }
2211
Chandler Carruth713aa942012-09-14 09:22:59 +00002212 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
2213 assert(VecTy && "Can only call getIndex when rewriting a vector");
2214 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2215 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2216 uint32_t Index = RelOffset / ElementSize;
2217 assert(Index * ElementSize == RelOffset);
2218 return IRB.getInt32(Index);
2219 }
2220
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002221 Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy,
2222 uint64_t Offset) {
2223 assert(IntPromotionTy && "Alloca is not an integer we can extract from");
Chandler Carruth81b001a2012-09-26 10:27:46 +00002224 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2225 getName(".load"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002226 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2227 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002228 assert(TD.getTypeStoreSize(TargetTy) + RelOffset <=
2229 TD.getTypeStoreSize(IntPromotionTy) &&
2230 "Element load outside of alloca store");
2231 uint64_t ShAmt = 8*RelOffset;
2232 if (TD.isBigEndian())
2233 ShAmt = 8*(TD.getTypeStoreSize(IntPromotionTy) -
2234 TD.getTypeStoreSize(TargetTy) - RelOffset);
2235 if (ShAmt)
2236 V = IRB.CreateLShr(V, ShAmt, getName(".shift"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002237 if (TargetTy != IntPromotionTy) {
2238 assert(TargetTy->getBitWidth() < IntPromotionTy->getBitWidth() &&
2239 "Cannot extract to a larger integer!");
2240 V = IRB.CreateTrunc(V, TargetTy, getName(".trunc"));
2241 }
2242 return V;
2243 }
2244
2245 StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) {
2246 IntegerType *Ty = cast<IntegerType>(V->getType());
2247 if (Ty == IntPromotionTy)
Chandler Carruth81b001a2012-09-26 10:27:46 +00002248 return IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002249
2250 assert(Ty->getBitWidth() < IntPromotionTy->getBitWidth() &&
2251 "Cannot insert a larger integer!");
2252 V = IRB.CreateZExt(V, IntPromotionTy, getName(".ext"));
2253 assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
2254 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002255 assert(TD.getTypeStoreSize(Ty) + RelOffset <=
2256 TD.getTypeStoreSize(IntPromotionTy) &&
2257 "Element store outside of alloca store");
2258 uint64_t ShAmt = 8*RelOffset;
2259 if (TD.isBigEndian())
2260 ShAmt = 8*(TD.getTypeStoreSize(IntPromotionTy) - TD.getTypeStoreSize(Ty)
2261 - RelOffset);
2262 if (ShAmt)
2263 V = IRB.CreateShl(V, ShAmt, getName(".shift"));
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002264
Chandler Carruthaa3cb332012-10-04 10:39:28 +00002265 APInt Mask = ~Ty->getMask().zext(IntPromotionTy->getBitWidth()).shl(ShAmt);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002266 Value *Old = IRB.CreateAnd(IRB.CreateAlignedLoad(&NewAI,
2267 NewAI.getAlignment(),
2268 getName(".oldload")),
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002269 Mask, getName(".mask"));
Chandler Carruth81b001a2012-09-26 10:27:46 +00002270 return IRB.CreateAlignedStore(IRB.CreateOr(Old, V, getName(".insert")),
2271 &NewAI, NewAI.getAlignment());
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002272 }
2273
Chandler Carruth713aa942012-09-14 09:22:59 +00002274 void deleteIfTriviallyDead(Value *V) {
2275 Instruction *I = cast<Instruction>(V);
2276 if (isInstructionTriviallyDead(I))
2277 Pass.DeadInsts.push_back(I);
2278 }
2279
2280 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
2281 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2282 return IRB.CreateIntToPtr(V, Ty);
2283 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2284 return IRB.CreatePtrToInt(V, Ty);
2285
2286 return IRB.CreateBitCast(V, Ty);
2287 }
2288
2289 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
2290 Value *Result;
2291 if (LI.getType() == VecTy->getElementType() ||
2292 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002293 Result = IRB.CreateExtractElement(
2294 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2295 getIndex(IRB, BeginOffset), getName(".extract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002296 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002297 Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2298 getName(".load"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002299 }
2300 if (Result->getType() != LI.getType())
2301 Result = getValueCast(IRB, Result, LI.getType());
2302 LI.replaceAllUsesWith(Result);
2303 Pass.DeadInsts.push_back(&LI);
2304
2305 DEBUG(dbgs() << " to: " << *Result << "\n");
2306 return true;
2307 }
2308
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002309 bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
2310 assert(!LI.isVolatile());
2311 Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()),
2312 BeginOffset);
2313 LI.replaceAllUsesWith(Result);
2314 Pass.DeadInsts.push_back(&LI);
2315 DEBUG(dbgs() << " to: " << *Result << "\n");
2316 return true;
2317 }
2318
Chandler Carruth713aa942012-09-14 09:22:59 +00002319 bool visitLoadInst(LoadInst &LI) {
2320 DEBUG(dbgs() << " original: " << LI << "\n");
2321 Value *OldOp = LI.getOperand(0);
2322 assert(OldOp == OldPtr);
2323 IRBuilder<> IRB(&LI);
2324
2325 if (VecTy)
2326 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002327 if (IntPromotionTy)
2328 return rewriteIntegerLoad(IRB, LI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002329
2330 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2331 LI.getPointerOperand()->getType());
2332 LI.setOperand(0, NewPtr);
Chandler Carruthf710fb12012-10-03 08:14:02 +00002333 LI.setAlignment(getPartitionTypeAlign(LI.getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002334 DEBUG(dbgs() << " to: " << LI << "\n");
2335
2336 deleteIfTriviallyDead(OldOp);
2337 return NewPtr == &NewAI && !LI.isVolatile();
2338 }
2339
2340 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
2341 Value *OldOp) {
2342 Value *V = SI.getValueOperand();
2343 if (V->getType() == ElementTy ||
2344 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
2345 if (V->getType() != ElementTy)
2346 V = getValueCast(IRB, V, ElementTy);
Chandler Carruth81b001a2012-09-26 10:27:46 +00002347 LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2348 getName(".load"));
2349 V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002350 getName(".insert"));
2351 } else if (V->getType() != VecTy) {
2352 V = getValueCast(IRB, V, VecTy);
2353 }
Chandler Carruth81b001a2012-09-26 10:27:46 +00002354 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002355 Pass.DeadInsts.push_back(&SI);
2356
2357 (void)Store;
2358 DEBUG(dbgs() << " to: " << *Store << "\n");
2359 return true;
2360 }
2361
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002362 bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
2363 assert(!SI.isVolatile());
2364 StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset);
2365 Pass.DeadInsts.push_back(&SI);
2366 (void)Store;
2367 DEBUG(dbgs() << " to: " << *Store << "\n");
2368 return true;
2369 }
2370
Chandler Carruth713aa942012-09-14 09:22:59 +00002371 bool visitStoreInst(StoreInst &SI) {
2372 DEBUG(dbgs() << " original: " << SI << "\n");
2373 Value *OldOp = SI.getOperand(1);
2374 assert(OldOp == OldPtr);
2375 IRBuilder<> IRB(&SI);
2376
2377 if (VecTy)
2378 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
Chandler Carruthbc4021f2012-09-24 00:34:20 +00002379 if (IntPromotionTy)
2380 return rewriteIntegerStore(IRB, SI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002381
2382 Value *NewPtr = getAdjustedAllocaPtr(IRB,
2383 SI.getPointerOperand()->getType());
2384 SI.setOperand(1, NewPtr);
Chandler Carruthf710fb12012-10-03 08:14:02 +00002385 SI.setAlignment(getPartitionTypeAlign(SI.getValueOperand()->getType()));
Chandler Carruth713aa942012-09-14 09:22:59 +00002386 DEBUG(dbgs() << " to: " << SI << "\n");
2387
2388 deleteIfTriviallyDead(OldOp);
2389 return NewPtr == &NewAI && !SI.isVolatile();
2390 }
2391
2392 bool visitMemSetInst(MemSetInst &II) {
2393 DEBUG(dbgs() << " original: " << II << "\n");
2394 IRBuilder<> IRB(&II);
2395 assert(II.getRawDest() == OldPtr);
2396
2397 // If the memset has a variable size, it cannot be split, just adjust the
2398 // pointer to the new alloca.
2399 if (!isa<Constant>(II.getLength())) {
2400 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002401 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruthf710fb12012-10-03 08:14:02 +00002402 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002403
Chandler Carruth713aa942012-09-14 09:22:59 +00002404 deleteIfTriviallyDead(OldPtr);
2405 return false;
2406 }
2407
2408 // Record this instruction for deletion.
2409 if (Pass.DeadSplitInsts.insert(&II))
2410 Pass.DeadInsts.push_back(&II);
2411
2412 Type *AllocaTy = NewAI.getAllocatedType();
2413 Type *ScalarTy = AllocaTy->getScalarType();
2414
2415 // If this doesn't map cleanly onto the alloca type, and that type isn't
2416 // a single value type, just emit a memset.
2417 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
2418 EndOffset != NewAllocaEndOffset ||
2419 !AllocaTy->isSingleValueType() ||
2420 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
2421 Type *SizeTy = II.getLength()->getType();
2422 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002423 CallInst *New
2424 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2425 II.getRawDest()->getType()),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002426 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth713aa942012-09-14 09:22:59 +00002427 II.isVolatile());
2428 (void)New;
2429 DEBUG(dbgs() << " to: " << *New << "\n");
2430 return false;
2431 }
2432
2433 // If we can represent this as a simple value, we have to build the actual
2434 // value to store, which requires expanding the byte present in memset to
2435 // a sensible representation for the alloca type. This is essentially
2436 // splatting the byte to a sufficiently wide integer, bitcasting to the
2437 // desired scalar type, and splatting it across any desired vector type.
2438 Value *V = II.getValue();
2439 IntegerType *VTy = cast<IntegerType>(V->getType());
2440 Type *IntTy = Type::getIntNTy(VTy->getContext(),
2441 TD.getTypeSizeInBits(ScalarTy));
2442 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
2443 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
2444 ConstantExpr::getUDiv(
2445 Constant::getAllOnesValue(IntTy),
2446 ConstantExpr::getZExt(
2447 Constant::getAllOnesValue(V->getType()),
2448 IntTy)),
2449 getName(".isplat"));
2450 if (V->getType() != ScalarTy) {
2451 if (ScalarTy->isPointerTy())
2452 V = IRB.CreateIntToPtr(V, ScalarTy);
2453 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
2454 V = IRB.CreateBitCast(V, ScalarTy);
2455 else if (ScalarTy->isIntegerTy())
2456 llvm_unreachable("Computed different integer types with equal widths");
2457 else
2458 llvm_unreachable("Invalid scalar type");
2459 }
2460
2461 // If this is an element-wide memset of a vectorizable alloca, insert it.
2462 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
2463 EndOffset < NewAllocaEndOffset)) {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002464 StoreInst *Store = IRB.CreateAlignedStore(
2465 IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
2466 NewAI.getAlignment(),
2467 getName(".load")),
2468 V, getIndex(IRB, BeginOffset),
Chandler Carruth713aa942012-09-14 09:22:59 +00002469 getName(".insert")),
Chandler Carruth81b001a2012-09-26 10:27:46 +00002470 &NewAI, NewAI.getAlignment());
Chandler Carruth713aa942012-09-14 09:22:59 +00002471 (void)Store;
2472 DEBUG(dbgs() << " to: " << *Store << "\n");
2473 return true;
2474 }
2475
2476 // Splat to a vector if needed.
2477 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
2478 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
2479 V = IRB.CreateShuffleVector(
2480 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
2481 IRB.getInt32(0), getName(".vsplat.insert")),
2482 UndefValue::get(SplatSourceTy),
2483 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
2484 getName(".vsplat.shuffle"));
2485 assert(V->getType() == VecTy);
2486 }
2487
Chandler Carruth81b001a2012-09-26 10:27:46 +00002488 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2489 II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002490 (void)New;
2491 DEBUG(dbgs() << " to: " << *New << "\n");
2492 return !II.isVolatile();
2493 }
2494
2495 bool visitMemTransferInst(MemTransferInst &II) {
2496 // Rewriting of memory transfer instructions can be a bit tricky. We break
2497 // them into two categories: split intrinsics and unsplit intrinsics.
2498
2499 DEBUG(dbgs() << " original: " << II << "\n");
2500 IRBuilder<> IRB(&II);
2501
2502 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2503 bool IsDest = II.getRawDest() == OldPtr;
2504
2505 const AllocaPartitioning::MemTransferOffsets &MTO
2506 = P.getMemTransferOffsets(II);
2507
Chandler Carruth673850a2012-10-01 12:16:54 +00002508 // Compute the relative offset within the transfer.
2509 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2510 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2511 : MTO.SourceBegin));
2512
2513 unsigned Align = II.getAlignment();
2514 if (Align > 1)
2515 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruthf710fb12012-10-03 08:14:02 +00002516 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth673850a2012-10-01 12:16:54 +00002517
Chandler Carruth713aa942012-09-14 09:22:59 +00002518 // For unsplit intrinsics, we simply modify the source and destination
2519 // pointers in place. This isn't just an optimization, it is a matter of
2520 // correctness. With unsplit intrinsics we may be dealing with transfers
2521 // within a single alloca before SROA ran, or with transfers that have
2522 // a variable length. We may also be dealing with memmove instead of
2523 // memcpy, and so simply updating the pointers is the necessary for us to
2524 // update both source and dest of a single call.
2525 if (!MTO.IsSplittable) {
2526 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2527 if (IsDest)
2528 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2529 else
2530 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2531
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002532 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth673850a2012-10-01 12:16:54 +00002533 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruthd0ac06d2012-09-26 10:59:22 +00002534
Chandler Carruth713aa942012-09-14 09:22:59 +00002535 DEBUG(dbgs() << " to: " << II << "\n");
2536 deleteIfTriviallyDead(OldOp);
2537 return false;
2538 }
2539 // For split transfer intrinsics we have an incredibly useful assurance:
2540 // the source and destination do not reside within the same alloca, and at
2541 // least one of them does not escape. This means that we can replace
2542 // memmove with memcpy, and we don't need to worry about all manner of
2543 // downsides to splitting and transforming the operations.
2544
Chandler Carruth713aa942012-09-14 09:22:59 +00002545 // If this doesn't map cleanly onto the alloca type, and that type isn't
2546 // a single value type, just emit a memcpy.
2547 bool EmitMemCpy
2548 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2549 EndOffset != NewAllocaEndOffset ||
2550 !NewAI.getAllocatedType()->isSingleValueType());
2551
2552 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2553 // size hasn't been shrunk based on analysis of the viable range, this is
2554 // a no-op.
2555 if (EmitMemCpy && &OldAI == &NewAI) {
2556 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2557 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2558 // Ensure the start lines up.
2559 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002560 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002561
2562 // Rewrite the size as needed.
2563 if (EndOffset != OrigEnd)
2564 II.setLength(ConstantInt::get(II.getLength()->getType(),
2565 EndOffset - BeginOffset));
2566 return false;
2567 }
2568 // Record this instruction for deletion.
2569 if (Pass.DeadSplitInsts.insert(&II))
2570 Pass.DeadInsts.push_back(&II);
2571
2572 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2573 EndOffset < NewAllocaEndOffset);
2574
2575 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2576 : II.getRawDest()->getType();
2577 if (!EmitMemCpy)
2578 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2579 : NewAI.getType();
2580
2581 // Compute the other pointer, folding as much as possible to produce
2582 // a single, simple GEP in most cases.
2583 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2584 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2585 getName("." + OtherPtr->getName()));
2586
2587 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2588 // alloca that should be re-examined after rewriting this instruction.
2589 if (AllocaInst *AI
2590 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruthb3dca3f2012-09-26 07:41:40 +00002591 Pass.Worklist.insert(AI);
Chandler Carruth713aa942012-09-14 09:22:59 +00002592
2593 if (EmitMemCpy) {
2594 Value *OurPtr
2595 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2596 : II.getRawSource()->getType());
2597 Type *SizeTy = II.getLength()->getType();
2598 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2599
2600 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2601 IsDest ? OtherPtr : OurPtr,
Chandler Carruth81b001a2012-09-26 10:27:46 +00002602 Size, Align, II.isVolatile());
Chandler Carruth713aa942012-09-14 09:22:59 +00002603 (void)New;
2604 DEBUG(dbgs() << " to: " << *New << "\n");
2605 return false;
2606 }
2607
Chandler Carruth322e9ba2012-10-03 08:26:28 +00002608 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2609 // is equivalent to 1, but that isn't true if we end up rewriting this as
2610 // a load or store.
2611 if (!Align)
2612 Align = 1;
2613
Chandler Carruth713aa942012-09-14 09:22:59 +00002614 Value *SrcPtr = OtherPtr;
2615 Value *DstPtr = &NewAI;
2616 if (!IsDest)
2617 std::swap(SrcPtr, DstPtr);
2618
2619 Value *Src;
2620 if (IsVectorElement && !IsDest) {
2621 // We have to extract rather than load.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002622 Src = IRB.CreateExtractElement(
2623 IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
2624 getIndex(IRB, BeginOffset),
2625 getName(".copyextract"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002626 } else {
Chandler Carruth81b001a2012-09-26 10:27:46 +00002627 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
2628 getName(".copyload"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002629 }
2630
2631 if (IsVectorElement && IsDest) {
2632 // We have to insert into a loaded copy before storing.
Chandler Carruth81b001a2012-09-26 10:27:46 +00002633 Src = IRB.CreateInsertElement(
2634 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
2635 Src, getIndex(IRB, BeginOffset),
2636 getName(".insert"));
Chandler Carruth713aa942012-09-14 09:22:59 +00002637 }
2638
Chandler Carruth81b001a2012-09-26 10:27:46 +00002639 StoreInst *Store = cast<StoreInst>(
2640 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
2641 (void)Store;
Chandler Carruth713aa942012-09-14 09:22:59 +00002642 DEBUG(dbgs() << " to: " << *Store << "\n");
2643 return !II.isVolatile();
2644 }
2645
2646 bool visitIntrinsicInst(IntrinsicInst &II) {
2647 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2648 II.getIntrinsicID() == Intrinsic::lifetime_end);
2649 DEBUG(dbgs() << " original: " << II << "\n");
2650 IRBuilder<> IRB(&II);
2651 assert(II.getArgOperand(1) == OldPtr);
2652
2653 // Record this instruction for deletion.
2654 if (Pass.DeadSplitInsts.insert(&II))
2655 Pass.DeadInsts.push_back(&II);
2656
2657 ConstantInt *Size
2658 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2659 EndOffset - BeginOffset);
2660 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2661 Value *New;
2662 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2663 New = IRB.CreateLifetimeStart(Ptr, Size);
2664 else
2665 New = IRB.CreateLifetimeEnd(Ptr, Size);
2666
2667 DEBUG(dbgs() << " to: " << *New << "\n");
2668 return true;
2669 }
2670
Chandler Carruth713aa942012-09-14 09:22:59 +00002671 bool visitPHINode(PHINode &PN) {
2672 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002673
Chandler Carruth713aa942012-09-14 09:22:59 +00002674 // We would like to compute a new pointer in only one place, but have it be
2675 // as local as possible to the PHI. To do that, we re-use the location of
2676 // the old pointer, which necessarily must be in the right position to
2677 // dominate the PHI.
2678 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2679
Chandler Carruth713aa942012-09-14 09:22:59 +00002680 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002681 // Replace the operands which were using the old pointer.
2682 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2683 for (; OI != OE; ++OI)
2684 if (*OI == OldPtr)
2685 *OI = NewPtr;
Chandler Carruth713aa942012-09-14 09:22:59 +00002686
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002687 DEBUG(dbgs() << " to: " << PN << "\n");
2688 deleteIfTriviallyDead(OldPtr);
2689 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002690 }
2691
2692 bool visitSelectInst(SelectInst &SI) {
2693 DEBUG(dbgs() << " original: " << SI << "\n");
2694 IRBuilder<> IRB(&SI);
2695
2696 // Find the operand we need to rewrite here.
2697 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2698 if (IsTrueVal)
2699 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2700 else
2701 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002702
Chandler Carruth713aa942012-09-14 09:22:59 +00002703 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002704 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2705 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth713aa942012-09-14 09:22:59 +00002706 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00002707 return false;
Chandler Carruth713aa942012-09-14 09:22:59 +00002708 }
2709
2710};
2711}
2712
Chandler Carruthc370acd2012-09-18 12:57:43 +00002713namespace {
2714/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2715///
2716/// This pass aggressively rewrites all aggregate loads and stores on
2717/// a particular pointer (or any pointer derived from it which we can identify)
2718/// with scalar loads and stores.
2719class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2720 // Befriend the base class so it can delegate to private visit methods.
2721 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2722
2723 const TargetData &TD;
2724
2725 /// Queue of pointer uses to analyze and potentially rewrite.
2726 SmallVector<Use *, 8> Queue;
2727
2728 /// Set to prevent us from cycling with phi nodes and loops.
2729 SmallPtrSet<User *, 8> Visited;
2730
2731 /// The current pointer use being rewritten. This is used to dig up the used
2732 /// value (as opposed to the user).
2733 Use *U;
2734
2735public:
2736 AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
2737
2738 /// Rewrite loads and stores through a pointer and all pointers derived from
2739 /// it.
2740 bool rewrite(Instruction &I) {
2741 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2742 enqueueUsers(I);
2743 bool Changed = false;
2744 while (!Queue.empty()) {
2745 U = Queue.pop_back_val();
2746 Changed |= visit(cast<Instruction>(U->getUser()));
2747 }
2748 return Changed;
2749 }
2750
2751private:
2752 /// Enqueue all the users of the given instruction for further processing.
2753 /// This uses a set to de-duplicate users.
2754 void enqueueUsers(Instruction &I) {
2755 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2756 ++UI)
2757 if (Visited.insert(*UI))
2758 Queue.push_back(&UI.getUse());
2759 }
2760
2761 // Conservative default is to not rewrite anything.
2762 bool visitInstruction(Instruction &I) { return false; }
2763
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002764 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002765 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002766 class OpSplitter {
2767 protected:
2768 /// The builder used to form new instructions.
2769 IRBuilder<> IRB;
2770 /// The indices which to be used with insert- or extractvalue to select the
2771 /// appropriate value within the aggregate.
2772 SmallVector<unsigned, 4> Indices;
2773 /// The indices to a GEP instruction which will move Ptr to the correct slot
2774 /// within the aggregate.
2775 SmallVector<Value *, 4> GEPIndices;
2776 /// The base pointer of the original op, used as a base for GEPing the
2777 /// split operations.
2778 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002779
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002780 /// Initialize the splitter with an insertion point, Ptr and start with a
2781 /// single zero GEP index.
2782 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002783 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002784
2785 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002786 /// \brief Generic recursive split emission routine.
2787 ///
2788 /// This method recursively splits an aggregate op (load or store) into
2789 /// scalar or vector ops. It splits recursively until it hits a single value
2790 /// and emits that single value operation via the template argument.
2791 ///
2792 /// The logic of this routine relies on GEPs and insertvalue and
2793 /// extractvalue all operating with the same fundamental index list, merely
2794 /// formatted differently (GEPs need actual values).
2795 ///
2796 /// \param Ty The type being split recursively into smaller ops.
2797 /// \param Agg The aggregate value being built up or stored, depending on
2798 /// whether this is splitting a load or a store respectively.
2799 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2800 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002801 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002802
2803 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2804 unsigned OldSize = Indices.size();
2805 (void)OldSize;
2806 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2807 ++Idx) {
2808 assert(Indices.size() == OldSize && "Did not return to the old size");
2809 Indices.push_back(Idx);
2810 GEPIndices.push_back(IRB.getInt32(Idx));
2811 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2812 GEPIndices.pop_back();
2813 Indices.pop_back();
2814 }
2815 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002816 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00002817
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002818 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2819 unsigned OldSize = Indices.size();
2820 (void)OldSize;
2821 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2822 ++Idx) {
2823 assert(Indices.size() == OldSize && "Did not return to the old size");
2824 Indices.push_back(Idx);
2825 GEPIndices.push_back(IRB.getInt32(Idx));
2826 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2827 GEPIndices.pop_back();
2828 Indices.pop_back();
2829 }
2830 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002831 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002832
2833 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002834 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002835 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002836
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002837 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002838 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002839 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00002840
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002841 /// Emit a leaf load of a single value. This is called at the leaves of the
2842 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002843 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002844 assert(Ty->isSingleValueType());
2845 // Load the single value and insert it using the indices.
2846 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
2847 Name + ".gep"),
2848 Name + ".load");
2849 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2850 DEBUG(dbgs() << " to: " << *Load << "\n");
2851 }
2852 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002853
2854 bool visitLoadInst(LoadInst &LI) {
2855 assert(LI.getPointerOperand() == *U);
2856 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2857 return false;
2858
2859 // We have an aggregate being loaded, split it apart.
2860 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002861 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00002862 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002863 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002864 LI.replaceAllUsesWith(V);
2865 LI.eraseFromParent();
2866 return true;
2867 }
2868
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002869 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002870 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002871 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002872
2873 /// Emit a leaf store of a single value. This is called at the leaves of the
2874 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002875 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002876 assert(Ty->isSingleValueType());
2877 // Extract the single value and store it using the indices.
2878 Value *Store = IRB.CreateStore(
2879 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2880 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2881 (void)Store;
2882 DEBUG(dbgs() << " to: " << *Store << "\n");
2883 }
2884 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002885
2886 bool visitStoreInst(StoreInst &SI) {
2887 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2888 return false;
2889 Value *V = SI.getValueOperand();
2890 if (V->getType()->isSingleValueType())
2891 return false;
2892
2893 // We have an aggregate being stored, split it apart.
2894 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002895 StoreOpSplitter Splitter(&SI, *U);
2896 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002897 SI.eraseFromParent();
2898 return true;
2899 }
2900
2901 bool visitBitCastInst(BitCastInst &BC) {
2902 enqueueUsers(BC);
2903 return false;
2904 }
2905
2906 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2907 enqueueUsers(GEPI);
2908 return false;
2909 }
2910
2911 bool visitPHINode(PHINode &PN) {
2912 enqueueUsers(PN);
2913 return false;
2914 }
2915
2916 bool visitSelectInst(SelectInst &SI) {
2917 enqueueUsers(SI);
2918 return false;
2919 }
2920};
2921}
2922
Chandler Carruth713aa942012-09-14 09:22:59 +00002923/// \brief Try to find a partition of the aggregate type passed in for a given
2924/// offset and size.
2925///
2926/// This recurses through the aggregate type and tries to compute a subtype
2927/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00002928/// of an array, it will even compute a new array type for that sub-section,
2929/// and the same for structs.
2930///
2931/// Note that this routine is very strict and tries to find a partition of the
2932/// type which produces the *exact* right offset and size. It is not forgiving
2933/// when the size or offset cause either end of type-based partition to be off.
2934/// Also, this is a best-effort routine. It is reasonable to give up and not
2935/// return a type if necessary.
Chandler Carruth713aa942012-09-14 09:22:59 +00002936static Type *getTypePartition(const TargetData &TD, Type *Ty,
2937 uint64_t Offset, uint64_t Size) {
2938 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2939 return Ty;
2940
2941 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2942 // We can't partition pointers...
2943 if (SeqTy->isPointerTy())
2944 return 0;
2945
2946 Type *ElementTy = SeqTy->getElementType();
2947 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2948 uint64_t NumSkippedElements = Offset / ElementSize;
2949 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2950 if (NumSkippedElements >= ArrTy->getNumElements())
2951 return 0;
2952 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2953 if (NumSkippedElements >= VecTy->getNumElements())
2954 return 0;
2955 Offset -= NumSkippedElements * ElementSize;
2956
2957 // First check if we need to recurse.
2958 if (Offset > 0 || Size < ElementSize) {
2959 // Bail if the partition ends in a different array element.
2960 if ((Offset + Size) > ElementSize)
2961 return 0;
2962 // Recurse through the element type trying to peel off offset bytes.
2963 return getTypePartition(TD, ElementTy, Offset, Size);
2964 }
2965 assert(Offset == 0);
2966
2967 if (Size == ElementSize)
2968 return ElementTy;
2969 assert(Size > ElementSize);
2970 uint64_t NumElements = Size / ElementSize;
2971 if (NumElements * ElementSize != Size)
2972 return 0;
2973 return ArrayType::get(ElementTy, NumElements);
2974 }
2975
2976 StructType *STy = dyn_cast<StructType>(Ty);
2977 if (!STy)
2978 return 0;
2979
2980 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002981 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00002982 return 0;
2983 uint64_t EndOffset = Offset + Size;
2984 if (EndOffset > SL->getSizeInBytes())
2985 return 0;
2986
2987 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002988 Offset -= SL->getElementOffset(Index);
2989
2990 Type *ElementTy = STy->getElementType(Index);
2991 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2992 if (Offset >= ElementSize)
2993 return 0; // The offset points into alignment padding.
2994
2995 // See if any partition must be contained by the element.
2996 if (Offset > 0 || Size < ElementSize) {
2997 if ((Offset + Size) > ElementSize)
2998 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002999 return getTypePartition(TD, ElementTy, Offset, Size);
3000 }
3001 assert(Offset == 0);
3002
3003 if (Size == ElementSize)
3004 return ElementTy;
3005
3006 StructType::element_iterator EI = STy->element_begin() + Index,
3007 EE = STy->element_end();
3008 if (EndOffset < SL->getSizeInBytes()) {
3009 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3010 if (Index == EndIndex)
3011 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00003012
3013 // Don't try to form "natural" types if the elements don't line up with the
3014 // expected size.
3015 // FIXME: We could potentially recurse down through the last element in the
3016 // sub-struct to find a natural end point.
3017 if (SL->getElementOffset(EndIndex) != EndOffset)
3018 return 0;
3019
Chandler Carruth713aa942012-09-14 09:22:59 +00003020 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00003021 EE = STy->element_begin() + EndIndex;
3022 }
3023
3024 // Try to build up a sub-structure.
3025 SmallVector<Type *, 4> ElementTys;
3026 do {
3027 ElementTys.push_back(*EI++);
3028 } while (EI != EE);
3029 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
3030 STy->isPacked());
3031 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00003032 if (Size != SubSL->getSizeInBytes())
3033 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00003034
Chandler Carruth6b547a22012-09-14 11:08:31 +00003035 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00003036}
3037
3038/// \brief Rewrite an alloca partition's users.
3039///
3040/// This routine drives both of the rewriting goals of the SROA pass. It tries
3041/// to rewrite uses of an alloca partition to be conducive for SSA value
3042/// promotion. If the partition needs a new, more refined alloca, this will
3043/// build that new alloca, preserving as much type information as possible, and
3044/// rewrite the uses of the old alloca to point at the new one and have the
3045/// appropriate new offsets. It also evaluates how successful the rewrite was
3046/// at enabling promotion and if it was successful queues the alloca to be
3047/// promoted.
3048bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3049 AllocaPartitioning &P,
3050 AllocaPartitioning::iterator PI) {
3051 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruthfdb15852012-10-02 18:57:13 +00003052 bool IsLive = false;
3053 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3054 UE = P.use_end(PI);
3055 UI != UE && !IsLive; ++UI)
3056 if (UI->U)
3057 IsLive = true;
3058 if (!IsLive)
Chandler Carruth713aa942012-09-14 09:22:59 +00003059 return false; // No live uses left of this partition.
3060
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003061 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3062 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3063
3064 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3065 DEBUG(dbgs() << " speculating ");
3066 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carrutha346f462012-10-02 17:49:47 +00003067 Speculator.visitUsers(PI);
Chandler Carruth1e1b16c2012-10-01 10:54:05 +00003068
Chandler Carruth713aa942012-09-14 09:22:59 +00003069 // Try to compute a friendly type for this partition of the alloca. This
3070 // won't always succeed, in which case we fall back to a legal integer type
3071 // or an i8 array of an appropriate size.
3072 Type *AllocaTy = 0;
3073 if (Type *PartitionTy = P.getCommonType(PI))
3074 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3075 AllocaTy = PartitionTy;
3076 if (!AllocaTy)
3077 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3078 PI->BeginOffset, AllocaSize))
3079 AllocaTy = PartitionTy;
3080 if ((!AllocaTy ||
3081 (AllocaTy->isArrayTy() &&
3082 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3083 TD->isLegalInteger(AllocaSize * 8))
3084 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3085 if (!AllocaTy)
3086 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00003087 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00003088
3089 // Check for the case where we're going to rewrite to a new alloca of the
3090 // exact same type as the original, and with the same access offsets. In that
3091 // case, re-use the existing alloca, but still run through the rewriter to
3092 // performe phi and select speculation.
3093 AllocaInst *NewAI;
3094 if (AllocaTy == AI.getAllocatedType()) {
3095 assert(PI->BeginOffset == 0 &&
3096 "Non-zero begin offset but same alloca type");
3097 assert(PI == P.begin() && "Begin offset is zero on later partition");
3098 NewAI = &AI;
3099 } else {
Chandler Carruthb67c9a52012-09-29 10:41:21 +00003100 unsigned Alignment = AI.getAlignment();
3101 if (!Alignment) {
3102 // The minimum alignment which users can rely on when the explicit
3103 // alignment is omitted or zero is that required by the ABI for this
3104 // type.
3105 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3106 }
3107 Alignment = MinAlign(Alignment, PI->BeginOffset);
3108 // If we will get at least this much alignment from the type alone, leave
3109 // the alloca's alignment unconstrained.
3110 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3111 Alignment = 0;
3112 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth713aa942012-09-14 09:22:59 +00003113 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3114 &AI);
3115 ++NumNewAllocas;
3116 }
3117
3118 DEBUG(dbgs() << "Rewriting alloca partition "
3119 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3120 << *NewAI << "\n");
3121
3122 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3123 PI->BeginOffset, PI->EndOffset);
3124 DEBUG(dbgs() << " rewriting ");
3125 DEBUG(P.print(dbgs(), PI, ""));
3126 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
3127 DEBUG(dbgs() << " and queuing for promotion\n");
3128 PromotableAllocas.push_back(NewAI);
3129 } else if (NewAI != &AI) {
3130 // If we can't promote the alloca, iterate on it to check for new
3131 // refinements exposed by splitting the current alloca. Don't iterate on an
3132 // alloca which didn't actually change and didn't get promoted.
3133 Worklist.insert(NewAI);
3134 }
3135 return true;
3136}
3137
3138/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3139bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3140 bool Changed = false;
3141 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3142 ++PI)
3143 Changed |= rewriteAllocaPartition(AI, P, PI);
3144
3145 return Changed;
3146}
3147
3148/// \brief Analyze an alloca for SROA.
3149///
3150/// This analyzes the alloca to ensure we can reason about it, builds
3151/// a partitioning of the alloca, and then hands it off to be split and
3152/// rewritten as needed.
3153bool SROA::runOnAlloca(AllocaInst &AI) {
3154 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3155 ++NumAllocasAnalyzed;
3156
3157 // Special case dead allocas, as they're trivial.
3158 if (AI.use_empty()) {
3159 AI.eraseFromParent();
3160 return true;
3161 }
3162
3163 // Skip alloca forms that this analysis can't handle.
3164 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3165 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3166 return false;
3167
3168 // First check if this is a non-aggregate type that we should simply promote.
3169 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
3170 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
3171 PromotableAllocas.push_back(&AI);
3172 return false;
3173 }
3174
Chandler Carruthc370acd2012-09-18 12:57:43 +00003175 bool Changed = false;
3176
3177 // First, split any FCA loads and stores touching this alloca to promote
3178 // better splitting and promotion opportunities.
3179 AggLoadStoreRewriter AggRewriter(*TD);
3180 Changed |= AggRewriter.rewrite(AI);
3181
Chandler Carruth713aa942012-09-14 09:22:59 +00003182 // Build the partition set using a recursive instruction-visiting builder.
3183 AllocaPartitioning P(*TD, AI);
3184 DEBUG(P.print(dbgs()));
3185 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003186 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003187
3188 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3189 if (P.begin() == P.end())
Chandler Carruthc370acd2012-09-18 12:57:43 +00003190 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00003191
3192 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00003193 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3194 DE = P.dead_user_end();
3195 DI != DE; ++DI) {
3196 Changed = true;
3197 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
3198 DeadInsts.push_back(*DI);
3199 }
3200 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3201 DE = P.dead_op_end();
3202 DO != DE; ++DO) {
3203 Value *OldV = **DO;
3204 // Clobber the use with an undef value.
3205 **DO = UndefValue::get(OldV->getType());
3206 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3207 if (isInstructionTriviallyDead(OldI)) {
3208 Changed = true;
3209 DeadInsts.push_back(OldI);
3210 }
3211 }
3212
3213 return splitAlloca(AI, P) || Changed;
3214}
3215
Chandler Carruth8615cd22012-09-14 10:26:38 +00003216/// \brief Delete the dead instructions accumulated in this run.
3217///
3218/// Recursively deletes the dead instructions we've accumulated. This is done
3219/// at the very end to maximize locality of the recursive delete and to
3220/// minimize the problems of invalidated instruction pointers as such pointers
3221/// are used heavily in the intermediate stages of the algorithm.
3222///
3223/// We also record the alloca instructions deleted here so that they aren't
3224/// subsequently handed to mem2reg to promote.
3225void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00003226 DeadSplitInsts.clear();
3227 while (!DeadInsts.empty()) {
3228 Instruction *I = DeadInsts.pop_back_val();
3229 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3230
3231 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3232 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3233 // Zero out the operand and see if it becomes trivially dead.
3234 *OI = 0;
3235 if (isInstructionTriviallyDead(U))
3236 DeadInsts.push_back(U);
3237 }
3238
3239 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3240 DeletedAllocas.insert(AI);
3241
3242 ++NumDeleted;
3243 I->eraseFromParent();
3244 }
3245}
3246
Chandler Carruth1c8db502012-09-15 11:43:14 +00003247/// \brief Promote the allocas, using the best available technique.
3248///
3249/// This attempts to promote whatever allocas have been identified as viable in
3250/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3251/// If there is a domtree available, we attempt to promote using the full power
3252/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3253/// based on the SSAUpdater utilities. This function returns whether any
3254/// promotion occured.
3255bool SROA::promoteAllocas(Function &F) {
3256 if (PromotableAllocas.empty())
3257 return false;
3258
3259 NumPromoted += PromotableAllocas.size();
3260
3261 if (DT && !ForceSSAUpdater) {
3262 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3263 PromoteMemToReg(PromotableAllocas, *DT);
3264 PromotableAllocas.clear();
3265 return true;
3266 }
3267
3268 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3269 SSAUpdater SSA;
3270 DIBuilder DIB(*F.getParent());
3271 SmallVector<Instruction*, 64> Insts;
3272
3273 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3274 AllocaInst *AI = PromotableAllocas[Idx];
3275 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3276 UI != UE;) {
3277 Instruction *I = cast<Instruction>(*UI++);
3278 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3279 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3280 // leading to them) here. Eventually it should use them to optimize the
3281 // scalar values produced.
3282 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3283 assert(onlyUsedByLifetimeMarkers(I) &&
3284 "Found a bitcast used outside of a lifetime marker.");
3285 while (!I->use_empty())
3286 cast<Instruction>(*I->use_begin())->eraseFromParent();
3287 I->eraseFromParent();
3288 continue;
3289 }
3290 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3291 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3292 II->getIntrinsicID() == Intrinsic::lifetime_end);
3293 II->eraseFromParent();
3294 continue;
3295 }
3296
3297 Insts.push_back(I);
3298 }
3299 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3300 Insts.clear();
3301 }
3302
3303 PromotableAllocas.clear();
3304 return true;
3305}
3306
Chandler Carruth713aa942012-09-14 09:22:59 +00003307namespace {
3308 /// \brief A predicate to test whether an alloca belongs to a set.
3309 class IsAllocaInSet {
3310 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3311 const SetType &Set;
3312
3313 public:
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003314 typedef AllocaInst *argument_type;
3315
Chandler Carruth713aa942012-09-14 09:22:59 +00003316 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth75eac5f2012-10-03 00:03:00 +00003317 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth713aa942012-09-14 09:22:59 +00003318 };
3319}
3320
3321bool SROA::runOnFunction(Function &F) {
3322 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3323 C = &F.getContext();
3324 TD = getAnalysisIfAvailable<TargetData>();
3325 if (!TD) {
3326 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3327 return false;
3328 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003329 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003330
3331 BasicBlock &EntryBB = F.getEntryBlock();
3332 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3333 I != E; ++I)
3334 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3335 Worklist.insert(AI);
3336
3337 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003338 // A set of deleted alloca instruction pointers which should be removed from
3339 // the list of promotable allocas.
3340 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3341
Chandler Carruth713aa942012-09-14 09:22:59 +00003342 while (!Worklist.empty()) {
3343 Changed |= runOnAlloca(*Worklist.pop_back_val());
Chandler Carruth8615cd22012-09-14 10:26:38 +00003344 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth5c5b3cf2012-10-02 22:46:45 +00003345
3346 // Remove the deleted allocas from various lists so that we don't try to
3347 // continue processing them.
Chandler Carruth713aa942012-09-14 09:22:59 +00003348 if (!DeletedAllocas.empty()) {
Chandler Carruth5c5b3cf2012-10-02 22:46:45 +00003349 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
Chandler Carruth713aa942012-09-14 09:22:59 +00003350 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3351 PromotableAllocas.end(),
3352 IsAllocaInSet(DeletedAllocas)),
3353 PromotableAllocas.end());
3354 DeletedAllocas.clear();
3355 }
3356 }
3357
Chandler Carruth1c8db502012-09-15 11:43:14 +00003358 Changed |= promoteAllocas(F);
Chandler Carruth713aa942012-09-14 09:22:59 +00003359
3360 return Changed;
3361}
3362
3363void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003364 if (RequiresDomTree)
3365 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003366 AU.setPreservesCFG();
3367}