blob: 5a9247ea1b59cebf12a6bd696dc73707c09b4f14 [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"
33#include "llvm/GlobalVariable.h"
34#include "llvm/IRBuilder.h"
35#include "llvm/Instructions.h"
36#include "llvm/IntrinsicInst.h"
37#include "llvm/LLVMContext.h"
38#include "llvm/Module.h"
39#include "llvm/Operator.h"
40#include "llvm/Pass.h"
41#include "llvm/ADT/SetVector.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/TinyPtrVector.h"
46#include "llvm/Analysis/Dominators.h"
47#include "llvm/Analysis/Loads.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/Support/CallSite.h"
Chandler Carruth1c8db502012-09-15 11:43:14 +000050#include "llvm/Support/CommandLine.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/GetElementPtrTypeIterator.h"
54#include "llvm/Support/InstVisitor.h"
55#include "llvm/Support/MathExtras.h"
56#include "llvm/Support/ValueHandle.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/Target/TargetData.h"
59#include "llvm/Transforms/Utils/Local.h"
60#include "llvm/Transforms/Utils/PromoteMemToReg.h"
61#include "llvm/Transforms/Utils/SSAUpdater.h"
62using namespace llvm;
63
64STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
65STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
67STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
68STATISTIC(NumDeleted, "Number of instructions deleted");
69STATISTIC(NumVectorized, "Number of vectorized aggregates");
70
Chandler Carruth1c8db502012-09-15 11:43:14 +000071/// Hidden option to force the pass to not use DomTree and mem2reg, instead
72/// forming SSA values through the SSAUpdater infrastructure.
73static cl::opt<bool>
74ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
75
Chandler Carruth713aa942012-09-14 09:22:59 +000076namespace {
77/// \brief Alloca partitioning representation.
78///
79/// This class represents a partitioning of an alloca into slices, and
80/// information about the nature of uses of each slice of the alloca. The goal
81/// is that this information is sufficient to decide if and how to split the
82/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth7f5bede2012-09-14 10:18:49 +000083/// structure can capture the relevant information needed both to decide about
Chandler Carruth713aa942012-09-14 09:22:59 +000084/// and to enact these transformations.
85class AllocaPartitioning {
86public:
87 /// \brief A common base class for representing a half-open byte range.
88 struct ByteRange {
89 /// \brief The beginning offset of the range.
90 uint64_t BeginOffset;
91
92 /// \brief The ending offset, not included in the range.
93 uint64_t EndOffset;
94
95 ByteRange() : BeginOffset(), EndOffset() {}
96 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
97 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
98
99 /// \brief Support for ordering ranges.
100 ///
101 /// This provides an ordering over ranges such that start offsets are
102 /// always increasing, and within equal start offsets, the end offsets are
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000103 /// decreasing. Thus the spanning range comes first in a cluster with the
Chandler Carruth713aa942012-09-14 09:22:59 +0000104 /// same start position.
105 bool operator<(const ByteRange &RHS) const {
106 if (BeginOffset < RHS.BeginOffset) return true;
107 if (BeginOffset > RHS.BeginOffset) return false;
108 if (EndOffset > RHS.EndOffset) return true;
109 return false;
110 }
111
112 /// \brief Support comparison with a single offset to allow binary searches.
Benjamin Kramer2d1c2a22012-09-17 16:42:36 +0000113 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
114 return LHS.BeginOffset < RHSOffset;
115 }
116
117 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
118 const ByteRange &RHS) {
119 return LHSOffset < RHS.BeginOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000120 }
121
122 bool operator==(const ByteRange &RHS) const {
123 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
124 }
125 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
126 };
127
128 /// \brief A partition of an alloca.
129 ///
130 /// This structure represents a contiguous partition of the alloca. These are
131 /// formed by examining the uses of the alloca. During formation, they may
132 /// overlap but once an AllocaPartitioning is built, the Partitions within it
133 /// are all disjoint.
134 struct Partition : public ByteRange {
135 /// \brief Whether this partition is splittable into smaller partitions.
136 ///
137 /// We flag partitions as splittable when they are formed entirely due to
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000138 /// accesses by trivially splittable operations such as memset and memcpy.
Chandler Carruth713aa942012-09-14 09:22:59 +0000139 ///
140 /// FIXME: At some point we should consider loads and stores of FCAs to be
141 /// splittable and eagerly split them into scalar values.
142 bool IsSplittable;
143
144 Partition() : ByteRange(), IsSplittable() {}
145 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
146 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
147 };
148
149 /// \brief A particular use of a partition of the alloca.
150 ///
151 /// This structure is used to associate uses of a partition with it. They
152 /// mark the range of bytes which are referenced by a particular instruction,
153 /// and includes a handle to the user itself and the pointer value in use.
154 /// The bounds of these uses are determined by intersecting the bounds of the
155 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000156 /// intentionally overlap between various uses of the same partition.
Chandler Carruth713aa942012-09-14 09:22:59 +0000157 struct PartitionUse : public ByteRange {
158 /// \brief The user of this range of the alloca.
159 AssertingVH<Instruction> User;
160
161 /// \brief The particular pointer value derived from this alloca in use.
162 AssertingVH<Instruction> Ptr;
163
164 PartitionUse() : ByteRange(), User(), Ptr() {}
165 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset,
166 Instruction *User, Instruction *Ptr)
167 : ByteRange(BeginOffset, EndOffset), User(User), Ptr(Ptr) {}
168 };
169
170 /// \brief Construct a partitioning of a particular alloca.
171 ///
172 /// Construction does most of the work for partitioning the alloca. This
173 /// performs the necessary walks of users and builds a partitioning from it.
174 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
175
176 /// \brief Test whether a pointer to the allocation escapes our analysis.
177 ///
178 /// If this is true, the partitioning is never fully built and should be
179 /// ignored.
180 bool isEscaped() const { return PointerEscapingInstr; }
181
182 /// \brief Support for iterating over the partitions.
183 /// @{
184 typedef SmallVectorImpl<Partition>::iterator iterator;
185 iterator begin() { return Partitions.begin(); }
186 iterator end() { return Partitions.end(); }
187
188 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
189 const_iterator begin() const { return Partitions.begin(); }
190 const_iterator end() const { return Partitions.end(); }
191 /// @}
192
193 /// \brief Support for iterating over and manipulating a particular
194 /// partition's uses.
195 ///
196 /// The iteration support provided for uses is more limited, but also
197 /// includes some manipulation routines to support rewriting the uses of
198 /// partitions during SROA.
199 /// @{
200 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
201 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
202 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
203 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
204 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
205 void use_insert(unsigned Idx, use_iterator UI, const PartitionUse &U) {
206 Uses[Idx].insert(UI, U);
207 }
208 void use_insert(const_iterator I, use_iterator UI, const PartitionUse &U) {
209 Uses[I - begin()].insert(UI, U);
210 }
211 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
212 void use_erase(const_iterator I, use_iterator UI) {
213 Uses[I - begin()].erase(UI);
214 }
215
216 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
217 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
218 const_use_iterator use_begin(const_iterator I) const {
219 return Uses[I - begin()].begin();
220 }
221 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
222 const_use_iterator use_end(const_iterator I) const {
223 return Uses[I - begin()].end();
224 }
225 /// @}
226
227 /// \brief Allow iterating the dead users for this alloca.
228 ///
229 /// These are instructions which will never actually use the alloca as they
230 /// are outside the allocated range. They are safe to replace with undef and
231 /// delete.
232 /// @{
233 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
234 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
235 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
236 /// @}
237
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000238 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000239 ///
240 /// These are operands which have cannot actually be used to refer to the
241 /// alloca as they are outside its range and the user doesn't correct for
242 /// that. These mostly consist of PHI node inputs and the like which we just
243 /// need to replace with undef.
244 /// @{
245 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
246 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
247 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
248 /// @}
249
250 /// \brief MemTransferInst auxiliary data.
251 /// This struct provides some auxiliary data about memory transfer
252 /// intrinsics such as memcpy and memmove. These intrinsics can use two
253 /// different ranges within the same alloca, and provide other challenges to
254 /// correctly represent. We stash extra data to help us untangle this
255 /// after the partitioning is complete.
256 struct MemTransferOffsets {
257 uint64_t DestBegin, DestEnd;
258 uint64_t SourceBegin, SourceEnd;
259 bool IsSplittable;
260 };
261 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
262 return MemTransferInstData.lookup(&II);
263 }
264
265 /// \brief Map from a PHI or select operand back to a partition.
266 ///
267 /// When manipulating PHI nodes or selects, they can use more than one
268 /// partition of an alloca. We store a special mapping to allow finding the
269 /// partition referenced by each of these operands, if any.
270 iterator findPartitionForPHIOrSelectOperand(Instruction &I, Value *Op) {
271 SmallDenseMap<std::pair<Instruction *, Value *>,
272 std::pair<unsigned, unsigned> >::const_iterator MapIt
273 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
274 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.
285 use_iterator findPartitionUseForPHIOrSelectOperand(Instruction &I,
286 Value *Op) {
287 SmallDenseMap<std::pair<Instruction *, Value *>,
288 std::pair<unsigned, unsigned> >::const_iterator MapIt
289 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
290 assert(MapIt != PHIOrSelectOpMap.end());
291 return Uses[MapIt->second.first].begin() + MapIt->second.second;
292 }
293
294 /// \brief Compute a common type among the uses of a particular partition.
295 ///
296 /// This routines walks all of the uses of a particular partition and tries
297 /// to find a common type between them. Untyped operations such as memset and
298 /// memcpy are ignored.
299 Type *getCommonType(iterator I) const;
300
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000301#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000302 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
303 void printUsers(raw_ostream &OS, const_iterator I,
304 StringRef Indent = " ") const;
305 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000306 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
307 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000308#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000309
310private:
311 template <typename DerivedT, typename RetT = void> class BuilderBase;
312 class PartitionBuilder;
313 friend class AllocaPartitioning::PartitionBuilder;
314 class UseBuilder;
315 friend class AllocaPartitioning::UseBuilder;
316
Benjamin Kramerd0807692012-09-14 13:08:09 +0000317#ifndef NDEBUG
Chandler Carruth713aa942012-09-14 09:22:59 +0000318 /// \brief Handle to alloca instruction to simplify method interfaces.
319 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000320#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000321
322 /// \brief The instruction responsible for this alloca having no partitioning.
323 ///
324 /// When an instruction (potentially) escapes the pointer to the alloca, we
325 /// store a pointer to that here and abort trying to partition the alloca.
326 /// This will be null if the alloca is partitioned successfully.
327 Instruction *PointerEscapingInstr;
328
329 /// \brief The partitions of the alloca.
330 ///
331 /// We store a vector of the partitions over the alloca here. This vector is
332 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000333 /// the Partition inner class for more details. Initially (during
334 /// construction) there are overlaps, but we form a disjoint sequence of
335 /// partitions while finishing construction and a fully constructed object is
336 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000337 SmallVector<Partition, 8> Partitions;
338
339 /// \brief The uses of the partitions.
340 ///
341 /// This is essentially a mapping from each partition to a list of uses of
342 /// that partition. The mapping is done with a Uses vector that has the exact
343 /// same number of entries as the partition vector. Each entry is itself
344 /// a vector of the uses.
345 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
346
347 /// \brief Instructions which will become dead if we rewrite the alloca.
348 ///
349 /// Note that these are not separated by partition. This is because we expect
350 /// a partitioned alloca to be completely rewritten or not rewritten at all.
351 /// If rewritten, all these instructions can simply be removed and replaced
352 /// with undef as they come from outside of the allocated space.
353 SmallVector<Instruction *, 8> DeadUsers;
354
355 /// \brief Operands which will become dead if we rewrite the alloca.
356 ///
357 /// These are operands that in their particular use can be replaced with
358 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
359 /// to PHI nodes and the like. They aren't entirely dead (there might be
360 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
361 /// want to swap this particular input for undef to simplify the use lists of
362 /// the alloca.
363 SmallVector<Use *, 8> DeadOperands;
364
365 /// \brief The underlying storage for auxiliary memcpy and memset info.
366 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
367
368 /// \brief A side datastructure used when building up the partitions and uses.
369 ///
370 /// This mapping is only really used during the initial building of the
371 /// partitioning so that we can retain information about PHI and select nodes
372 /// processed.
373 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
374
375 /// \brief Auxiliary information for particular PHI or select operands.
376 SmallDenseMap<std::pair<Instruction *, Value *>,
377 std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
378
379 /// \brief A utility routine called from the constructor.
380 ///
381 /// This does what it says on the tin. It is the key of the alloca partition
382 /// splitting and merging. After it is called we have the desired disjoint
383 /// collection of partitions.
384 void splitAndMergePartitions();
385};
386}
387
388template <typename DerivedT, typename RetT>
389class AllocaPartitioning::BuilderBase
390 : public InstVisitor<DerivedT, RetT> {
391public:
392 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
393 : TD(TD),
394 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
395 P(P) {
396 enqueueUsers(AI, 0);
397 }
398
399protected:
400 const TargetData &TD;
401 const uint64_t AllocSize;
402 AllocaPartitioning &P;
403
404 struct OffsetUse {
405 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000406 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000407 };
408 SmallVector<OffsetUse, 8> Queue;
409
410 // The active offset and use while visiting.
411 Use *U;
Chandler Carruth02e92a02012-09-23 11:43:14 +0000412 int64_t Offset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000413
Chandler Carruth02e92a02012-09-23 11:43:14 +0000414 void enqueueUsers(Instruction &I, int64_t UserOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000415 SmallPtrSet<User *, 8> UserSet;
416 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
417 UI != UE; ++UI) {
418 if (!UserSet.insert(*UI))
419 continue;
420
421 OffsetUse OU = { &UI.getUse(), UserOffset };
422 Queue.push_back(OU);
423 }
424 }
425
Chandler Carruth02e92a02012-09-23 11:43:14 +0000426 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000427 GEPOffset = Offset;
428 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
429 GTI != GTE; ++GTI) {
430 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
431 if (!OpC)
432 return false;
433 if (OpC->isZero())
434 continue;
435
436 // Handle a struct index, which adds its field offset to the pointer.
437 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
438 unsigned ElementIdx = OpC->getZExtValue();
439 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth02e92a02012-09-23 11:43:14 +0000440 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
441 // Check that we can continue to model this GEP in a signed 64-bit offset.
442 if (ElementOffset > INT64_MAX ||
443 (GEPOffset >= 0 &&
444 ((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
445 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
446 << "what can be represented in an int64_t!\n"
447 << " alloca: " << P.AI << "\n");
448 return false;
449 }
450 if (GEPOffset < 0)
451 GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
452 else
453 GEPOffset += ElementOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000454 continue;
455 }
456
Chandler Carruth02e92a02012-09-23 11:43:14 +0000457 APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
458 Index *= APInt(Index.getBitWidth(),
459 TD.getTypeAllocSize(GTI.getIndexedType()));
460 Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
461 /*isSigned*/true);
462 // Check if the result can be stored in our int64_t offset.
463 if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
464 DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
465 << "what can be represented in an int64_t!\n"
466 << " alloca: " << P.AI << "\n");
467 return false;
468 }
469
470 GEPOffset = Index.getSExtValue();
Chandler Carruth713aa942012-09-14 09:22:59 +0000471 }
472 return true;
473 }
474
475 Value *foldSelectInst(SelectInst &SI) {
476 // If the condition being selected on is a constant or the same value is
477 // being selected between, fold the select. Yes this does (rarely) happen
478 // early on.
479 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
480 return SI.getOperand(1+CI->isZero());
481 if (SI.getOperand(1) == SI.getOperand(2)) {
482 assert(*U == SI.getOperand(1));
483 return SI.getOperand(1);
484 }
485 return 0;
486 }
487};
488
489/// \brief Builder for the alloca partitioning.
490///
491/// This class builds an alloca partitioning by recursively visiting the uses
492/// of an alloca and splitting the partitions for each load and store at each
493/// offset.
494class AllocaPartitioning::PartitionBuilder
495 : public BuilderBase<PartitionBuilder, bool> {
496 friend class InstVisitor<PartitionBuilder, bool>;
497
498 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
499
500public:
501 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000502 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000503
504 /// \brief Run the builder over the allocation.
505 bool operator()() {
506 // Note that we have to re-evaluate size on each trip through the loop as
507 // the queue grows at the tail.
508 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
509 U = Queue[Idx].U;
510 Offset = Queue[Idx].Offset;
511 if (!visit(cast<Instruction>(U->getUser())))
512 return false;
513 }
514 return true;
515 }
516
517private:
518 bool markAsEscaping(Instruction &I) {
519 P.PointerEscapingInstr = &I;
520 return false;
521 }
522
Chandler Carruth02e92a02012-09-23 11:43:14 +0000523 void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
Chandler Carruth63392ea2012-09-16 19:39:50 +0000524 bool IsSplittable = false) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000525 // Completely skip uses which don't overlap the allocation.
526 if ((Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
527 (Offset < 0 && (uint64_t)-Offset >= Size)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000528 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
529 << " which starts past the end of the " << AllocSize
530 << " byte alloca:\n"
531 << " alloca: " << P.AI << "\n"
532 << " use: " << I << "\n");
533 return;
534 }
535
Chandler Carruth02e92a02012-09-23 11:43:14 +0000536 // Clamp the start to the beginning of the allocation.
537 if (Offset < 0) {
538 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
539 << " to start at the beginning of the alloca:\n"
540 << " alloca: " << P.AI << "\n"
541 << " use: " << I << "\n");
542 Size -= (uint64_t)-Offset;
543 Offset = 0;
544 }
545
546 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
547
548 // Clamp the end offset to the end of the allocation. Note that this is
549 // formulated to handle even the case where "BeginOffset + Size" overflows.
550 assert(AllocSize >= BeginOffset); // Established above.
551 if (Size > AllocSize - BeginOffset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000552 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
553 << " to remain within the " << AllocSize << " byte alloca:\n"
554 << " alloca: " << P.AI << "\n"
555 << " use: " << I << "\n");
556 EndOffset = AllocSize;
557 }
558
559 // See if we can just add a user onto the last slot currently occupied.
560 if (!P.Partitions.empty() &&
561 P.Partitions.back().BeginOffset == BeginOffset &&
562 P.Partitions.back().EndOffset == EndOffset) {
563 P.Partitions.back().IsSplittable &= IsSplittable;
564 return;
565 }
566
567 Partition New(BeginOffset, EndOffset, IsSplittable);
568 P.Partitions.push_back(New);
569 }
570
Chandler Carruth02e92a02012-09-23 11:43:14 +0000571 bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000572 uint64_t Size = TD.getTypeStoreSize(Ty);
573
574 // If this memory access can be shown to *statically* extend outside the
575 // bounds of of the allocation, it's behavior is undefined, so simply
576 // ignore it. Note that this is more strict than the generic clamping
577 // behavior of insertUse. We also try to handle cases which might run the
578 // risk of overflow.
579 // FIXME: We should instead consider the pointer to have escaped if this
580 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000581 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
582 Size > (AllocSize - (uint64_t)Offset)) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000583 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
584 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
585 << " which extends past the end of the " << AllocSize
586 << " byte alloca:\n"
587 << " alloca: " << P.AI << "\n"
588 << " use: " << I << "\n");
589 return true;
590 }
591
Chandler Carruth63392ea2012-09-16 19:39:50 +0000592 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000593 return true;
594 }
595
596 bool visitBitCastInst(BitCastInst &BC) {
597 enqueueUsers(BC, Offset);
598 return true;
599 }
600
601 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth02e92a02012-09-23 11:43:14 +0000602 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000603 if (!computeConstantGEPOffset(GEPI, GEPOffset))
604 return markAsEscaping(GEPI);
605
606 enqueueUsers(GEPI, GEPOffset);
607 return true;
608 }
609
610 bool visitLoadInst(LoadInst &LI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000611 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
612 "All simple FCA loads should have been pre-split");
Chandler Carruth63392ea2012-09-16 19:39:50 +0000613 return handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000614 }
615
616 bool visitStoreInst(StoreInst &SI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +0000617 Value *ValOp = SI.getValueOperand();
618 if (ValOp == *U)
Chandler Carruth713aa942012-09-14 09:22:59 +0000619 return markAsEscaping(SI);
620
Chandler Carruthc370acd2012-09-18 12:57:43 +0000621 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
622 "All simple FCA stores should have been pre-split");
623 return handleLoadOrStore(ValOp->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000624 }
625
626
627 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000628 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000629 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000630 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
631 insertUse(II, Offset, Size, Length);
Chandler Carruth713aa942012-09-14 09:22:59 +0000632 return true;
633 }
634
635 bool visitMemTransferInst(MemTransferInst &II) {
636 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
637 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
638 if (!Size)
639 // Zero-length mem transfer intrinsics can be ignored entirely.
640 return true;
641
642 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
643
644 // Only intrinsics with a constant length can be split.
645 Offsets.IsSplittable = Length;
646
647 if (*U != II.getRawDest()) {
648 assert(*U == II.getRawSource());
649 Offsets.SourceBegin = Offset;
650 Offsets.SourceEnd = Offset + Size;
651 } else {
652 Offsets.DestBegin = Offset;
653 Offsets.DestEnd = Offset + Size;
654 }
655
Chandler Carruth63392ea2012-09-16 19:39:50 +0000656 insertUse(II, Offset, Size, Offsets.IsSplittable);
Chandler Carruth713aa942012-09-14 09:22:59 +0000657 unsigned NewIdx = P.Partitions.size() - 1;
658
659 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
660 bool Inserted = false;
661 llvm::tie(PMI, Inserted)
662 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
663 if (!Inserted && Offsets.IsSplittable) {
664 // We've found a memory transfer intrinsic which refers to the alloca as
665 // both a source and dest. We refuse to split these to simplify splitting
666 // logic. If possible, SROA will still split them into separate allocas
667 // and then re-analyze.
668 Offsets.IsSplittable = false;
669 P.Partitions[PMI->second].IsSplittable = false;
670 P.Partitions[NewIdx].IsSplittable = false;
671 }
672
673 return true;
674 }
675
676 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000677 // FIXME: What about debug instrinsics? This matches old behavior, but
678 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000679 bool visitIntrinsicInst(IntrinsicInst &II) {
680 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
681 II.getIntrinsicID() == Intrinsic::lifetime_end) {
682 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
683 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000684 insertUse(II, Offset, Size, true);
Chandler Carruth713aa942012-09-14 09:22:59 +0000685 return true;
686 }
687
688 return markAsEscaping(II);
689 }
690
691 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
692 // We consider any PHI or select that results in a direct load or store of
693 // the same offset to be a viable use for partitioning purposes. These uses
694 // are considered unsplittable and the size is the maximum loaded or stored
695 // size.
696 SmallPtrSet<Instruction *, 4> Visited;
697 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
698 Visited.insert(Root);
699 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
700 do {
701 Instruction *I, *UsedI;
702 llvm::tie(UsedI, I) = Uses.pop_back_val();
703
704 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
705 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
706 continue;
707 }
708 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
709 Value *Op = SI->getOperand(0);
710 if (Op == UsedI)
711 return SI;
712 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
713 continue;
714 }
715
716 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
717 if (!GEP->hasAllZeroIndices())
718 return GEP;
719 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
720 !isa<SelectInst>(I)) {
721 return I;
722 }
723
724 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
725 ++UI)
726 if (Visited.insert(cast<Instruction>(*UI)))
727 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
728 } while (!Uses.empty());
729
730 return 0;
731 }
732
733 bool visitPHINode(PHINode &PN) {
734 // See if we already have computed info on this node.
735 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
736 if (PHIInfo.first) {
737 PHIInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000738 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000739 return true;
740 }
741
742 // Check for an unsafe use of the PHI node.
743 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
744 return markAsEscaping(*EscapingI);
745
Chandler Carruth63392ea2012-09-16 19:39:50 +0000746 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000747 return true;
748 }
749
750 bool visitSelectInst(SelectInst &SI) {
751 if (Value *Result = foldSelectInst(SI)) {
752 if (Result == *U)
753 // If the result of the constant fold will be the pointer, recurse
754 // through the select as if we had RAUW'ed it.
755 enqueueUsers(SI, Offset);
756
757 return true;
758 }
759
760 // See if we already have computed info on this node.
761 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
762 if (SelectInfo.first) {
763 SelectInfo.second = true;
Chandler Carruth63392ea2012-09-16 19:39:50 +0000764 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000765 return true;
766 }
767
768 // Check for an unsafe use of the PHI node.
769 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
770 return markAsEscaping(*EscapingI);
771
Chandler Carruth63392ea2012-09-16 19:39:50 +0000772 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth713aa942012-09-14 09:22:59 +0000773 return true;
774 }
775
776 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
777 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
778};
779
780
781/// \brief Use adder for the alloca partitioning.
782///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000783/// This class adds the uses of an alloca to all of the partitions which they
784/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000785/// walk of the partitions, but the number of steps remains bounded by the
786/// total result instruction size:
787/// - The number of partitions is a result of the number unsplittable
788/// instructions using the alloca.
789/// - The number of users of each partition is at worst the total number of
790/// splittable instructions using the alloca.
791/// Thus we will produce N * M instructions in the end, where N are the number
792/// of unsplittable uses and M are the number of splittable. This visitor does
793/// the exact same number of updates to the partitioning.
794///
795/// In the more common case, this visitor will leverage the fact that the
796/// partition space is pre-sorted, and do a logarithmic search for the
797/// partition needed, making the total visit a classical ((N + M) * log(N))
798/// complexity operation.
799class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
800 friend class InstVisitor<UseBuilder>;
801
802 /// \brief Set to de-duplicate dead instructions found in the use walk.
803 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
804
805public:
806 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000807 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000808
809 /// \brief Run the builder over the allocation.
810 void operator()() {
811 // Note that we have to re-evaluate size on each trip through the loop as
812 // the queue grows at the tail.
813 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
814 U = Queue[Idx].U;
815 Offset = Queue[Idx].Offset;
816 this->visit(cast<Instruction>(U->getUser()));
817 }
818 }
819
820private:
821 void markAsDead(Instruction &I) {
822 if (VisitedDeadInsts.insert(&I))
823 P.DeadUsers.push_back(&I);
824 }
825
Chandler Carruth02e92a02012-09-23 11:43:14 +0000826 void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000827 // If the use extends outside of the allocation, record it as a dead use
828 // for elimination later.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000829 if ((uint64_t)Offset >= AllocSize ||
830 (Offset < 0 && (uint64_t)-Offset >= Size))
Chandler Carruth713aa942012-09-14 09:22:59 +0000831 return markAsDead(User);
832
Chandler Carruth02e92a02012-09-23 11:43:14 +0000833 // Clamp the start to the beginning of the allocation.
834 if (Offset < 0) {
835 Size -= (uint64_t)-Offset;
836 Offset = 0;
837 }
838
839 uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
840
841 // Clamp the end offset to the end of the allocation. Note that this is
842 // formulated to handle even the case where "BeginOffset + Size" overflows.
843 assert(AllocSize >= BeginOffset); // Established above.
844 if (Size > AllocSize - BeginOffset)
Chandler Carruth713aa942012-09-14 09:22:59 +0000845 EndOffset = AllocSize;
846
847 // NB: This only works if we have zero overlapping partitions.
848 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
849 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
850 B = llvm::prior(B);
851 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
852 ++I) {
853 PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
854 std::min(I->EndOffset, EndOffset),
855 &User, cast<Instruction>(*U));
856 P.Uses[I - P.begin()].push_back(NewUse);
857 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
858 P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
859 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
860 }
861 }
862
Chandler Carruth02e92a02012-09-23 11:43:14 +0000863 void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000864 uint64_t Size = TD.getTypeStoreSize(Ty);
865
866 // If this memory access can be shown to *statically* extend outside the
867 // bounds of of the allocation, it's behavior is undefined, so simply
868 // ignore it. Note that this is more strict than the generic clamping
869 // behavior of insertUse.
Chandler Carruth02e92a02012-09-23 11:43:14 +0000870 if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
871 Size > (AllocSize - (uint64_t)Offset))
Chandler Carruth713aa942012-09-14 09:22:59 +0000872 return markAsDead(I);
873
Chandler Carruth63392ea2012-09-16 19:39:50 +0000874 insertUse(I, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000875 }
876
877 void visitBitCastInst(BitCastInst &BC) {
878 if (BC.use_empty())
879 return markAsDead(BC);
880
881 enqueueUsers(BC, Offset);
882 }
883
884 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
885 if (GEPI.use_empty())
886 return markAsDead(GEPI);
887
Chandler Carruth02e92a02012-09-23 11:43:14 +0000888 int64_t GEPOffset;
Chandler Carruth713aa942012-09-14 09:22:59 +0000889 if (!computeConstantGEPOffset(GEPI, GEPOffset))
890 llvm_unreachable("Unable to compute constant offset for use");
891
892 enqueueUsers(GEPI, GEPOffset);
893 }
894
895 void visitLoadInst(LoadInst &LI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000896 handleLoadOrStore(LI.getType(), LI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000897 }
898
899 void visitStoreInst(StoreInst &SI) {
Chandler Carruth63392ea2012-09-16 19:39:50 +0000900 handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000901 }
902
903 void visitMemSetInst(MemSetInst &II) {
904 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000905 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
906 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000907 }
908
909 void visitMemTransferInst(MemTransferInst &II) {
910 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth63392ea2012-09-16 19:39:50 +0000911 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
912 insertUse(II, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000913 }
914
915 void visitIntrinsicInst(IntrinsicInst &II) {
916 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
917 II.getIntrinsicID() == Intrinsic::lifetime_end);
918
919 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruth63392ea2012-09-16 19:39:50 +0000920 insertUse(II, Offset,
921 std::min(AllocSize - Offset, Length->getLimitedValue()));
Chandler Carruth713aa942012-09-14 09:22:59 +0000922 }
923
Chandler Carruth63392ea2012-09-16 19:39:50 +0000924 void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000925 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
926
927 // For PHI and select operands outside the alloca, we can't nuke the entire
928 // phi or select -- the other side might still be relevant, so we special
929 // case them here and use a separate structure to track the operands
930 // themselves which should be replaced with undef.
931 if (Offset >= AllocSize) {
932 P.DeadOperands.push_back(U);
933 return;
934 }
935
Chandler Carruth63392ea2012-09-16 19:39:50 +0000936 insertUse(User, Offset, Size);
Chandler Carruth713aa942012-09-14 09:22:59 +0000937 }
938 void visitPHINode(PHINode &PN) {
939 if (PN.use_empty())
940 return markAsDead(PN);
941
Chandler Carruth63392ea2012-09-16 19:39:50 +0000942 insertPHIOrSelect(PN, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000943 }
944 void visitSelectInst(SelectInst &SI) {
945 if (SI.use_empty())
946 return markAsDead(SI);
947
948 if (Value *Result = foldSelectInst(SI)) {
949 if (Result == *U)
950 // If the result of the constant fold will be the pointer, recurse
951 // through the select as if we had RAUW'ed it.
952 enqueueUsers(SI, Offset);
Chandler Carruthd54a6b52012-09-21 23:36:40 +0000953 else
954 // Otherwise the operand to the select is dead, and we can replace it
955 // with undef.
956 P.DeadOperands.push_back(U);
Chandler Carruth713aa942012-09-14 09:22:59 +0000957
958 return;
959 }
960
Chandler Carruth63392ea2012-09-16 19:39:50 +0000961 insertPHIOrSelect(SI, Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +0000962 }
963
964 /// \brief Unreachable, we've already visited the alloca once.
965 void visitInstruction(Instruction &I) {
966 llvm_unreachable("Unhandled instruction in use builder.");
967 }
968};
969
970void AllocaPartitioning::splitAndMergePartitions() {
971 size_t NumDeadPartitions = 0;
972
973 // Track the range of splittable partitions that we pass when accumulating
974 // overlapping unsplittable partitions.
975 uint64_t SplitEndOffset = 0ull;
976
977 Partition New(0ull, 0ull, false);
978
979 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
980 ++j;
981
982 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
983 assert(New.BeginOffset == New.EndOffset);
984 New = Partitions[i];
985 } else {
986 assert(New.IsSplittable);
987 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
988 }
989 assert(New.BeginOffset != New.EndOffset);
990
991 // Scan the overlapping partitions.
992 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
993 // If the new partition we are forming is splittable, stop at the first
994 // unsplittable partition.
995 if (New.IsSplittable && !Partitions[j].IsSplittable)
996 break;
997
998 // Grow the new partition to include any equally splittable range. 'j' is
999 // always equally splittable when New is splittable, but when New is not
1000 // splittable, we may subsume some (or part of some) splitable partition
1001 // without growing the new one.
1002 if (New.IsSplittable == Partitions[j].IsSplittable) {
1003 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1004 } else {
1005 assert(!New.IsSplittable);
1006 assert(Partitions[j].IsSplittable);
1007 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1008 }
1009
1010 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
1011 ++NumDeadPartitions;
1012 ++j;
1013 }
1014
1015 // If the new partition is splittable, chop off the end as soon as the
1016 // unsplittable subsequent partition starts and ensure we eventually cover
1017 // the splittable area.
1018 if (j != e && New.IsSplittable) {
1019 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1020 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1021 }
1022
1023 // Add the new partition if it differs from the original one and is
1024 // non-empty. We can end up with an empty partition here if it was
1025 // splittable but there is an unsplittable one that starts at the same
1026 // offset.
1027 if (New != Partitions[i]) {
1028 if (New.BeginOffset != New.EndOffset)
1029 Partitions.push_back(New);
1030 // Mark the old one for removal.
1031 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
1032 ++NumDeadPartitions;
1033 }
1034
1035 New.BeginOffset = New.EndOffset;
1036 if (!New.IsSplittable) {
1037 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1038 if (j != e && !Partitions[j].IsSplittable)
1039 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1040 New.IsSplittable = true;
1041 // If there is a trailing splittable partition which won't be fused into
1042 // the next splittable partition go ahead and add it onto the partitions
1043 // list.
1044 if (New.BeginOffset < New.EndOffset &&
1045 (j == e || !Partitions[j].IsSplittable ||
1046 New.EndOffset < Partitions[j].BeginOffset)) {
1047 Partitions.push_back(New);
1048 New.BeginOffset = New.EndOffset = 0ull;
1049 }
1050 }
1051 }
1052
1053 // Re-sort the partitions now that they have been split and merged into
1054 // disjoint set of partitions. Also remove any of the dead partitions we've
1055 // replaced in the process.
1056 std::sort(Partitions.begin(), Partitions.end());
1057 if (NumDeadPartitions) {
1058 assert(Partitions.back().BeginOffset == UINT64_MAX);
1059 assert(Partitions.back().EndOffset == UINT64_MAX);
1060 assert((ptrdiff_t)NumDeadPartitions ==
1061 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1062 }
1063 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1064}
1065
1066AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +00001067 :
1068#ifndef NDEBUG
1069 AI(AI),
1070#endif
1071 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001072 PartitionBuilder PB(TD, AI, *this);
1073 if (!PB())
1074 return;
1075
1076 if (Partitions.size() > 1) {
1077 // Sort the uses. This arranges for the offsets to be in ascending order,
1078 // and the sizes to be in descending order.
1079 std::sort(Partitions.begin(), Partitions.end());
1080
1081 // Intersect splittability for all partitions with equal offsets and sizes.
1082 // Then remove all but the first so that we have a sequence of non-equal but
1083 // potentially overlapping partitions.
1084 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1085 I = J) {
1086 ++J;
1087 while (J != E && *I == *J) {
1088 I->IsSplittable &= J->IsSplittable;
1089 ++J;
1090 }
1091 }
1092 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1093 Partitions.end());
1094
1095 // Split splittable and merge unsplittable partitions into a disjoint set
1096 // of partitions over the used space of the allocation.
1097 splitAndMergePartitions();
1098 }
1099
1100 // Now build up the user lists for each of these disjoint partitions by
1101 // re-walking the recursive users of the alloca.
1102 Uses.resize(Partitions.size());
1103 UseBuilder UB(TD, AI, *this);
1104 UB();
1105 for (iterator I = Partitions.begin(), E = Partitions.end(); I != E; ++I)
1106 std::stable_sort(use_begin(I), use_end(I));
1107}
1108
1109Type *AllocaPartitioning::getCommonType(iterator I) const {
1110 Type *Ty = 0;
1111 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carruthc370acd2012-09-18 12:57:43 +00001112 if (isa<IntrinsicInst>(*UI->User))
Chandler Carruth713aa942012-09-14 09:22:59 +00001113 continue;
1114 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruth7c8df7a2012-09-18 17:49:37 +00001115 continue;
Chandler Carruth713aa942012-09-14 09:22:59 +00001116
1117 Type *UserTy = 0;
1118 if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1119 UserTy = LI->getType();
1120 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1121 UserTy = SI->getValueOperand()->getType();
1122 } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1123 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1124 UserTy = PtrTy->getElementType();
1125 } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1126 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1127 UserTy = PtrTy->getElementType();
1128 }
1129
1130 if (Ty && Ty != UserTy)
1131 return 0;
1132
1133 Ty = UserTy;
1134 }
1135 return Ty;
1136}
1137
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001138#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1139
Chandler Carruth713aa942012-09-14 09:22:59 +00001140void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1141 StringRef Indent) const {
1142 OS << Indent << "partition #" << (I - begin())
1143 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1144 << (I->IsSplittable ? " (splittable)" : "")
1145 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1146 << "\n";
1147}
1148
1149void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1150 StringRef Indent) const {
1151 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1152 UI != UE; ++UI) {
1153 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1154 << "used by: " << *UI->User << "\n";
1155 if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1156 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:
1335 friend class AllocaPartitionRewriter;
1336 friend class AllocaPartitionVectorRewriter;
1337
1338 bool rewriteAllocaPartition(AllocaInst &AI,
1339 AllocaPartitioning &P,
1340 AllocaPartitioning::iterator PI);
1341 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1342 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001343 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001344 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001345};
1346}
1347
1348char SROA::ID = 0;
1349
Chandler Carruth1c8db502012-09-15 11:43:14 +00001350FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1351 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001352}
1353
1354INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1355 false, false)
1356INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1357INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1358 false, false)
1359
1360/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1361///
1362/// If the provided GEP is all-constant, the total byte offset formed by the
1363/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1364/// operands, the function returns false and the value of Offset is unmodified.
1365static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1366 APInt &Offset) {
1367 APInt GEPOffset(Offset.getBitWidth(), 0);
1368 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1369 GTI != GTE; ++GTI) {
1370 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1371 if (!OpC)
1372 return false;
1373 if (OpC->isZero()) continue;
1374
1375 // Handle a struct index, which adds its field offset to the pointer.
1376 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1377 unsigned ElementIdx = OpC->getZExtValue();
1378 const StructLayout *SL = TD.getStructLayout(STy);
1379 GEPOffset += APInt(Offset.getBitWidth(),
1380 SL->getElementOffset(ElementIdx));
1381 continue;
1382 }
1383
1384 APInt TypeSize(Offset.getBitWidth(),
1385 TD.getTypeAllocSize(GTI.getIndexedType()));
1386 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1387 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1388 "vector element size is not a multiple of 8, cannot GEP over it");
1389 TypeSize = VTy->getScalarSizeInBits() / 8;
1390 }
1391
1392 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1393 }
1394 Offset = GEPOffset;
1395 return true;
1396}
1397
1398/// \brief Build a GEP out of a base pointer and indices.
1399///
1400/// This will return the BasePtr if that is valid, or build a new GEP
1401/// instruction using the IRBuilder if GEP-ing is needed.
1402static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1403 SmallVectorImpl<Value *> &Indices,
1404 const Twine &Prefix) {
1405 if (Indices.empty())
1406 return BasePtr;
1407
1408 // A single zero index is a no-op, so check for this and avoid building a GEP
1409 // in that case.
1410 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1411 return BasePtr;
1412
1413 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1414}
1415
1416/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1417/// TargetTy without changing the offset of the pointer.
1418///
1419/// This routine assumes we've already established a properly offset GEP with
1420/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1421/// zero-indices down through type layers until we find one the same as
1422/// TargetTy. If we can't find one with the same type, we at least try to use
1423/// one with the same size. If none of that works, we just produce the GEP as
1424/// indicated by Indices to have the correct offset.
1425static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1426 Value *BasePtr, Type *Ty, Type *TargetTy,
1427 SmallVectorImpl<Value *> &Indices,
1428 const Twine &Prefix) {
1429 if (Ty == TargetTy)
1430 return buildGEP(IRB, BasePtr, Indices, Prefix);
1431
1432 // See if we can descend into a struct and locate a field with the correct
1433 // type.
1434 unsigned NumLayers = 0;
1435 Type *ElementTy = Ty;
1436 do {
1437 if (ElementTy->isPointerTy())
1438 break;
1439 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1440 ElementTy = SeqTy->getElementType();
1441 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1442 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1443 ElementTy = *STy->element_begin();
1444 Indices.push_back(IRB.getInt32(0));
1445 } else {
1446 break;
1447 }
1448 ++NumLayers;
1449 } while (ElementTy != TargetTy);
1450 if (ElementTy != TargetTy)
1451 Indices.erase(Indices.end() - NumLayers, Indices.end());
1452
1453 return buildGEP(IRB, BasePtr, Indices, Prefix);
1454}
1455
1456/// \brief Recursively compute indices for a natural GEP.
1457///
1458/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1459/// element types adding appropriate indices for the GEP.
1460static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1461 Value *Ptr, Type *Ty, APInt &Offset,
1462 Type *TargetTy,
1463 SmallVectorImpl<Value *> &Indices,
1464 const Twine &Prefix) {
1465 if (Offset == 0)
1466 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1467
1468 // We can't recurse through pointer types.
1469 if (Ty->isPointerTy())
1470 return 0;
1471
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001472 // We try to analyze GEPs over vectors here, but note that these GEPs are
1473 // extremely poorly defined currently. The long-term goal is to remove GEPing
1474 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001475 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1476 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1477 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001478 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001479 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1480 APInt NumSkippedElements = Offset.udiv(ElementSize);
1481 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1482 return 0;
1483 Offset -= NumSkippedElements * ElementSize;
1484 Indices.push_back(IRB.getInt(NumSkippedElements));
1485 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1486 Offset, TargetTy, Indices, Prefix);
1487 }
1488
1489 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1490 Type *ElementTy = ArrTy->getElementType();
1491 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1492 APInt NumSkippedElements = Offset.udiv(ElementSize);
1493 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1494 return 0;
1495
1496 Offset -= NumSkippedElements * ElementSize;
1497 Indices.push_back(IRB.getInt(NumSkippedElements));
1498 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1499 Indices, Prefix);
1500 }
1501
1502 StructType *STy = dyn_cast<StructType>(Ty);
1503 if (!STy)
1504 return 0;
1505
1506 const StructLayout *SL = TD.getStructLayout(STy);
1507 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001508 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001509 return 0;
1510 unsigned Index = SL->getElementContainingOffset(StructOffset);
1511 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1512 Type *ElementTy = STy->getElementType(Index);
1513 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1514 return 0; // The offset points into alignment padding.
1515
1516 Indices.push_back(IRB.getInt32(Index));
1517 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1518 Indices, Prefix);
1519}
1520
1521/// \brief Get a natural GEP from a base pointer to a particular offset and
1522/// resulting in a particular type.
1523///
1524/// The goal is to produce a "natural" looking GEP that works with the existing
1525/// composite types to arrive at the appropriate offset and element type for
1526/// a pointer. TargetTy is the element type the returned GEP should point-to if
1527/// possible. We recurse by decreasing Offset, adding the appropriate index to
1528/// Indices, and setting Ty to the result subtype.
1529///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001530/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth713aa942012-09-14 09:22:59 +00001531static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1532 Value *Ptr, APInt Offset, Type *TargetTy,
1533 SmallVectorImpl<Value *> &Indices,
1534 const Twine &Prefix) {
1535 PointerType *Ty = cast<PointerType>(Ptr->getType());
1536
1537 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1538 // an i8.
1539 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1540 return 0;
1541
1542 Type *ElementTy = Ty->getElementType();
Chandler Carruth38f35fd2012-09-18 22:37:19 +00001543 if (!ElementTy->isSized())
1544 return 0; // We can't GEP through an unsized element.
Chandler Carruth713aa942012-09-14 09:22:59 +00001545 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1546 if (ElementSize == 0)
1547 return 0; // Zero-length arrays can't help us build a natural GEP.
1548 APInt NumSkippedElements = Offset.udiv(ElementSize);
1549
1550 Offset -= NumSkippedElements * ElementSize;
1551 Indices.push_back(IRB.getInt(NumSkippedElements));
1552 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1553 Indices, Prefix);
1554}
1555
1556/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1557/// resulting pointer has PointerTy.
1558///
1559/// This tries very hard to compute a "natural" GEP which arrives at the offset
1560/// and produces the pointer type desired. Where it cannot, it will try to use
1561/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1562/// fails, it will try to use an existing i8* and GEP to the byte offset and
1563/// bitcast to the type.
1564///
1565/// The strategy for finding the more natural GEPs is to peel off layers of the
1566/// pointer, walking back through bit casts and GEPs, searching for a base
1567/// pointer from which we can compute a natural GEP with the desired
1568/// properities. The algorithm tries to fold as many constant indices into
1569/// a single GEP as possible, thus making each GEP more independent of the
1570/// surrounding code.
1571static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1572 Value *Ptr, APInt Offset, Type *PointerTy,
1573 const Twine &Prefix) {
1574 // Even though we don't look through PHI nodes, we could be called on an
1575 // instruction in an unreachable block, which may be on a cycle.
1576 SmallPtrSet<Value *, 4> Visited;
1577 Visited.insert(Ptr);
1578 SmallVector<Value *, 4> Indices;
1579
1580 // We may end up computing an offset pointer that has the wrong type. If we
1581 // never are able to compute one directly that has the correct type, we'll
1582 // fall back to it, so keep it around here.
1583 Value *OffsetPtr = 0;
1584
1585 // Remember any i8 pointer we come across to re-use if we need to do a raw
1586 // byte offset.
1587 Value *Int8Ptr = 0;
1588 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1589
1590 Type *TargetTy = PointerTy->getPointerElementType();
1591
1592 do {
1593 // First fold any existing GEPs into the offset.
1594 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1595 APInt GEPOffset(Offset.getBitWidth(), 0);
1596 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1597 break;
1598 Offset += GEPOffset;
1599 Ptr = GEP->getPointerOperand();
1600 if (!Visited.insert(Ptr))
1601 break;
1602 }
1603
1604 // See if we can perform a natural GEP here.
1605 Indices.clear();
1606 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1607 Indices, Prefix)) {
1608 if (P->getType() == PointerTy) {
1609 // Zap any offset pointer that we ended up computing in previous rounds.
1610 if (OffsetPtr && OffsetPtr->use_empty())
1611 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1612 I->eraseFromParent();
1613 return P;
1614 }
1615 if (!OffsetPtr) {
1616 OffsetPtr = P;
1617 }
1618 }
1619
1620 // Stash this pointer if we've found an i8*.
1621 if (Ptr->getType()->isIntegerTy(8)) {
1622 Int8Ptr = Ptr;
1623 Int8PtrOffset = Offset;
1624 }
1625
1626 // Peel off a layer of the pointer and update the offset appropriately.
1627 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1628 Ptr = cast<Operator>(Ptr)->getOperand(0);
1629 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1630 if (GA->mayBeOverridden())
1631 break;
1632 Ptr = GA->getAliasee();
1633 } else {
1634 break;
1635 }
1636 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1637 } while (Visited.insert(Ptr));
1638
1639 if (!OffsetPtr) {
1640 if (!Int8Ptr) {
1641 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1642 Prefix + ".raw_cast");
1643 Int8PtrOffset = Offset;
1644 }
1645
1646 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1647 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1648 Prefix + ".raw_idx");
1649 }
1650 Ptr = OffsetPtr;
1651
1652 // On the off chance we were targeting i8*, guard the bitcast here.
1653 if (Ptr->getType() != PointerTy)
1654 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1655
1656 return Ptr;
1657}
1658
1659/// \brief Test whether the given alloca partition can be promoted to a vector.
1660///
1661/// This is a quick test to check whether we can rewrite a particular alloca
1662/// partition (and its newly formed alloca) into a vector alloca with only
1663/// whole-vector loads and stores such that it could be promoted to a vector
1664/// SSA value. We only can ensure this for a limited set of operations, and we
1665/// don't want to do the rewrites unless we are confident that the result will
1666/// be promotable, so we have an early test here.
1667static bool isVectorPromotionViable(const TargetData &TD,
1668 Type *AllocaTy,
1669 AllocaPartitioning &P,
1670 uint64_t PartitionBeginOffset,
1671 uint64_t PartitionEndOffset,
1672 AllocaPartitioning::const_use_iterator I,
1673 AllocaPartitioning::const_use_iterator E) {
1674 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1675 if (!Ty)
1676 return false;
1677
1678 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1679 uint64_t ElementSize = Ty->getScalarSizeInBits();
1680
1681 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1682 // that aren't byte sized.
1683 if (ElementSize % 8)
1684 return false;
1685 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1686 VecSize /= 8;
1687 ElementSize /= 8;
1688
1689 for (; I != E; ++I) {
1690 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1691 uint64_t BeginIndex = BeginOffset / ElementSize;
1692 if (BeginIndex * ElementSize != BeginOffset ||
1693 BeginIndex >= Ty->getNumElements())
1694 return false;
1695 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1696 uint64_t EndIndex = EndOffset / ElementSize;
1697 if (EndIndex * ElementSize != EndOffset ||
1698 EndIndex > Ty->getNumElements())
1699 return false;
1700
1701 // FIXME: We should build shuffle vector instructions to handle
1702 // non-element-sized accesses.
1703 if ((EndOffset - BeginOffset) != ElementSize &&
1704 (EndOffset - BeginOffset) != VecSize)
1705 return false;
1706
1707 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1708 if (MI->isVolatile())
1709 return false;
1710 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1711 const AllocaPartitioning::MemTransferOffsets &MTO
1712 = P.getMemTransferOffsets(*MTI);
1713 if (!MTO.IsSplittable)
1714 return false;
1715 }
1716 } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1717 // Disable vector promotion when there are loads or stores of an FCA.
1718 return false;
1719 } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1720 return false;
1721 }
1722 }
1723 return true;
1724}
1725
1726namespace {
1727/// \brief Visitor to rewrite instructions using a partition of an alloca to
1728/// use a new alloca.
1729///
1730/// Also implements the rewriting to vector-based accesses when the partition
1731/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1732/// lives here.
1733class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1734 bool> {
1735 // Befriend the base class so it can delegate to private visit methods.
1736 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1737
1738 const TargetData &TD;
1739 AllocaPartitioning &P;
1740 SROA &Pass;
1741 AllocaInst &OldAI, &NewAI;
1742 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1743
1744 // If we are rewriting an alloca partition which can be written as pure
1745 // vector operations, we stash extra information here. When VecTy is
1746 // non-null, we have some strict guarantees about the rewriten alloca:
1747 // - The new alloca is exactly the size of the vector type here.
1748 // - The accesses all either map to the entire vector or to a single
1749 // element.
1750 // - The set of accessing instructions is only one of those handled above
1751 // in isVectorPromotionViable. Generally these are the same access kinds
1752 // which are promotable via mem2reg.
1753 VectorType *VecTy;
1754 Type *ElementTy;
1755 uint64_t ElementSize;
1756
1757 // The offset of the partition user currently being rewritten.
1758 uint64_t BeginOffset, EndOffset;
1759 Instruction *OldPtr;
1760
1761 // The name prefix to use when rewriting instructions for this alloca.
1762 std::string NamePrefix;
1763
1764public:
1765 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1766 AllocaPartitioning::iterator PI,
1767 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1768 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1769 : TD(TD), P(P), Pass(Pass),
1770 OldAI(OldAI), NewAI(NewAI),
1771 NewAllocaBeginOffset(NewBeginOffset),
1772 NewAllocaEndOffset(NewEndOffset),
1773 VecTy(), ElementTy(), ElementSize(),
1774 BeginOffset(), EndOffset() {
1775 }
1776
1777 /// \brief Visit the users of the alloca partition and rewrite them.
1778 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1779 AllocaPartitioning::const_use_iterator E) {
1780 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1781 NewAllocaBeginOffset, NewAllocaEndOffset,
1782 I, E)) {
1783 ++NumVectorized;
1784 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1785 ElementTy = VecTy->getElementType();
1786 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1787 "Only multiple-of-8 sized vector elements are viable");
1788 ElementSize = VecTy->getScalarSizeInBits() / 8;
1789 }
1790 bool CanSROA = true;
1791 for (; I != E; ++I) {
1792 BeginOffset = I->BeginOffset;
1793 EndOffset = I->EndOffset;
1794 OldPtr = I->Ptr;
1795 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1796 CanSROA &= visit(I->User);
1797 }
1798 if (VecTy) {
1799 assert(CanSROA);
1800 VecTy = 0;
1801 ElementTy = 0;
1802 ElementSize = 0;
1803 }
1804 return CanSROA;
1805 }
1806
1807private:
1808 // Every instruction which can end up as a user must have a rewrite rule.
1809 bool visitInstruction(Instruction &I) {
1810 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1811 llvm_unreachable("No rewrite rule for this instruction!");
1812 }
1813
1814 Twine getName(const Twine &Suffix) {
1815 return NamePrefix + Suffix;
1816 }
1817
1818 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1819 assert(BeginOffset >= NewAllocaBeginOffset);
1820 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1821 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1822 }
1823
1824 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1825 assert(VecTy && "Can only call getIndex when rewriting a vector");
1826 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1827 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1828 uint32_t Index = RelOffset / ElementSize;
1829 assert(Index * ElementSize == RelOffset);
1830 return IRB.getInt32(Index);
1831 }
1832
1833 void deleteIfTriviallyDead(Value *V) {
1834 Instruction *I = cast<Instruction>(V);
1835 if (isInstructionTriviallyDead(I))
1836 Pass.DeadInsts.push_back(I);
1837 }
1838
1839 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1840 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1841 return IRB.CreateIntToPtr(V, Ty);
1842 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1843 return IRB.CreatePtrToInt(V, Ty);
1844
1845 return IRB.CreateBitCast(V, Ty);
1846 }
1847
1848 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1849 Value *Result;
1850 if (LI.getType() == VecTy->getElementType() ||
1851 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1852 Result
1853 = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1854 getIndex(IRB, BeginOffset),
1855 getName(".extract"));
1856 } else {
1857 Result = IRB.CreateLoad(&NewAI, getName(".load"));
1858 }
1859 if (Result->getType() != LI.getType())
1860 Result = getValueCast(IRB, Result, LI.getType());
1861 LI.replaceAllUsesWith(Result);
1862 Pass.DeadInsts.push_back(&LI);
1863
1864 DEBUG(dbgs() << " to: " << *Result << "\n");
1865 return true;
1866 }
1867
1868 bool visitLoadInst(LoadInst &LI) {
1869 DEBUG(dbgs() << " original: " << LI << "\n");
1870 Value *OldOp = LI.getOperand(0);
1871 assert(OldOp == OldPtr);
1872 IRBuilder<> IRB(&LI);
1873
1874 if (VecTy)
1875 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1876
1877 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1878 LI.getPointerOperand()->getType());
1879 LI.setOperand(0, NewPtr);
1880 DEBUG(dbgs() << " to: " << LI << "\n");
1881
1882 deleteIfTriviallyDead(OldOp);
1883 return NewPtr == &NewAI && !LI.isVolatile();
1884 }
1885
1886 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1887 Value *OldOp) {
1888 Value *V = SI.getValueOperand();
1889 if (V->getType() == ElementTy ||
1890 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1891 if (V->getType() != ElementTy)
1892 V = getValueCast(IRB, V, ElementTy);
1893 V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1894 getIndex(IRB, BeginOffset),
1895 getName(".insert"));
1896 } else if (V->getType() != VecTy) {
1897 V = getValueCast(IRB, V, VecTy);
1898 }
1899 StoreInst *Store = IRB.CreateStore(V, &NewAI);
1900 Pass.DeadInsts.push_back(&SI);
1901
1902 (void)Store;
1903 DEBUG(dbgs() << " to: " << *Store << "\n");
1904 return true;
1905 }
1906
1907 bool visitStoreInst(StoreInst &SI) {
1908 DEBUG(dbgs() << " original: " << SI << "\n");
1909 Value *OldOp = SI.getOperand(1);
1910 assert(OldOp == OldPtr);
1911 IRBuilder<> IRB(&SI);
1912
1913 if (VecTy)
1914 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
1915
1916 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1917 SI.getPointerOperand()->getType());
1918 SI.setOperand(1, NewPtr);
1919 DEBUG(dbgs() << " to: " << SI << "\n");
1920
1921 deleteIfTriviallyDead(OldOp);
1922 return NewPtr == &NewAI && !SI.isVolatile();
1923 }
1924
1925 bool visitMemSetInst(MemSetInst &II) {
1926 DEBUG(dbgs() << " original: " << II << "\n");
1927 IRBuilder<> IRB(&II);
1928 assert(II.getRawDest() == OldPtr);
1929
1930 // If the memset has a variable size, it cannot be split, just adjust the
1931 // pointer to the new alloca.
1932 if (!isa<Constant>(II.getLength())) {
1933 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1934 deleteIfTriviallyDead(OldPtr);
1935 return false;
1936 }
1937
1938 // Record this instruction for deletion.
1939 if (Pass.DeadSplitInsts.insert(&II))
1940 Pass.DeadInsts.push_back(&II);
1941
1942 Type *AllocaTy = NewAI.getAllocatedType();
1943 Type *ScalarTy = AllocaTy->getScalarType();
1944
1945 // If this doesn't map cleanly onto the alloca type, and that type isn't
1946 // a single value type, just emit a memset.
1947 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
1948 EndOffset != NewAllocaEndOffset ||
1949 !AllocaTy->isSingleValueType() ||
1950 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
1951 Type *SizeTy = II.getLength()->getType();
1952 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1953
1954 CallInst *New
1955 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
1956 II.getRawDest()->getType()),
1957 II.getValue(), Size, II.getAlignment(),
1958 II.isVolatile());
1959 (void)New;
1960 DEBUG(dbgs() << " to: " << *New << "\n");
1961 return false;
1962 }
1963
1964 // If we can represent this as a simple value, we have to build the actual
1965 // value to store, which requires expanding the byte present in memset to
1966 // a sensible representation for the alloca type. This is essentially
1967 // splatting the byte to a sufficiently wide integer, bitcasting to the
1968 // desired scalar type, and splatting it across any desired vector type.
1969 Value *V = II.getValue();
1970 IntegerType *VTy = cast<IntegerType>(V->getType());
1971 Type *IntTy = Type::getIntNTy(VTy->getContext(),
1972 TD.getTypeSizeInBits(ScalarTy));
1973 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
1974 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
1975 ConstantExpr::getUDiv(
1976 Constant::getAllOnesValue(IntTy),
1977 ConstantExpr::getZExt(
1978 Constant::getAllOnesValue(V->getType()),
1979 IntTy)),
1980 getName(".isplat"));
1981 if (V->getType() != ScalarTy) {
1982 if (ScalarTy->isPointerTy())
1983 V = IRB.CreateIntToPtr(V, ScalarTy);
1984 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
1985 V = IRB.CreateBitCast(V, ScalarTy);
1986 else if (ScalarTy->isIntegerTy())
1987 llvm_unreachable("Computed different integer types with equal widths");
1988 else
1989 llvm_unreachable("Invalid scalar type");
1990 }
1991
1992 // If this is an element-wide memset of a vectorizable alloca, insert it.
1993 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
1994 EndOffset < NewAllocaEndOffset)) {
1995 StoreInst *Store = IRB.CreateStore(
1996 IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1997 getIndex(IRB, BeginOffset),
1998 getName(".insert")),
1999 &NewAI);
2000 (void)Store;
2001 DEBUG(dbgs() << " to: " << *Store << "\n");
2002 return true;
2003 }
2004
2005 // Splat to a vector if needed.
2006 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
2007 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
2008 V = IRB.CreateShuffleVector(
2009 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
2010 IRB.getInt32(0), getName(".vsplat.insert")),
2011 UndefValue::get(SplatSourceTy),
2012 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
2013 getName(".vsplat.shuffle"));
2014 assert(V->getType() == VecTy);
2015 }
2016
2017 Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
2018 (void)New;
2019 DEBUG(dbgs() << " to: " << *New << "\n");
2020 return !II.isVolatile();
2021 }
2022
2023 bool visitMemTransferInst(MemTransferInst &II) {
2024 // Rewriting of memory transfer instructions can be a bit tricky. We break
2025 // them into two categories: split intrinsics and unsplit intrinsics.
2026
2027 DEBUG(dbgs() << " original: " << II << "\n");
2028 IRBuilder<> IRB(&II);
2029
2030 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2031 bool IsDest = II.getRawDest() == OldPtr;
2032
2033 const AllocaPartitioning::MemTransferOffsets &MTO
2034 = P.getMemTransferOffsets(II);
2035
2036 // For unsplit intrinsics, we simply modify the source and destination
2037 // pointers in place. This isn't just an optimization, it is a matter of
2038 // correctness. With unsplit intrinsics we may be dealing with transfers
2039 // within a single alloca before SROA ran, or with transfers that have
2040 // a variable length. We may also be dealing with memmove instead of
2041 // memcpy, and so simply updating the pointers is the necessary for us to
2042 // update both source and dest of a single call.
2043 if (!MTO.IsSplittable) {
2044 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2045 if (IsDest)
2046 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2047 else
2048 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2049
2050 DEBUG(dbgs() << " to: " << II << "\n");
2051 deleteIfTriviallyDead(OldOp);
2052 return false;
2053 }
2054 // For split transfer intrinsics we have an incredibly useful assurance:
2055 // the source and destination do not reside within the same alloca, and at
2056 // least one of them does not escape. This means that we can replace
2057 // memmove with memcpy, and we don't need to worry about all manner of
2058 // downsides to splitting and transforming the operations.
2059
2060 // Compute the relative offset within the transfer.
2061 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2062 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2063 : MTO.SourceBegin));
2064
2065 // If this doesn't map cleanly onto the alloca type, and that type isn't
2066 // a single value type, just emit a memcpy.
2067 bool EmitMemCpy
2068 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
2069 EndOffset != NewAllocaEndOffset ||
2070 !NewAI.getAllocatedType()->isSingleValueType());
2071
2072 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2073 // size hasn't been shrunk based on analysis of the viable range, this is
2074 // a no-op.
2075 if (EmitMemCpy && &OldAI == &NewAI) {
2076 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2077 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2078 // Ensure the start lines up.
2079 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002080 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002081
2082 // Rewrite the size as needed.
2083 if (EndOffset != OrigEnd)
2084 II.setLength(ConstantInt::get(II.getLength()->getType(),
2085 EndOffset - BeginOffset));
2086 return false;
2087 }
2088 // Record this instruction for deletion.
2089 if (Pass.DeadSplitInsts.insert(&II))
2090 Pass.DeadInsts.push_back(&II);
2091
2092 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2093 EndOffset < NewAllocaEndOffset);
2094
2095 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2096 : II.getRawDest()->getType();
2097 if (!EmitMemCpy)
2098 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2099 : NewAI.getType();
2100
2101 // Compute the other pointer, folding as much as possible to produce
2102 // a single, simple GEP in most cases.
2103 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2104 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2105 getName("." + OtherPtr->getName()));
2106
2107 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2108 // alloca that should be re-examined after rewriting this instruction.
2109 if (AllocaInst *AI
2110 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2111 Pass.Worklist.insert(AI);
2112
2113 if (EmitMemCpy) {
2114 Value *OurPtr
2115 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2116 : II.getRawSource()->getType());
2117 Type *SizeTy = II.getLength()->getType();
2118 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2119
2120 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2121 IsDest ? OtherPtr : OurPtr,
2122 Size, II.getAlignment(),
2123 II.isVolatile());
2124 (void)New;
2125 DEBUG(dbgs() << " to: " << *New << "\n");
2126 return false;
2127 }
2128
2129 Value *SrcPtr = OtherPtr;
2130 Value *DstPtr = &NewAI;
2131 if (!IsDest)
2132 std::swap(SrcPtr, DstPtr);
2133
2134 Value *Src;
2135 if (IsVectorElement && !IsDest) {
2136 // We have to extract rather than load.
2137 Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
2138 getName(".copyload")),
2139 getIndex(IRB, BeginOffset),
2140 getName(".copyextract"));
2141 } else {
2142 Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
2143 }
2144
2145 if (IsVectorElement && IsDest) {
2146 // We have to insert into a loaded copy before storing.
2147 Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
2148 Src, getIndex(IRB, BeginOffset),
2149 getName(".insert"));
2150 }
2151
2152 Value *Store = IRB.CreateStore(Src, DstPtr, II.isVolatile());
2153 (void)Store;
2154 DEBUG(dbgs() << " to: " << *Store << "\n");
2155 return !II.isVolatile();
2156 }
2157
2158 bool visitIntrinsicInst(IntrinsicInst &II) {
2159 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2160 II.getIntrinsicID() == Intrinsic::lifetime_end);
2161 DEBUG(dbgs() << " original: " << II << "\n");
2162 IRBuilder<> IRB(&II);
2163 assert(II.getArgOperand(1) == OldPtr);
2164
2165 // Record this instruction for deletion.
2166 if (Pass.DeadSplitInsts.insert(&II))
2167 Pass.DeadInsts.push_back(&II);
2168
2169 ConstantInt *Size
2170 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2171 EndOffset - BeginOffset);
2172 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2173 Value *New;
2174 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2175 New = IRB.CreateLifetimeStart(Ptr, Size);
2176 else
2177 New = IRB.CreateLifetimeEnd(Ptr, Size);
2178
2179 DEBUG(dbgs() << " to: " << *New << "\n");
2180 return true;
2181 }
2182
2183 /// PHI instructions that use an alloca and are subsequently loaded can be
2184 /// rewritten to load both input pointers in the pred blocks and then PHI the
2185 /// results, allowing the load of the alloca to be promoted.
2186 /// From this:
2187 /// %P2 = phi [i32* %Alloca, i32* %Other]
2188 /// %V = load i32* %P2
2189 /// to:
2190 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2191 /// ...
2192 /// %V2 = load i32* %Other
2193 /// ...
2194 /// %V = phi [i32 %V1, i32 %V2]
2195 ///
2196 /// We can do this to a select if its only uses are loads and if the operand
2197 /// to the select can be loaded unconditionally.
2198 ///
2199 /// FIXME: This should be hoisted into a generic utility, likely in
2200 /// Transforms/Util/Local.h
2201 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2202 // For now, we can only do this promotion if the load is in the same block
2203 // as the PHI, and if there are no stores between the phi and load.
2204 // TODO: Allow recursive phi users.
2205 // TODO: Allow stores.
2206 BasicBlock *BB = PN.getParent();
2207 unsigned MaxAlign = 0;
2208 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2209 UI != UE; ++UI) {
2210 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2211 if (LI == 0 || !LI->isSimple()) return false;
2212
2213 // For now we only allow loads in the same block as the PHI. This is
2214 // a common case that happens when instcombine merges two loads through
2215 // a PHI.
2216 if (LI->getParent() != BB) return false;
2217
2218 // Ensure that there are no instructions between the PHI and the load that
2219 // could store.
2220 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2221 if (BBI->mayWriteToMemory())
2222 return false;
2223
2224 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2225 Loads.push_back(LI);
2226 }
2227
2228 // We can only transform this if it is safe to push the loads into the
2229 // predecessor blocks. The only thing to watch out for is that we can't put
2230 // a possibly trapping load in the predecessor if it is a critical edge.
2231 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2232 ++Idx) {
2233 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2234 Value *InVal = PN.getIncomingValue(Idx);
2235
2236 // If the value is produced by the terminator of the predecessor (an
2237 // invoke) or it has side-effects, there is no valid place to put a load
2238 // in the predecessor.
2239 if (TI == InVal || TI->mayHaveSideEffects())
2240 return false;
2241
2242 // If the predecessor has a single successor, then the edge isn't
2243 // critical.
2244 if (TI->getNumSuccessors() == 1)
2245 continue;
2246
2247 // If this pointer is always safe to load, or if we can prove that there
2248 // is already a load in the block, then we can move the load to the pred
2249 // block.
2250 if (InVal->isDereferenceablePointer() ||
2251 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2252 continue;
2253
2254 return false;
2255 }
2256
2257 return true;
2258 }
2259
2260 bool visitPHINode(PHINode &PN) {
2261 DEBUG(dbgs() << " original: " << PN << "\n");
2262 // We would like to compute a new pointer in only one place, but have it be
2263 // as local as possible to the PHI. To do that, we re-use the location of
2264 // the old pointer, which necessarily must be in the right position to
2265 // dominate the PHI.
2266 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2267
2268 SmallVector<LoadInst *, 4> Loads;
2269 if (!isSafePHIToSpeculate(PN, Loads)) {
2270 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2271 // Replace the operands which were using the old pointer.
2272 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2273 for (; OI != OE; ++OI)
2274 if (*OI == OldPtr)
2275 *OI = NewPtr;
2276
2277 DEBUG(dbgs() << " to: " << PN << "\n");
2278 deleteIfTriviallyDead(OldPtr);
2279 return false;
2280 }
2281 assert(!Loads.empty());
2282
2283 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2284 IRBuilder<> PHIBuilder(&PN);
2285 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2286 NewPN->takeName(&PN);
2287
2288 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2289 // matter which one we get and if any differ, it doesn't matter.
2290 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2291 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2292 unsigned Align = SomeLoad->getAlignment();
2293 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2294
2295 // Rewrite all loads of the PN to use the new PHI.
2296 do {
2297 LoadInst *LI = Loads.pop_back_val();
2298 LI->replaceAllUsesWith(NewPN);
2299 Pass.DeadInsts.push_back(LI);
2300 } while (!Loads.empty());
2301
2302 // Inject loads into all of the pred blocks.
2303 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2304 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2305 TerminatorInst *TI = Pred->getTerminator();
2306 Value *InVal = PN.getIncomingValue(Idx);
2307 IRBuilder<> PredBuilder(TI);
2308
2309 // Map the value to the new alloca pointer if this was the old alloca
2310 // pointer.
2311 bool ThisOperand = InVal == OldPtr;
2312 if (ThisOperand)
2313 InVal = NewPtr;
2314
2315 LoadInst *Load
2316 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2317 Pred->getName()));
2318 ++NumLoadsSpeculated;
2319 Load->setAlignment(Align);
2320 if (TBAATag)
2321 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2322 NewPN->addIncoming(Load, Pred);
2323
2324 if (ThisOperand)
2325 continue;
2326 Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2327 if (!OtherPtr)
2328 // No uses to rewrite.
2329 continue;
2330
2331 // Try to lookup and rewrite any partition uses corresponding to this phi
2332 // input.
2333 AllocaPartitioning::iterator PI
2334 = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2335 if (PI != P.end()) {
2336 // If the other pointer is within the partitioning, replace the PHI in
2337 // its uses with the load we just speculated, or add another load for
2338 // it to rewrite if we've already replaced the PHI.
2339 AllocaPartitioning::use_iterator UI
2340 = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2341 if (isa<PHINode>(*UI->User))
2342 UI->User = Load;
2343 else {
2344 AllocaPartitioning::PartitionUse OtherUse = *UI;
2345 OtherUse.User = Load;
2346 P.use_insert(PI, std::upper_bound(UI, P.use_end(PI), OtherUse),
2347 OtherUse);
2348 }
2349 }
2350 }
2351 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2352 return NewPtr == &NewAI;
2353 }
2354
2355 /// Select instructions that use an alloca and are subsequently loaded can be
2356 /// rewritten to load both input pointers and then select between the result,
2357 /// allowing the load of the alloca to be promoted.
2358 /// From this:
2359 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2360 /// %V = load i32* %P2
2361 /// to:
2362 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2363 /// %V2 = load i32* %Other
2364 /// %V = select i1 %cond, i32 %V1, i32 %V2
2365 ///
2366 /// We can do this to a select if its only uses are loads and if the operand
2367 /// to the select can be loaded unconditionally.
2368 bool isSafeSelectToSpeculate(SelectInst &SI,
2369 SmallVectorImpl<LoadInst *> &Loads) {
2370 Value *TValue = SI.getTrueValue();
2371 Value *FValue = SI.getFalseValue();
2372 bool TDerefable = TValue->isDereferenceablePointer();
2373 bool FDerefable = FValue->isDereferenceablePointer();
2374
2375 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2376 UI != UE; ++UI) {
2377 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2378 if (LI == 0 || !LI->isSimple()) return false;
2379
2380 // Both operands to the select need to be dereferencable, either
2381 // absolutely (e.g. allocas) or at this point because we can see other
2382 // accesses to it.
2383 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2384 LI->getAlignment(), &TD))
2385 return false;
2386 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2387 LI->getAlignment(), &TD))
2388 return false;
2389 Loads.push_back(LI);
2390 }
2391
2392 return true;
2393 }
2394
2395 bool visitSelectInst(SelectInst &SI) {
2396 DEBUG(dbgs() << " original: " << SI << "\n");
2397 IRBuilder<> IRB(&SI);
2398
2399 // Find the operand we need to rewrite here.
2400 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2401 if (IsTrueVal)
2402 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2403 else
2404 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2405 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2406
2407 // If the select isn't safe to speculate, just use simple logic to emit it.
2408 SmallVector<LoadInst *, 4> Loads;
2409 if (!isSafeSelectToSpeculate(SI, Loads)) {
2410 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2411 DEBUG(dbgs() << " to: " << SI << "\n");
2412 deleteIfTriviallyDead(OldPtr);
2413 return false;
2414 }
2415
2416 Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2417 AllocaPartitioning::iterator PI
2418 = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2419 AllocaPartitioning::PartitionUse OtherUse;
2420 if (PI != P.end()) {
2421 // If the other pointer is within the partitioning, remove the select
2422 // from its uses. We'll add in the new loads below.
2423 AllocaPartitioning::use_iterator UI
2424 = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2425 OtherUse = *UI;
2426 P.use_erase(PI, UI);
2427 }
2428
2429 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2430 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2431 // Replace the loads of the select with a select of two loads.
2432 while (!Loads.empty()) {
2433 LoadInst *LI = Loads.pop_back_val();
2434
2435 IRB.SetInsertPoint(LI);
2436 LoadInst *TL =
2437 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2438 LoadInst *FL =
2439 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2440 NumLoadsSpeculated += 2;
2441 if (PI != P.end()) {
2442 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2443 assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2444 OtherUse.User = OtherLoad;
2445 P.use_insert(PI, P.use_end(PI), OtherUse);
2446 }
2447
2448 // Transfer alignment and TBAA info if present.
2449 TL->setAlignment(LI->getAlignment());
2450 FL->setAlignment(LI->getAlignment());
2451 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2452 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2453 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2454 }
2455
2456 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2457 V->takeName(LI);
2458 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2459 LI->replaceAllUsesWith(V);
2460 Pass.DeadInsts.push_back(LI);
2461 }
2462 if (PI != P.end())
2463 std::stable_sort(P.use_begin(PI), P.use_end(PI));
2464
2465 deleteIfTriviallyDead(OldPtr);
2466 return NewPtr == &NewAI;
2467 }
2468
2469};
2470}
2471
Chandler Carruthc370acd2012-09-18 12:57:43 +00002472namespace {
2473/// \brief Visitor to rewrite aggregate loads and stores as scalar.
2474///
2475/// This pass aggressively rewrites all aggregate loads and stores on
2476/// a particular pointer (or any pointer derived from it which we can identify)
2477/// with scalar loads and stores.
2478class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
2479 // Befriend the base class so it can delegate to private visit methods.
2480 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
2481
2482 const TargetData &TD;
2483
2484 /// Queue of pointer uses to analyze and potentially rewrite.
2485 SmallVector<Use *, 8> Queue;
2486
2487 /// Set to prevent us from cycling with phi nodes and loops.
2488 SmallPtrSet<User *, 8> Visited;
2489
2490 /// The current pointer use being rewritten. This is used to dig up the used
2491 /// value (as opposed to the user).
2492 Use *U;
2493
2494public:
2495 AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
2496
2497 /// Rewrite loads and stores through a pointer and all pointers derived from
2498 /// it.
2499 bool rewrite(Instruction &I) {
2500 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
2501 enqueueUsers(I);
2502 bool Changed = false;
2503 while (!Queue.empty()) {
2504 U = Queue.pop_back_val();
2505 Changed |= visit(cast<Instruction>(U->getUser()));
2506 }
2507 return Changed;
2508 }
2509
2510private:
2511 /// Enqueue all the users of the given instruction for further processing.
2512 /// This uses a set to de-duplicate users.
2513 void enqueueUsers(Instruction &I) {
2514 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
2515 ++UI)
2516 if (Visited.insert(*UI))
2517 Queue.push_back(&UI.getUse());
2518 }
2519
2520 // Conservative default is to not rewrite anything.
2521 bool visitInstruction(Instruction &I) { return false; }
2522
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002523 /// \brief Generic recursive split emission class.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002524 template <typename Derived>
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002525 class OpSplitter {
2526 protected:
2527 /// The builder used to form new instructions.
2528 IRBuilder<> IRB;
2529 /// The indices which to be used with insert- or extractvalue to select the
2530 /// appropriate value within the aggregate.
2531 SmallVector<unsigned, 4> Indices;
2532 /// The indices to a GEP instruction which will move Ptr to the correct slot
2533 /// within the aggregate.
2534 SmallVector<Value *, 4> GEPIndices;
2535 /// The base pointer of the original op, used as a base for GEPing the
2536 /// split operations.
2537 Value *Ptr;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002538
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002539 /// Initialize the splitter with an insertion point, Ptr and start with a
2540 /// single zero GEP index.
2541 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002542 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002543
2544 public:
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002545 /// \brief Generic recursive split emission routine.
2546 ///
2547 /// This method recursively splits an aggregate op (load or store) into
2548 /// scalar or vector ops. It splits recursively until it hits a single value
2549 /// and emits that single value operation via the template argument.
2550 ///
2551 /// The logic of this routine relies on GEPs and insertvalue and
2552 /// extractvalue all operating with the same fundamental index list, merely
2553 /// formatted differently (GEPs need actual values).
2554 ///
2555 /// \param Ty The type being split recursively into smaller ops.
2556 /// \param Agg The aggregate value being built up or stored, depending on
2557 /// whether this is splitting a load or a store respectively.
2558 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
2559 if (Ty->isSingleValueType())
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002560 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002561
2562 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2563 unsigned OldSize = Indices.size();
2564 (void)OldSize;
2565 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
2566 ++Idx) {
2567 assert(Indices.size() == OldSize && "Did not return to the old size");
2568 Indices.push_back(Idx);
2569 GEPIndices.push_back(IRB.getInt32(Idx));
2570 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
2571 GEPIndices.pop_back();
2572 Indices.pop_back();
2573 }
2574 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002575 }
Chandler Carruthc370acd2012-09-18 12:57:43 +00002576
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002577 if (StructType *STy = dyn_cast<StructType>(Ty)) {
2578 unsigned OldSize = Indices.size();
2579 (void)OldSize;
2580 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
2581 ++Idx) {
2582 assert(Indices.size() == OldSize && "Did not return to the old size");
2583 Indices.push_back(Idx);
2584 GEPIndices.push_back(IRB.getInt32(Idx));
2585 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
2586 GEPIndices.pop_back();
2587 Indices.pop_back();
2588 }
2589 return;
Chandler Carruthc370acd2012-09-18 12:57:43 +00002590 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002591
2592 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002593 }
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002594 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002595
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002596 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002597 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002598 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruthc370acd2012-09-18 12:57:43 +00002599
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002600 /// Emit a leaf load of a single value. This is called at the leaves of the
2601 /// recursive emission to actually load values.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002602 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002603 assert(Ty->isSingleValueType());
2604 // Load the single value and insert it using the indices.
2605 Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
2606 Name + ".gep"),
2607 Name + ".load");
2608 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
2609 DEBUG(dbgs() << " to: " << *Load << "\n");
2610 }
2611 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002612
2613 bool visitLoadInst(LoadInst &LI) {
2614 assert(LI.getPointerOperand() == *U);
2615 if (!LI.isSimple() || LI.getType()->isSingleValueType())
2616 return false;
2617
2618 // We have an aggregate being loaded, split it apart.
2619 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002620 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruthc370acd2012-09-18 12:57:43 +00002621 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002622 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002623 LI.replaceAllUsesWith(V);
2624 LI.eraseFromParent();
2625 return true;
2626 }
2627
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002628 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002629 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer3b682bd2012-09-18 17:11:47 +00002630 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002631
2632 /// Emit a leaf store of a single value. This is called at the leaves of the
2633 /// recursive emission to actually produce stores.
Benjamin Kramer371d5d82012-09-18 17:06:32 +00002634 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002635 assert(Ty->isSingleValueType());
2636 // Extract the single value and store it using the indices.
2637 Value *Store = IRB.CreateStore(
2638 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
2639 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
2640 (void)Store;
2641 DEBUG(dbgs() << " to: " << *Store << "\n");
2642 }
2643 };
Chandler Carruthc370acd2012-09-18 12:57:43 +00002644
2645 bool visitStoreInst(StoreInst &SI) {
2646 if (!SI.isSimple() || SI.getPointerOperand() != *U)
2647 return false;
2648 Value *V = SI.getValueOperand();
2649 if (V->getType()->isSingleValueType())
2650 return false;
2651
2652 // We have an aggregate being stored, split it apart.
2653 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer6e67b252012-09-18 16:20:46 +00002654 StoreOpSplitter Splitter(&SI, *U);
2655 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruthc370acd2012-09-18 12:57:43 +00002656 SI.eraseFromParent();
2657 return true;
2658 }
2659
2660 bool visitBitCastInst(BitCastInst &BC) {
2661 enqueueUsers(BC);
2662 return false;
2663 }
2664
2665 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
2666 enqueueUsers(GEPI);
2667 return false;
2668 }
2669
2670 bool visitPHINode(PHINode &PN) {
2671 enqueueUsers(PN);
2672 return false;
2673 }
2674
2675 bool visitSelectInst(SelectInst &SI) {
2676 enqueueUsers(SI);
2677 return false;
2678 }
2679};
2680}
2681
Chandler Carruth713aa942012-09-14 09:22:59 +00002682/// \brief Try to find a partition of the aggregate type passed in for a given
2683/// offset and size.
2684///
2685/// This recurses through the aggregate type and tries to compute a subtype
2686/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00002687/// of an array, it will even compute a new array type for that sub-section,
2688/// and the same for structs.
2689///
2690/// Note that this routine is very strict and tries to find a partition of the
2691/// type which produces the *exact* right offset and size. It is not forgiving
2692/// when the size or offset cause either end of type-based partition to be off.
2693/// Also, this is a best-effort routine. It is reasonable to give up and not
2694/// return a type if necessary.
Chandler Carruth713aa942012-09-14 09:22:59 +00002695static Type *getTypePartition(const TargetData &TD, Type *Ty,
2696 uint64_t Offset, uint64_t Size) {
2697 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2698 return Ty;
2699
2700 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2701 // We can't partition pointers...
2702 if (SeqTy->isPointerTy())
2703 return 0;
2704
2705 Type *ElementTy = SeqTy->getElementType();
2706 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2707 uint64_t NumSkippedElements = Offset / ElementSize;
2708 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2709 if (NumSkippedElements >= ArrTy->getNumElements())
2710 return 0;
2711 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2712 if (NumSkippedElements >= VecTy->getNumElements())
2713 return 0;
2714 Offset -= NumSkippedElements * ElementSize;
2715
2716 // First check if we need to recurse.
2717 if (Offset > 0 || Size < ElementSize) {
2718 // Bail if the partition ends in a different array element.
2719 if ((Offset + Size) > ElementSize)
2720 return 0;
2721 // Recurse through the element type trying to peel off offset bytes.
2722 return getTypePartition(TD, ElementTy, Offset, Size);
2723 }
2724 assert(Offset == 0);
2725
2726 if (Size == ElementSize)
2727 return ElementTy;
2728 assert(Size > ElementSize);
2729 uint64_t NumElements = Size / ElementSize;
2730 if (NumElements * ElementSize != Size)
2731 return 0;
2732 return ArrayType::get(ElementTy, NumElements);
2733 }
2734
2735 StructType *STy = dyn_cast<StructType>(Ty);
2736 if (!STy)
2737 return 0;
2738
2739 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002740 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00002741 return 0;
2742 uint64_t EndOffset = Offset + Size;
2743 if (EndOffset > SL->getSizeInBytes())
2744 return 0;
2745
2746 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002747 Offset -= SL->getElementOffset(Index);
2748
2749 Type *ElementTy = STy->getElementType(Index);
2750 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2751 if (Offset >= ElementSize)
2752 return 0; // The offset points into alignment padding.
2753
2754 // See if any partition must be contained by the element.
2755 if (Offset > 0 || Size < ElementSize) {
2756 if ((Offset + Size) > ElementSize)
2757 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002758 return getTypePartition(TD, ElementTy, Offset, Size);
2759 }
2760 assert(Offset == 0);
2761
2762 if (Size == ElementSize)
2763 return ElementTy;
2764
2765 StructType::element_iterator EI = STy->element_begin() + Index,
2766 EE = STy->element_end();
2767 if (EndOffset < SL->getSizeInBytes()) {
2768 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2769 if (Index == EndIndex)
2770 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00002771
2772 // Don't try to form "natural" types if the elements don't line up with the
2773 // expected size.
2774 // FIXME: We could potentially recurse down through the last element in the
2775 // sub-struct to find a natural end point.
2776 if (SL->getElementOffset(EndIndex) != EndOffset)
2777 return 0;
2778
Chandler Carruth713aa942012-09-14 09:22:59 +00002779 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00002780 EE = STy->element_begin() + EndIndex;
2781 }
2782
2783 // Try to build up a sub-structure.
2784 SmallVector<Type *, 4> ElementTys;
2785 do {
2786 ElementTys.push_back(*EI++);
2787 } while (EI != EE);
2788 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2789 STy->isPacked());
2790 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002791 if (Size != SubSL->getSizeInBytes())
2792 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00002793
Chandler Carruth6b547a22012-09-14 11:08:31 +00002794 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00002795}
2796
2797/// \brief Rewrite an alloca partition's users.
2798///
2799/// This routine drives both of the rewriting goals of the SROA pass. It tries
2800/// to rewrite uses of an alloca partition to be conducive for SSA value
2801/// promotion. If the partition needs a new, more refined alloca, this will
2802/// build that new alloca, preserving as much type information as possible, and
2803/// rewrite the uses of the old alloca to point at the new one and have the
2804/// appropriate new offsets. It also evaluates how successful the rewrite was
2805/// at enabling promotion and if it was successful queues the alloca to be
2806/// promoted.
2807bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2808 AllocaPartitioning &P,
2809 AllocaPartitioning::iterator PI) {
2810 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2811 if (P.use_begin(PI) == P.use_end(PI))
2812 return false; // No live uses left of this partition.
2813
2814 // Try to compute a friendly type for this partition of the alloca. This
2815 // won't always succeed, in which case we fall back to a legal integer type
2816 // or an i8 array of an appropriate size.
2817 Type *AllocaTy = 0;
2818 if (Type *PartitionTy = P.getCommonType(PI))
2819 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2820 AllocaTy = PartitionTy;
2821 if (!AllocaTy)
2822 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2823 PI->BeginOffset, AllocaSize))
2824 AllocaTy = PartitionTy;
2825 if ((!AllocaTy ||
2826 (AllocaTy->isArrayTy() &&
2827 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2828 TD->isLegalInteger(AllocaSize * 8))
2829 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2830 if (!AllocaTy)
2831 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00002832 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00002833
2834 // Check for the case where we're going to rewrite to a new alloca of the
2835 // exact same type as the original, and with the same access offsets. In that
2836 // case, re-use the existing alloca, but still run through the rewriter to
2837 // performe phi and select speculation.
2838 AllocaInst *NewAI;
2839 if (AllocaTy == AI.getAllocatedType()) {
2840 assert(PI->BeginOffset == 0 &&
2841 "Non-zero begin offset but same alloca type");
2842 assert(PI == P.begin() && "Begin offset is zero on later partition");
2843 NewAI = &AI;
2844 } else {
2845 // FIXME: The alignment here is overly conservative -- we could in many
2846 // cases get away with much weaker alignment constraints.
2847 NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2848 AI.getName() + ".sroa." + Twine(PI - P.begin()),
2849 &AI);
2850 ++NumNewAllocas;
2851 }
2852
2853 DEBUG(dbgs() << "Rewriting alloca partition "
2854 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2855 << *NewAI << "\n");
2856
2857 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2858 PI->BeginOffset, PI->EndOffset);
2859 DEBUG(dbgs() << " rewriting ");
2860 DEBUG(P.print(dbgs(), PI, ""));
2861 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2862 DEBUG(dbgs() << " and queuing for promotion\n");
2863 PromotableAllocas.push_back(NewAI);
2864 } else if (NewAI != &AI) {
2865 // If we can't promote the alloca, iterate on it to check for new
2866 // refinements exposed by splitting the current alloca. Don't iterate on an
2867 // alloca which didn't actually change and didn't get promoted.
2868 Worklist.insert(NewAI);
2869 }
2870 return true;
2871}
2872
2873/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2874bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2875 bool Changed = false;
2876 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2877 ++PI)
2878 Changed |= rewriteAllocaPartition(AI, P, PI);
2879
2880 return Changed;
2881}
2882
2883/// \brief Analyze an alloca for SROA.
2884///
2885/// This analyzes the alloca to ensure we can reason about it, builds
2886/// a partitioning of the alloca, and then hands it off to be split and
2887/// rewritten as needed.
2888bool SROA::runOnAlloca(AllocaInst &AI) {
2889 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
2890 ++NumAllocasAnalyzed;
2891
2892 // Special case dead allocas, as they're trivial.
2893 if (AI.use_empty()) {
2894 AI.eraseFromParent();
2895 return true;
2896 }
2897
2898 // Skip alloca forms that this analysis can't handle.
2899 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
2900 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
2901 return false;
2902
2903 // First check if this is a non-aggregate type that we should simply promote.
2904 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
2905 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
2906 PromotableAllocas.push_back(&AI);
2907 return false;
2908 }
2909
Chandler Carruthc370acd2012-09-18 12:57:43 +00002910 bool Changed = false;
2911
2912 // First, split any FCA loads and stores touching this alloca to promote
2913 // better splitting and promotion opportunities.
2914 AggLoadStoreRewriter AggRewriter(*TD);
2915 Changed |= AggRewriter.rewrite(AI);
2916
Chandler Carruth713aa942012-09-14 09:22:59 +00002917 // Build the partition set using a recursive instruction-visiting builder.
2918 AllocaPartitioning P(*TD, AI);
2919 DEBUG(P.print(dbgs()));
2920 if (P.isEscaped())
Chandler Carruthc370acd2012-09-18 12:57:43 +00002921 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00002922
2923 // No partitions to split. Leave the dead alloca for a later pass to clean up.
2924 if (P.begin() == P.end())
Chandler Carruthc370acd2012-09-18 12:57:43 +00002925 return Changed;
Chandler Carruth713aa942012-09-14 09:22:59 +00002926
2927 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth713aa942012-09-14 09:22:59 +00002928 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
2929 DE = P.dead_user_end();
2930 DI != DE; ++DI) {
2931 Changed = true;
2932 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
2933 DeadInsts.push_back(*DI);
2934 }
2935 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
2936 DE = P.dead_op_end();
2937 DO != DE; ++DO) {
2938 Value *OldV = **DO;
2939 // Clobber the use with an undef value.
2940 **DO = UndefValue::get(OldV->getType());
2941 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
2942 if (isInstructionTriviallyDead(OldI)) {
2943 Changed = true;
2944 DeadInsts.push_back(OldI);
2945 }
2946 }
2947
2948 return splitAlloca(AI, P) || Changed;
2949}
2950
Chandler Carruth8615cd22012-09-14 10:26:38 +00002951/// \brief Delete the dead instructions accumulated in this run.
2952///
2953/// Recursively deletes the dead instructions we've accumulated. This is done
2954/// at the very end to maximize locality of the recursive delete and to
2955/// minimize the problems of invalidated instruction pointers as such pointers
2956/// are used heavily in the intermediate stages of the algorithm.
2957///
2958/// We also record the alloca instructions deleted here so that they aren't
2959/// subsequently handed to mem2reg to promote.
2960void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002961 DeadSplitInsts.clear();
2962 while (!DeadInsts.empty()) {
2963 Instruction *I = DeadInsts.pop_back_val();
2964 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
2965
2966 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
2967 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
2968 // Zero out the operand and see if it becomes trivially dead.
2969 *OI = 0;
2970 if (isInstructionTriviallyDead(U))
2971 DeadInsts.push_back(U);
2972 }
2973
2974 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2975 DeletedAllocas.insert(AI);
2976
2977 ++NumDeleted;
2978 I->eraseFromParent();
2979 }
2980}
2981
Chandler Carruth1c8db502012-09-15 11:43:14 +00002982/// \brief Promote the allocas, using the best available technique.
2983///
2984/// This attempts to promote whatever allocas have been identified as viable in
2985/// the PromotableAllocas list. If that list is empty, there is nothing to do.
2986/// If there is a domtree available, we attempt to promote using the full power
2987/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
2988/// based on the SSAUpdater utilities. This function returns whether any
2989/// promotion occured.
2990bool SROA::promoteAllocas(Function &F) {
2991 if (PromotableAllocas.empty())
2992 return false;
2993
2994 NumPromoted += PromotableAllocas.size();
2995
2996 if (DT && !ForceSSAUpdater) {
2997 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
2998 PromoteMemToReg(PromotableAllocas, *DT);
2999 PromotableAllocas.clear();
3000 return true;
3001 }
3002
3003 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3004 SSAUpdater SSA;
3005 DIBuilder DIB(*F.getParent());
3006 SmallVector<Instruction*, 64> Insts;
3007
3008 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3009 AllocaInst *AI = PromotableAllocas[Idx];
3010 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3011 UI != UE;) {
3012 Instruction *I = cast<Instruction>(*UI++);
3013 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3014 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3015 // leading to them) here. Eventually it should use them to optimize the
3016 // scalar values produced.
3017 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3018 assert(onlyUsedByLifetimeMarkers(I) &&
3019 "Found a bitcast used outside of a lifetime marker.");
3020 while (!I->use_empty())
3021 cast<Instruction>(*I->use_begin())->eraseFromParent();
3022 I->eraseFromParent();
3023 continue;
3024 }
3025 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3026 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3027 II->getIntrinsicID() == Intrinsic::lifetime_end);
3028 II->eraseFromParent();
3029 continue;
3030 }
3031
3032 Insts.push_back(I);
3033 }
3034 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3035 Insts.clear();
3036 }
3037
3038 PromotableAllocas.clear();
3039 return true;
3040}
3041
Chandler Carruth713aa942012-09-14 09:22:59 +00003042namespace {
3043 /// \brief A predicate to test whether an alloca belongs to a set.
3044 class IsAllocaInSet {
3045 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3046 const SetType &Set;
3047
3048 public:
3049 IsAllocaInSet(const SetType &Set) : Set(Set) {}
3050 bool operator()(AllocaInst *AI) { return Set.count(AI); }
3051 };
3052}
3053
3054bool SROA::runOnFunction(Function &F) {
3055 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3056 C = &F.getContext();
3057 TD = getAnalysisIfAvailable<TargetData>();
3058 if (!TD) {
3059 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3060 return false;
3061 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00003062 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003063
3064 BasicBlock &EntryBB = F.getEntryBlock();
3065 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3066 I != E; ++I)
3067 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3068 Worklist.insert(AI);
3069
3070 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00003071 // A set of deleted alloca instruction pointers which should be removed from
3072 // the list of promotable allocas.
3073 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3074
Chandler Carruth713aa942012-09-14 09:22:59 +00003075 while (!Worklist.empty()) {
3076 Changed |= runOnAlloca(*Worklist.pop_back_val());
Chandler Carruth8615cd22012-09-14 10:26:38 +00003077 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth713aa942012-09-14 09:22:59 +00003078 if (!DeletedAllocas.empty()) {
3079 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3080 PromotableAllocas.end(),
3081 IsAllocaInSet(DeletedAllocas)),
3082 PromotableAllocas.end());
3083 DeletedAllocas.clear();
3084 }
3085 }
3086
Chandler Carruth1c8db502012-09-15 11:43:14 +00003087 Changed |= promoteAllocas(F);
Chandler Carruth713aa942012-09-14 09:22:59 +00003088
3089 return Changed;
3090}
3091
3092void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00003093 if (RequiresDomTree)
3094 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00003095 AU.setPreservesCFG();
3096}