blob: 717c3f449a6960460d06d7d37bfabbd2f8488785 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000034#include "llvm/Analysis/PtrUseVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000036#include "llvm/DIBuilder.h"
37#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
40#include "llvm/IR/DerivedTypes.h"
41#include "llvm/IR/Function.h"
42#include "llvm/IR/IRBuilder.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Operator.h"
Chandler Carruthdbd69582012-11-30 03:08:41 +000047#include "llvm/InstVisitor.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000048#include "llvm/Pass.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000049#include "llvm/Support/CommandLine.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000050#include "llvm/Support/Debug.h"
51#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000052#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000053#include "llvm/Support/raw_ostream.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000054#include "llvm/Transforms/Utils/Local.h"
55#include "llvm/Transforms/Utils/PromoteMemToReg.h"
56#include "llvm/Transforms/Utils/SSAUpdater.h"
57using namespace llvm;
58
59STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000060STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
61STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions");
62STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses found");
63STATISTIC(MaxPartitionUsesPerAlloca, "Maximum number of partition uses");
64STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
65STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000066STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +000067STATISTIC(NumDeleted, "Number of instructions deleted");
68STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +000069
Chandler Carruth70b44c52012-09-15 11:43:14 +000070/// Hidden option to force the pass to not use DomTree and mem2reg, instead
71/// forming SSA values through the SSAUpdater infrastructure.
72static cl::opt<bool>
73ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
74
Chandler Carruth1b398ae2012-09-14 09:22:59 +000075namespace {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +000076/// \brief A custom IRBuilder inserter which prefixes all names if they are
77/// preserved.
78template <bool preserveNames = true>
79class IRBuilderPrefixedInserter :
80 public IRBuilderDefaultInserter<preserveNames> {
81 std::string Prefix;
82
83public:
84 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
85
86protected:
87 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
88 BasicBlock::iterator InsertPt) const {
89 IRBuilderDefaultInserter<preserveNames>::InsertHelper(
90 I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
91 }
92};
93
94// Specialization for not preserving the name is trivial.
95template <>
96class IRBuilderPrefixedInserter<false> :
97 public IRBuilderDefaultInserter<false> {
98public:
99 void SetNamePrefix(const Twine &P) {}
100};
101
Chandler Carruthd177f862013-03-20 07:30:36 +0000102/// \brief Provide a typedef for IRBuilder that drops names in release builds.
103#ifndef NDEBUG
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000104typedef llvm::IRBuilder<true, ConstantFolder,
105 IRBuilderPrefixedInserter<true> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000106#else
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000107typedef llvm::IRBuilder<false, ConstantFolder,
108 IRBuilderPrefixedInserter<false> > IRBuilderTy;
Chandler Carruthd177f862013-03-20 07:30:36 +0000109#endif
110}
111
112namespace {
Chandler Carruthf74654d2013-03-18 08:36:46 +0000113/// \brief A common base class for representing a half-open byte range.
114struct ByteRange {
115 /// \brief The beginning offset of the range.
116 uint64_t BeginOffset;
117
118 /// \brief The ending offset, not included in the range.
119 uint64_t EndOffset;
120
121 ByteRange() : BeginOffset(), EndOffset() {}
122 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
123 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
124
125 /// \brief Support for ordering ranges.
126 ///
127 /// This provides an ordering over ranges such that start offsets are
128 /// always increasing, and within equal start offsets, the end offsets are
129 /// decreasing. Thus the spanning range comes first in a cluster with the
130 /// same start position.
131 bool operator<(const ByteRange &RHS) const {
132 if (BeginOffset < RHS.BeginOffset) return true;
133 if (BeginOffset > RHS.BeginOffset) return false;
134 if (EndOffset > RHS.EndOffset) return true;
135 return false;
136 }
137
138 /// \brief Support comparison with a single offset to allow binary searches.
139 friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
140 return LHS.BeginOffset < RHSOffset;
141 }
142
143 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
144 const ByteRange &RHS) {
145 return LHSOffset < RHS.BeginOffset;
146 }
147
148 bool operator==(const ByteRange &RHS) const {
149 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
150 }
151 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
152};
153
154/// \brief A partition of an alloca.
155///
156/// This structure represents a contiguous partition of the alloca. These are
157/// formed by examining the uses of the alloca. During formation, they may
158/// overlap but once an AllocaPartitioning is built, the Partitions within it
159/// are all disjoint.
160struct Partition : public ByteRange {
161 /// \brief Whether this partition is splittable into smaller partitions.
162 ///
163 /// We flag partitions as splittable when they are formed entirely due to
164 /// accesses by trivially splittable operations such as memset and memcpy.
165 bool IsSplittable;
166
167 /// \brief Test whether a partition has been marked as dead.
168 bool isDead() const {
169 if (BeginOffset == UINT64_MAX) {
170 assert(EndOffset == UINT64_MAX);
171 return true;
172 }
173 return false;
174 }
175
176 /// \brief Kill a partition.
177 /// This is accomplished by setting both its beginning and end offset to
178 /// the maximum possible value.
179 void kill() {
180 assert(!isDead() && "He's Dead, Jim!");
181 BeginOffset = EndOffset = UINT64_MAX;
182 }
183
184 Partition() : ByteRange(), IsSplittable() {}
185 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
186 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
187};
188
189/// \brief A particular use of a partition of the alloca.
190///
191/// This structure is used to associate uses of a partition with it. They
192/// mark the range of bytes which are referenced by a particular instruction,
193/// and includes a handle to the user itself and the pointer value in use.
194/// The bounds of these uses are determined by intersecting the bounds of the
195/// memory use itself with a particular partition. As a consequence there is
196/// intentionally overlap between various uses of the same partition.
197class PartitionUse : public ByteRange {
198 /// \brief Combined storage for both the Use* and split state.
199 PointerIntPair<Use*, 1, bool> UsePtrAndIsSplit;
200
201public:
202 PartitionUse() : ByteRange(), UsePtrAndIsSplit() {}
203 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U,
204 bool IsSplit)
205 : ByteRange(BeginOffset, EndOffset), UsePtrAndIsSplit(U, IsSplit) {}
206
207 /// \brief The use in question. Provides access to both user and used value.
208 ///
209 /// Note that this may be null if the partition use is *dead*, that is, it
210 /// should be ignored.
211 Use *getUse() const { return UsePtrAndIsSplit.getPointer(); }
212
213 /// \brief Set the use for this partition use range.
214 void setUse(Use *U) { UsePtrAndIsSplit.setPointer(U); }
215
216 /// \brief Whether this use is split across multiple partitions.
217 bool isSplit() const { return UsePtrAndIsSplit.getInt(); }
218};
219}
220
221namespace llvm {
222template <> struct isPodLike<Partition> : llvm::true_type {};
223template <> struct isPodLike<PartitionUse> : llvm::true_type {};
224}
225
226namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000227/// \brief Alloca partitioning representation.
228///
229/// This class represents a partitioning of an alloca into slices, and
230/// information about the nature of uses of each slice of the alloca. The goal
231/// is that this information is sufficient to decide if and how to split the
232/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth93a21e72012-09-14 10:18:49 +0000233/// structure can capture the relevant information needed both to decide about
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000234/// and to enact these transformations.
235class AllocaPartitioning {
236public:
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000237 /// \brief Construct a partitioning of a particular alloca.
238 ///
239 /// Construction does most of the work for partitioning the alloca. This
240 /// performs the necessary walks of users and builds a partitioning from it.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000241 AllocaPartitioning(const DataLayout &TD, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000242
243 /// \brief Test whether a pointer to the allocation escapes our analysis.
244 ///
245 /// If this is true, the partitioning is never fully built and should be
246 /// ignored.
247 bool isEscaped() const { return PointerEscapingInstr; }
248
249 /// \brief Support for iterating over the partitions.
250 /// @{
251 typedef SmallVectorImpl<Partition>::iterator iterator;
252 iterator begin() { return Partitions.begin(); }
253 iterator end() { return Partitions.end(); }
254
255 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
256 const_iterator begin() const { return Partitions.begin(); }
257 const_iterator end() const { return Partitions.end(); }
258 /// @}
259
260 /// \brief Support for iterating over and manipulating a particular
261 /// partition's uses.
262 ///
263 /// The iteration support provided for uses is more limited, but also
264 /// includes some manipulation routines to support rewriting the uses of
265 /// partitions during SROA.
266 /// @{
267 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
268 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
269 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
270 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
271 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000272
273 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
274 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
275 const_use_iterator use_begin(const_iterator I) const {
276 return Uses[I - begin()].begin();
277 }
278 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
279 const_use_iterator use_end(const_iterator I) const {
280 return Uses[I - begin()].end();
281 }
Chandler Carruth3903e052012-10-02 17:49:47 +0000282
283 unsigned use_size(unsigned Idx) const { return Uses[Idx].size(); }
284 unsigned use_size(const_iterator I) const { return Uses[I - begin()].size(); }
285 const PartitionUse &getUse(unsigned PIdx, unsigned UIdx) const {
286 return Uses[PIdx][UIdx];
287 }
288 const PartitionUse &getUse(const_iterator I, unsigned UIdx) const {
289 return Uses[I - begin()][UIdx];
290 }
291
292 void use_push_back(unsigned Idx, const PartitionUse &PU) {
293 Uses[Idx].push_back(PU);
294 }
295 void use_push_back(const_iterator I, const PartitionUse &PU) {
296 Uses[I - begin()].push_back(PU);
297 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000298 /// @}
299
300 /// \brief Allow iterating the dead users for this alloca.
301 ///
302 /// These are instructions which will never actually use the alloca as they
303 /// are outside the allocated range. They are safe to replace with undef and
304 /// delete.
305 /// @{
306 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
307 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
308 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
309 /// @}
310
Chandler Carruth93a21e72012-09-14 10:18:49 +0000311 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000312 ///
313 /// These are operands which have cannot actually be used to refer to the
314 /// alloca as they are outside its range and the user doesn't correct for
315 /// that. These mostly consist of PHI node inputs and the like which we just
316 /// need to replace with undef.
317 /// @{
318 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
319 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
320 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
321 /// @}
322
323 /// \brief MemTransferInst auxiliary data.
324 /// This struct provides some auxiliary data about memory transfer
325 /// intrinsics such as memcpy and memmove. These intrinsics can use two
326 /// different ranges within the same alloca, and provide other challenges to
327 /// correctly represent. We stash extra data to help us untangle this
328 /// after the partitioning is complete.
329 struct MemTransferOffsets {
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000330 /// The destination begin and end offsets when the destination is within
331 /// this alloca. If the end offset is zero the destination is not within
332 /// this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000333 uint64_t DestBegin, DestEnd;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000334
335 /// The source begin and end offsets when the source is within this alloca.
336 /// If the end offset is zero, the source is not within this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000337 uint64_t SourceBegin, SourceEnd;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000338
339 /// Flag for whether an alloca is splittable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000340 bool IsSplittable;
341 };
342 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
343 return MemTransferInstData.lookup(&II);
344 }
345
346 /// \brief Map from a PHI or select operand back to a partition.
347 ///
348 /// When manipulating PHI nodes or selects, they can use more than one
349 /// partition of an alloca. We store a special mapping to allow finding the
350 /// partition referenced by each of these operands, if any.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000351 iterator findPartitionForPHIOrSelectOperand(Use *U) {
352 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
353 = PHIOrSelectOpMap.find(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000354 if (MapIt == PHIOrSelectOpMap.end())
355 return end();
356
357 return begin() + MapIt->second.first;
358 }
359
360 /// \brief Map from a PHI or select operand back to the specific use of
361 /// a partition.
362 ///
363 /// Similar to mapping these operands back to the partitions, this maps
364 /// directly to the use structure of that partition.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000365 use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
366 SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
367 = PHIOrSelectOpMap.find(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000368 assert(MapIt != PHIOrSelectOpMap.end());
369 return Uses[MapIt->second.first].begin() + MapIt->second.second;
370 }
371
372 /// \brief Compute a common type among the uses of a particular partition.
373 ///
374 /// This routines walks all of the uses of a particular partition and tries
375 /// to find a common type between them. Untyped operations such as memset and
376 /// memcpy are ignored.
377 Type *getCommonType(iterator I) const;
378
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000379#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000380 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
381 void printUsers(raw_ostream &OS, const_iterator I,
382 StringRef Indent = " ") const;
383 void print(raw_ostream &OS) const;
NAKAMURA Takumi4bbca0b2012-09-14 10:06:10 +0000384 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
385 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000386#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000387
388private:
389 template <typename DerivedT, typename RetT = void> class BuilderBase;
390 class PartitionBuilder;
391 friend class AllocaPartitioning::PartitionBuilder;
392 class UseBuilder;
393 friend class AllocaPartitioning::UseBuilder;
394
Chandler Carruthb7915f72012-11-20 10:23:07 +0000395#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000396 /// \brief Handle to alloca instruction to simplify method interfaces.
397 AllocaInst &AI;
Benjamin Kramer4622cd72012-09-14 13:08:09 +0000398#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000399
400 /// \brief The instruction responsible for this alloca having no partitioning.
401 ///
402 /// When an instruction (potentially) escapes the pointer to the alloca, we
403 /// store a pointer to that here and abort trying to partition the alloca.
404 /// This will be null if the alloca is partitioned successfully.
405 Instruction *PointerEscapingInstr;
406
407 /// \brief The partitions of the alloca.
408 ///
409 /// We store a vector of the partitions over the alloca here. This vector is
410 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth93a21e72012-09-14 10:18:49 +0000411 /// the Partition inner class for more details. Initially (during
412 /// construction) there are overlaps, but we form a disjoint sequence of
413 /// partitions while finishing construction and a fully constructed object is
414 /// expected to always have this as a disjoint space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000415 SmallVector<Partition, 8> Partitions;
416
417 /// \brief The uses of the partitions.
418 ///
419 /// This is essentially a mapping from each partition to a list of uses of
420 /// that partition. The mapping is done with a Uses vector that has the exact
421 /// same number of entries as the partition vector. Each entry is itself
422 /// a vector of the uses.
423 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
424
425 /// \brief Instructions which will become dead if we rewrite the alloca.
426 ///
427 /// Note that these are not separated by partition. This is because we expect
428 /// a partitioned alloca to be completely rewritten or not rewritten at all.
429 /// If rewritten, all these instructions can simply be removed and replaced
430 /// with undef as they come from outside of the allocated space.
431 SmallVector<Instruction *, 8> DeadUsers;
432
433 /// \brief Operands which will become dead if we rewrite the alloca.
434 ///
435 /// These are operands that in their particular use can be replaced with
436 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
437 /// to PHI nodes and the like. They aren't entirely dead (there might be
438 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
439 /// want to swap this particular input for undef to simplify the use lists of
440 /// the alloca.
441 SmallVector<Use *, 8> DeadOperands;
442
443 /// \brief The underlying storage for auxiliary memcpy and memset info.
444 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
445
446 /// \brief A side datastructure used when building up the partitions and uses.
447 ///
448 /// This mapping is only really used during the initial building of the
449 /// partitioning so that we can retain information about PHI and select nodes
450 /// processed.
451 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
452
453 /// \brief Auxiliary information for particular PHI or select operands.
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000454 SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000455
456 /// \brief A utility routine called from the constructor.
457 ///
458 /// This does what it says on the tin. It is the key of the alloca partition
459 /// splitting and merging. After it is called we have the desired disjoint
460 /// collection of partitions.
461 void splitAndMergePartitions();
462};
463}
464
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000465static Value *foldSelectInst(SelectInst &SI) {
466 // If the condition being selected on is a constant or the same value is
467 // being selected between, fold the select. Yes this does (rarely) happen
468 // early on.
469 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
470 return SI.getOperand(1+CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000471 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000472 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000473
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000474 return 0;
475}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000476
477/// \brief Builder for the alloca partitioning.
478///
479/// This class builds an alloca partitioning by recursively visiting the uses
480/// of an alloca and splitting the partitions for each load and store at each
481/// offset.
482class AllocaPartitioning::PartitionBuilder
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000483 : public PtrUseVisitor<PartitionBuilder> {
484 friend class PtrUseVisitor<PartitionBuilder>;
485 friend class InstVisitor<PartitionBuilder>;
486 typedef PtrUseVisitor<PartitionBuilder> Base;
487
488 const uint64_t AllocSize;
489 AllocaPartitioning &P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000490
491 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
492
493public:
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000494 PartitionBuilder(const DataLayout &DL, AllocaInst &AI, AllocaPartitioning &P)
495 : PtrUseVisitor<PartitionBuilder>(DL),
496 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())),
497 P(P) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000498
499private:
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000500 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000501 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000502 // Completely skip uses which have a zero size or start either before or
503 // past the end of the allocation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000504 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000505 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000506 << " which has zero size or starts outside of the "
507 << AllocSize << " byte alloca:\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000508 << " alloca: " << P.AI << "\n"
509 << " use: " << I << "\n");
510 return;
511 }
512
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000513 uint64_t BeginOffset = Offset.getZExtValue();
514 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000515
516 // Clamp the end offset to the end of the allocation. Note that this is
517 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000518 // This may appear superficially to be something we could ignore entirely,
519 // but that is not so! There may be widened loads or PHI-node uses where
520 // some instructions are dead but not others. We can't completely ignore
521 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000522 assert(AllocSize >= BeginOffset); // Established above.
523 if (Size > AllocSize - BeginOffset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000524 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
525 << " to remain within the " << AllocSize << " byte alloca:\n"
526 << " alloca: " << P.AI << "\n"
527 << " use: " << I << "\n");
528 EndOffset = AllocSize;
529 }
530
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000531 Partition New(BeginOffset, EndOffset, IsSplittable);
532 P.Partitions.push_back(New);
533 }
534
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000535 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000536 uint64_t Size, bool IsVolatile) {
Chandler Carruth58d05562012-10-25 04:37:07 +0000537 // We allow splitting of loads and stores where the type is an integer type
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000538 // and cover the entire alloca. This prevents us from splitting over
539 // eagerly.
540 // FIXME: In the great blue eventually, we should eagerly split all integer
541 // loads and stores, and then have a separate step that merges adjacent
542 // alloca partitions into a single partition suitable for integer widening.
543 // Or we should skip the merge step and rely on GVN and other passes to
544 // merge adjacent loads and stores that survive mem2reg.
545 bool IsSplittable =
546 Ty->isIntegerTy() && !IsVolatile && Offset == 0 && Size >= AllocSize;
Chandler Carruth58d05562012-10-25 04:37:07 +0000547
548 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000549 }
550
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000551 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000552 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
553 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000554
555 if (!IsOffsetKnown)
556 return PI.setAborted(&LI);
557
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000558 uint64_t Size = DL.getTypeStoreSize(LI.getType());
559 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000560 }
561
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000562 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000563 Value *ValOp = SI.getValueOperand();
564 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000565 return PI.setEscapedAndAborted(&SI);
566 if (!IsOffsetKnown)
567 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000568
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000569 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
570
571 // If this memory access can be shown to *statically* extend outside the
572 // bounds of of the allocation, it's behavior is undefined, so simply
573 // ignore it. Note that this is more strict than the generic clamping
574 // behavior of insertUse. We also try to handle cases which might run the
575 // risk of overflow.
576 // FIXME: We should instead consider the pointer to have escaped if this
577 // function is being instrumented for addressing bugs or race conditions.
578 if (Offset.isNegative() || Size > AllocSize ||
579 Offset.ugt(AllocSize - Size)) {
580 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
581 << " which extends past the end of the " << AllocSize
582 << " byte alloca:\n"
583 << " alloca: " << P.AI << "\n"
584 << " use: " << SI << "\n");
585 return;
586 }
587
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000588 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
589 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000590 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000591 }
592
593
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000594 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000595 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000596 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000597 if ((Length && Length->getValue() == 0) ||
598 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
599 // Zero-length mem transfer intrinsics can be ignored entirely.
600 return;
601
602 if (!IsOffsetKnown)
603 return PI.setAborted(&II);
604
605 insertUse(II, Offset,
606 Length ? Length->getLimitedValue()
607 : AllocSize - Offset.getLimitedValue(),
608 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000609 }
610
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000611 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000612 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000613 if ((Length && Length->getValue() == 0) ||
614 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000615 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000616 return;
617
618 if (!IsOffsetKnown)
619 return PI.setAborted(&II);
620
621 uint64_t RawOffset = Offset.getLimitedValue();
622 uint64_t Size = Length ? Length->getLimitedValue()
623 : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000624
625 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
626
627 // Only intrinsics with a constant length can be split.
628 Offsets.IsSplittable = Length;
629
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000630 if (*U == II.getRawDest()) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000631 Offsets.DestBegin = RawOffset;
632 Offsets.DestEnd = RawOffset + Size;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000633 }
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000634 if (*U == II.getRawSource()) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000635 Offsets.SourceBegin = RawOffset;
636 Offsets.SourceEnd = RawOffset + Size;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000637 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000638
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000639 // If we have set up end offsets for both the source and the destination,
640 // we have found both sides of this transfer pointing at the same alloca.
641 bool SeenBothEnds = Offsets.SourceEnd && Offsets.DestEnd;
642 if (SeenBothEnds && II.getRawDest() != II.getRawSource()) {
643 unsigned PrevIdx = MemTransferPartitionMap[&II];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000644
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000645 // Check if the begin offsets match and this is a non-volatile transfer.
646 // In that case, we can completely elide the transfer.
647 if (!II.isVolatile() && Offsets.SourceBegin == Offsets.DestBegin) {
648 P.Partitions[PrevIdx].kill();
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000649 return;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000650 }
651
652 // Otherwise we have an offset transfer within the same alloca. We can't
653 // split those.
654 P.Partitions[PrevIdx].IsSplittable = Offsets.IsSplittable = false;
655 } else if (SeenBothEnds) {
656 // Handle the case where this exact use provides both ends of the
657 // operation.
658 assert(II.getRawDest() == II.getRawSource());
659
660 // For non-volatile transfers this is a no-op.
661 if (!II.isVolatile())
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000662 return;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000663
664 // Otherwise just suppress splitting.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000665 Offsets.IsSplittable = false;
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000666 }
667
668
669 // Insert the use now that we've fixed up the splittable nature.
670 insertUse(II, Offset, Size, Offsets.IsSplittable);
671
672 // Setup the mapping from intrinsic to partition of we've not seen both
673 // ends of this transfer.
674 if (!SeenBothEnds) {
675 unsigned NewIdx = P.Partitions.size() - 1;
676 bool Inserted
677 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx)).second;
678 assert(Inserted &&
679 "Already have intrinsic in map but haven't seen both ends");
NAKAMURA Takumi605fe782012-10-05 13:56:23 +0000680 (void)Inserted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000681 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000682 }
683
684 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000685 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000686 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000687 void visitIntrinsicInst(IntrinsicInst &II) {
688 if (!IsOffsetKnown)
689 return PI.setAborted(&II);
690
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000691 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
692 II.getIntrinsicID() == Intrinsic::lifetime_end) {
693 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000694 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
695 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000696 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000697 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000698 }
699
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000700 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000701 }
702
703 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
704 // We consider any PHI or select that results in a direct load or store of
705 // the same offset to be a viable use for partitioning purposes. These uses
706 // are considered unsplittable and the size is the maximum loaded or stored
707 // size.
708 SmallPtrSet<Instruction *, 4> Visited;
709 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
710 Visited.insert(Root);
711 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Chandler Carruth8b907e82012-09-25 10:03:40 +0000712 // If there are no loads or stores, the access is dead. We mark that as
713 // a size zero access.
714 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000715 do {
716 Instruction *I, *UsedI;
717 llvm::tie(UsedI, I) = Uses.pop_back_val();
718
719 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000720 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000721 continue;
722 }
723 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
724 Value *Op = SI->getOperand(0);
725 if (Op == UsedI)
726 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000727 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000728 continue;
729 }
730
731 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
732 if (!GEP->hasAllZeroIndices())
733 return GEP;
734 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
735 !isa<SelectInst>(I)) {
736 return I;
737 }
738
739 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
740 ++UI)
741 if (Visited.insert(cast<Instruction>(*UI)))
742 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
743 } while (!Uses.empty());
744
745 return 0;
746 }
747
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000748 void visitPHINode(PHINode &PN) {
749 if (PN.use_empty())
750 return;
751 if (!IsOffsetKnown)
752 return PI.setAborted(&PN);
753
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000754 // See if we already have computed info on this node.
755 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
756 if (PHIInfo.first) {
757 PHIInfo.second = true;
Chandler Carruth97121172012-09-16 19:39:50 +0000758 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000759 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000760 }
761
762 // Check for an unsafe use of the PHI node.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000763 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
764 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000765
Chandler Carruth97121172012-09-16 19:39:50 +0000766 insertUse(PN, Offset, PHIInfo.first);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000767 }
768
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000769 void visitSelectInst(SelectInst &SI) {
770 if (SI.use_empty())
771 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000772 if (Value *Result = foldSelectInst(SI)) {
773 if (Result == *U)
774 // If the result of the constant fold will be the pointer, recurse
775 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000776 enqueueUsers(SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000777
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000778 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000779 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000780 if (!IsOffsetKnown)
781 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000782
783 // See if we already have computed info on this node.
784 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
785 if (SelectInfo.first) {
786 SelectInfo.second = true;
Chandler Carruth97121172012-09-16 19:39:50 +0000787 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000788 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000789 }
790
791 // Check for an unsafe use of the PHI node.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000792 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
793 return PI.setAborted(UnsafeI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000794
Chandler Carruth97121172012-09-16 19:39:50 +0000795 insertUse(SI, Offset, SelectInfo.first);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000796 }
797
798 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000799 void visitInstruction(Instruction &I) {
800 PI.setAborted(&I);
801 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000802};
803
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000804/// \brief Use adder for the alloca partitioning.
805///
Chandler Carruth93a21e72012-09-14 10:18:49 +0000806/// This class adds the uses of an alloca to all of the partitions which they
807/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000808/// walk of the partitions, but the number of steps remains bounded by the
809/// total result instruction size:
810/// - The number of partitions is a result of the number unsplittable
811/// instructions using the alloca.
812/// - The number of users of each partition is at worst the total number of
813/// splittable instructions using the alloca.
814/// Thus we will produce N * M instructions in the end, where N are the number
815/// of unsplittable uses and M are the number of splittable. This visitor does
816/// the exact same number of updates to the partitioning.
817///
818/// In the more common case, this visitor will leverage the fact that the
819/// partition space is pre-sorted, and do a logarithmic search for the
820/// partition needed, making the total visit a classical ((N + M) * log(N))
821/// complexity operation.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000822class AllocaPartitioning::UseBuilder : public PtrUseVisitor<UseBuilder> {
823 friend class PtrUseVisitor<UseBuilder>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000824 friend class InstVisitor<UseBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000825 typedef PtrUseVisitor<UseBuilder> Base;
826
827 const uint64_t AllocSize;
828 AllocaPartitioning &P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000829
830 /// \brief Set to de-duplicate dead instructions found in the use walk.
831 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
832
833public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000834 UseBuilder(const DataLayout &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000835 : PtrUseVisitor<UseBuilder>(TD),
836 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
837 P(P) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000838
839private:
840 void markAsDead(Instruction &I) {
841 if (VisitedDeadInsts.insert(&I))
842 P.DeadUsers.push_back(&I);
843 }
844
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000845 void insertUse(Instruction &User, const APInt &Offset, uint64_t Size) {
Chandler Carruth8b907e82012-09-25 10:03:40 +0000846 // If the use has a zero size or extends outside of the allocation, record
847 // it as a dead use for elimination later.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000848 if (Size == 0 || Offset.isNegative() || Offset.uge(AllocSize))
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000849 return markAsDead(User);
850
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000851 uint64_t BeginOffset = Offset.getZExtValue();
852 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000853
854 // Clamp the end offset to the end of the allocation. Note that this is
855 // formulated to handle even the case where "BeginOffset + Size" overflows.
856 assert(AllocSize >= BeginOffset); // Established above.
857 if (Size > AllocSize - BeginOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000858 EndOffset = AllocSize;
859
860 // NB: This only works if we have zero overlapping partitions.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000861 iterator I = std::lower_bound(P.begin(), P.end(), BeginOffset);
862 if (I != P.begin() && llvm::prior(I)->EndOffset > BeginOffset)
863 I = llvm::prior(I);
864 iterator E = P.end();
865 bool IsSplit = llvm::next(I) != E && llvm::next(I)->BeginOffset < EndOffset;
866 for (; I != E && I->BeginOffset < EndOffset; ++I) {
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000867 PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000868 std::min(I->EndOffset, EndOffset), U, IsSplit);
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000869 P.use_push_back(I, NewPU);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000870 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
Chandler Carruth54e8f0b2012-10-01 01:49:22 +0000871 P.PHIOrSelectOpMap[U]
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000872 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
873 }
874 }
875
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000876 void visitBitCastInst(BitCastInst &BC) {
877 if (BC.use_empty())
878 return markAsDead(BC);
879
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000880 return Base::visitBitCastInst(BC);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000881 }
882
883 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
884 if (GEPI.use_empty())
885 return markAsDead(GEPI);
886
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000887 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000888 }
889
890 void visitLoadInst(LoadInst &LI) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000891 assert(IsOffsetKnown);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000892 uint64_t Size = DL.getTypeStoreSize(LI.getType());
893 insertUse(LI, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000894 }
895
896 void visitStoreInst(StoreInst &SI) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000897 assert(IsOffsetKnown);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000898 uint64_t Size = DL.getTypeStoreSize(SI.getOperand(0)->getType());
899
900 // If this memory access can be shown to *statically* extend outside the
901 // bounds of of the allocation, it's behavior is undefined, so simply
902 // ignore it. Note that this is more strict than the generic clamping
903 // behavior of insertUse.
904 if (Offset.isNegative() || Size > AllocSize ||
905 Offset.ugt(AllocSize - Size))
906 return markAsDead(SI);
907
908 insertUse(SI, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000909 }
910
911 void visitMemSetInst(MemSetInst &II) {
912 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000913 if ((Length && Length->getValue() == 0) ||
914 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
915 return markAsDead(II);
916
917 assert(IsOffsetKnown);
918 insertUse(II, Offset, Length ? Length->getLimitedValue()
919 : AllocSize - Offset.getLimitedValue());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000920 }
921
922 void visitMemTransferInst(MemTransferInst &II) {
923 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000924 if ((Length && Length->getValue() == 0) ||
925 (IsOffsetKnown && !Offset.isNegative() && Offset.uge(AllocSize)))
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000926 return markAsDead(II);
927
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000928 assert(IsOffsetKnown);
929 uint64_t Size = Length ? Length->getLimitedValue()
930 : AllocSize - Offset.getLimitedValue();
931
Jakub Staszak4f9d1e82013-03-24 09:56:28 +0000932 const MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000933 if (!II.isVolatile() && Offsets.DestEnd && Offsets.SourceEnd &&
934 Offsets.DestBegin == Offsets.SourceBegin)
935 return markAsDead(II); // Skip identity transfers without side-effects.
936
Chandler Carruth97121172012-09-16 19:39:50 +0000937 insertUse(II, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000938 }
939
940 void visitIntrinsicInst(IntrinsicInst &II) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000941 assert(IsOffsetKnown);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000942 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
943 II.getIntrinsicID() == Intrinsic::lifetime_end);
944
945 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000946 insertUse(II, Offset, std::min(Length->getLimitedValue(),
947 AllocSize - Offset.getLimitedValue()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000948 }
949
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000950 void insertPHIOrSelect(Instruction &User, const APInt &Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000951 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
952
953 // For PHI and select operands outside the alloca, we can't nuke the entire
954 // phi or select -- the other side might still be relevant, so we special
955 // case them here and use a separate structure to track the operands
956 // themselves which should be replaced with undef.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000957 if ((Offset.isNegative() && Offset.uge(Size)) ||
958 (!Offset.isNegative() && Offset.uge(AllocSize))) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000959 P.DeadOperands.push_back(U);
960 return;
961 }
962
Chandler Carruth97121172012-09-16 19:39:50 +0000963 insertUse(User, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000964 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000965
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000966 void visitPHINode(PHINode &PN) {
967 if (PN.use_empty())
968 return markAsDead(PN);
969
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000970 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000971 insertPHIOrSelect(PN, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000972 }
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000973
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000974 void visitSelectInst(SelectInst &SI) {
975 if (SI.use_empty())
976 return markAsDead(SI);
977
978 if (Value *Result = foldSelectInst(SI)) {
979 if (Result == *U)
980 // If the result of the constant fold will be the pointer, recurse
981 // through the select as if we had RAUW'ed it.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000982 enqueueUsers(SI);
Chandler Carruth225d4bd2012-09-21 23:36:40 +0000983 else
984 // Otherwise the operand to the select is dead, and we can replace it
985 // with undef.
986 P.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000987
988 return;
989 }
990
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000991 assert(IsOffsetKnown);
Chandler Carruth97121172012-09-16 19:39:50 +0000992 insertPHIOrSelect(SI, Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000993 }
994
995 /// \brief Unreachable, we've already visited the alloca once.
996 void visitInstruction(Instruction &I) {
997 llvm_unreachable("Unhandled instruction in use builder.");
998 }
999};
1000
1001void AllocaPartitioning::splitAndMergePartitions() {
1002 size_t NumDeadPartitions = 0;
1003
1004 // Track the range of splittable partitions that we pass when accumulating
1005 // overlapping unsplittable partitions.
1006 uint64_t SplitEndOffset = 0ull;
1007
1008 Partition New(0ull, 0ull, false);
1009
1010 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
1011 ++j;
1012
1013 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
1014 assert(New.BeginOffset == New.EndOffset);
1015 New = Partitions[i];
1016 } else {
1017 assert(New.IsSplittable);
1018 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
1019 }
1020 assert(New.BeginOffset != New.EndOffset);
1021
1022 // Scan the overlapping partitions.
1023 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
1024 // If the new partition we are forming is splittable, stop at the first
1025 // unsplittable partition.
1026 if (New.IsSplittable && !Partitions[j].IsSplittable)
1027 break;
1028
1029 // Grow the new partition to include any equally splittable range. 'j' is
1030 // always equally splittable when New is splittable, but when New is not
1031 // splittable, we may subsume some (or part of some) splitable partition
1032 // without growing the new one.
1033 if (New.IsSplittable == Partitions[j].IsSplittable) {
1034 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
1035 } else {
1036 assert(!New.IsSplittable);
1037 assert(Partitions[j].IsSplittable);
1038 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
1039 }
1040
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001041 Partitions[j].kill();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001042 ++NumDeadPartitions;
1043 ++j;
1044 }
1045
1046 // If the new partition is splittable, chop off the end as soon as the
1047 // unsplittable subsequent partition starts and ensure we eventually cover
1048 // the splittable area.
1049 if (j != e && New.IsSplittable) {
1050 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
1051 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1052 }
1053
1054 // Add the new partition if it differs from the original one and is
1055 // non-empty. We can end up with an empty partition here if it was
1056 // splittable but there is an unsplittable one that starts at the same
1057 // offset.
1058 if (New != Partitions[i]) {
1059 if (New.BeginOffset != New.EndOffset)
1060 Partitions.push_back(New);
1061 // Mark the old one for removal.
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001062 Partitions[i].kill();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001063 ++NumDeadPartitions;
1064 }
1065
1066 New.BeginOffset = New.EndOffset;
1067 if (!New.IsSplittable) {
1068 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
1069 if (j != e && !Partitions[j].IsSplittable)
1070 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
1071 New.IsSplittable = true;
1072 // If there is a trailing splittable partition which won't be fused into
1073 // the next splittable partition go ahead and add it onto the partitions
1074 // list.
1075 if (New.BeginOffset < New.EndOffset &&
1076 (j == e || !Partitions[j].IsSplittable ||
1077 New.EndOffset < Partitions[j].BeginOffset)) {
1078 Partitions.push_back(New);
1079 New.BeginOffset = New.EndOffset = 0ull;
1080 }
1081 }
1082 }
1083
1084 // Re-sort the partitions now that they have been split and merged into
1085 // disjoint set of partitions. Also remove any of the dead partitions we've
1086 // replaced in the process.
1087 std::sort(Partitions.begin(), Partitions.end());
1088 if (NumDeadPartitions) {
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001089 assert(Partitions.back().isDead());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001090 assert((ptrdiff_t)NumDeadPartitions ==
1091 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
1092 }
1093 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
1094}
1095
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001096AllocaPartitioning::AllocaPartitioning(const DataLayout &TD, AllocaInst &AI)
Benjamin Kramer4622cd72012-09-14 13:08:09 +00001097 :
Chandler Carruthb7915f72012-11-20 10:23:07 +00001098#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Benjamin Kramer4622cd72012-09-14 13:08:09 +00001099 AI(AI),
1100#endif
1101 PointerEscapingInstr(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001102 PartitionBuilder PB(TD, AI, *this);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001103 PartitionBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1104 if (PtrI.isEscaped() || PtrI.isAborted()) {
1105 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1106 // possibly by just storing the PtrInfo in the AllocaPartitioning.
1107 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1108 : PtrI.getAbortingInst();
1109 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001110 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001111 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001112
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001113 // Sort the uses. This arranges for the offsets to be in ascending order,
1114 // and the sizes to be in descending order.
1115 std::sort(Partitions.begin(), Partitions.end());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001116
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001117 // Remove any partitions from the back which are marked as dead.
1118 while (!Partitions.empty() && Partitions.back().isDead())
1119 Partitions.pop_back();
1120
1121 if (Partitions.size() > 1) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001122 // Intersect splittability for all partitions with equal offsets and sizes.
1123 // Then remove all but the first so that we have a sequence of non-equal but
1124 // potentially overlapping partitions.
1125 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1126 I = J) {
1127 ++J;
1128 while (J != E && *I == *J) {
1129 I->IsSplittable &= J->IsSplittable;
1130 ++J;
1131 }
1132 }
1133 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1134 Partitions.end());
1135
1136 // Split splittable and merge unsplittable partitions into a disjoint set
1137 // of partitions over the used space of the allocation.
1138 splitAndMergePartitions();
1139 }
1140
Chandler Carruth5f5b6162013-03-20 06:30:46 +00001141 // Record how many partitions we end up with.
1142 NumAllocaPartitions += Partitions.size();
1143 MaxPartitionsPerAlloca = std::max<unsigned>(Partitions.size(), MaxPartitionsPerAlloca);
1144
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001145 // Now build up the user lists for each of these disjoint partitions by
1146 // re-walking the recursive users of the alloca.
1147 Uses.resize(Partitions.size());
1148 UseBuilder UB(TD, AI, *this);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001149 PtrI = UB.visitPtr(AI);
1150 assert(!PtrI.isEscaped() && "Previously analyzed pointer now escapes!");
1151 assert(!PtrI.isAborted() && "Early aborted the visit of the pointer.");
Chandler Carruth5f5b6162013-03-20 06:30:46 +00001152
1153 unsigned NumUses = 0;
1154#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
1155 for (unsigned Idx = 0, Size = Uses.size(); Idx != Size; ++Idx)
1156 NumUses += Uses[Idx].size();
Chandler Carruth5f5b6162013-03-20 06:30:46 +00001157#endif
Chandler Carruth0941b662013-03-20 06:47:00 +00001158 NumAllocaPartitionUses += NumUses;
Chandler Carruth5f5b6162013-03-20 06:30:46 +00001159 MaxPartitionUsesPerAlloca = std::max<unsigned>(NumUses, MaxPartitionUsesPerAlloca);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001160}
1161
1162Type *AllocaPartitioning::getCommonType(iterator I) const {
1163 Type *Ty = 0;
1164 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001165 Use *U = UI->getUse();
1166 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001167 continue; // Skip dead uses.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001168 if (isa<IntrinsicInst>(*U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001169 continue;
1170 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
Chandler Carruthd356fd02012-09-18 17:49:37 +00001171 continue;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001172
1173 Type *UserTy = 0;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001174 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001175 UserTy = LI->getType();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001176 else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser()))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001177 UserTy = SI->getValueOperand()->getType();
Jakub Staszakfd566112013-03-07 22:20:06 +00001178 else
Chandler Carruth58d05562012-10-25 04:37:07 +00001179 return 0; // Bail if we have weird uses.
Chandler Carruth58d05562012-10-25 04:37:07 +00001180
1181 if (IntegerType *ITy = dyn_cast<IntegerType>(UserTy)) {
1182 // If the type is larger than the partition, skip it. We only encounter
1183 // this for split integer operations where we want to use the type of the
1184 // entity causing the split.
1185 if (ITy->getBitWidth() > (I->EndOffset - I->BeginOffset)*8)
1186 continue;
1187
1188 // If we have found an integer type use covering the alloca, use that
1189 // regardless of the other types, as integers are often used for a "bucket
1190 // of bits" type.
1191 return ITy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001192 }
1193
1194 if (Ty && Ty != UserTy)
1195 return 0;
1196
1197 Ty = UserTy;
1198 }
1199 return Ty;
1200}
1201
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001202#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1203
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001204void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1205 StringRef Indent) const {
1206 OS << Indent << "partition #" << (I - begin())
1207 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1208 << (I->IsSplittable ? " (splittable)" : "")
1209 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1210 << "\n";
1211}
1212
1213void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1214 StringRef Indent) const {
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001215 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001216 if (!UI->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00001217 continue; // Skip dead uses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001218 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001219 << "used by: " << *UI->getUse()->getUser() << "\n";
1220 if (MemTransferInst *II =
1221 dyn_cast<MemTransferInst>(UI->getUse()->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001222 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1223 bool IsDest;
1224 if (!MTO.IsSplittable)
1225 IsDest = UI->BeginOffset == MTO.DestBegin;
1226 else
1227 IsDest = MTO.DestBegin != 0u;
1228 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1229 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1230 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1231 }
1232 }
1233}
1234
1235void AllocaPartitioning::print(raw_ostream &OS) const {
1236 if (PointerEscapingInstr) {
1237 OS << "No partitioning for alloca: " << AI << "\n"
1238 << " A pointer to this alloca escaped by:\n"
1239 << " " << *PointerEscapingInstr << "\n";
1240 return;
1241 }
1242
1243 OS << "Partitioning of alloca: " << AI << "\n";
Jakub Staszakae2fd9c2013-02-19 22:17:58 +00001244 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001245 print(OS, I);
1246 printUsers(OS, I);
1247 }
1248}
1249
1250void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1251void AllocaPartitioning::dump() const { print(dbgs()); }
1252
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001253#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1254
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001255
1256namespace {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001257/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1258///
1259/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1260/// the loads and stores of an alloca instruction, as well as updating its
1261/// debug information. This is used when a domtree is unavailable and thus
1262/// mem2reg in its full form can't be used to handle promotion of allocas to
1263/// scalar values.
1264class AllocaPromoter : public LoadAndStorePromoter {
1265 AllocaInst &AI;
1266 DIBuilder &DIB;
1267
1268 SmallVector<DbgDeclareInst *, 4> DDIs;
1269 SmallVector<DbgValueInst *, 4> DVIs;
1270
1271public:
1272 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1273 AllocaInst &AI, DIBuilder &DIB)
1274 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1275
1276 void run(const SmallVectorImpl<Instruction*> &Insts) {
1277 // Remember which alloca we're promoting (for isInstInList).
1278 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1279 for (Value::use_iterator UI = DebugNode->use_begin(),
1280 UE = DebugNode->use_end();
1281 UI != UE; ++UI)
1282 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1283 DDIs.push_back(DDI);
1284 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1285 DVIs.push_back(DVI);
1286 }
1287
1288 LoadAndStorePromoter::run(Insts);
1289 AI.eraseFromParent();
1290 while (!DDIs.empty())
1291 DDIs.pop_back_val()->eraseFromParent();
1292 while (!DVIs.empty())
1293 DVIs.pop_back_val()->eraseFromParent();
1294 }
1295
1296 virtual bool isInstInList(Instruction *I,
1297 const SmallVectorImpl<Instruction*> &Insts) const {
1298 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1299 return LI->getOperand(0) == &AI;
1300 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1301 }
1302
1303 virtual void updateDebugInfo(Instruction *Inst) const {
Craig Topper31ee5862013-07-03 15:07:05 +00001304 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +00001305 E = DDIs.end(); I != E; ++I) {
1306 DbgDeclareInst *DDI = *I;
1307 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1308 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1309 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1310 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1311 }
Craig Topper31ee5862013-07-03 15:07:05 +00001312 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Chandler Carruth70b44c52012-09-15 11:43:14 +00001313 E = DVIs.end(); I != E; ++I) {
1314 DbgValueInst *DVI = *I;
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001315 Value *Arg = 0;
Chandler Carruth70b44c52012-09-15 11:43:14 +00001316 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1317 // If an argument is zero extended then use argument directly. The ZExt
1318 // may be zapped by an optimization pass in future.
1319 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1320 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001321 else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Chandler Carruth70b44c52012-09-15 11:43:14 +00001322 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1323 if (!Arg)
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001324 Arg = SI->getValueOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +00001325 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00001326 Arg = LI->getPointerOperand();
Chandler Carruth70b44c52012-09-15 11:43:14 +00001327 } else {
1328 continue;
1329 }
1330 Instruction *DbgVal =
1331 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1332 Inst);
1333 DbgVal->setDebugLoc(DVI->getDebugLoc());
1334 }
1335 }
1336};
1337} // end anon namespace
1338
1339
1340namespace {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001341/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1342///
1343/// This pass takes allocations which can be completely analyzed (that is, they
1344/// don't escape) and tries to turn them into scalar SSA values. There are
1345/// a few steps to this process.
1346///
1347/// 1) It takes allocations of aggregates and analyzes the ways in which they
1348/// are used to try to split them into smaller allocations, ideally of
1349/// a single scalar data type. It will split up memcpy and memset accesses
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001350/// as necessary and try to isolate individual scalar accesses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001351/// 2) It will transform accesses into forms which are suitable for SSA value
1352/// promotion. This can be replacing a memset with a scalar store of an
1353/// integer value, or it can involve speculating operations on a PHI or
1354/// select to be a PHI or select of the results.
1355/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1356/// onto insert and extract operations on a vector value, and convert them to
1357/// this form. By doing so, it will enable promotion of vector aggregates to
1358/// SSA vector values.
1359class SROA : public FunctionPass {
Chandler Carruth70b44c52012-09-15 11:43:14 +00001360 const bool RequiresDomTree;
1361
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001362 LLVMContext *C;
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001363 const DataLayout *TD;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001364 DominatorTree *DT;
1365
1366 /// \brief Worklist of alloca instructions to simplify.
1367 ///
1368 /// Each alloca in the function is added to this. Each new alloca formed gets
1369 /// added to it as well to recursively simplify unless that alloca can be
1370 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1371 /// the one being actively rewritten, we add it back onto the list if not
1372 /// already present to ensure it is re-visited.
1373 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1374
1375 /// \brief A collection of instructions to delete.
1376 /// We try to batch deletions to simplify code and make things a bit more
1377 /// efficient.
Chandler Carruth18db7952012-11-20 01:12:50 +00001378 SetVector<Instruction *, SmallVector<Instruction *, 8> > DeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001379
Chandler Carruthac8317f2012-10-04 12:33:50 +00001380 /// \brief Post-promotion worklist.
1381 ///
1382 /// Sometimes we discover an alloca which has a high probability of becoming
1383 /// viable for SROA after a round of promotion takes place. In those cases,
1384 /// the alloca is enqueued here for re-processing.
1385 ///
1386 /// Note that we have to be very careful to clear allocas out of this list in
1387 /// the event they are deleted.
1388 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > PostPromotionWorklist;
1389
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001390 /// \brief A collection of alloca instructions we can directly promote.
1391 std::vector<AllocaInst *> PromotableAllocas;
1392
1393public:
Chandler Carruth70b44c52012-09-15 11:43:14 +00001394 SROA(bool RequiresDomTree = true)
1395 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1396 C(0), TD(0), DT(0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001397 initializeSROAPass(*PassRegistry::getPassRegistry());
1398 }
1399 bool runOnFunction(Function &F);
1400 void getAnalysisUsage(AnalysisUsage &AU) const;
1401
1402 const char *getPassName() const { return "SROA"; }
1403 static char ID;
1404
1405private:
Chandler Carruth82a57542012-10-01 10:54:05 +00001406 friend class PHIOrSelectSpeculator;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001407 friend class AllocaPartitionRewriter;
1408 friend class AllocaPartitionVectorRewriter;
1409
1410 bool rewriteAllocaPartition(AllocaInst &AI,
1411 AllocaPartitioning &P,
1412 AllocaPartitioning::iterator PI);
1413 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1414 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth19450da2012-09-14 10:26:38 +00001415 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth70b44c52012-09-15 11:43:14 +00001416 bool promoteAllocas(Function &F);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001417};
1418}
1419
1420char SROA::ID = 0;
1421
Chandler Carruth70b44c52012-09-15 11:43:14 +00001422FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1423 return new SROA(RequiresDomTree);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001424}
1425
1426INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1427 false, false)
1428INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1429INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1430 false, false)
1431
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001432namespace {
1433/// \brief Visitor to speculate PHIs and Selects where possible.
1434class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
1435 // Befriend the base class so it can delegate to private visit methods.
1436 friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
1437
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001438 const DataLayout &TD;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001439 AllocaPartitioning &P;
1440 SROA &Pass;
1441
1442public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001443 PHIOrSelectSpeculator(const DataLayout &TD, AllocaPartitioning &P, SROA &Pass)
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001444 : TD(TD), P(P), Pass(Pass) {}
1445
1446 /// \brief Visit the users of an alloca partition and rewrite them.
1447 void visitUsers(AllocaPartitioning::const_iterator PI) {
1448 // Note that we need to use an index here as the underlying vector of uses
1449 // may be grown during speculation. However, we never need to re-visit the
1450 // new uses, and so we can use the initial size bound.
1451 for (unsigned Idx = 0, Size = P.use_size(PI); Idx != Size; ++Idx) {
Chandler Carruthf74654d2013-03-18 08:36:46 +00001452 const PartitionUse &PU = P.getUse(PI, Idx);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001453 if (!PU.getUse())
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001454 continue; // Skip dead use.
1455
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001456 visit(cast<Instruction>(PU.getUse()->getUser()));
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001457 }
1458 }
1459
1460private:
1461 // By default, skip this instruction.
1462 void visitInstruction(Instruction &I) {}
1463
1464 /// PHI instructions that use an alloca and are subsequently loaded can be
1465 /// rewritten to load both input pointers in the pred blocks and then PHI the
1466 /// results, allowing the load of the alloca to be promoted.
1467 /// From this:
1468 /// %P2 = phi [i32* %Alloca, i32* %Other]
1469 /// %V = load i32* %P2
1470 /// to:
1471 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1472 /// ...
1473 /// %V2 = load i32* %Other
1474 /// ...
1475 /// %V = phi [i32 %V1, i32 %V2]
1476 ///
1477 /// We can do this to a select if its only uses are loads and if the operands
1478 /// to the select can be loaded unconditionally.
1479 ///
1480 /// FIXME: This should be hoisted into a generic utility, likely in
1481 /// Transforms/Util/Local.h
1482 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
1483 // For now, we can only do this promotion if the load is in the same block
1484 // as the PHI, and if there are no stores between the phi and load.
1485 // TODO: Allow recursive phi users.
1486 // TODO: Allow stores.
1487 BasicBlock *BB = PN.getParent();
1488 unsigned MaxAlign = 0;
1489 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
1490 UI != UE; ++UI) {
1491 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1492 if (LI == 0 || !LI->isSimple()) return false;
1493
1494 // For now we only allow loads in the same block as the PHI. This is
1495 // a common case that happens when instcombine merges two loads through
1496 // a PHI.
1497 if (LI->getParent() != BB) return false;
1498
1499 // Ensure that there are no instructions between the PHI and the load that
1500 // could store.
1501 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
1502 if (BBI->mayWriteToMemory())
1503 return false;
1504
1505 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1506 Loads.push_back(LI);
1507 }
1508
1509 // We can only transform this if it is safe to push the loads into the
1510 // predecessor blocks. The only thing to watch out for is that we can't put
1511 // a possibly trapping load in the predecessor if it is a critical edge.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00001512 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001513 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1514 Value *InVal = PN.getIncomingValue(Idx);
1515
1516 // If the value is produced by the terminator of the predecessor (an
1517 // invoke) or it has side-effects, there is no valid place to put a load
1518 // in the predecessor.
1519 if (TI == InVal || TI->mayHaveSideEffects())
1520 return false;
1521
1522 // If the predecessor has a single successor, then the edge isn't
1523 // critical.
1524 if (TI->getNumSuccessors() == 1)
1525 continue;
1526
1527 // If this pointer is always safe to load, or if we can prove that there
1528 // is already a load in the block, then we can move the load to the pred
1529 // block.
1530 if (InVal->isDereferenceablePointer() ||
1531 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
1532 continue;
1533
1534 return false;
1535 }
1536
1537 return true;
1538 }
1539
1540 void visitPHINode(PHINode &PN) {
1541 DEBUG(dbgs() << " original: " << PN << "\n");
1542
1543 SmallVector<LoadInst *, 4> Loads;
1544 if (!isSafePHIToSpeculate(PN, Loads))
1545 return;
1546
1547 assert(!Loads.empty());
1548
1549 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
Chandler Carruthd177f862013-03-20 07:30:36 +00001550 IRBuilderTy PHIBuilder(&PN);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001551 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1552 PN.getName() + ".sroa.speculated");
1553
1554 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001555 // matter which one we get and if any differ.
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001556 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
1557 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
1558 unsigned Align = SomeLoad->getAlignment();
1559
1560 // Rewrite all loads of the PN to use the new PHI.
1561 do {
1562 LoadInst *LI = Loads.pop_back_val();
1563 LI->replaceAllUsesWith(NewPN);
Chandler Carruth18db7952012-11-20 01:12:50 +00001564 Pass.DeadInsts.insert(LI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001565 } while (!Loads.empty());
1566
1567 // Inject loads into all of the pred blocks.
1568 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1569 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1570 TerminatorInst *TI = Pred->getTerminator();
1571 Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
1572 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthd177f862013-03-20 07:30:36 +00001573 IRBuilderTy PredBuilder(TI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001574
1575 LoadInst *Load
1576 = PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
1577 Pred->getName()));
1578 ++NumLoadsSpeculated;
1579 Load->setAlignment(Align);
1580 if (TBAATag)
1581 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
1582 NewPN->addIncoming(Load, Pred);
1583
1584 Instruction *Ptr = dyn_cast<Instruction>(InVal);
1585 if (!Ptr)
1586 // No uses to rewrite.
1587 continue;
1588
1589 // Try to lookup and rewrite any partition uses corresponding to this phi
1590 // input.
1591 AllocaPartitioning::iterator PI
1592 = P.findPartitionForPHIOrSelectOperand(InUse);
1593 if (PI == P.end())
1594 continue;
1595
1596 // Replace the Use in the PartitionUse for this operand with the Use
1597 // inside the load.
1598 AllocaPartitioning::use_iterator UI
1599 = P.findPartitionUseForPHIOrSelectOperand(InUse);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001600 assert(isa<PHINode>(*UI->getUse()->getUser()));
1601 UI->setUse(&Load->getOperandUse(Load->getPointerOperandIndex()));
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001602 }
1603 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
1604 }
1605
1606 /// Select instructions that use an alloca and are subsequently loaded can be
1607 /// rewritten to load both input pointers and then select between the result,
1608 /// allowing the load of the alloca to be promoted.
1609 /// From this:
1610 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1611 /// %V = load i32* %P2
1612 /// to:
1613 /// %V1 = load i32* %Alloca -> will be mem2reg'd
1614 /// %V2 = load i32* %Other
1615 /// %V = select i1 %cond, i32 %V1, i32 %V2
1616 ///
1617 /// We can do this to a select if its only uses are loads and if the operand
1618 /// to the select can be loaded unconditionally.
1619 bool isSafeSelectToSpeculate(SelectInst &SI,
1620 SmallVectorImpl<LoadInst *> &Loads) {
1621 Value *TValue = SI.getTrueValue();
1622 Value *FValue = SI.getFalseValue();
1623 bool TDerefable = TValue->isDereferenceablePointer();
1624 bool FDerefable = FValue->isDereferenceablePointer();
1625
1626 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
1627 UI != UE; ++UI) {
1628 LoadInst *LI = dyn_cast<LoadInst>(*UI);
1629 if (LI == 0 || !LI->isSimple()) return false;
1630
1631 // Both operands to the select need to be dereferencable, either
1632 // absolutely (e.g. allocas) or at this point because we can see other
1633 // accesses to it.
1634 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
1635 LI->getAlignment(), &TD))
1636 return false;
1637 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
1638 LI->getAlignment(), &TD))
1639 return false;
1640 Loads.push_back(LI);
1641 }
1642
1643 return true;
1644 }
1645
1646 void visitSelectInst(SelectInst &SI) {
1647 DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001648
1649 // If the select isn't safe to speculate, just use simple logic to emit it.
1650 SmallVector<LoadInst *, 4> Loads;
1651 if (!isSafeSelectToSpeculate(SI, Loads))
1652 return;
1653
Chandler Carruthd177f862013-03-20 07:30:36 +00001654 IRBuilderTy IRB(&SI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001655 Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
1656 AllocaPartitioning::iterator PIs[2];
Chandler Carruthf74654d2013-03-18 08:36:46 +00001657 PartitionUse PUs[2];
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001658 for (unsigned i = 0, e = 2; i != e; ++i) {
1659 PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
1660 if (PIs[i] != P.end()) {
1661 // If the pointer is within the partitioning, remove the select from
1662 // its uses. We'll add in the new loads below.
1663 AllocaPartitioning::use_iterator UI
1664 = P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
1665 PUs[i] = *UI;
1666 // Clear out the use here so that the offsets into the use list remain
1667 // stable but this use is ignored when rewriting.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001668 UI->setUse(0);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001669 }
1670 }
1671
1672 Value *TV = SI.getTrueValue();
1673 Value *FV = SI.getFalseValue();
1674 // Replace the loads of the select with a select of two loads.
1675 while (!Loads.empty()) {
1676 LoadInst *LI = Loads.pop_back_val();
1677
1678 IRB.SetInsertPoint(LI);
1679 LoadInst *TL =
1680 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1681 LoadInst *FL =
1682 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1683 NumLoadsSpeculated += 2;
1684
1685 // Transfer alignment and TBAA info if present.
1686 TL->setAlignment(LI->getAlignment());
1687 FL->setAlignment(LI->getAlignment());
1688 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
1689 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
1690 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
1691 }
1692
1693 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1694 LI->getName() + ".sroa.speculated");
1695
1696 LoadInst *Loads[2] = { TL, FL };
1697 for (unsigned i = 0, e = 2; i != e; ++i) {
1698 if (PIs[i] != P.end()) {
1699 Use *LoadUse = &Loads[i]->getOperandUse(0);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001700 assert(PUs[i].getUse()->get() == LoadUse->get());
1701 PUs[i].setUse(LoadUse);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001702 P.use_push_back(PIs[i], PUs[i]);
1703 }
1704 }
1705
1706 DEBUG(dbgs() << " speculated to: " << *V << "\n");
1707 LI->replaceAllUsesWith(V);
Chandler Carruth18db7952012-11-20 01:12:50 +00001708 Pass.DeadInsts.insert(LI);
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001709 }
1710 }
1711};
1712}
1713
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001714/// \brief Build a GEP out of a base pointer and indices.
1715///
1716/// This will return the BasePtr if that is valid, or build a new GEP
1717/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001718static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001719 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001720 if (Indices.empty())
1721 return BasePtr;
1722
1723 // A single zero index is a no-op, so check for this and avoid building a GEP
1724 // in that case.
1725 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1726 return BasePtr;
1727
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001728 return IRB.CreateInBoundsGEP(BasePtr, Indices, "idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001729}
1730
1731/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1732/// TargetTy without changing the offset of the pointer.
1733///
1734/// This routine assumes we've already established a properly offset GEP with
1735/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1736/// zero-indices down through type layers until we find one the same as
1737/// TargetTy. If we can't find one with the same type, we at least try to use
1738/// one with the same size. If none of that works, we just produce the GEP as
1739/// indicated by Indices to have the correct offset.
Chandler Carruthd177f862013-03-20 07:30:36 +00001740static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001741 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001742 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001743 if (Ty == TargetTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001744 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001745
1746 // See if we can descend into a struct and locate a field with the correct
1747 // type.
1748 unsigned NumLayers = 0;
1749 Type *ElementTy = Ty;
1750 do {
1751 if (ElementTy->isPointerTy())
1752 break;
1753 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1754 ElementTy = SeqTy->getElementType();
Chandler Carruth40617f52012-10-17 07:22:16 +00001755 // Note that we use the default address space as this index is over an
1756 // array or a vector, not a pointer.
1757 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(0), 0)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001758 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001759 if (STy->element_begin() == STy->element_end())
1760 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001761 ElementTy = *STy->element_begin();
1762 Indices.push_back(IRB.getInt32(0));
1763 } else {
1764 break;
1765 }
1766 ++NumLayers;
1767 } while (ElementTy != TargetTy);
1768 if (ElementTy != TargetTy)
1769 Indices.erase(Indices.end() - NumLayers, Indices.end());
1770
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001771 return buildGEP(IRB, BasePtr, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001772}
1773
1774/// \brief Recursively compute indices for a natural GEP.
1775///
1776/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1777/// element types adding appropriate indices for the GEP.
Chandler Carruthd177f862013-03-20 07:30:36 +00001778static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001779 Value *Ptr, Type *Ty, APInt &Offset,
1780 Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001781 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001782 if (Offset == 0)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001783 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001784
1785 // We can't recurse through pointer types.
1786 if (Ty->isPointerTy())
1787 return 0;
1788
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001789 // We try to analyze GEPs over vectors here, but note that these GEPs are
1790 // extremely poorly defined currently. The long-term goal is to remove GEPing
1791 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001792 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Nadav Rotema5024fc2012-12-18 05:23:31 +00001793 unsigned ElementSizeInBits = TD.getTypeSizeInBits(VecTy->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001794 if (ElementSizeInBits % 8)
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001795 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001796 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001797 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001798 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1799 return 0;
1800 Offset -= NumSkippedElements * ElementSize;
1801 Indices.push_back(IRB.getInt(NumSkippedElements));
1802 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001803 Offset, TargetTy, Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001804 }
1805
1806 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1807 Type *ElementTy = ArrTy->getElementType();
1808 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001809 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001810 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1811 return 0;
1812
1813 Offset -= NumSkippedElements * ElementSize;
1814 Indices.push_back(IRB.getInt(NumSkippedElements));
1815 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001816 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001817 }
1818
1819 StructType *STy = dyn_cast<StructType>(Ty);
1820 if (!STy)
1821 return 0;
1822
1823 const StructLayout *SL = TD.getStructLayout(STy);
1824 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001825 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001826 return 0;
1827 unsigned Index = SL->getElementContainingOffset(StructOffset);
1828 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1829 Type *ElementTy = STy->getElementType(Index);
1830 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1831 return 0; // The offset points into alignment padding.
1832
1833 Indices.push_back(IRB.getInt32(Index));
1834 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001835 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001836}
1837
1838/// \brief Get a natural GEP from a base pointer to a particular offset and
1839/// resulting in a particular type.
1840///
1841/// The goal is to produce a "natural" looking GEP that works with the existing
1842/// composite types to arrive at the appropriate offset and element type for
1843/// a pointer. TargetTy is the element type the returned GEP should point-to if
1844/// possible. We recurse by decreasing Offset, adding the appropriate index to
1845/// Indices, and setting Ty to the result subtype.
1846///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001847/// If no natural GEP can be constructed, this function returns null.
Chandler Carruthd177f862013-03-20 07:30:36 +00001848static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001849 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001850 SmallVectorImpl<Value *> &Indices) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001851 PointerType *Ty = cast<PointerType>(Ptr->getType());
1852
1853 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1854 // an i8.
1855 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1856 return 0;
1857
1858 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001859 if (!ElementTy->isSized())
1860 return 0; // We can't GEP through an unsized element.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001861 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1862 if (ElementSize == 0)
1863 return 0; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001864 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001865
1866 Offset -= NumSkippedElements * ElementSize;
1867 Indices.push_back(IRB.getInt(NumSkippedElements));
1868 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001869 Indices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001870}
1871
1872/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1873/// resulting pointer has PointerTy.
1874///
1875/// This tries very hard to compute a "natural" GEP which arrives at the offset
1876/// and produces the pointer type desired. Where it cannot, it will try to use
1877/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1878/// fails, it will try to use an existing i8* and GEP to the byte offset and
1879/// bitcast to the type.
1880///
1881/// The strategy for finding the more natural GEPs is to peel off layers of the
1882/// pointer, walking back through bit casts and GEPs, searching for a base
1883/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001884/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001885/// a single GEP as possible, thus making each GEP more independent of the
1886/// surrounding code.
Chandler Carruthd177f862013-03-20 07:30:36 +00001887static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &TD,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001888 Value *Ptr, APInt Offset, Type *PointerTy) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001889 // Even though we don't look through PHI nodes, we could be called on an
1890 // instruction in an unreachable block, which may be on a cycle.
1891 SmallPtrSet<Value *, 4> Visited;
1892 Visited.insert(Ptr);
1893 SmallVector<Value *, 4> Indices;
1894
1895 // We may end up computing an offset pointer that has the wrong type. If we
1896 // never are able to compute one directly that has the correct type, we'll
1897 // fall back to it, so keep it around here.
1898 Value *OffsetPtr = 0;
1899
1900 // Remember any i8 pointer we come across to re-use if we need to do a raw
1901 // byte offset.
1902 Value *Int8Ptr = 0;
1903 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1904
1905 Type *TargetTy = PointerTy->getPointerElementType();
1906
1907 do {
1908 // First fold any existing GEPs into the offset.
1909 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1910 APInt GEPOffset(Offset.getBitWidth(), 0);
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001911 if (!GEP->accumulateConstantOffset(TD, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001912 break;
1913 Offset += GEPOffset;
1914 Ptr = GEP->getPointerOperand();
1915 if (!Visited.insert(Ptr))
1916 break;
1917 }
1918
1919 // See if we can perform a natural GEP here.
1920 Indices.clear();
1921 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001922 Indices)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001923 if (P->getType() == PointerTy) {
1924 // Zap any offset pointer that we ended up computing in previous rounds.
1925 if (OffsetPtr && OffsetPtr->use_empty())
1926 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1927 I->eraseFromParent();
1928 return P;
1929 }
1930 if (!OffsetPtr) {
1931 OffsetPtr = P;
1932 }
1933 }
1934
1935 // Stash this pointer if we've found an i8*.
1936 if (Ptr->getType()->isIntegerTy(8)) {
1937 Int8Ptr = Ptr;
1938 Int8PtrOffset = Offset;
1939 }
1940
1941 // Peel off a layer of the pointer and update the offset appropriately.
1942 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1943 Ptr = cast<Operator>(Ptr)->getOperand(0);
1944 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1945 if (GA->mayBeOverridden())
1946 break;
1947 Ptr = GA->getAliasee();
1948 } else {
1949 break;
1950 }
1951 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1952 } while (Visited.insert(Ptr));
1953
1954 if (!OffsetPtr) {
1955 if (!Int8Ptr) {
1956 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001957 "raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001958 Int8PtrOffset = Offset;
1959 }
1960
1961 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1962 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001963 "raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001964 }
1965 Ptr = OffsetPtr;
1966
1967 // On the off chance we were targeting i8*, guard the bitcast here.
1968 if (Ptr->getType() != PointerTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00001969 Ptr = IRB.CreateBitCast(Ptr, PointerTy, "cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001970
1971 return Ptr;
1972}
1973
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001974/// \brief Test whether we can convert a value from the old to the new type.
1975///
1976/// This predicate should be used to guard calls to convertValue in order to
1977/// ensure that we only try to convert viable values. The strategy is that we
1978/// will peel off single element struct and array wrappings to get to an
1979/// underlying value, and convert that value.
1980static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1981 if (OldTy == NewTy)
1982 return true;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00001983 if (IntegerType *OldITy = dyn_cast<IntegerType>(OldTy))
1984 if (IntegerType *NewITy = dyn_cast<IntegerType>(NewTy))
1985 if (NewITy->getBitWidth() >= OldITy->getBitWidth())
1986 return true;
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001987 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1988 return false;
1989 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1990 return false;
1991
1992 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1993 if (NewTy->isPointerTy() && OldTy->isPointerTy())
1994 return true;
1995 if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
1996 return true;
1997 return false;
1998 }
1999
2000 return true;
2001}
2002
2003/// \brief Generic routine to convert an SSA value to a value of a different
2004/// type.
2005///
2006/// This will try various different casting techniques, such as bitcasts,
2007/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
2008/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00002009static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00002010 Type *Ty) {
2011 assert(canConvertValue(DL, V->getType(), Ty) &&
2012 "Value not convertable to type");
2013 if (V->getType() == Ty)
2014 return V;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002015 if (IntegerType *OldITy = dyn_cast<IntegerType>(V->getType()))
2016 if (IntegerType *NewITy = dyn_cast<IntegerType>(Ty))
2017 if (NewITy->getBitWidth() > OldITy->getBitWidth())
2018 return IRB.CreateZExt(V, NewITy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00002019 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
2020 return IRB.CreateIntToPtr(V, Ty);
2021 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
2022 return IRB.CreatePtrToInt(V, Ty);
2023
2024 return IRB.CreateBitCast(V, Ty);
2025}
2026
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002027/// \brief Test whether the given alloca partition can be promoted to a vector.
2028///
2029/// This is a quick test to check whether we can rewrite a particular alloca
2030/// partition (and its newly formed alloca) into a vector alloca with only
2031/// whole-vector loads and stores such that it could be promoted to a vector
2032/// SSA value. We only can ensure this for a limited set of operations, and we
2033/// don't want to do the rewrites unless we are confident that the result will
2034/// be promotable, so we have an early test here.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002035static bool isVectorPromotionViable(const DataLayout &TD,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002036 Type *AllocaTy,
2037 AllocaPartitioning &P,
2038 uint64_t PartitionBeginOffset,
2039 uint64_t PartitionEndOffset,
2040 AllocaPartitioning::const_use_iterator I,
2041 AllocaPartitioning::const_use_iterator E) {
2042 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
2043 if (!Ty)
2044 return false;
2045
Nadav Rotema5024fc2012-12-18 05:23:31 +00002046 uint64_t ElementSize = TD.getTypeSizeInBits(Ty->getScalarType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002047
2048 // While the definition of LLVM vectors is bitpacked, we don't support sizes
2049 // that aren't byte sized.
2050 if (ElementSize % 8)
2051 return false;
Benjamin Kramerc003a452013-01-01 16:13:35 +00002052 assert((TD.getTypeSizeInBits(Ty) % 8) == 0 &&
2053 "vector size not a multiple of element size?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002054 ElementSize /= 8;
2055
2056 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002057 Use *U = I->getUse();
2058 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002059 continue; // Skip dead use.
2060
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002061 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
2062 uint64_t BeginIndex = BeginOffset / ElementSize;
2063 if (BeginIndex * ElementSize != BeginOffset ||
2064 BeginIndex >= Ty->getNumElements())
2065 return false;
2066 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
2067 uint64_t EndIndex = EndOffset / ElementSize;
2068 if (EndIndex * ElementSize != EndOffset ||
2069 EndIndex > Ty->getNumElements())
2070 return false;
2071
Chandler Carruth845b73c2012-11-21 08:16:30 +00002072 assert(EndIndex > BeginIndex && "Empty vector!");
2073 uint64_t NumElements = EndIndex - BeginIndex;
2074 Type *PartitionTy
2075 = (NumElements == 1) ? Ty->getElementType()
2076 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002077
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002078 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002079 if (MI->isVolatile())
2080 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002081 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U->getUser())) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002082 const AllocaPartitioning::MemTransferOffsets &MTO
2083 = P.getMemTransferOffsets(*MTI);
2084 if (!MTO.IsSplittable)
2085 return false;
2086 }
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002087 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002088 // Disable vector promotion when there are loads or stores of an FCA.
2089 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002090 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002091 if (LI->isVolatile())
2092 return false;
Chandler Carruth845b73c2012-11-21 08:16:30 +00002093 if (!canConvertValue(TD, PartitionTy, LI->getType()))
2094 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002095 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002096 if (SI->isVolatile())
2097 return false;
Chandler Carruth845b73c2012-11-21 08:16:30 +00002098 if (!canConvertValue(TD, SI->getValueOperand()->getType(), PartitionTy))
2099 return false;
Chandler Carruth18db7952012-11-20 01:12:50 +00002100 } else {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002101 return false;
2102 }
2103 }
2104 return true;
2105}
2106
Chandler Carruth435c4e02012-10-15 08:40:30 +00002107/// \brief Test whether the given alloca partition's integer operations can be
2108/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002109///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002110/// This is a quick test to check whether we can rewrite the integer loads and
2111/// stores to a particular alloca into wider loads and stores and be able to
2112/// promote the resulting alloca.
2113static bool isIntegerWideningViable(const DataLayout &TD,
2114 Type *AllocaTy,
2115 uint64_t AllocBeginOffset,
2116 AllocaPartitioning &P,
2117 AllocaPartitioning::const_use_iterator I,
2118 AllocaPartitioning::const_use_iterator E) {
2119 uint64_t SizeInBits = TD.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002120 // Don't create integer types larger than the maximum bitwidth.
2121 if (SizeInBits > IntegerType::MAX_INT_BITS)
2122 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002123
2124 // Don't try to handle allocas with bit-padding.
2125 if (SizeInBits != TD.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002126 return false;
2127
Chandler Carruth58d05562012-10-25 04:37:07 +00002128 // We need to ensure that an integer type with the appropriate bitwidth can
2129 // be converted to the alloca type, whatever that is. We don't want to force
2130 // the alloca itself to have an integer type if there is a more suitable one.
2131 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2132 if (!canConvertValue(TD, AllocaTy, IntTy) ||
2133 !canConvertValue(TD, IntTy, AllocaTy))
2134 return false;
2135
Chandler Carruth435c4e02012-10-15 08:40:30 +00002136 uint64_t Size = TD.getTypeStoreSize(AllocaTy);
2137
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002138 // Check the uses to ensure the uses are (likely) promotable integer uses.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002139 // Also ensure that the alloca has a covering load or store. We don't want
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002140 // to widen the integer operations only to fail to promote due to some other
Chandler Carruth435c4e02012-10-15 08:40:30 +00002141 // unsplittable entry (which we may make splittable later).
Chandler Carruth92924fd2012-09-24 00:34:20 +00002142 bool WholeAllocaOp = false;
2143 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002144 Use *U = I->getUse();
2145 if (!U)
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002146 continue; // Skip dead use.
Chandler Carruth43c8b462012-10-04 10:39:28 +00002147
Chandler Carruth435c4e02012-10-15 08:40:30 +00002148 uint64_t RelBegin = I->BeginOffset - AllocBeginOffset;
2149 uint64_t RelEnd = I->EndOffset - AllocBeginOffset;
2150
Chandler Carruth43c8b462012-10-04 10:39:28 +00002151 // We can't reasonably handle cases where the load or store extends past
2152 // the end of the aloca's type and into its padding.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002153 if (RelEnd > Size)
Chandler Carruth43c8b462012-10-04 10:39:28 +00002154 return false;
2155
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002156 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002157 if (LI->isVolatile())
Chandler Carruth92924fd2012-09-24 00:34:20 +00002158 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002159 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruth92924fd2012-09-24 00:34:20 +00002160 WholeAllocaOp = true;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002161 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruthe45f4652012-12-10 00:54:45 +00002162 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth435c4e02012-10-15 08:40:30 +00002163 return false;
2164 continue;
2165 }
2166 // Non-integer loads need to be convertible from the alloca type so that
2167 // they are promotable.
2168 if (RelBegin != 0 || RelEnd != Size ||
2169 !canConvertValue(TD, AllocaTy, LI->getType()))
2170 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002171 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002172 Type *ValueTy = SI->getValueOperand()->getType();
2173 if (SI->isVolatile())
Chandler Carruth92924fd2012-09-24 00:34:20 +00002174 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002175 if (RelBegin == 0 && RelEnd == Size)
Chandler Carruth92924fd2012-09-24 00:34:20 +00002176 WholeAllocaOp = true;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002177 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruthe45f4652012-12-10 00:54:45 +00002178 if (ITy->getBitWidth() < TD.getTypeStoreSizeInBits(ITy))
Chandler Carruth435c4e02012-10-15 08:40:30 +00002179 return false;
2180 continue;
2181 }
2182 // Non-integer stores need to be convertible to the alloca type so that
2183 // they are promotable.
2184 if (RelBegin != 0 || RelEnd != Size ||
2185 !canConvertValue(TD, ValueTy, AllocaTy))
2186 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002187 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
Chandler Carruthe3f41192012-12-17 18:48:07 +00002188 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002189 return false;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002190 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U->getUser())) {
Chandler Carruth92924fd2012-09-24 00:34:20 +00002191 const AllocaPartitioning::MemTransferOffsets &MTO
2192 = P.getMemTransferOffsets(*MTI);
2193 if (!MTO.IsSplittable)
2194 return false;
2195 }
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002196 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Chandler Carruth435c4e02012-10-15 08:40:30 +00002197 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2198 II->getIntrinsicID() != Intrinsic::lifetime_end)
2199 return false;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002200 } else {
2201 return false;
2202 }
2203 }
2204 return WholeAllocaOp;
2205}
2206
Chandler Carruthd177f862013-03-20 07:30:36 +00002207static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002208 IntegerType *Ty, uint64_t Offset,
2209 const Twine &Name) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002210 DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002211 IntegerType *IntTy = cast<IntegerType>(V->getType());
2212 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2213 "Element extends past full value");
2214 uint64_t ShAmt = 8*Offset;
2215 if (DL.isBigEndian())
2216 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002217 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002218 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002219 DEBUG(dbgs() << " shifted: " << *V << "\n");
2220 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002221 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2222 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002223 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002224 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Chandler Carruth18db7952012-11-20 01:12:50 +00002225 DEBUG(dbgs() << " trunced: " << *V << "\n");
2226 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002227 return V;
2228}
2229
Chandler Carruthd177f862013-03-20 07:30:36 +00002230static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002231 Value *V, uint64_t Offset, const Twine &Name) {
2232 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2233 IntegerType *Ty = cast<IntegerType>(V->getType());
2234 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2235 "Cannot insert a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002236 DEBUG(dbgs() << " start: " << *V << "\n");
2237 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002238 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Chandler Carruth18db7952012-11-20 01:12:50 +00002239 DEBUG(dbgs() << " extended: " << *V << "\n");
2240 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002241 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2242 "Element store outside of alloca store");
2243 uint64_t ShAmt = 8*Offset;
2244 if (DL.isBigEndian())
2245 ShAmt = 8*(DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002246 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002247 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Chandler Carruth18db7952012-11-20 01:12:50 +00002248 DEBUG(dbgs() << " shifted: " << *V << "\n");
2249 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002250
2251 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2252 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2253 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Chandler Carruth18db7952012-11-20 01:12:50 +00002254 DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002255 V = IRB.CreateOr(Old, V, Name + ".insert");
Chandler Carruth18db7952012-11-20 01:12:50 +00002256 DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002257 }
2258 return V;
2259}
2260
Chandler Carruthd177f862013-03-20 07:30:36 +00002261static Value *extractVector(IRBuilderTy &IRB, Value *V,
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002262 unsigned BeginIndex, unsigned EndIndex,
2263 const Twine &Name) {
2264 VectorType *VecTy = cast<VectorType>(V->getType());
2265 unsigned NumElements = EndIndex - BeginIndex;
2266 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2267
2268 if (NumElements == VecTy->getNumElements())
2269 return V;
2270
2271 if (NumElements == 1) {
2272 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2273 Name + ".extract");
2274 DEBUG(dbgs() << " extract: " << *V << "\n");
2275 return V;
2276 }
2277
2278 SmallVector<Constant*, 8> Mask;
2279 Mask.reserve(NumElements);
2280 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2281 Mask.push_back(IRB.getInt32(i));
2282 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2283 ConstantVector::get(Mask),
2284 Name + ".extract");
2285 DEBUG(dbgs() << " shuffle: " << *V << "\n");
2286 return V;
2287}
2288
Chandler Carruthd177f862013-03-20 07:30:36 +00002289static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002290 unsigned BeginIndex, const Twine &Name) {
2291 VectorType *VecTy = cast<VectorType>(Old->getType());
2292 assert(VecTy && "Can only insert a vector into a vector");
2293
2294 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2295 if (!Ty) {
2296 // Single element to insert.
2297 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2298 Name + ".insert");
2299 DEBUG(dbgs() << " insert: " << *V << "\n");
2300 return V;
2301 }
2302
2303 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2304 "Too many elements!");
2305 if (Ty->getNumElements() == VecTy->getNumElements()) {
2306 assert(V->getType() == VecTy && "Vector type mismatch");
2307 return V;
2308 }
2309 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2310
2311 // When inserting a smaller vector into the larger to store, we first
2312 // use a shuffle vector to widen it with undef elements, and then
2313 // a second shuffle vector to select between the loaded vector and the
2314 // incoming vector.
2315 SmallVector<Constant*, 8> Mask;
2316 Mask.reserve(VecTy->getNumElements());
2317 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2318 if (i >= BeginIndex && i < EndIndex)
2319 Mask.push_back(IRB.getInt32(i - BeginIndex));
2320 else
2321 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2322 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2323 ConstantVector::get(Mask),
2324 Name + ".expand");
Nadav Rotem1e211912013-05-01 19:53:30 +00002325 DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002326
2327 Mask.clear();
2328 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002329 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2330
2331 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2332
2333 DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002334 return V;
2335}
2336
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002337namespace {
2338/// \brief Visitor to rewrite instructions using a partition of an alloca to
2339/// use a new alloca.
2340///
2341/// Also implements the rewriting to vector-based accesses when the partition
2342/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2343/// lives here.
2344class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
2345 bool> {
2346 // Befriend the base class so it can delegate to private visit methods.
2347 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
2348
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002349 const DataLayout &TD;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002350 AllocaPartitioning &P;
2351 SROA &Pass;
2352 AllocaInst &OldAI, &NewAI;
2353 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002354 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002355
2356 // If we are rewriting an alloca partition which can be written as pure
2357 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002358 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002359 // - The new alloca is exactly the size of the vector type here.
2360 // - The accesses all either map to the entire vector or to a single
2361 // element.
2362 // - The set of accessing instructions is only one of those handled above
2363 // in isVectorPromotionViable. Generally these are the same access kinds
2364 // which are promotable via mem2reg.
2365 VectorType *VecTy;
2366 Type *ElementTy;
2367 uint64_t ElementSize;
2368
Chandler Carruth92924fd2012-09-24 00:34:20 +00002369 // This is a convenience and flag variable that will be null unless the new
Chandler Carruth435c4e02012-10-15 08:40:30 +00002370 // alloca's integer operations should be widened to this integer type due to
2371 // passing isIntegerWideningViable above. If it is non-null, the desired
Chandler Carruth92924fd2012-09-24 00:34:20 +00002372 // integer type will be stored here for easy access during rewriting.
Chandler Carruth435c4e02012-10-15 08:40:30 +00002373 IntegerType *IntTy;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002374
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002375 // The offset of the partition user currently being rewritten.
2376 uint64_t BeginOffset, EndOffset;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002377 bool IsSplit;
Chandler Carruth54e8f0b2012-10-01 01:49:22 +00002378 Use *OldUse;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002379 Instruction *OldPtr;
2380
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002381 // Utility IR builder, whose name prefix is setup for each visited use, and
2382 // the insertion point is set to point to the user.
2383 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002384
2385public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002386 AllocaPartitionRewriter(const DataLayout &TD, AllocaPartitioning &P,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002387 AllocaPartitioning::iterator PI,
2388 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
2389 uint64_t NewBeginOffset, uint64_t NewEndOffset)
2390 : TD(TD), P(P), Pass(Pass),
2391 OldAI(OldAI), NewAI(NewAI),
2392 NewAllocaBeginOffset(NewBeginOffset),
2393 NewAllocaEndOffset(NewEndOffset),
Chandler Carruth891fec02012-10-13 02:41:05 +00002394 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruth435c4e02012-10-15 08:40:30 +00002395 VecTy(), ElementTy(), ElementSize(), IntTy(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002396 BeginOffset(), EndOffset(), IsSplit(), OldUse(), OldPtr(),
2397 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002398 }
2399
2400 /// \brief Visit the users of the alloca partition and rewrite them.
2401 bool visitUsers(AllocaPartitioning::const_use_iterator I,
2402 AllocaPartitioning::const_use_iterator E) {
2403 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
2404 NewAllocaBeginOffset, NewAllocaEndOffset,
2405 I, E)) {
2406 ++NumVectorized;
2407 VecTy = cast<VectorType>(NewAI.getAllocatedType());
2408 ElementTy = VecTy->getElementType();
Nadav Rotema5024fc2012-12-18 05:23:31 +00002409 assert((TD.getTypeSizeInBits(VecTy->getScalarType()) % 8) == 0 &&
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002410 "Only multiple-of-8 sized vector elements are viable");
Nadav Rotema5024fc2012-12-18 05:23:31 +00002411 ElementSize = TD.getTypeSizeInBits(VecTy->getScalarType()) / 8;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002412 } else if (isIntegerWideningViable(TD, NewAI.getAllocatedType(),
2413 NewAllocaBeginOffset, P, I, E)) {
2414 IntTy = Type::getIntNTy(NewAI.getContext(),
2415 TD.getTypeSizeInBits(NewAI.getAllocatedType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002416 }
2417 bool CanSROA = true;
2418 for (; I != E; ++I) {
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002419 if (!I->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00002420 continue; // Skip dead uses.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002421 BeginOffset = I->BeginOffset;
2422 EndOffset = I->EndOffset;
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002423 IsSplit = I->isSplit();
2424 OldUse = I->getUse();
2425 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002426
2427 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2428 IRB.SetInsertPoint(OldUserI);
2429 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2430 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
2431 ".");
2432
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002433 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002434 }
2435 if (VecTy) {
2436 assert(CanSROA);
2437 VecTy = 0;
2438 ElementTy = 0;
2439 ElementSize = 0;
2440 }
Chandler Carruth435c4e02012-10-15 08:40:30 +00002441 if (IntTy) {
2442 assert(CanSROA);
2443 IntTy = 0;
2444 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002445 return CanSROA;
2446 }
2447
2448private:
2449 // Every instruction which can end up as a user must have a rewrite rule.
2450 bool visitInstruction(Instruction &I) {
2451 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
2452 llvm_unreachable("No rewrite rule for this instruction!");
2453 }
2454
Chandler Carruthd177f862013-03-20 07:30:36 +00002455 Value *getAdjustedAllocaPtr(IRBuilderTy &IRB, Type *PointerTy) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002456 assert(BeginOffset >= NewAllocaBeginOffset);
Chandler Carruth5da3f052012-11-01 09:14:31 +00002457 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002458 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002459 }
2460
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002461 /// \brief Compute suitable alignment to access an offset into the new alloca.
2462 unsigned getOffsetAlign(uint64_t Offset) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002463 unsigned NewAIAlign = NewAI.getAlignment();
2464 if (!NewAIAlign)
2465 NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
2466 return MinAlign(NewAIAlign, Offset);
2467 }
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002468
2469 /// \brief Compute suitable alignment to access this partition of the new
2470 /// alloca.
2471 unsigned getPartitionAlign() {
2472 return getOffsetAlign(BeginOffset - NewAllocaBeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002473 }
2474
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002475 /// \brief Compute suitable alignment to access a type at an offset of the
2476 /// new alloca.
2477 ///
2478 /// \returns zero if the type's ABI alignment is a suitable alignment,
2479 /// otherwise returns the maximal suitable alignment.
2480 unsigned getOffsetTypeAlign(Type *Ty, uint64_t Offset) {
2481 unsigned Align = getOffsetAlign(Offset);
2482 return Align == TD.getABITypeAlignment(Ty) ? 0 : Align;
2483 }
2484
2485 /// \brief Compute suitable alignment to access a type at the beginning of
2486 /// this partition of the new alloca.
2487 ///
2488 /// See \c getOffsetTypeAlign for details; this routine delegates to it.
2489 unsigned getPartitionTypeAlign(Type *Ty) {
2490 return getOffsetTypeAlign(Ty, BeginOffset - NewAllocaBeginOffset);
Chandler Carruth176ca712012-10-01 12:16:54 +00002491 }
2492
Chandler Carruth845b73c2012-11-21 08:16:30 +00002493 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002494 assert(VecTy && "Can only call getIndex when rewriting a vector");
2495 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2496 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2497 uint32_t Index = RelOffset / ElementSize;
2498 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002499 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002500 }
2501
2502 void deleteIfTriviallyDead(Value *V) {
2503 Instruction *I = cast<Instruction>(V);
2504 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002505 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002506 }
2507
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002508 Value *rewriteVectorizedLoadInst() {
Chandler Carruth769445e2012-12-17 12:50:21 +00002509 unsigned BeginIndex = getIndex(BeginOffset);
2510 unsigned EndIndex = getIndex(EndOffset);
2511 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002512
2513 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002514 "load");
2515 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002516 }
2517
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002518 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002519 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002520 assert(!LI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002521 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002522 "load");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002523 V = convertValue(TD, IRB, V, IntTy);
2524 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2525 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth18db7952012-11-20 01:12:50 +00002526 if (Offset > 0 || EndOffset < NewAllocaEndOffset)
2527 V = extractInteger(TD, IRB, V, cast<IntegerType>(LI.getType()), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002528 "extract");
Chandler Carruth18db7952012-11-20 01:12:50 +00002529 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002530 }
2531
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002532 bool visitLoadInst(LoadInst &LI) {
2533 DEBUG(dbgs() << " original: " << LI << "\n");
2534 Value *OldOp = LI.getOperand(0);
2535 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002536
Chandler Carruth58d05562012-10-25 04:37:07 +00002537 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth3e994a22012-11-20 10:02:19 +00002538
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002539 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), Size * 8)
2540 : LI.getType();
Chandler Carruth18db7952012-11-20 01:12:50 +00002541 bool IsPtrAdjusted = false;
2542 Value *V;
2543 if (VecTy) {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002544 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002545 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002546 V = rewriteIntegerLoad(LI);
Chandler Carruth18db7952012-11-20 01:12:50 +00002547 } else if (BeginOffset == NewAllocaBeginOffset &&
2548 canConvertValue(TD, NewAllocaTy, LI.getType())) {
2549 V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002550 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002551 } else {
2552 Type *LTy = TargetTy->getPointerTo();
2553 V = IRB.CreateAlignedLoad(getAdjustedAllocaPtr(IRB, LTy),
2554 getPartitionTypeAlign(TargetTy),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002555 LI.isVolatile(), "load");
Chandler Carruth18db7952012-11-20 01:12:50 +00002556 IsPtrAdjusted = true;
2557 }
2558 V = convertValue(TD, IRB, V, TargetTy);
2559
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002560 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002561 assert(!LI.isVolatile());
2562 assert(LI.getType()->isIntegerTy() &&
2563 "Only integer type loads and stores are split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002564 assert(Size < TD.getTypeStoreSize(LI.getType()) &&
2565 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002566 assert(LI.getType()->getIntegerBitWidth() ==
2567 TD.getTypeStoreSizeInBits(LI.getType()) &&
2568 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002569 // Move the insertion point just past the load so that we can refer to it.
2570 IRB.SetInsertPoint(llvm::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002571 // Create a placeholder value with the same type as LI to use as the
2572 // basis for the new value. This allows us to replace the uses of LI with
2573 // the computed value, and then replace the placeholder with LI, leaving
2574 // LI only used for this computation.
2575 Value *Placeholder
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002576 = new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
Chandler Carruth58d05562012-10-25 04:37:07 +00002577 V = insertInteger(TD, IRB, Placeholder, V, BeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002578 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002579 LI.replaceAllUsesWith(V);
2580 Placeholder->replaceAllUsesWith(&LI);
Jakub Staszak4e45abf2012-11-01 01:10:43 +00002581 delete Placeholder;
Chandler Carruth18db7952012-11-20 01:12:50 +00002582 } else {
2583 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002584 }
2585
Chandler Carruth18db7952012-11-20 01:12:50 +00002586 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002587 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002588 DEBUG(dbgs() << " to: " << *V << "\n");
2589 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002590 }
2591
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002592 bool rewriteVectorizedStoreInst(Value *V,
Chandler Carruth18db7952012-11-20 01:12:50 +00002593 StoreInst &SI, Value *OldOp) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002594 if (V->getType() != VecTy) {
2595 unsigned BeginIndex = getIndex(BeginOffset);
2596 unsigned EndIndex = getIndex(EndOffset);
2597 assert(EndIndex > BeginIndex && "Empty vector!");
2598 unsigned NumElements = EndIndex - BeginIndex;
2599 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2600 Type *PartitionTy
2601 = (NumElements == 1) ? ElementTy
2602 : VectorType::get(ElementTy, NumElements);
2603 if (V->getType() != PartitionTy)
2604 V = convertValue(TD, IRB, V, PartitionTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002605
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002606 // Mix in the existing elements.
2607 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2608 "load");
2609 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2610 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002611 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002612 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002613
2614 (void)Store;
2615 DEBUG(dbgs() << " to: " << *Store << "\n");
2616 return true;
2617 }
2618
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002619 bool rewriteIntegerStore(Value *V, StoreInst &SI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002620 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002621 assert(!SI.isVolatile());
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002622 if (TD.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2623 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002624 "oldload");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002625 Old = convertValue(TD, IRB, Old, IntTy);
2626 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2627 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2628 V = insertInteger(TD, IRB, Old, SI.getValueOperand(), Offset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002629 "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002630 }
2631 V = convertValue(TD, IRB, V, NewAllocaTy);
2632 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Chandler Carruth18db7952012-11-20 01:12:50 +00002633 Pass.DeadInsts.insert(&SI);
Chandler Carruth92924fd2012-09-24 00:34:20 +00002634 (void)Store;
2635 DEBUG(dbgs() << " to: " << *Store << "\n");
2636 return true;
2637 }
2638
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002639 bool visitStoreInst(StoreInst &SI) {
2640 DEBUG(dbgs() << " original: " << SI << "\n");
2641 Value *OldOp = SI.getOperand(1);
2642 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002643
Chandler Carruth18db7952012-11-20 01:12:50 +00002644 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002645
Chandler Carruthac8317f2012-10-04 12:33:50 +00002646 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2647 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002648 if (V->getType()->isPointerTy())
2649 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002650 Pass.PostPromotionWorklist.insert(AI);
2651
Chandler Carruth18db7952012-11-20 01:12:50 +00002652 uint64_t Size = EndOffset - BeginOffset;
2653 if (Size < TD.getTypeStoreSize(V->getType())) {
2654 assert(!SI.isVolatile());
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002655 assert(IsSplit && "A seemingly split store isn't splittable");
Chandler Carruth18db7952012-11-20 01:12:50 +00002656 assert(V->getType()->isIntegerTy() &&
2657 "Only integer type loads and stores are split");
2658 assert(V->getType()->getIntegerBitWidth() ==
2659 TD.getTypeStoreSizeInBits(V->getType()) &&
2660 "Non-byte-multiple bit width");
Chandler Carruth18db7952012-11-20 01:12:50 +00002661 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), Size * 8);
2662 V = extractInteger(TD, IRB, V, NarrowTy, BeginOffset,
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002663 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002664 }
2665
Chandler Carruth18db7952012-11-20 01:12:50 +00002666 if (VecTy)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002667 return rewriteVectorizedStoreInst(V, SI, OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002668 if (IntTy && V->getType()->isIntegerTy())
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002669 return rewriteIntegerStore(V, SI);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002670
Chandler Carruth18db7952012-11-20 01:12:50 +00002671 StoreInst *NewSI;
2672 if (BeginOffset == NewAllocaBeginOffset &&
Chandler Carruth0e8a52d2013-04-07 11:47:54 +00002673 EndOffset == NewAllocaEndOffset &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002674 canConvertValue(TD, V->getType(), NewAllocaTy)) {
2675 V = convertValue(TD, IRB, V, NewAllocaTy);
2676 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2677 SI.isVolatile());
2678 } else {
2679 Value *NewPtr = getAdjustedAllocaPtr(IRB, V->getType()->getPointerTo());
2680 NewSI = IRB.CreateAlignedStore(V, NewPtr,
2681 getPartitionTypeAlign(V->getType()),
2682 SI.isVolatile());
2683 }
2684 (void)NewSI;
2685 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002686 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002687
2688 DEBUG(dbgs() << " to: " << *NewSI << "\n");
2689 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002690 }
2691
Chandler Carruth514f34f2012-12-17 04:07:30 +00002692 /// \brief Compute an integer value from splatting an i8 across the given
2693 /// number of bytes.
2694 ///
2695 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2696 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002697 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002698 ///
2699 /// \param V The i8 value to splat.
2700 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002701 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002702 assert(Size > 0 && "Expected a positive number of bytes.");
2703 IntegerType *VTy = cast<IntegerType>(V->getType());
2704 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2705 if (Size == 1)
2706 return V;
2707
2708 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size*8);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002709 V = IRB.CreateMul(IRB.CreateZExt(V, SplatIntTy, "zext"),
Chandler Carruth514f34f2012-12-17 04:07:30 +00002710 ConstantExpr::getUDiv(
2711 Constant::getAllOnesValue(SplatIntTy),
2712 ConstantExpr::getZExt(
2713 Constant::getAllOnesValue(V->getType()),
2714 SplatIntTy)),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002715 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002716 return V;
2717 }
2718
Chandler Carruthccca5042012-12-17 04:07:37 +00002719 /// \brief Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002720 Value *getVectorSplat(Value *V, unsigned NumElements) {
2721 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Chandler Carruthccca5042012-12-17 04:07:37 +00002722 DEBUG(dbgs() << " splat: " << *V << "\n");
2723 return V;
2724 }
2725
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002726 bool visitMemSetInst(MemSetInst &II) {
2727 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002728 assert(II.getRawDest() == OldPtr);
2729
2730 // If the memset has a variable size, it cannot be split, just adjust the
2731 // pointer to the new alloca.
2732 if (!isa<Constant>(II.getLength())) {
2733 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002734 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002735 II.setAlignment(ConstantInt::get(CstTy, getPartitionAlign()));
Chandler Carruth208124f2012-09-26 10:59:22 +00002736
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002737 deleteIfTriviallyDead(OldPtr);
2738 return false;
2739 }
2740
2741 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002742 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002743
2744 Type *AllocaTy = NewAI.getAllocatedType();
2745 Type *ScalarTy = AllocaTy->getScalarType();
2746
2747 // If this doesn't map cleanly onto the alloca type, and that type isn't
2748 // a single value type, just emit a memset.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002749 if (!VecTy && !IntTy &&
2750 (BeginOffset != NewAllocaBeginOffset ||
2751 EndOffset != NewAllocaEndOffset ||
2752 !AllocaTy->isSingleValueType() ||
Chandler Carruthccca5042012-12-17 04:07:37 +00002753 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)) ||
2754 TD.getTypeSizeInBits(ScalarTy)%8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002755 Type *SizeTy = II.getLength()->getType();
2756 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002757 CallInst *New
2758 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
2759 II.getRawDest()->getType()),
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002760 II.getValue(), Size, getPartitionAlign(),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002761 II.isVolatile());
2762 (void)New;
2763 DEBUG(dbgs() << " to: " << *New << "\n");
2764 return false;
2765 }
2766
2767 // If we can represent this as a simple value, we have to build the actual
2768 // value to store, which requires expanding the byte present in memset to
2769 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002770 // splatting the byte to a sufficiently wide integer, splatting it across
2771 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002772 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002773
Chandler Carruthccca5042012-12-17 04:07:37 +00002774 if (VecTy) {
2775 // If this is a memset of a vectorized alloca, insert it.
2776 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002777
Chandler Carruthccca5042012-12-17 04:07:37 +00002778 unsigned BeginIndex = getIndex(BeginOffset);
2779 unsigned EndIndex = getIndex(EndOffset);
2780 assert(EndIndex > BeginIndex && "Empty vector!");
2781 unsigned NumElements = EndIndex - BeginIndex;
2782 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2783
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002784 Value *Splat =
2785 getIntegerSplat(II.getValue(), TD.getTypeSizeInBits(ElementTy) / 8);
Chandler Carruthcacda252012-12-17 14:03:01 +00002786 Splat = convertValue(TD, IRB, Splat, ElementTy);
2787 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002788 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002789
Chandler Carruthce4562b2012-12-17 13:41:21 +00002790 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002791 "oldload");
2792 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002793 } else if (IntTy) {
2794 // If this is a memset on an alloca where we can widen stores, insert the
2795 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002796 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002797
Benjamin Kramerc003a452013-01-01 16:13:35 +00002798 uint64_t Size = EndOffset - BeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002799 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002800
2801 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2802 EndOffset != NewAllocaBeginOffset)) {
2803 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002804 "oldload");
Chandler Carruthccca5042012-12-17 04:07:37 +00002805 Old = convertValue(TD, IRB, Old, IntTy);
2806 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2807 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002808 V = insertInteger(TD, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002809 } else {
2810 assert(V->getType() == IntTy &&
2811 "Wrong type for an alloca wide integer!");
2812 }
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002813 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002814 } else {
2815 // Established these invariants above.
2816 assert(BeginOffset == NewAllocaBeginOffset);
2817 assert(EndOffset == NewAllocaEndOffset);
2818
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002819 V = getIntegerSplat(II.getValue(), TD.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002820 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002821 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002822
2823 V = convertValue(TD, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002824 }
2825
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002826 Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
Chandler Carruth871ba722012-09-26 10:27:46 +00002827 II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002828 (void)New;
2829 DEBUG(dbgs() << " to: " << *New << "\n");
2830 return !II.isVolatile();
2831 }
2832
2833 bool visitMemTransferInst(MemTransferInst &II) {
2834 // Rewriting of memory transfer instructions can be a bit tricky. We break
2835 // them into two categories: split intrinsics and unsplit intrinsics.
2836
2837 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002838
2839 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
2840 bool IsDest = II.getRawDest() == OldPtr;
2841
2842 const AllocaPartitioning::MemTransferOffsets &MTO
2843 = P.getMemTransferOffsets(II);
2844
Chandler Carruth176ca712012-10-01 12:16:54 +00002845 // Compute the relative offset within the transfer.
Chandler Carruth5da3f052012-11-01 09:14:31 +00002846 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth176ca712012-10-01 12:16:54 +00002847 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
2848 : MTO.SourceBegin));
2849
2850 unsigned Align = II.getAlignment();
2851 if (Align > 1)
2852 Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002853 MinAlign(II.getAlignment(), getPartitionAlign()));
Chandler Carruth176ca712012-10-01 12:16:54 +00002854
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002855 // For unsplit intrinsics, we simply modify the source and destination
2856 // pointers in place. This isn't just an optimization, it is a matter of
2857 // correctness. With unsplit intrinsics we may be dealing with transfers
2858 // within a single alloca before SROA ran, or with transfers that have
2859 // a variable length. We may also be dealing with memmove instead of
2860 // memcpy, and so simply updating the pointers is the necessary for us to
2861 // update both source and dest of a single call.
2862 if (!MTO.IsSplittable) {
2863 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
2864 if (IsDest)
2865 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
2866 else
2867 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
2868
Chandler Carruth208124f2012-09-26 10:59:22 +00002869 Type *CstTy = II.getAlignmentCst()->getType();
Chandler Carruth176ca712012-10-01 12:16:54 +00002870 II.setAlignment(ConstantInt::get(CstTy, Align));
Chandler Carruth208124f2012-09-26 10:59:22 +00002871
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002872 DEBUG(dbgs() << " to: " << II << "\n");
2873 deleteIfTriviallyDead(OldOp);
2874 return false;
2875 }
2876 // For split transfer intrinsics we have an incredibly useful assurance:
2877 // the source and destination do not reside within the same alloca, and at
2878 // least one of them does not escape. This means that we can replace
2879 // memmove with memcpy, and we don't need to worry about all manner of
2880 // downsides to splitting and transforming the operations.
2881
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002882 // If this doesn't map cleanly onto the alloca type, and that type isn't
2883 // a single value type, just emit a memcpy.
2884 bool EmitMemCpy
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002885 = !VecTy && !IntTy && (BeginOffset != NewAllocaBeginOffset ||
2886 EndOffset != NewAllocaEndOffset ||
2887 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002888
2889 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2890 // size hasn't been shrunk based on analysis of the viable range, this is
2891 // a no-op.
2892 if (EmitMemCpy && &OldAI == &NewAI) {
2893 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2894 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2895 // Ensure the start lines up.
2896 assert(BeginOffset == OrigBegin);
Benjamin Kramer4622cd72012-09-14 13:08:09 +00002897 (void)OrigBegin;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002898
2899 // Rewrite the size as needed.
2900 if (EndOffset != OrigEnd)
2901 II.setLength(ConstantInt::get(II.getLength()->getType(),
2902 EndOffset - BeginOffset));
2903 return false;
2904 }
2905 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002906 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002907
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002908 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2909 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002910 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002911 if (AllocaInst *AI
2912 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002913 Pass.Worklist.insert(AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002914
2915 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002916 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2917 : II.getRawDest()->getType();
2918
2919 // Compute the other pointer, folding as much as possible to produce
2920 // a single, simple GEP in most cases.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002921 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002922
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002923 Value *OurPtr
2924 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2925 : II.getRawSource()->getType());
2926 Type *SizeTy = II.getLength()->getType();
2927 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2928
2929 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2930 IsDest ? OtherPtr : OurPtr,
Chandler Carruth871ba722012-09-26 10:27:46 +00002931 Size, Align, II.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002932 (void)New;
2933 DEBUG(dbgs() << " to: " << *New << "\n");
2934 return false;
2935 }
2936
Chandler Carruth08e5f492012-10-03 08:26:28 +00002937 // Note that we clamp the alignment to 1 here as a 0 alignment for a memcpy
2938 // is equivalent to 1, but that isn't true if we end up rewriting this as
2939 // a load or store.
2940 if (!Align)
2941 Align = 1;
2942
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002943 bool IsWholeAlloca = BeginOffset == NewAllocaBeginOffset &&
2944 EndOffset == NewAllocaEndOffset;
2945 uint64_t Size = EndOffset - BeginOffset;
2946 unsigned BeginIndex = VecTy ? getIndex(BeginOffset) : 0;
2947 unsigned EndIndex = VecTy ? getIndex(EndOffset) : 0;
2948 unsigned NumElements = EndIndex - BeginIndex;
2949 IntegerType *SubIntTy
2950 = IntTy ? Type::getIntNTy(IntTy->getContext(), Size*8) : 0;
2951
2952 Type *OtherPtrTy = NewAI.getType();
2953 if (VecTy && !IsWholeAlloca) {
2954 if (NumElements == 1)
2955 OtherPtrTy = VecTy->getElementType();
2956 else
2957 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2958
2959 OtherPtrTy = OtherPtrTy->getPointerTo();
2960 } else if (IntTy && !IsWholeAlloca) {
2961 OtherPtrTy = SubIntTy->getPointerTo();
2962 }
2963
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002964 Value *SrcPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002965 Value *DstPtr = &NewAI;
2966 if (!IsDest)
2967 std::swap(SrcPtr, DstPtr);
2968
2969 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002970 if (VecTy && !IsWholeAlloca && !IsDest) {
2971 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002972 "load");
2973 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002974 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002975 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002976 "load");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002977 Src = convertValue(TD, IRB, Src, IntTy);
2978 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2979 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002980 Src = extractInteger(TD, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002981 } else {
Chandler Carruth871ba722012-09-26 10:27:46 +00002982 Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002983 "copyload");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002984 }
2985
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002986 if (VecTy && !IsWholeAlloca && IsDest) {
2987 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002988 "oldload");
2989 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002990 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002991 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002992 "oldload");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002993 Old = convertValue(TD, IRB, Old, IntTy);
2994 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2995 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002996 Src = insertInteger(TD, IRB, Old, Src, Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002997 Src = convertValue(TD, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002998 }
2999
Chandler Carruth871ba722012-09-26 10:27:46 +00003000 StoreInst *Store = cast<StoreInst>(
3001 IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
3002 (void)Store;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003003 DEBUG(dbgs() << " to: " << *Store << "\n");
3004 return !II.isVolatile();
3005 }
3006
3007 bool visitIntrinsicInst(IntrinsicInst &II) {
3008 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
3009 II.getIntrinsicID() == Intrinsic::lifetime_end);
3010 DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003011 assert(II.getArgOperand(1) == OldPtr);
3012
3013 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003014 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003015
3016 ConstantInt *Size
3017 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3018 EndOffset - BeginOffset);
3019 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
3020 Value *New;
3021 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3022 New = IRB.CreateLifetimeStart(Ptr, Size);
3023 else
3024 New = IRB.CreateLifetimeEnd(Ptr, Size);
3025
Edwin Vane82f80d42013-01-29 17:42:24 +00003026 (void)New;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003027 DEBUG(dbgs() << " to: " << *New << "\n");
3028 return true;
3029 }
3030
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003031 bool visitPHINode(PHINode &PN) {
3032 DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00003033
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003034 // We would like to compute a new pointer in only one place, but have it be
3035 // as local as possible to the PHI. To do that, we re-use the location of
3036 // the old pointer, which necessarily must be in the right position to
3037 // dominate the PHI.
Chandler Carruthd177f862013-03-20 07:30:36 +00003038 IRBuilderTy PtrBuilder(cast<Instruction>(OldPtr));
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003039 PtrBuilder.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) +
3040 ".");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003041
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003042 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003043 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003044 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003045
Chandler Carruth82a57542012-10-01 10:54:05 +00003046 DEBUG(dbgs() << " to: " << PN << "\n");
3047 deleteIfTriviallyDead(OldPtr);
3048 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003049 }
3050
3051 bool visitSelectInst(SelectInst &SI) {
3052 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003053 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3054 "Pointer isn't an operand!");
Chandler Carruth82a57542012-10-01 10:54:05 +00003055
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003056 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003057 // Replace the operands which were using the old pointer.
3058 if (SI.getOperand(1) == OldPtr)
3059 SI.setOperand(1, NewPtr);
3060 if (SI.getOperand(2) == OldPtr)
3061 SI.setOperand(2, NewPtr);
3062
Chandler Carruth82a57542012-10-01 10:54:05 +00003063 DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003064 deleteIfTriviallyDead(OldPtr);
Chandler Carruth82a57542012-10-01 10:54:05 +00003065 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003066 }
3067
3068};
3069}
3070
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003071namespace {
3072/// \brief Visitor to rewrite aggregate loads and stores as scalar.
3073///
3074/// This pass aggressively rewrites all aggregate loads and stores on
3075/// a particular pointer (or any pointer derived from it which we can identify)
3076/// with scalar loads and stores.
3077class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3078 // Befriend the base class so it can delegate to private visit methods.
3079 friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
3080
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003081 const DataLayout &TD;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003082
3083 /// Queue of pointer uses to analyze and potentially rewrite.
3084 SmallVector<Use *, 8> Queue;
3085
3086 /// Set to prevent us from cycling with phi nodes and loops.
3087 SmallPtrSet<User *, 8> Visited;
3088
3089 /// The current pointer use being rewritten. This is used to dig up the used
3090 /// value (as opposed to the user).
3091 Use *U;
3092
3093public:
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003094 AggLoadStoreRewriter(const DataLayout &TD) : TD(TD) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003095
3096 /// Rewrite loads and stores through a pointer and all pointers derived from
3097 /// it.
3098 bool rewrite(Instruction &I) {
3099 DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
3100 enqueueUsers(I);
3101 bool Changed = false;
3102 while (!Queue.empty()) {
3103 U = Queue.pop_back_val();
3104 Changed |= visit(cast<Instruction>(U->getUser()));
3105 }
3106 return Changed;
3107 }
3108
3109private:
3110 /// Enqueue all the users of the given instruction for further processing.
3111 /// This uses a set to de-duplicate users.
3112 void enqueueUsers(Instruction &I) {
3113 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
3114 ++UI)
3115 if (Visited.insert(*UI))
3116 Queue.push_back(&UI.getUse());
3117 }
3118
3119 // Conservative default is to not rewrite anything.
3120 bool visitInstruction(Instruction &I) { return false; }
3121
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003122 /// \brief Generic recursive split emission class.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003123 template <typename Derived>
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003124 class OpSplitter {
3125 protected:
3126 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003127 IRBuilderTy IRB;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003128 /// The indices which to be used with insert- or extractvalue to select the
3129 /// appropriate value within the aggregate.
3130 SmallVector<unsigned, 4> Indices;
3131 /// The indices to a GEP instruction which will move Ptr to the correct slot
3132 /// within the aggregate.
3133 SmallVector<Value *, 4> GEPIndices;
3134 /// The base pointer of the original op, used as a base for GEPing the
3135 /// split operations.
3136 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003137
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003138 /// Initialize the splitter with an insertion point, Ptr and start with a
3139 /// single zero GEP index.
3140 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003141 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003142
3143 public:
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003144 /// \brief Generic recursive split emission routine.
3145 ///
3146 /// This method recursively splits an aggregate op (load or store) into
3147 /// scalar or vector ops. It splits recursively until it hits a single value
3148 /// and emits that single value operation via the template argument.
3149 ///
3150 /// The logic of this routine relies on GEPs and insertvalue and
3151 /// extractvalue all operating with the same fundamental index list, merely
3152 /// formatted differently (GEPs need actual values).
3153 ///
3154 /// \param Ty The type being split recursively into smaller ops.
3155 /// \param Agg The aggregate value being built up or stored, depending on
3156 /// whether this is splitting a load or a store respectively.
3157 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3158 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003159 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003160
3161 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3162 unsigned OldSize = Indices.size();
3163 (void)OldSize;
3164 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3165 ++Idx) {
3166 assert(Indices.size() == OldSize && "Did not return to the old size");
3167 Indices.push_back(Idx);
3168 GEPIndices.push_back(IRB.getInt32(Idx));
3169 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3170 GEPIndices.pop_back();
3171 Indices.pop_back();
3172 }
3173 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003174 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003175
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003176 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3177 unsigned OldSize = Indices.size();
3178 (void)OldSize;
3179 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3180 ++Idx) {
3181 assert(Indices.size() == OldSize && "Did not return to the old size");
3182 Indices.push_back(Idx);
3183 GEPIndices.push_back(IRB.getInt32(Idx));
3184 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3185 GEPIndices.pop_back();
3186 Indices.pop_back();
3187 }
3188 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003189 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003190
3191 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003192 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003193 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003194
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003195 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003196 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00003197 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003198
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003199 /// Emit a leaf load of a single value. This is called at the leaves of the
3200 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003201 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003202 assert(Ty->isSingleValueType());
3203 // Load the single value and insert it using the indices.
Jakub Staszak3c6583a2013-02-19 22:14:45 +00003204 Value *GEP = IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep");
3205 Value *Load = IRB.CreateLoad(GEP, Name + ".load");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003206 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3207 DEBUG(dbgs() << " to: " << *Load << "\n");
3208 }
3209 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003210
3211 bool visitLoadInst(LoadInst &LI) {
3212 assert(LI.getPointerOperand() == *U);
3213 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3214 return false;
3215
3216 // We have an aggregate being loaded, split it apart.
3217 DEBUG(dbgs() << " original: " << LI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003218 LoadOpSplitter Splitter(&LI, *U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003219 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003220 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003221 LI.replaceAllUsesWith(V);
3222 LI.eraseFromParent();
3223 return true;
3224 }
3225
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003226 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003227 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
Benjamin Kramera59ef572012-09-18 17:11:47 +00003228 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003229
3230 /// Emit a leaf store of a single value. This is called at the leaves of the
3231 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003232 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003233 assert(Ty->isSingleValueType());
3234 // Extract the single value and store it using the indices.
3235 Value *Store = IRB.CreateStore(
3236 IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
3237 IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
3238 (void)Store;
3239 DEBUG(dbgs() << " to: " << *Store << "\n");
3240 }
3241 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003242
3243 bool visitStoreInst(StoreInst &SI) {
3244 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3245 return false;
3246 Value *V = SI.getValueOperand();
3247 if (V->getType()->isSingleValueType())
3248 return false;
3249
3250 // We have an aggregate being stored, split it apart.
3251 DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003252 StoreOpSplitter Splitter(&SI, *U);
3253 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003254 SI.eraseFromParent();
3255 return true;
3256 }
3257
3258 bool visitBitCastInst(BitCastInst &BC) {
3259 enqueueUsers(BC);
3260 return false;
3261 }
3262
3263 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3264 enqueueUsers(GEPI);
3265 return false;
3266 }
3267
3268 bool visitPHINode(PHINode &PN) {
3269 enqueueUsers(PN);
3270 return false;
3271 }
3272
3273 bool visitSelectInst(SelectInst &SI) {
3274 enqueueUsers(SI);
3275 return false;
3276 }
3277};
3278}
3279
Chandler Carruthba931992012-10-13 10:49:33 +00003280/// \brief Strip aggregate type wrapping.
3281///
3282/// This removes no-op aggregate types wrapping an underlying type. It will
3283/// strip as many layers of types as it can without changing either the type
3284/// size or the allocated size.
3285static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3286 if (Ty->isSingleValueType())
3287 return Ty;
3288
3289 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3290 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3291
3292 Type *InnerTy;
3293 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3294 InnerTy = ArrTy->getElementType();
3295 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3296 const StructLayout *SL = DL.getStructLayout(STy);
3297 unsigned Index = SL->getElementContainingOffset(0);
3298 InnerTy = STy->getElementType(Index);
3299 } else {
3300 return Ty;
3301 }
3302
3303 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3304 TypeSize > DL.getTypeSizeInBits(InnerTy))
3305 return Ty;
3306
3307 return stripAggregateTypeWrapping(DL, InnerTy);
3308}
3309
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003310/// \brief Try to find a partition of the aggregate type passed in for a given
3311/// offset and size.
3312///
3313/// This recurses through the aggregate type and tries to compute a subtype
3314/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003315/// of an array, it will even compute a new array type for that sub-section,
3316/// and the same for structs.
3317///
3318/// Note that this routine is very strict and tries to find a partition of the
3319/// type which produces the *exact* right offset and size. It is not forgiving
3320/// when the size or offset cause either end of type-based partition to be off.
3321/// Also, this is a best-effort routine. It is reasonable to give up and not
3322/// return a type if necessary.
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003323static Type *getTypePartition(const DataLayout &TD, Type *Ty,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003324 uint64_t Offset, uint64_t Size) {
3325 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
Chandler Carruthba931992012-10-13 10:49:33 +00003326 return stripAggregateTypeWrapping(TD, Ty);
Chandler Carruth58d05562012-10-25 04:37:07 +00003327 if (Offset > TD.getTypeAllocSize(Ty) ||
3328 (TD.getTypeAllocSize(Ty) - Offset) < Size)
3329 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003330
3331 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3332 // We can't partition pointers...
3333 if (SeqTy->isPointerTy())
3334 return 0;
3335
3336 Type *ElementTy = SeqTy->getElementType();
3337 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3338 uint64_t NumSkippedElements = Offset / ElementSize;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003339 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003340 if (NumSkippedElements >= ArrTy->getNumElements())
3341 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003342 } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003343 if (NumSkippedElements >= VecTy->getNumElements())
3344 return 0;
Jakub Staszak4f9d1e82013-03-24 09:56:28 +00003345 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003346 Offset -= NumSkippedElements * ElementSize;
3347
3348 // First check if we need to recurse.
3349 if (Offset > 0 || Size < ElementSize) {
3350 // Bail if the partition ends in a different array element.
3351 if ((Offset + Size) > ElementSize)
3352 return 0;
3353 // Recurse through the element type trying to peel off offset bytes.
3354 return getTypePartition(TD, ElementTy, Offset, Size);
3355 }
3356 assert(Offset == 0);
3357
3358 if (Size == ElementSize)
Chandler Carruthba931992012-10-13 10:49:33 +00003359 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003360 assert(Size > ElementSize);
3361 uint64_t NumElements = Size / ElementSize;
3362 if (NumElements * ElementSize != Size)
3363 return 0;
3364 return ArrayType::get(ElementTy, NumElements);
3365 }
3366
3367 StructType *STy = dyn_cast<StructType>(Ty);
3368 if (!STy)
3369 return 0;
3370
3371 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003372 if (Offset >= SL->getSizeInBytes())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003373 return 0;
3374 uint64_t EndOffset = Offset + Size;
3375 if (EndOffset > SL->getSizeInBytes())
3376 return 0;
3377
3378 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003379 Offset -= SL->getElementOffset(Index);
3380
3381 Type *ElementTy = STy->getElementType(Index);
3382 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
3383 if (Offset >= ElementSize)
3384 return 0; // The offset points into alignment padding.
3385
3386 // See if any partition must be contained by the element.
3387 if (Offset > 0 || Size < ElementSize) {
3388 if ((Offset + Size) > ElementSize)
3389 return 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003390 return getTypePartition(TD, ElementTy, Offset, Size);
3391 }
3392 assert(Offset == 0);
3393
3394 if (Size == ElementSize)
Chandler Carruthba931992012-10-13 10:49:33 +00003395 return stripAggregateTypeWrapping(TD, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003396
3397 StructType::element_iterator EI = STy->element_begin() + Index,
3398 EE = STy->element_end();
3399 if (EndOffset < SL->getSizeInBytes()) {
3400 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3401 if (Index == EndIndex)
3402 return 0; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003403
3404 // Don't try to form "natural" types if the elements don't line up with the
3405 // expected size.
3406 // FIXME: We could potentially recurse down through the last element in the
3407 // sub-struct to find a natural end point.
3408 if (SL->getElementOffset(EndIndex) != EndOffset)
3409 return 0;
3410
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003411 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003412 EE = STy->element_begin() + EndIndex;
3413 }
3414
3415 // Try to build up a sub-structure.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003416 StructType *SubTy = StructType::get(STy->getContext(), makeArrayRef(EI, EE),
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003417 STy->isPacked());
3418 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003419 if (Size != SubSL->getSizeInBytes())
3420 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003421
Chandler Carruth054a40a2012-09-14 11:08:31 +00003422 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003423}
3424
3425/// \brief Rewrite an alloca partition's users.
3426///
3427/// This routine drives both of the rewriting goals of the SROA pass. It tries
3428/// to rewrite uses of an alloca partition to be conducive for SSA value
3429/// promotion. If the partition needs a new, more refined alloca, this will
3430/// build that new alloca, preserving as much type information as possible, and
3431/// rewrite the uses of the old alloca to point at the new one and have the
3432/// appropriate new offsets. It also evaluates how successful the rewrite was
3433/// at enabling promotion and if it was successful queues the alloca to be
3434/// promoted.
3435bool SROA::rewriteAllocaPartition(AllocaInst &AI,
3436 AllocaPartitioning &P,
3437 AllocaPartitioning::iterator PI) {
3438 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
Chandler Carruth6c3890b2012-10-02 18:57:13 +00003439 bool IsLive = false;
3440 for (AllocaPartitioning::use_iterator UI = P.use_begin(PI),
3441 UE = P.use_end(PI);
3442 UI != UE && !IsLive; ++UI)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00003443 if (UI->getUse())
Chandler Carruth6c3890b2012-10-02 18:57:13 +00003444 IsLive = true;
3445 if (!IsLive)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003446 return false; // No live uses left of this partition.
3447
Chandler Carruth82a57542012-10-01 10:54:05 +00003448 DEBUG(dbgs() << "Speculating PHIs and selects in partition "
3449 << "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
3450
3451 PHIOrSelectSpeculator Speculator(*TD, P, *this);
3452 DEBUG(dbgs() << " speculating ");
3453 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruth3903e052012-10-02 17:49:47 +00003454 Speculator.visitUsers(PI);
Chandler Carruth82a57542012-10-01 10:54:05 +00003455
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003456 // Try to compute a friendly type for this partition of the alloca. This
3457 // won't always succeed, in which case we fall back to a legal integer type
3458 // or an i8 array of an appropriate size.
3459 Type *AllocaTy = 0;
3460 if (Type *PartitionTy = P.getCommonType(PI))
3461 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
3462 AllocaTy = PartitionTy;
3463 if (!AllocaTy)
3464 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
3465 PI->BeginOffset, AllocaSize))
3466 AllocaTy = PartitionTy;
3467 if ((!AllocaTy ||
3468 (AllocaTy->isArrayTy() &&
3469 AllocaTy->getArrayElementType()->isIntegerTy())) &&
3470 TD->isLegalInteger(AllocaSize * 8))
3471 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
3472 if (!AllocaTy)
3473 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb0de6dd2012-09-14 10:26:34 +00003474 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003475
3476 // Check for the case where we're going to rewrite to a new alloca of the
3477 // exact same type as the original, and with the same access offsets. In that
3478 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003479 // perform phi and select speculation.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003480 AllocaInst *NewAI;
3481 if (AllocaTy == AI.getAllocatedType()) {
3482 assert(PI->BeginOffset == 0 &&
3483 "Non-zero begin offset but same alloca type");
3484 assert(PI == P.begin() && "Begin offset is zero on later partition");
3485 NewAI = &AI;
3486 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00003487 unsigned Alignment = AI.getAlignment();
3488 if (!Alignment) {
3489 // The minimum alignment which users can rely on when the explicit
3490 // alignment is omitted or zero is that required by the ABI for this
3491 // type.
3492 Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
3493 }
3494 Alignment = MinAlign(Alignment, PI->BeginOffset);
3495 // If we will get at least this much alignment from the type alone, leave
3496 // the alloca's alignment unconstrained.
3497 if (Alignment <= TD->getABITypeAlignment(AllocaTy))
3498 Alignment = 0;
3499 NewAI = new AllocaInst(AllocaTy, 0, Alignment,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003500 AI.getName() + ".sroa." + Twine(PI - P.begin()),
3501 &AI);
3502 ++NumNewAllocas;
3503 }
3504
3505 DEBUG(dbgs() << "Rewriting alloca partition "
3506 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
3507 << *NewAI << "\n");
3508
Chandler Carruthac8317f2012-10-04 12:33:50 +00003509 // Track the high watermark of the post-promotion worklist. We will reset it
3510 // to this point if the alloca is not in fact scheduled for promotion.
3511 unsigned PPWOldSize = PostPromotionWorklist.size();
3512
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003513 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
3514 PI->BeginOffset, PI->EndOffset);
3515 DEBUG(dbgs() << " rewriting ");
3516 DEBUG(P.print(dbgs(), PI, ""));
Chandler Carruthac8317f2012-10-04 12:33:50 +00003517 bool Promotable = Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI));
3518 if (Promotable) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003519 DEBUG(dbgs() << " and queuing for promotion\n");
3520 PromotableAllocas.push_back(NewAI);
3521 } else if (NewAI != &AI) {
3522 // If we can't promote the alloca, iterate on it to check for new
3523 // refinements exposed by splitting the current alloca. Don't iterate on an
3524 // alloca which didn't actually change and didn't get promoted.
3525 Worklist.insert(NewAI);
3526 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00003527
3528 // Drop any post-promotion work items if promotion didn't happen.
3529 if (!Promotable)
3530 while (PostPromotionWorklist.size() > PPWOldSize)
3531 PostPromotionWorklist.pop_back();
3532
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003533 return true;
3534}
3535
3536/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
3537bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
3538 bool Changed = false;
3539 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
3540 ++PI)
3541 Changed |= rewriteAllocaPartition(AI, P, PI);
3542
3543 return Changed;
3544}
3545
3546/// \brief Analyze an alloca for SROA.
3547///
3548/// This analyzes the alloca to ensure we can reason about it, builds
3549/// a partitioning of the alloca, and then hands it off to be split and
3550/// rewritten as needed.
3551bool SROA::runOnAlloca(AllocaInst &AI) {
3552 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
3553 ++NumAllocasAnalyzed;
3554
3555 // Special case dead allocas, as they're trivial.
3556 if (AI.use_empty()) {
3557 AI.eraseFromParent();
3558 return true;
3559 }
3560
3561 // Skip alloca forms that this analysis can't handle.
3562 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
3563 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
3564 return false;
3565
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003566 bool Changed = false;
3567
3568 // First, split any FCA loads and stores touching this alloca to promote
3569 // better splitting and promotion opportunities.
3570 AggLoadStoreRewriter AggRewriter(*TD);
3571 Changed |= AggRewriter.rewrite(AI);
3572
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003573 // Build the partition set using a recursive instruction-visiting builder.
3574 AllocaPartitioning P(*TD, AI);
3575 DEBUG(P.print(dbgs()));
3576 if (P.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003577 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003578
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003579 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003580 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
3581 DE = P.dead_user_end();
3582 DI != DE; ++DI) {
3583 Changed = true;
3584 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
Chandler Carruth18db7952012-11-20 01:12:50 +00003585 DeadInsts.insert(*DI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003586 }
3587 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
3588 DE = P.dead_op_end();
3589 DO != DE; ++DO) {
3590 Value *OldV = **DO;
3591 // Clobber the use with an undef value.
3592 **DO = UndefValue::get(OldV->getType());
3593 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
3594 if (isInstructionTriviallyDead(OldI)) {
3595 Changed = true;
Chandler Carruth18db7952012-11-20 01:12:50 +00003596 DeadInsts.insert(OldI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003597 }
3598 }
3599
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00003600 // No partitions to split. Leave the dead alloca for a later pass to clean up.
3601 if (P.begin() == P.end())
3602 return Changed;
3603
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003604 return splitAlloca(AI, P) || Changed;
3605}
3606
Chandler Carruth19450da2012-09-14 10:26:38 +00003607/// \brief Delete the dead instructions accumulated in this run.
3608///
3609/// Recursively deletes the dead instructions we've accumulated. This is done
3610/// at the very end to maximize locality of the recursive delete and to
3611/// minimize the problems of invalidated instruction pointers as such pointers
3612/// are used heavily in the intermediate stages of the algorithm.
3613///
3614/// We also record the alloca instructions deleted here so that they aren't
3615/// subsequently handed to mem2reg to promote.
3616void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003617 while (!DeadInsts.empty()) {
3618 Instruction *I = DeadInsts.pop_back_val();
3619 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
3620
Chandler Carruth58d05562012-10-25 04:37:07 +00003621 I->replaceAllUsesWith(UndefValue::get(I->getType()));
3622
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003623 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
3624 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
3625 // Zero out the operand and see if it becomes trivially dead.
3626 *OI = 0;
3627 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00003628 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003629 }
3630
3631 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3632 DeletedAllocas.insert(AI);
3633
3634 ++NumDeleted;
3635 I->eraseFromParent();
3636 }
3637}
3638
Chandler Carruth70b44c52012-09-15 11:43:14 +00003639/// \brief Promote the allocas, using the best available technique.
3640///
3641/// This attempts to promote whatever allocas have been identified as viable in
3642/// the PromotableAllocas list. If that list is empty, there is nothing to do.
3643/// If there is a domtree available, we attempt to promote using the full power
3644/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
3645/// based on the SSAUpdater utilities. This function returns whether any
Jakub Staszak086f6cd2013-02-19 22:02:21 +00003646/// promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00003647bool SROA::promoteAllocas(Function &F) {
3648 if (PromotableAllocas.empty())
3649 return false;
3650
3651 NumPromoted += PromotableAllocas.size();
3652
3653 if (DT && !ForceSSAUpdater) {
3654 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
3655 PromoteMemToReg(PromotableAllocas, *DT);
3656 PromotableAllocas.clear();
3657 return true;
3658 }
3659
3660 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
3661 SSAUpdater SSA;
3662 DIBuilder DIB(*F.getParent());
3663 SmallVector<Instruction*, 64> Insts;
3664
3665 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
3666 AllocaInst *AI = PromotableAllocas[Idx];
3667 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
3668 UI != UE;) {
3669 Instruction *I = cast<Instruction>(*UI++);
3670 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
3671 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
3672 // leading to them) here. Eventually it should use them to optimize the
3673 // scalar values produced.
3674 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
3675 assert(onlyUsedByLifetimeMarkers(I) &&
3676 "Found a bitcast used outside of a lifetime marker.");
3677 while (!I->use_empty())
3678 cast<Instruction>(*I->use_begin())->eraseFromParent();
3679 I->eraseFromParent();
3680 continue;
3681 }
3682 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
3683 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
3684 II->getIntrinsicID() == Intrinsic::lifetime_end);
3685 II->eraseFromParent();
3686 continue;
3687 }
3688
3689 Insts.push_back(I);
3690 }
3691 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
3692 Insts.clear();
3693 }
3694
3695 PromotableAllocas.clear();
3696 return true;
3697}
3698
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003699namespace {
3700 /// \brief A predicate to test whether an alloca belongs to a set.
3701 class IsAllocaInSet {
3702 typedef SmallPtrSet<AllocaInst *, 4> SetType;
3703 const SetType &Set;
3704
3705 public:
Chandler Carruth3f57b822012-10-03 00:03:00 +00003706 typedef AllocaInst *argument_type;
3707
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003708 IsAllocaInSet(const SetType &Set) : Set(Set) {}
Chandler Carruth3f57b822012-10-03 00:03:00 +00003709 bool operator()(AllocaInst *AI) const { return Set.count(AI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003710 };
3711}
3712
3713bool SROA::runOnFunction(Function &F) {
3714 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
3715 C = &F.getContext();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003716 TD = getAnalysisIfAvailable<DataLayout>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003717 if (!TD) {
3718 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
3719 return false;
3720 }
Chandler Carruth70b44c52012-09-15 11:43:14 +00003721 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003722
3723 BasicBlock &EntryBB = F.getEntryBlock();
3724 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
3725 I != E; ++I)
3726 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
3727 Worklist.insert(AI);
3728
3729 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00003730 // A set of deleted alloca instruction pointers which should be removed from
3731 // the list of promotable allocas.
3732 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
3733
Chandler Carruthac8317f2012-10-04 12:33:50 +00003734 do {
3735 while (!Worklist.empty()) {
3736 Changed |= runOnAlloca(*Worklist.pop_back_val());
3737 deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00003738
Chandler Carruthac8317f2012-10-04 12:33:50 +00003739 // Remove the deleted allocas from various lists so that we don't try to
3740 // continue processing them.
3741 if (!DeletedAllocas.empty()) {
3742 Worklist.remove_if(IsAllocaInSet(DeletedAllocas));
3743 PostPromotionWorklist.remove_if(IsAllocaInSet(DeletedAllocas));
3744 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
3745 PromotableAllocas.end(),
3746 IsAllocaInSet(DeletedAllocas)),
3747 PromotableAllocas.end());
3748 DeletedAllocas.clear();
3749 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003750 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003751
Chandler Carruthac8317f2012-10-04 12:33:50 +00003752 Changed |= promoteAllocas(F);
3753
3754 Worklist = PostPromotionWorklist;
3755 PostPromotionWorklist.clear();
3756 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003757
3758 return Changed;
3759}
3760
3761void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth70b44c52012-09-15 11:43:14 +00003762 if (RequiresDomTree)
3763 AU.addRequired<DominatorTree>();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003764 AU.setPreservesCFG();
3765}