blob: 6691059d355ee1a43e1f0693b290f16f6609f6f1 [file] [log] [blame]
Chandler Carruth713aa942012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
26#define DEBUG_TYPE "sroa"
27#include "llvm/Transforms/Scalar.h"
28#include "llvm/Constants.h"
29#include "llvm/DIBuilder.h"
30#include "llvm/DebugInfo.h"
31#include "llvm/DerivedTypes.h"
32#include "llvm/Function.h"
33#include "llvm/GlobalVariable.h"
34#include "llvm/IRBuilder.h"
35#include "llvm/Instructions.h"
36#include "llvm/IntrinsicInst.h"
37#include "llvm/LLVMContext.h"
38#include "llvm/Module.h"
39#include "llvm/Operator.h"
40#include "llvm/Pass.h"
41#include "llvm/ADT/SetVector.h"
42#include "llvm/ADT/SmallVector.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/TinyPtrVector.h"
46#include "llvm/Analysis/Dominators.h"
47#include "llvm/Analysis/Loads.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/Support/CallSite.h"
Chandler Carruth1c8db502012-09-15 11:43:14 +000050#include "llvm/Support/CommandLine.h"
Chandler Carruth713aa942012-09-14 09:22:59 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/GetElementPtrTypeIterator.h"
54#include "llvm/Support/InstVisitor.h"
55#include "llvm/Support/MathExtras.h"
56#include "llvm/Support/ValueHandle.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/Target/TargetData.h"
59#include "llvm/Transforms/Utils/Local.h"
60#include "llvm/Transforms/Utils/PromoteMemToReg.h"
61#include "llvm/Transforms/Utils/SSAUpdater.h"
62using namespace llvm;
63
64STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
65STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
66STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
67STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
68STATISTIC(NumDeleted, "Number of instructions deleted");
69STATISTIC(NumVectorized, "Number of vectorized aggregates");
70
Chandler Carruth1c8db502012-09-15 11:43:14 +000071/// Hidden option to force the pass to not use DomTree and mem2reg, instead
72/// forming SSA values through the SSAUpdater infrastructure.
73static cl::opt<bool>
74ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
75
Chandler Carruth713aa942012-09-14 09:22:59 +000076namespace {
77/// \brief Alloca partitioning representation.
78///
79/// This class represents a partitioning of an alloca into slices, and
80/// information about the nature of uses of each slice of the alloca. The goal
81/// is that this information is sufficient to decide if and how to split the
82/// alloca apart and replace slices with scalars. It is also intended that this
Chandler Carruth7f5bede2012-09-14 10:18:49 +000083/// structure can capture the relevant information needed both to decide about
Chandler Carruth713aa942012-09-14 09:22:59 +000084/// and to enact these transformations.
85class AllocaPartitioning {
86public:
87 /// \brief A common base class for representing a half-open byte range.
88 struct ByteRange {
89 /// \brief The beginning offset of the range.
90 uint64_t BeginOffset;
91
92 /// \brief The ending offset, not included in the range.
93 uint64_t EndOffset;
94
95 ByteRange() : BeginOffset(), EndOffset() {}
96 ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
97 : BeginOffset(BeginOffset), EndOffset(EndOffset) {}
98
99 /// \brief Support for ordering ranges.
100 ///
101 /// This provides an ordering over ranges such that start offsets are
102 /// always increasing, and within equal start offsets, the end offsets are
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000103 /// decreasing. Thus the spanning range comes first in a cluster with the
Chandler Carruth713aa942012-09-14 09:22:59 +0000104 /// same start position.
105 bool operator<(const ByteRange &RHS) const {
106 if (BeginOffset < RHS.BeginOffset) return true;
107 if (BeginOffset > RHS.BeginOffset) return false;
108 if (EndOffset > RHS.EndOffset) return true;
109 return false;
110 }
111
112 /// \brief Support comparison with a single offset to allow binary searches.
113 bool operator<(uint64_t RHSOffset) const {
114 return BeginOffset < RHSOffset;
115 }
116
117 bool operator==(const ByteRange &RHS) const {
118 return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
119 }
120 bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
121 };
122
123 /// \brief A partition of an alloca.
124 ///
125 /// This structure represents a contiguous partition of the alloca. These are
126 /// formed by examining the uses of the alloca. During formation, they may
127 /// overlap but once an AllocaPartitioning is built, the Partitions within it
128 /// are all disjoint.
129 struct Partition : public ByteRange {
130 /// \brief Whether this partition is splittable into smaller partitions.
131 ///
132 /// We flag partitions as splittable when they are formed entirely due to
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000133 /// accesses by trivially splittable operations such as memset and memcpy.
Chandler Carruth713aa942012-09-14 09:22:59 +0000134 ///
135 /// FIXME: At some point we should consider loads and stores of FCAs to be
136 /// splittable and eagerly split them into scalar values.
137 bool IsSplittable;
138
139 Partition() : ByteRange(), IsSplittable() {}
140 Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
141 : ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
142 };
143
144 /// \brief A particular use of a partition of the alloca.
145 ///
146 /// This structure is used to associate uses of a partition with it. They
147 /// mark the range of bytes which are referenced by a particular instruction,
148 /// and includes a handle to the user itself and the pointer value in use.
149 /// The bounds of these uses are determined by intersecting the bounds of the
150 /// memory use itself with a particular partition. As a consequence there is
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000151 /// intentionally overlap between various uses of the same partition.
Chandler Carruth713aa942012-09-14 09:22:59 +0000152 struct PartitionUse : public ByteRange {
153 /// \brief The user of this range of the alloca.
154 AssertingVH<Instruction> User;
155
156 /// \brief The particular pointer value derived from this alloca in use.
157 AssertingVH<Instruction> Ptr;
158
159 PartitionUse() : ByteRange(), User(), Ptr() {}
160 PartitionUse(uint64_t BeginOffset, uint64_t EndOffset,
161 Instruction *User, Instruction *Ptr)
162 : ByteRange(BeginOffset, EndOffset), User(User), Ptr(Ptr) {}
163 };
164
165 /// \brief Construct a partitioning of a particular alloca.
166 ///
167 /// Construction does most of the work for partitioning the alloca. This
168 /// performs the necessary walks of users and builds a partitioning from it.
169 AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
170
171 /// \brief Test whether a pointer to the allocation escapes our analysis.
172 ///
173 /// If this is true, the partitioning is never fully built and should be
174 /// ignored.
175 bool isEscaped() const { return PointerEscapingInstr; }
176
177 /// \brief Support for iterating over the partitions.
178 /// @{
179 typedef SmallVectorImpl<Partition>::iterator iterator;
180 iterator begin() { return Partitions.begin(); }
181 iterator end() { return Partitions.end(); }
182
183 typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
184 const_iterator begin() const { return Partitions.begin(); }
185 const_iterator end() const { return Partitions.end(); }
186 /// @}
187
188 /// \brief Support for iterating over and manipulating a particular
189 /// partition's uses.
190 ///
191 /// The iteration support provided for uses is more limited, but also
192 /// includes some manipulation routines to support rewriting the uses of
193 /// partitions during SROA.
194 /// @{
195 typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
196 use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
197 use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
198 use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
199 use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
200 void use_insert(unsigned Idx, use_iterator UI, const PartitionUse &U) {
201 Uses[Idx].insert(UI, U);
202 }
203 void use_insert(const_iterator I, use_iterator UI, const PartitionUse &U) {
204 Uses[I - begin()].insert(UI, U);
205 }
206 void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
207 void use_erase(const_iterator I, use_iterator UI) {
208 Uses[I - begin()].erase(UI);
209 }
210
211 typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
212 const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
213 const_use_iterator use_begin(const_iterator I) const {
214 return Uses[I - begin()].begin();
215 }
216 const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
217 const_use_iterator use_end(const_iterator I) const {
218 return Uses[I - begin()].end();
219 }
220 /// @}
221
222 /// \brief Allow iterating the dead users for this alloca.
223 ///
224 /// These are instructions which will never actually use the alloca as they
225 /// are outside the allocated range. They are safe to replace with undef and
226 /// delete.
227 /// @{
228 typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
229 dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
230 dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
231 /// @}
232
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000233 /// \brief Allow iterating the dead expressions referring to this alloca.
Chandler Carruth713aa942012-09-14 09:22:59 +0000234 ///
235 /// These are operands which have cannot actually be used to refer to the
236 /// alloca as they are outside its range and the user doesn't correct for
237 /// that. These mostly consist of PHI node inputs and the like which we just
238 /// need to replace with undef.
239 /// @{
240 typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
241 dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
242 dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
243 /// @}
244
245 /// \brief MemTransferInst auxiliary data.
246 /// This struct provides some auxiliary data about memory transfer
247 /// intrinsics such as memcpy and memmove. These intrinsics can use two
248 /// different ranges within the same alloca, and provide other challenges to
249 /// correctly represent. We stash extra data to help us untangle this
250 /// after the partitioning is complete.
251 struct MemTransferOffsets {
252 uint64_t DestBegin, DestEnd;
253 uint64_t SourceBegin, SourceEnd;
254 bool IsSplittable;
255 };
256 MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
257 return MemTransferInstData.lookup(&II);
258 }
259
260 /// \brief Map from a PHI or select operand back to a partition.
261 ///
262 /// When manipulating PHI nodes or selects, they can use more than one
263 /// partition of an alloca. We store a special mapping to allow finding the
264 /// partition referenced by each of these operands, if any.
265 iterator findPartitionForPHIOrSelectOperand(Instruction &I, Value *Op) {
266 SmallDenseMap<std::pair<Instruction *, Value *>,
267 std::pair<unsigned, unsigned> >::const_iterator MapIt
268 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
269 if (MapIt == PHIOrSelectOpMap.end())
270 return end();
271
272 return begin() + MapIt->second.first;
273 }
274
275 /// \brief Map from a PHI or select operand back to the specific use of
276 /// a partition.
277 ///
278 /// Similar to mapping these operands back to the partitions, this maps
279 /// directly to the use structure of that partition.
280 use_iterator findPartitionUseForPHIOrSelectOperand(Instruction &I,
281 Value *Op) {
282 SmallDenseMap<std::pair<Instruction *, Value *>,
283 std::pair<unsigned, unsigned> >::const_iterator MapIt
284 = PHIOrSelectOpMap.find(std::make_pair(&I, Op));
285 assert(MapIt != PHIOrSelectOpMap.end());
286 return Uses[MapIt->second.first].begin() + MapIt->second.second;
287 }
288
289 /// \brief Compute a common type among the uses of a particular partition.
290 ///
291 /// This routines walks all of the uses of a particular partition and tries
292 /// to find a common type between them. Untyped operations such as memset and
293 /// memcpy are ignored.
294 Type *getCommonType(iterator I) const;
295
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000296#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth713aa942012-09-14 09:22:59 +0000297 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
298 void printUsers(raw_ostream &OS, const_iterator I,
299 StringRef Indent = " ") const;
300 void print(raw_ostream &OS) const;
NAKAMURA Takumiad9f5b82012-09-14 10:06:10 +0000301 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
302 void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
Chandler Carruthba13d2e2012-09-14 10:18:51 +0000303#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000304
305private:
306 template <typename DerivedT, typename RetT = void> class BuilderBase;
307 class PartitionBuilder;
308 friend class AllocaPartitioning::PartitionBuilder;
309 class UseBuilder;
310 friend class AllocaPartitioning::UseBuilder;
311
Benjamin Kramerd0807692012-09-14 13:08:09 +0000312#ifndef NDEBUG
Chandler Carruth713aa942012-09-14 09:22:59 +0000313 /// \brief Handle to alloca instruction to simplify method interfaces.
314 AllocaInst &AI;
Benjamin Kramerd0807692012-09-14 13:08:09 +0000315#endif
Chandler Carruth713aa942012-09-14 09:22:59 +0000316
317 /// \brief The instruction responsible for this alloca having no partitioning.
318 ///
319 /// When an instruction (potentially) escapes the pointer to the alloca, we
320 /// store a pointer to that here and abort trying to partition the alloca.
321 /// This will be null if the alloca is partitioned successfully.
322 Instruction *PointerEscapingInstr;
323
324 /// \brief The partitions of the alloca.
325 ///
326 /// We store a vector of the partitions over the alloca here. This vector is
327 /// sorted by increasing begin offset, and then by decreasing end offset. See
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000328 /// the Partition inner class for more details. Initially (during
329 /// construction) there are overlaps, but we form a disjoint sequence of
330 /// partitions while finishing construction and a fully constructed object is
331 /// expected to always have this as a disjoint space.
Chandler Carruth713aa942012-09-14 09:22:59 +0000332 SmallVector<Partition, 8> Partitions;
333
334 /// \brief The uses of the partitions.
335 ///
336 /// This is essentially a mapping from each partition to a list of uses of
337 /// that partition. The mapping is done with a Uses vector that has the exact
338 /// same number of entries as the partition vector. Each entry is itself
339 /// a vector of the uses.
340 SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
341
342 /// \brief Instructions which will become dead if we rewrite the alloca.
343 ///
344 /// Note that these are not separated by partition. This is because we expect
345 /// a partitioned alloca to be completely rewritten or not rewritten at all.
346 /// If rewritten, all these instructions can simply be removed and replaced
347 /// with undef as they come from outside of the allocated space.
348 SmallVector<Instruction *, 8> DeadUsers;
349
350 /// \brief Operands which will become dead if we rewrite the alloca.
351 ///
352 /// These are operands that in their particular use can be replaced with
353 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
354 /// to PHI nodes and the like. They aren't entirely dead (there might be
355 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
356 /// want to swap this particular input for undef to simplify the use lists of
357 /// the alloca.
358 SmallVector<Use *, 8> DeadOperands;
359
360 /// \brief The underlying storage for auxiliary memcpy and memset info.
361 SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
362
363 /// \brief A side datastructure used when building up the partitions and uses.
364 ///
365 /// This mapping is only really used during the initial building of the
366 /// partitioning so that we can retain information about PHI and select nodes
367 /// processed.
368 SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
369
370 /// \brief Auxiliary information for particular PHI or select operands.
371 SmallDenseMap<std::pair<Instruction *, Value *>,
372 std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
373
374 /// \brief A utility routine called from the constructor.
375 ///
376 /// This does what it says on the tin. It is the key of the alloca partition
377 /// splitting and merging. After it is called we have the desired disjoint
378 /// collection of partitions.
379 void splitAndMergePartitions();
380};
381}
382
383template <typename DerivedT, typename RetT>
384class AllocaPartitioning::BuilderBase
385 : public InstVisitor<DerivedT, RetT> {
386public:
387 BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
388 : TD(TD),
389 AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
390 P(P) {
391 enqueueUsers(AI, 0);
392 }
393
394protected:
395 const TargetData &TD;
396 const uint64_t AllocSize;
397 AllocaPartitioning &P;
398
399 struct OffsetUse {
400 Use *U;
401 uint64_t Offset;
402 };
403 SmallVector<OffsetUse, 8> Queue;
404
405 // The active offset and use while visiting.
406 Use *U;
407 uint64_t Offset;
408
409 void enqueueUsers(Instruction &I, uint64_t UserOffset) {
410 SmallPtrSet<User *, 8> UserSet;
411 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
412 UI != UE; ++UI) {
413 if (!UserSet.insert(*UI))
414 continue;
415
416 OffsetUse OU = { &UI.getUse(), UserOffset };
417 Queue.push_back(OU);
418 }
419 }
420
421 bool computeConstantGEPOffset(GetElementPtrInst &GEPI, uint64_t &GEPOffset) {
422 GEPOffset = Offset;
423 for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
424 GTI != GTE; ++GTI) {
425 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
426 if (!OpC)
427 return false;
428 if (OpC->isZero())
429 continue;
430
431 // Handle a struct index, which adds its field offset to the pointer.
432 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
433 unsigned ElementIdx = OpC->getZExtValue();
434 const StructLayout *SL = TD.getStructLayout(STy);
435 GEPOffset += SL->getElementOffset(ElementIdx);
436 continue;
437 }
438
439 GEPOffset
440 += OpC->getZExtValue() * TD.getTypeAllocSize(GTI.getIndexedType());
441 }
442 return true;
443 }
444
445 Value *foldSelectInst(SelectInst &SI) {
446 // If the condition being selected on is a constant or the same value is
447 // being selected between, fold the select. Yes this does (rarely) happen
448 // early on.
449 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
450 return SI.getOperand(1+CI->isZero());
451 if (SI.getOperand(1) == SI.getOperand(2)) {
452 assert(*U == SI.getOperand(1));
453 return SI.getOperand(1);
454 }
455 return 0;
456 }
457};
458
459/// \brief Builder for the alloca partitioning.
460///
461/// This class builds an alloca partitioning by recursively visiting the uses
462/// of an alloca and splitting the partitions for each load and store at each
463/// offset.
464class AllocaPartitioning::PartitionBuilder
465 : public BuilderBase<PartitionBuilder, bool> {
466 friend class InstVisitor<PartitionBuilder, bool>;
467
468 SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
469
470public:
471 PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000472 : BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000473
474 /// \brief Run the builder over the allocation.
475 bool operator()() {
476 // Note that we have to re-evaluate size on each trip through the loop as
477 // the queue grows at the tail.
478 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
479 U = Queue[Idx].U;
480 Offset = Queue[Idx].Offset;
481 if (!visit(cast<Instruction>(U->getUser())))
482 return false;
483 }
484 return true;
485 }
486
487private:
488 bool markAsEscaping(Instruction &I) {
489 P.PointerEscapingInstr = &I;
490 return false;
491 }
492
493 void insertUse(Instruction &I, uint64_t Size, bool IsSplittable = false) {
494 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
495
496 // Completely skip uses which start outside of the allocation.
497 if (BeginOffset >= AllocSize) {
498 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
499 << " which starts past the end of the " << AllocSize
500 << " byte alloca:\n"
501 << " alloca: " << P.AI << "\n"
502 << " use: " << I << "\n");
503 return;
504 }
505
506 // Clamp the size to the allocation.
507 if (EndOffset > AllocSize) {
508 DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
509 << " to remain within the " << AllocSize << " byte alloca:\n"
510 << " alloca: " << P.AI << "\n"
511 << " use: " << I << "\n");
512 EndOffset = AllocSize;
513 }
514
515 // See if we can just add a user onto the last slot currently occupied.
516 if (!P.Partitions.empty() &&
517 P.Partitions.back().BeginOffset == BeginOffset &&
518 P.Partitions.back().EndOffset == EndOffset) {
519 P.Partitions.back().IsSplittable &= IsSplittable;
520 return;
521 }
522
523 Partition New(BeginOffset, EndOffset, IsSplittable);
524 P.Partitions.push_back(New);
525 }
526
527 bool handleLoadOrStore(Type *Ty, Instruction &I) {
528 uint64_t Size = TD.getTypeStoreSize(Ty);
529
530 // If this memory access can be shown to *statically* extend outside the
531 // bounds of of the allocation, it's behavior is undefined, so simply
532 // ignore it. Note that this is more strict than the generic clamping
533 // behavior of insertUse. We also try to handle cases which might run the
534 // risk of overflow.
535 // FIXME: We should instead consider the pointer to have escaped if this
536 // function is being instrumented for addressing bugs or race conditions.
537 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize) {
538 DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
539 << (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
540 << " which extends past the end of the " << AllocSize
541 << " byte alloca:\n"
542 << " alloca: " << P.AI << "\n"
543 << " use: " << I << "\n");
544 return true;
545 }
546
547 insertUse(I, Size);
548 return true;
549 }
550
551 bool visitBitCastInst(BitCastInst &BC) {
552 enqueueUsers(BC, Offset);
553 return true;
554 }
555
556 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
Chandler Carruth713aa942012-09-14 09:22:59 +0000557 uint64_t GEPOffset;
558 if (!computeConstantGEPOffset(GEPI, GEPOffset))
559 return markAsEscaping(GEPI);
560
561 enqueueUsers(GEPI, GEPOffset);
562 return true;
563 }
564
565 bool visitLoadInst(LoadInst &LI) {
566 return handleLoadOrStore(LI.getType(), LI);
567 }
568
569 bool visitStoreInst(StoreInst &SI) {
570 if (SI.getOperand(0) == *U)
571 return markAsEscaping(SI);
572
573 return handleLoadOrStore(SI.getOperand(0)->getType(), SI);
574 }
575
576
577 bool visitMemSetInst(MemSetInst &II) {
Chandler Carruthb3dd9a12012-09-14 10:26:34 +0000578 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth713aa942012-09-14 09:22:59 +0000579 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
580 insertUse(II, Length ? Length->getZExtValue() : AllocSize - Offset, Length);
581 return true;
582 }
583
584 bool visitMemTransferInst(MemTransferInst &II) {
585 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
586 uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
587 if (!Size)
588 // Zero-length mem transfer intrinsics can be ignored entirely.
589 return true;
590
591 MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
592
593 // Only intrinsics with a constant length can be split.
594 Offsets.IsSplittable = Length;
595
596 if (*U != II.getRawDest()) {
597 assert(*U == II.getRawSource());
598 Offsets.SourceBegin = Offset;
599 Offsets.SourceEnd = Offset + Size;
600 } else {
601 Offsets.DestBegin = Offset;
602 Offsets.DestEnd = Offset + Size;
603 }
604
605 insertUse(II, Size, Offsets.IsSplittable);
606 unsigned NewIdx = P.Partitions.size() - 1;
607
608 SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
609 bool Inserted = false;
610 llvm::tie(PMI, Inserted)
611 = MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
612 if (!Inserted && Offsets.IsSplittable) {
613 // We've found a memory transfer intrinsic which refers to the alloca as
614 // both a source and dest. We refuse to split these to simplify splitting
615 // logic. If possible, SROA will still split them into separate allocas
616 // and then re-analyze.
617 Offsets.IsSplittable = false;
618 P.Partitions[PMI->second].IsSplittable = false;
619 P.Partitions[NewIdx].IsSplittable = false;
620 }
621
622 return true;
623 }
624
625 // Disable SRoA for any intrinsics except for lifetime invariants.
Chandler Carruth50754f02012-09-14 10:26:36 +0000626 // FIXME: What about debug instrinsics? This matches old behavior, but
627 // doesn't make sense.
Chandler Carruth713aa942012-09-14 09:22:59 +0000628 bool visitIntrinsicInst(IntrinsicInst &II) {
629 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
630 II.getIntrinsicID() == Intrinsic::lifetime_end) {
631 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
632 uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
633 insertUse(II, Size, true);
634 return true;
635 }
636
637 return markAsEscaping(II);
638 }
639
640 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
641 // We consider any PHI or select that results in a direct load or store of
642 // the same offset to be a viable use for partitioning purposes. These uses
643 // are considered unsplittable and the size is the maximum loaded or stored
644 // size.
645 SmallPtrSet<Instruction *, 4> Visited;
646 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
647 Visited.insert(Root);
648 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
649 do {
650 Instruction *I, *UsedI;
651 llvm::tie(UsedI, I) = Uses.pop_back_val();
652
653 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
654 Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
655 continue;
656 }
657 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
658 Value *Op = SI->getOperand(0);
659 if (Op == UsedI)
660 return SI;
661 Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
662 continue;
663 }
664
665 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
666 if (!GEP->hasAllZeroIndices())
667 return GEP;
668 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
669 !isa<SelectInst>(I)) {
670 return I;
671 }
672
673 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
674 ++UI)
675 if (Visited.insert(cast<Instruction>(*UI)))
676 Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
677 } while (!Uses.empty());
678
679 return 0;
680 }
681
682 bool visitPHINode(PHINode &PN) {
683 // See if we already have computed info on this node.
684 std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
685 if (PHIInfo.first) {
686 PHIInfo.second = true;
687 insertUse(PN, PHIInfo.first);
688 return true;
689 }
690
691 // Check for an unsafe use of the PHI node.
692 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
693 return markAsEscaping(*EscapingI);
694
695 insertUse(PN, PHIInfo.first);
696 return true;
697 }
698
699 bool visitSelectInst(SelectInst &SI) {
700 if (Value *Result = foldSelectInst(SI)) {
701 if (Result == *U)
702 // If the result of the constant fold will be the pointer, recurse
703 // through the select as if we had RAUW'ed it.
704 enqueueUsers(SI, Offset);
705
706 return true;
707 }
708
709 // See if we already have computed info on this node.
710 std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
711 if (SelectInfo.first) {
712 SelectInfo.second = true;
713 insertUse(SI, SelectInfo.first);
714 return true;
715 }
716
717 // Check for an unsafe use of the PHI node.
718 if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
719 return markAsEscaping(*EscapingI);
720
721 insertUse(SI, SelectInfo.first);
722 return true;
723 }
724
725 /// \brief Disable SROA entirely if there are unhandled users of the alloca.
726 bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
727};
728
729
730/// \brief Use adder for the alloca partitioning.
731///
Chandler Carruth7f5bede2012-09-14 10:18:49 +0000732/// This class adds the uses of an alloca to all of the partitions which they
733/// use. For splittable partitions, this can end up doing essentially a linear
Chandler Carruth713aa942012-09-14 09:22:59 +0000734/// walk of the partitions, but the number of steps remains bounded by the
735/// total result instruction size:
736/// - The number of partitions is a result of the number unsplittable
737/// instructions using the alloca.
738/// - The number of users of each partition is at worst the total number of
739/// splittable instructions using the alloca.
740/// Thus we will produce N * M instructions in the end, where N are the number
741/// of unsplittable uses and M are the number of splittable. This visitor does
742/// the exact same number of updates to the partitioning.
743///
744/// In the more common case, this visitor will leverage the fact that the
745/// partition space is pre-sorted, and do a logarithmic search for the
746/// partition needed, making the total visit a classical ((N + M) * log(N))
747/// complexity operation.
748class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
749 friend class InstVisitor<UseBuilder>;
750
751 /// \brief Set to de-duplicate dead instructions found in the use walk.
752 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
753
754public:
755 UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
Chandler Carruth2a9bf252012-09-14 09:30:33 +0000756 : BuilderBase<UseBuilder>(TD, AI, P) {}
Chandler Carruth713aa942012-09-14 09:22:59 +0000757
758 /// \brief Run the builder over the allocation.
759 void operator()() {
760 // Note that we have to re-evaluate size on each trip through the loop as
761 // the queue grows at the tail.
762 for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
763 U = Queue[Idx].U;
764 Offset = Queue[Idx].Offset;
765 this->visit(cast<Instruction>(U->getUser()));
766 }
767 }
768
769private:
770 void markAsDead(Instruction &I) {
771 if (VisitedDeadInsts.insert(&I))
772 P.DeadUsers.push_back(&I);
773 }
774
775 void insertUse(uint64_t Size, Instruction &User) {
776 uint64_t BeginOffset = Offset, EndOffset = Offset + Size;
777
778 // If the use extends outside of the allocation, record it as a dead use
779 // for elimination later.
780 if (BeginOffset >= AllocSize || Size == 0)
781 return markAsDead(User);
782
783 // Bound the use by the size of the allocation.
784 if (EndOffset > AllocSize)
785 EndOffset = AllocSize;
786
787 // NB: This only works if we have zero overlapping partitions.
788 iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
789 if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
790 B = llvm::prior(B);
791 for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
792 ++I) {
793 PartitionUse NewUse(std::max(I->BeginOffset, BeginOffset),
794 std::min(I->EndOffset, EndOffset),
795 &User, cast<Instruction>(*U));
796 P.Uses[I - P.begin()].push_back(NewUse);
797 if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
798 P.PHIOrSelectOpMap[std::make_pair(&User, U->get())]
799 = std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
800 }
801 }
802
803 void handleLoadOrStore(Type *Ty, Instruction &I) {
804 uint64_t Size = TD.getTypeStoreSize(Ty);
805
806 // If this memory access can be shown to *statically* extend outside the
807 // bounds of of the allocation, it's behavior is undefined, so simply
808 // ignore it. Note that this is more strict than the generic clamping
809 // behavior of insertUse.
810 if (Offset >= AllocSize || Size > AllocSize || Offset + Size > AllocSize)
811 return markAsDead(I);
812
813 insertUse(Size, I);
814 }
815
816 void visitBitCastInst(BitCastInst &BC) {
817 if (BC.use_empty())
818 return markAsDead(BC);
819
820 enqueueUsers(BC, Offset);
821 }
822
823 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
824 if (GEPI.use_empty())
825 return markAsDead(GEPI);
826
Chandler Carruth713aa942012-09-14 09:22:59 +0000827 uint64_t GEPOffset;
828 if (!computeConstantGEPOffset(GEPI, GEPOffset))
829 llvm_unreachable("Unable to compute constant offset for use");
830
831 enqueueUsers(GEPI, GEPOffset);
832 }
833
834 void visitLoadInst(LoadInst &LI) {
835 handleLoadOrStore(LI.getType(), LI);
836 }
837
838 void visitStoreInst(StoreInst &SI) {
839 handleLoadOrStore(SI.getOperand(0)->getType(), SI);
840 }
841
842 void visitMemSetInst(MemSetInst &II) {
843 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
844 insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
845 }
846
847 void visitMemTransferInst(MemTransferInst &II) {
848 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
849 insertUse(Length ? Length->getZExtValue() : AllocSize - Offset, II);
850 }
851
852 void visitIntrinsicInst(IntrinsicInst &II) {
853 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
854 II.getIntrinsicID() == Intrinsic::lifetime_end);
855
856 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
857 insertUse(std::min(AllocSize - Offset, Length->getLimitedValue()), II);
858 }
859
860 void insertPHIOrSelect(Instruction &User) {
861 uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
862
863 // For PHI and select operands outside the alloca, we can't nuke the entire
864 // phi or select -- the other side might still be relevant, so we special
865 // case them here and use a separate structure to track the operands
866 // themselves which should be replaced with undef.
867 if (Offset >= AllocSize) {
868 P.DeadOperands.push_back(U);
869 return;
870 }
871
872 insertUse(Size, User);
873 }
874 void visitPHINode(PHINode &PN) {
875 if (PN.use_empty())
876 return markAsDead(PN);
877
878 insertPHIOrSelect(PN);
879 }
880 void visitSelectInst(SelectInst &SI) {
881 if (SI.use_empty())
882 return markAsDead(SI);
883
884 if (Value *Result = foldSelectInst(SI)) {
885 if (Result == *U)
886 // If the result of the constant fold will be the pointer, recurse
887 // through the select as if we had RAUW'ed it.
888 enqueueUsers(SI, Offset);
889
890 return;
891 }
892
893 insertPHIOrSelect(SI);
894 }
895
896 /// \brief Unreachable, we've already visited the alloca once.
897 void visitInstruction(Instruction &I) {
898 llvm_unreachable("Unhandled instruction in use builder.");
899 }
900};
901
902void AllocaPartitioning::splitAndMergePartitions() {
903 size_t NumDeadPartitions = 0;
904
905 // Track the range of splittable partitions that we pass when accumulating
906 // overlapping unsplittable partitions.
907 uint64_t SplitEndOffset = 0ull;
908
909 Partition New(0ull, 0ull, false);
910
911 for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
912 ++j;
913
914 if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
915 assert(New.BeginOffset == New.EndOffset);
916 New = Partitions[i];
917 } else {
918 assert(New.IsSplittable);
919 New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
920 }
921 assert(New.BeginOffset != New.EndOffset);
922
923 // Scan the overlapping partitions.
924 while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
925 // If the new partition we are forming is splittable, stop at the first
926 // unsplittable partition.
927 if (New.IsSplittable && !Partitions[j].IsSplittable)
928 break;
929
930 // Grow the new partition to include any equally splittable range. 'j' is
931 // always equally splittable when New is splittable, but when New is not
932 // splittable, we may subsume some (or part of some) splitable partition
933 // without growing the new one.
934 if (New.IsSplittable == Partitions[j].IsSplittable) {
935 New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
936 } else {
937 assert(!New.IsSplittable);
938 assert(Partitions[j].IsSplittable);
939 SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
940 }
941
942 Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
943 ++NumDeadPartitions;
944 ++j;
945 }
946
947 // If the new partition is splittable, chop off the end as soon as the
948 // unsplittable subsequent partition starts and ensure we eventually cover
949 // the splittable area.
950 if (j != e && New.IsSplittable) {
951 SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
952 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
953 }
954
955 // Add the new partition if it differs from the original one and is
956 // non-empty. We can end up with an empty partition here if it was
957 // splittable but there is an unsplittable one that starts at the same
958 // offset.
959 if (New != Partitions[i]) {
960 if (New.BeginOffset != New.EndOffset)
961 Partitions.push_back(New);
962 // Mark the old one for removal.
963 Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
964 ++NumDeadPartitions;
965 }
966
967 New.BeginOffset = New.EndOffset;
968 if (!New.IsSplittable) {
969 New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
970 if (j != e && !Partitions[j].IsSplittable)
971 New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
972 New.IsSplittable = true;
973 // If there is a trailing splittable partition which won't be fused into
974 // the next splittable partition go ahead and add it onto the partitions
975 // list.
976 if (New.BeginOffset < New.EndOffset &&
977 (j == e || !Partitions[j].IsSplittable ||
978 New.EndOffset < Partitions[j].BeginOffset)) {
979 Partitions.push_back(New);
980 New.BeginOffset = New.EndOffset = 0ull;
981 }
982 }
983 }
984
985 // Re-sort the partitions now that they have been split and merged into
986 // disjoint set of partitions. Also remove any of the dead partitions we've
987 // replaced in the process.
988 std::sort(Partitions.begin(), Partitions.end());
989 if (NumDeadPartitions) {
990 assert(Partitions.back().BeginOffset == UINT64_MAX);
991 assert(Partitions.back().EndOffset == UINT64_MAX);
992 assert((ptrdiff_t)NumDeadPartitions ==
993 std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
994 }
995 Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
996}
997
998AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
Benjamin Kramerd0807692012-09-14 13:08:09 +0000999 :
1000#ifndef NDEBUG
1001 AI(AI),
1002#endif
1003 PointerEscapingInstr(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001004 PartitionBuilder PB(TD, AI, *this);
1005 if (!PB())
1006 return;
1007
1008 if (Partitions.size() > 1) {
1009 // Sort the uses. This arranges for the offsets to be in ascending order,
1010 // and the sizes to be in descending order.
1011 std::sort(Partitions.begin(), Partitions.end());
1012
1013 // Intersect splittability for all partitions with equal offsets and sizes.
1014 // Then remove all but the first so that we have a sequence of non-equal but
1015 // potentially overlapping partitions.
1016 for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
1017 I = J) {
1018 ++J;
1019 while (J != E && *I == *J) {
1020 I->IsSplittable &= J->IsSplittable;
1021 ++J;
1022 }
1023 }
1024 Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
1025 Partitions.end());
1026
1027 // Split splittable and merge unsplittable partitions into a disjoint set
1028 // of partitions over the used space of the allocation.
1029 splitAndMergePartitions();
1030 }
1031
1032 // Now build up the user lists for each of these disjoint partitions by
1033 // re-walking the recursive users of the alloca.
1034 Uses.resize(Partitions.size());
1035 UseBuilder UB(TD, AI, *this);
1036 UB();
1037 for (iterator I = Partitions.begin(), E = Partitions.end(); I != E; ++I)
1038 std::stable_sort(use_begin(I), use_end(I));
1039}
1040
1041Type *AllocaPartitioning::getCommonType(iterator I) const {
1042 Type *Ty = 0;
1043 for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
1044 if (isa<MemIntrinsic>(*UI->User))
1045 continue;
1046 if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
1047 break;
1048
1049 Type *UserTy = 0;
1050 if (LoadInst *LI = dyn_cast<LoadInst>(&*UI->User)) {
1051 UserTy = LI->getType();
1052 } else if (StoreInst *SI = dyn_cast<StoreInst>(&*UI->User)) {
1053 UserTy = SI->getValueOperand()->getType();
1054 } else if (SelectInst *SI = dyn_cast<SelectInst>(&*UI->User)) {
1055 if (PointerType *PtrTy = dyn_cast<PointerType>(SI->getType()))
1056 UserTy = PtrTy->getElementType();
1057 } else if (PHINode *PN = dyn_cast<PHINode>(&*UI->User)) {
1058 if (PointerType *PtrTy = dyn_cast<PointerType>(PN->getType()))
1059 UserTy = PtrTy->getElementType();
1060 }
1061
1062 if (Ty && Ty != UserTy)
1063 return 0;
1064
1065 Ty = UserTy;
1066 }
1067 return Ty;
1068}
1069
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001070#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1071
Chandler Carruth713aa942012-09-14 09:22:59 +00001072void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
1073 StringRef Indent) const {
1074 OS << Indent << "partition #" << (I - begin())
1075 << " [" << I->BeginOffset << "," << I->EndOffset << ")"
1076 << (I->IsSplittable ? " (splittable)" : "")
1077 << (Uses[I - begin()].empty() ? " (zero uses)" : "")
1078 << "\n";
1079}
1080
1081void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
1082 StringRef Indent) const {
1083 for (const_use_iterator UI = use_begin(I), UE = use_end(I);
1084 UI != UE; ++UI) {
1085 OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
1086 << "used by: " << *UI->User << "\n";
1087 if (MemTransferInst *II = dyn_cast<MemTransferInst>(&*UI->User)) {
1088 const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
1089 bool IsDest;
1090 if (!MTO.IsSplittable)
1091 IsDest = UI->BeginOffset == MTO.DestBegin;
1092 else
1093 IsDest = MTO.DestBegin != 0u;
1094 OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
1095 << "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
1096 << "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
1097 }
1098 }
1099}
1100
1101void AllocaPartitioning::print(raw_ostream &OS) const {
1102 if (PointerEscapingInstr) {
1103 OS << "No partitioning for alloca: " << AI << "\n"
1104 << " A pointer to this alloca escaped by:\n"
1105 << " " << *PointerEscapingInstr << "\n";
1106 return;
1107 }
1108
1109 OS << "Partitioning of alloca: " << AI << "\n";
1110 unsigned Num = 0;
1111 for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
1112 print(OS, I);
1113 printUsers(OS, I);
1114 }
1115}
1116
1117void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
1118void AllocaPartitioning::dump() const { print(dbgs()); }
1119
Chandler Carruthba13d2e2012-09-14 10:18:51 +00001120#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1121
Chandler Carruth713aa942012-09-14 09:22:59 +00001122
1123namespace {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001124/// \brief Implementation of LoadAndStorePromoter for promoting allocas.
1125///
1126/// This subclass of LoadAndStorePromoter adds overrides to handle promoting
1127/// the loads and stores of an alloca instruction, as well as updating its
1128/// debug information. This is used when a domtree is unavailable and thus
1129/// mem2reg in its full form can't be used to handle promotion of allocas to
1130/// scalar values.
1131class AllocaPromoter : public LoadAndStorePromoter {
1132 AllocaInst &AI;
1133 DIBuilder &DIB;
1134
1135 SmallVector<DbgDeclareInst *, 4> DDIs;
1136 SmallVector<DbgValueInst *, 4> DVIs;
1137
1138public:
1139 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
1140 AllocaInst &AI, DIBuilder &DIB)
1141 : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
1142
1143 void run(const SmallVectorImpl<Instruction*> &Insts) {
1144 // Remember which alloca we're promoting (for isInstInList).
1145 if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
1146 for (Value::use_iterator UI = DebugNode->use_begin(),
1147 UE = DebugNode->use_end();
1148 UI != UE; ++UI)
1149 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
1150 DDIs.push_back(DDI);
1151 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
1152 DVIs.push_back(DVI);
1153 }
1154
1155 LoadAndStorePromoter::run(Insts);
1156 AI.eraseFromParent();
1157 while (!DDIs.empty())
1158 DDIs.pop_back_val()->eraseFromParent();
1159 while (!DVIs.empty())
1160 DVIs.pop_back_val()->eraseFromParent();
1161 }
1162
1163 virtual bool isInstInList(Instruction *I,
1164 const SmallVectorImpl<Instruction*> &Insts) const {
1165 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1166 return LI->getOperand(0) == &AI;
1167 return cast<StoreInst>(I)->getPointerOperand() == &AI;
1168 }
1169
1170 virtual void updateDebugInfo(Instruction *Inst) const {
1171 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
1172 E = DDIs.end(); I != E; ++I) {
1173 DbgDeclareInst *DDI = *I;
1174 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1175 ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
1176 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1177 ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
1178 }
1179 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
1180 E = DVIs.end(); I != E; ++I) {
1181 DbgValueInst *DVI = *I;
1182 Value *Arg = NULL;
1183 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1184 // If an argument is zero extended then use argument directly. The ZExt
1185 // may be zapped by an optimization pass in future.
1186 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
1187 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
1188 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
1189 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1190 if (!Arg)
1191 Arg = SI->getOperand(0);
1192 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1193 Arg = LI->getOperand(0);
1194 } else {
1195 continue;
1196 }
1197 Instruction *DbgVal =
1198 DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
1199 Inst);
1200 DbgVal->setDebugLoc(DVI->getDebugLoc());
1201 }
1202 }
1203};
1204} // end anon namespace
1205
1206
1207namespace {
Chandler Carruth713aa942012-09-14 09:22:59 +00001208/// \brief An optimization pass providing Scalar Replacement of Aggregates.
1209///
1210/// This pass takes allocations which can be completely analyzed (that is, they
1211/// don't escape) and tries to turn them into scalar SSA values. There are
1212/// a few steps to this process.
1213///
1214/// 1) It takes allocations of aggregates and analyzes the ways in which they
1215/// are used to try to split them into smaller allocations, ideally of
1216/// a single scalar data type. It will split up memcpy and memset accesses
1217/// as necessary and try to isolate invidual scalar accesses.
1218/// 2) It will transform accesses into forms which are suitable for SSA value
1219/// promotion. This can be replacing a memset with a scalar store of an
1220/// integer value, or it can involve speculating operations on a PHI or
1221/// select to be a PHI or select of the results.
1222/// 3) Finally, this will try to detect a pattern of accesses which map cleanly
1223/// onto insert and extract operations on a vector value, and convert them to
1224/// this form. By doing so, it will enable promotion of vector aggregates to
1225/// SSA vector values.
1226class SROA : public FunctionPass {
Chandler Carruth1c8db502012-09-15 11:43:14 +00001227 const bool RequiresDomTree;
1228
Chandler Carruth713aa942012-09-14 09:22:59 +00001229 LLVMContext *C;
1230 const TargetData *TD;
1231 DominatorTree *DT;
1232
1233 /// \brief Worklist of alloca instructions to simplify.
1234 ///
1235 /// Each alloca in the function is added to this. Each new alloca formed gets
1236 /// added to it as well to recursively simplify unless that alloca can be
1237 /// directly promoted. Finally, each time we rewrite a use of an alloca other
1238 /// the one being actively rewritten, we add it back onto the list if not
1239 /// already present to ensure it is re-visited.
1240 SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
1241
1242 /// \brief A collection of instructions to delete.
1243 /// We try to batch deletions to simplify code and make things a bit more
1244 /// efficient.
1245 SmallVector<Instruction *, 8> DeadInsts;
1246
1247 /// \brief A set to prevent repeatedly marking an instruction split into many
1248 /// uses as dead. Only used to guard insertion into DeadInsts.
1249 SmallPtrSet<Instruction *, 4> DeadSplitInsts;
1250
Chandler Carruth713aa942012-09-14 09:22:59 +00001251 /// \brief A collection of alloca instructions we can directly promote.
1252 std::vector<AllocaInst *> PromotableAllocas;
1253
1254public:
Chandler Carruth1c8db502012-09-15 11:43:14 +00001255 SROA(bool RequiresDomTree = true)
1256 : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
1257 C(0), TD(0), DT(0) {
Chandler Carruth713aa942012-09-14 09:22:59 +00001258 initializeSROAPass(*PassRegistry::getPassRegistry());
1259 }
1260 bool runOnFunction(Function &F);
1261 void getAnalysisUsage(AnalysisUsage &AU) const;
1262
1263 const char *getPassName() const { return "SROA"; }
1264 static char ID;
1265
1266private:
1267 friend class AllocaPartitionRewriter;
1268 friend class AllocaPartitionVectorRewriter;
1269
1270 bool rewriteAllocaPartition(AllocaInst &AI,
1271 AllocaPartitioning &P,
1272 AllocaPartitioning::iterator PI);
1273 bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
1274 bool runOnAlloca(AllocaInst &AI);
Chandler Carruth8615cd22012-09-14 10:26:38 +00001275 void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
Chandler Carruth1c8db502012-09-15 11:43:14 +00001276 bool promoteAllocas(Function &F);
Chandler Carruth713aa942012-09-14 09:22:59 +00001277};
1278}
1279
1280char SROA::ID = 0;
1281
Chandler Carruth1c8db502012-09-15 11:43:14 +00001282FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
1283 return new SROA(RequiresDomTree);
Chandler Carruth713aa942012-09-14 09:22:59 +00001284}
1285
1286INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
1287 false, false)
1288INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1289INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
1290 false, false)
1291
1292/// \brief Accumulate the constant offsets in a GEP into a single APInt offset.
1293///
1294/// If the provided GEP is all-constant, the total byte offset formed by the
1295/// GEP is computed and Offset is set to it. If the GEP has any non-constant
1296/// operands, the function returns false and the value of Offset is unmodified.
1297static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
1298 APInt &Offset) {
1299 APInt GEPOffset(Offset.getBitWidth(), 0);
1300 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1301 GTI != GTE; ++GTI) {
1302 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1303 if (!OpC)
1304 return false;
1305 if (OpC->isZero()) continue;
1306
1307 // Handle a struct index, which adds its field offset to the pointer.
1308 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1309 unsigned ElementIdx = OpC->getZExtValue();
1310 const StructLayout *SL = TD.getStructLayout(STy);
1311 GEPOffset += APInt(Offset.getBitWidth(),
1312 SL->getElementOffset(ElementIdx));
1313 continue;
1314 }
1315
1316 APInt TypeSize(Offset.getBitWidth(),
1317 TD.getTypeAllocSize(GTI.getIndexedType()));
1318 if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
1319 assert((VTy->getScalarSizeInBits() % 8) == 0 &&
1320 "vector element size is not a multiple of 8, cannot GEP over it");
1321 TypeSize = VTy->getScalarSizeInBits() / 8;
1322 }
1323
1324 GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
1325 }
1326 Offset = GEPOffset;
1327 return true;
1328}
1329
1330/// \brief Build a GEP out of a base pointer and indices.
1331///
1332/// This will return the BasePtr if that is valid, or build a new GEP
1333/// instruction using the IRBuilder if GEP-ing is needed.
1334static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
1335 SmallVectorImpl<Value *> &Indices,
1336 const Twine &Prefix) {
1337 if (Indices.empty())
1338 return BasePtr;
1339
1340 // A single zero index is a no-op, so check for this and avoid building a GEP
1341 // in that case.
1342 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1343 return BasePtr;
1344
1345 return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
1346}
1347
1348/// \brief Get a natural GEP off of the BasePtr walking through Ty toward
1349/// TargetTy without changing the offset of the pointer.
1350///
1351/// This routine assumes we've already established a properly offset GEP with
1352/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1353/// zero-indices down through type layers until we find one the same as
1354/// TargetTy. If we can't find one with the same type, we at least try to use
1355/// one with the same size. If none of that works, we just produce the GEP as
1356/// indicated by Indices to have the correct offset.
1357static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
1358 Value *BasePtr, Type *Ty, Type *TargetTy,
1359 SmallVectorImpl<Value *> &Indices,
1360 const Twine &Prefix) {
1361 if (Ty == TargetTy)
1362 return buildGEP(IRB, BasePtr, Indices, Prefix);
1363
1364 // See if we can descend into a struct and locate a field with the correct
1365 // type.
1366 unsigned NumLayers = 0;
1367 Type *ElementTy = Ty;
1368 do {
1369 if (ElementTy->isPointerTy())
1370 break;
1371 if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
1372 ElementTy = SeqTy->getElementType();
1373 Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
1374 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1375 ElementTy = *STy->element_begin();
1376 Indices.push_back(IRB.getInt32(0));
1377 } else {
1378 break;
1379 }
1380 ++NumLayers;
1381 } while (ElementTy != TargetTy);
1382 if (ElementTy != TargetTy)
1383 Indices.erase(Indices.end() - NumLayers, Indices.end());
1384
1385 return buildGEP(IRB, BasePtr, Indices, Prefix);
1386}
1387
1388/// \brief Recursively compute indices for a natural GEP.
1389///
1390/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1391/// element types adding appropriate indices for the GEP.
1392static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
1393 Value *Ptr, Type *Ty, APInt &Offset,
1394 Type *TargetTy,
1395 SmallVectorImpl<Value *> &Indices,
1396 const Twine &Prefix) {
1397 if (Offset == 0)
1398 return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
1399
1400 // We can't recurse through pointer types.
1401 if (Ty->isPointerTy())
1402 return 0;
1403
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001404 // We try to analyze GEPs over vectors here, but note that these GEPs are
1405 // extremely poorly defined currently. The long-term goal is to remove GEPing
1406 // over a vector from the IR completely.
Chandler Carruth713aa942012-09-14 09:22:59 +00001407 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1408 unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
1409 if (ElementSizeInBits % 8)
Chandler Carruth8ed1ed82012-09-14 10:30:40 +00001410 return 0; // GEPs over non-multiple of 8 size vector elements are invalid.
Chandler Carruth713aa942012-09-14 09:22:59 +00001411 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1412 APInt NumSkippedElements = Offset.udiv(ElementSize);
1413 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1414 return 0;
1415 Offset -= NumSkippedElements * ElementSize;
1416 Indices.push_back(IRB.getInt(NumSkippedElements));
1417 return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
1418 Offset, TargetTy, Indices, Prefix);
1419 }
1420
1421 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1422 Type *ElementTy = ArrTy->getElementType();
1423 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1424 APInt NumSkippedElements = Offset.udiv(ElementSize);
1425 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1426 return 0;
1427
1428 Offset -= NumSkippedElements * ElementSize;
1429 Indices.push_back(IRB.getInt(NumSkippedElements));
1430 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1431 Indices, Prefix);
1432 }
1433
1434 StructType *STy = dyn_cast<StructType>(Ty);
1435 if (!STy)
1436 return 0;
1437
1438 const StructLayout *SL = TD.getStructLayout(STy);
1439 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthad41dcf2012-09-14 10:30:42 +00001440 if (StructOffset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00001441 return 0;
1442 unsigned Index = SL->getElementContainingOffset(StructOffset);
1443 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1444 Type *ElementTy = STy->getElementType(Index);
1445 if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
1446 return 0; // The offset points into alignment padding.
1447
1448 Indices.push_back(IRB.getInt32(Index));
1449 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1450 Indices, Prefix);
1451}
1452
1453/// \brief Get a natural GEP from a base pointer to a particular offset and
1454/// resulting in a particular type.
1455///
1456/// The goal is to produce a "natural" looking GEP that works with the existing
1457/// composite types to arrive at the appropriate offset and element type for
1458/// a pointer. TargetTy is the element type the returned GEP should point-to if
1459/// possible. We recurse by decreasing Offset, adding the appropriate index to
1460/// Indices, and setting Ty to the result subtype.
1461///
Chandler Carruth7f5bede2012-09-14 10:18:49 +00001462/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth713aa942012-09-14 09:22:59 +00001463static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
1464 Value *Ptr, APInt Offset, Type *TargetTy,
1465 SmallVectorImpl<Value *> &Indices,
1466 const Twine &Prefix) {
1467 PointerType *Ty = cast<PointerType>(Ptr->getType());
1468
1469 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1470 // an i8.
1471 if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
1472 return 0;
1473
1474 Type *ElementTy = Ty->getElementType();
1475 APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
1476 if (ElementSize == 0)
1477 return 0; // Zero-length arrays can't help us build a natural GEP.
1478 APInt NumSkippedElements = Offset.udiv(ElementSize);
1479
1480 Offset -= NumSkippedElements * ElementSize;
1481 Indices.push_back(IRB.getInt(NumSkippedElements));
1482 return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
1483 Indices, Prefix);
1484}
1485
1486/// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
1487/// resulting pointer has PointerTy.
1488///
1489/// This tries very hard to compute a "natural" GEP which arrives at the offset
1490/// and produces the pointer type desired. Where it cannot, it will try to use
1491/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1492/// fails, it will try to use an existing i8* and GEP to the byte offset and
1493/// bitcast to the type.
1494///
1495/// The strategy for finding the more natural GEPs is to peel off layers of the
1496/// pointer, walking back through bit casts and GEPs, searching for a base
1497/// pointer from which we can compute a natural GEP with the desired
1498/// properities. The algorithm tries to fold as many constant indices into
1499/// a single GEP as possible, thus making each GEP more independent of the
1500/// surrounding code.
1501static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
1502 Value *Ptr, APInt Offset, Type *PointerTy,
1503 const Twine &Prefix) {
1504 // Even though we don't look through PHI nodes, we could be called on an
1505 // instruction in an unreachable block, which may be on a cycle.
1506 SmallPtrSet<Value *, 4> Visited;
1507 Visited.insert(Ptr);
1508 SmallVector<Value *, 4> Indices;
1509
1510 // We may end up computing an offset pointer that has the wrong type. If we
1511 // never are able to compute one directly that has the correct type, we'll
1512 // fall back to it, so keep it around here.
1513 Value *OffsetPtr = 0;
1514
1515 // Remember any i8 pointer we come across to re-use if we need to do a raw
1516 // byte offset.
1517 Value *Int8Ptr = 0;
1518 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1519
1520 Type *TargetTy = PointerTy->getPointerElementType();
1521
1522 do {
1523 // First fold any existing GEPs into the offset.
1524 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1525 APInt GEPOffset(Offset.getBitWidth(), 0);
1526 if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
1527 break;
1528 Offset += GEPOffset;
1529 Ptr = GEP->getPointerOperand();
1530 if (!Visited.insert(Ptr))
1531 break;
1532 }
1533
1534 // See if we can perform a natural GEP here.
1535 Indices.clear();
1536 if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
1537 Indices, Prefix)) {
1538 if (P->getType() == PointerTy) {
1539 // Zap any offset pointer that we ended up computing in previous rounds.
1540 if (OffsetPtr && OffsetPtr->use_empty())
1541 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
1542 I->eraseFromParent();
1543 return P;
1544 }
1545 if (!OffsetPtr) {
1546 OffsetPtr = P;
1547 }
1548 }
1549
1550 // Stash this pointer if we've found an i8*.
1551 if (Ptr->getType()->isIntegerTy(8)) {
1552 Int8Ptr = Ptr;
1553 Int8PtrOffset = Offset;
1554 }
1555
1556 // Peel off a layer of the pointer and update the offset appropriately.
1557 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1558 Ptr = cast<Operator>(Ptr)->getOperand(0);
1559 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1560 if (GA->mayBeOverridden())
1561 break;
1562 Ptr = GA->getAliasee();
1563 } else {
1564 break;
1565 }
1566 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1567 } while (Visited.insert(Ptr));
1568
1569 if (!OffsetPtr) {
1570 if (!Int8Ptr) {
1571 Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
1572 Prefix + ".raw_cast");
1573 Int8PtrOffset = Offset;
1574 }
1575
1576 OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
1577 IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
1578 Prefix + ".raw_idx");
1579 }
1580 Ptr = OffsetPtr;
1581
1582 // On the off chance we were targeting i8*, guard the bitcast here.
1583 if (Ptr->getType() != PointerTy)
1584 Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
1585
1586 return Ptr;
1587}
1588
1589/// \brief Test whether the given alloca partition can be promoted to a vector.
1590///
1591/// This is a quick test to check whether we can rewrite a particular alloca
1592/// partition (and its newly formed alloca) into a vector alloca with only
1593/// whole-vector loads and stores such that it could be promoted to a vector
1594/// SSA value. We only can ensure this for a limited set of operations, and we
1595/// don't want to do the rewrites unless we are confident that the result will
1596/// be promotable, so we have an early test here.
1597static bool isVectorPromotionViable(const TargetData &TD,
1598 Type *AllocaTy,
1599 AllocaPartitioning &P,
1600 uint64_t PartitionBeginOffset,
1601 uint64_t PartitionEndOffset,
1602 AllocaPartitioning::const_use_iterator I,
1603 AllocaPartitioning::const_use_iterator E) {
1604 VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
1605 if (!Ty)
1606 return false;
1607
1608 uint64_t VecSize = TD.getTypeSizeInBits(Ty);
1609 uint64_t ElementSize = Ty->getScalarSizeInBits();
1610
1611 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1612 // that aren't byte sized.
1613 if (ElementSize % 8)
1614 return false;
1615 assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
1616 VecSize /= 8;
1617 ElementSize /= 8;
1618
1619 for (; I != E; ++I) {
1620 uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
1621 uint64_t BeginIndex = BeginOffset / ElementSize;
1622 if (BeginIndex * ElementSize != BeginOffset ||
1623 BeginIndex >= Ty->getNumElements())
1624 return false;
1625 uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
1626 uint64_t EndIndex = EndOffset / ElementSize;
1627 if (EndIndex * ElementSize != EndOffset ||
1628 EndIndex > Ty->getNumElements())
1629 return false;
1630
1631 // FIXME: We should build shuffle vector instructions to handle
1632 // non-element-sized accesses.
1633 if ((EndOffset - BeginOffset) != ElementSize &&
1634 (EndOffset - BeginOffset) != VecSize)
1635 return false;
1636
1637 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*I->User)) {
1638 if (MI->isVolatile())
1639 return false;
1640 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(&*I->User)) {
1641 const AllocaPartitioning::MemTransferOffsets &MTO
1642 = P.getMemTransferOffsets(*MTI);
1643 if (!MTO.IsSplittable)
1644 return false;
1645 }
1646 } else if (I->Ptr->getType()->getPointerElementType()->isStructTy()) {
1647 // Disable vector promotion when there are loads or stores of an FCA.
1648 return false;
1649 } else if (!isa<LoadInst>(*I->User) && !isa<StoreInst>(*I->User)) {
1650 return false;
1651 }
1652 }
1653 return true;
1654}
1655
1656namespace {
1657/// \brief Visitor to rewrite instructions using a partition of an alloca to
1658/// use a new alloca.
1659///
1660/// Also implements the rewriting to vector-based accesses when the partition
1661/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
1662/// lives here.
1663class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
1664 bool> {
1665 // Befriend the base class so it can delegate to private visit methods.
1666 friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
1667
1668 const TargetData &TD;
1669 AllocaPartitioning &P;
1670 SROA &Pass;
1671 AllocaInst &OldAI, &NewAI;
1672 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
1673
1674 // If we are rewriting an alloca partition which can be written as pure
1675 // vector operations, we stash extra information here. When VecTy is
1676 // non-null, we have some strict guarantees about the rewriten alloca:
1677 // - The new alloca is exactly the size of the vector type here.
1678 // - The accesses all either map to the entire vector or to a single
1679 // element.
1680 // - The set of accessing instructions is only one of those handled above
1681 // in isVectorPromotionViable. Generally these are the same access kinds
1682 // which are promotable via mem2reg.
1683 VectorType *VecTy;
1684 Type *ElementTy;
1685 uint64_t ElementSize;
1686
1687 // The offset of the partition user currently being rewritten.
1688 uint64_t BeginOffset, EndOffset;
1689 Instruction *OldPtr;
1690
1691 // The name prefix to use when rewriting instructions for this alloca.
1692 std::string NamePrefix;
1693
1694public:
1695 AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
1696 AllocaPartitioning::iterator PI,
1697 SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
1698 uint64_t NewBeginOffset, uint64_t NewEndOffset)
1699 : TD(TD), P(P), Pass(Pass),
1700 OldAI(OldAI), NewAI(NewAI),
1701 NewAllocaBeginOffset(NewBeginOffset),
1702 NewAllocaEndOffset(NewEndOffset),
1703 VecTy(), ElementTy(), ElementSize(),
1704 BeginOffset(), EndOffset() {
1705 }
1706
1707 /// \brief Visit the users of the alloca partition and rewrite them.
1708 bool visitUsers(AllocaPartitioning::const_use_iterator I,
1709 AllocaPartitioning::const_use_iterator E) {
1710 if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
1711 NewAllocaBeginOffset, NewAllocaEndOffset,
1712 I, E)) {
1713 ++NumVectorized;
1714 VecTy = cast<VectorType>(NewAI.getAllocatedType());
1715 ElementTy = VecTy->getElementType();
1716 assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
1717 "Only multiple-of-8 sized vector elements are viable");
1718 ElementSize = VecTy->getScalarSizeInBits() / 8;
1719 }
1720 bool CanSROA = true;
1721 for (; I != E; ++I) {
1722 BeginOffset = I->BeginOffset;
1723 EndOffset = I->EndOffset;
1724 OldPtr = I->Ptr;
1725 NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
1726 CanSROA &= visit(I->User);
1727 }
1728 if (VecTy) {
1729 assert(CanSROA);
1730 VecTy = 0;
1731 ElementTy = 0;
1732 ElementSize = 0;
1733 }
1734 return CanSROA;
1735 }
1736
1737private:
1738 // Every instruction which can end up as a user must have a rewrite rule.
1739 bool visitInstruction(Instruction &I) {
1740 DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
1741 llvm_unreachable("No rewrite rule for this instruction!");
1742 }
1743
1744 Twine getName(const Twine &Suffix) {
1745 return NamePrefix + Suffix;
1746 }
1747
1748 Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
1749 assert(BeginOffset >= NewAllocaBeginOffset);
1750 APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
1751 return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
1752 }
1753
1754 ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
1755 assert(VecTy && "Can only call getIndex when rewriting a vector");
1756 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
1757 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
1758 uint32_t Index = RelOffset / ElementSize;
1759 assert(Index * ElementSize == RelOffset);
1760 return IRB.getInt32(Index);
1761 }
1762
1763 void deleteIfTriviallyDead(Value *V) {
1764 Instruction *I = cast<Instruction>(V);
1765 if (isInstructionTriviallyDead(I))
1766 Pass.DeadInsts.push_back(I);
1767 }
1768
1769 Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
1770 if (V->getType()->isIntegerTy() && Ty->isPointerTy())
1771 return IRB.CreateIntToPtr(V, Ty);
1772 if (V->getType()->isPointerTy() && Ty->isIntegerTy())
1773 return IRB.CreatePtrToInt(V, Ty);
1774
1775 return IRB.CreateBitCast(V, Ty);
1776 }
1777
1778 bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
1779 Value *Result;
1780 if (LI.getType() == VecTy->getElementType() ||
1781 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1782 Result
1783 = IRB.CreateExtractElement(IRB.CreateLoad(&NewAI, getName(".load")),
1784 getIndex(IRB, BeginOffset),
1785 getName(".extract"));
1786 } else {
1787 Result = IRB.CreateLoad(&NewAI, getName(".load"));
1788 }
1789 if (Result->getType() != LI.getType())
1790 Result = getValueCast(IRB, Result, LI.getType());
1791 LI.replaceAllUsesWith(Result);
1792 Pass.DeadInsts.push_back(&LI);
1793
1794 DEBUG(dbgs() << " to: " << *Result << "\n");
1795 return true;
1796 }
1797
1798 bool visitLoadInst(LoadInst &LI) {
1799 DEBUG(dbgs() << " original: " << LI << "\n");
1800 Value *OldOp = LI.getOperand(0);
1801 assert(OldOp == OldPtr);
1802 IRBuilder<> IRB(&LI);
1803
1804 if (VecTy)
1805 return rewriteVectorizedLoadInst(IRB, LI, OldOp);
1806
1807 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1808 LI.getPointerOperand()->getType());
1809 LI.setOperand(0, NewPtr);
1810 DEBUG(dbgs() << " to: " << LI << "\n");
1811
1812 deleteIfTriviallyDead(OldOp);
1813 return NewPtr == &NewAI && !LI.isVolatile();
1814 }
1815
1816 bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
1817 Value *OldOp) {
1818 Value *V = SI.getValueOperand();
1819 if (V->getType() == ElementTy ||
1820 BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
1821 if (V->getType() != ElementTy)
1822 V = getValueCast(IRB, V, ElementTy);
1823 V = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1824 getIndex(IRB, BeginOffset),
1825 getName(".insert"));
1826 } else if (V->getType() != VecTy) {
1827 V = getValueCast(IRB, V, VecTy);
1828 }
1829 StoreInst *Store = IRB.CreateStore(V, &NewAI);
1830 Pass.DeadInsts.push_back(&SI);
1831
1832 (void)Store;
1833 DEBUG(dbgs() << " to: " << *Store << "\n");
1834 return true;
1835 }
1836
1837 bool visitStoreInst(StoreInst &SI) {
1838 DEBUG(dbgs() << " original: " << SI << "\n");
1839 Value *OldOp = SI.getOperand(1);
1840 assert(OldOp == OldPtr);
1841 IRBuilder<> IRB(&SI);
1842
1843 if (VecTy)
1844 return rewriteVectorizedStoreInst(IRB, SI, OldOp);
1845
1846 Value *NewPtr = getAdjustedAllocaPtr(IRB,
1847 SI.getPointerOperand()->getType());
1848 SI.setOperand(1, NewPtr);
1849 DEBUG(dbgs() << " to: " << SI << "\n");
1850
1851 deleteIfTriviallyDead(OldOp);
1852 return NewPtr == &NewAI && !SI.isVolatile();
1853 }
1854
1855 bool visitMemSetInst(MemSetInst &II) {
1856 DEBUG(dbgs() << " original: " << II << "\n");
1857 IRBuilder<> IRB(&II);
1858 assert(II.getRawDest() == OldPtr);
1859
1860 // If the memset has a variable size, it cannot be split, just adjust the
1861 // pointer to the new alloca.
1862 if (!isa<Constant>(II.getLength())) {
1863 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1864 deleteIfTriviallyDead(OldPtr);
1865 return false;
1866 }
1867
1868 // Record this instruction for deletion.
1869 if (Pass.DeadSplitInsts.insert(&II))
1870 Pass.DeadInsts.push_back(&II);
1871
1872 Type *AllocaTy = NewAI.getAllocatedType();
1873 Type *ScalarTy = AllocaTy->getScalarType();
1874
1875 // If this doesn't map cleanly onto the alloca type, and that type isn't
1876 // a single value type, just emit a memset.
1877 if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
1878 EndOffset != NewAllocaEndOffset ||
1879 !AllocaTy->isSingleValueType() ||
1880 !TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
1881 Type *SizeTy = II.getLength()->getType();
1882 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
1883
1884 CallInst *New
1885 = IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
1886 II.getRawDest()->getType()),
1887 II.getValue(), Size, II.getAlignment(),
1888 II.isVolatile());
1889 (void)New;
1890 DEBUG(dbgs() << " to: " << *New << "\n");
1891 return false;
1892 }
1893
1894 // If we can represent this as a simple value, we have to build the actual
1895 // value to store, which requires expanding the byte present in memset to
1896 // a sensible representation for the alloca type. This is essentially
1897 // splatting the byte to a sufficiently wide integer, bitcasting to the
1898 // desired scalar type, and splatting it across any desired vector type.
1899 Value *V = II.getValue();
1900 IntegerType *VTy = cast<IntegerType>(V->getType());
1901 Type *IntTy = Type::getIntNTy(VTy->getContext(),
1902 TD.getTypeSizeInBits(ScalarTy));
1903 if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
1904 V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
1905 ConstantExpr::getUDiv(
1906 Constant::getAllOnesValue(IntTy),
1907 ConstantExpr::getZExt(
1908 Constant::getAllOnesValue(V->getType()),
1909 IntTy)),
1910 getName(".isplat"));
1911 if (V->getType() != ScalarTy) {
1912 if (ScalarTy->isPointerTy())
1913 V = IRB.CreateIntToPtr(V, ScalarTy);
1914 else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
1915 V = IRB.CreateBitCast(V, ScalarTy);
1916 else if (ScalarTy->isIntegerTy())
1917 llvm_unreachable("Computed different integer types with equal widths");
1918 else
1919 llvm_unreachable("Invalid scalar type");
1920 }
1921
1922 // If this is an element-wide memset of a vectorizable alloca, insert it.
1923 if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
1924 EndOffset < NewAllocaEndOffset)) {
1925 StoreInst *Store = IRB.CreateStore(
1926 IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")), V,
1927 getIndex(IRB, BeginOffset),
1928 getName(".insert")),
1929 &NewAI);
1930 (void)Store;
1931 DEBUG(dbgs() << " to: " << *Store << "\n");
1932 return true;
1933 }
1934
1935 // Splat to a vector if needed.
1936 if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
1937 VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
1938 V = IRB.CreateShuffleVector(
1939 IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
1940 IRB.getInt32(0), getName(".vsplat.insert")),
1941 UndefValue::get(SplatSourceTy),
1942 ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
1943 getName(".vsplat.shuffle"));
1944 assert(V->getType() == VecTy);
1945 }
1946
1947 Value *New = IRB.CreateStore(V, &NewAI, II.isVolatile());
1948 (void)New;
1949 DEBUG(dbgs() << " to: " << *New << "\n");
1950 return !II.isVolatile();
1951 }
1952
1953 bool visitMemTransferInst(MemTransferInst &II) {
1954 // Rewriting of memory transfer instructions can be a bit tricky. We break
1955 // them into two categories: split intrinsics and unsplit intrinsics.
1956
1957 DEBUG(dbgs() << " original: " << II << "\n");
1958 IRBuilder<> IRB(&II);
1959
1960 assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
1961 bool IsDest = II.getRawDest() == OldPtr;
1962
1963 const AllocaPartitioning::MemTransferOffsets &MTO
1964 = P.getMemTransferOffsets(II);
1965
1966 // For unsplit intrinsics, we simply modify the source and destination
1967 // pointers in place. This isn't just an optimization, it is a matter of
1968 // correctness. With unsplit intrinsics we may be dealing with transfers
1969 // within a single alloca before SROA ran, or with transfers that have
1970 // a variable length. We may also be dealing with memmove instead of
1971 // memcpy, and so simply updating the pointers is the necessary for us to
1972 // update both source and dest of a single call.
1973 if (!MTO.IsSplittable) {
1974 Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
1975 if (IsDest)
1976 II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
1977 else
1978 II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
1979
1980 DEBUG(dbgs() << " to: " << II << "\n");
1981 deleteIfTriviallyDead(OldOp);
1982 return false;
1983 }
1984 // For split transfer intrinsics we have an incredibly useful assurance:
1985 // the source and destination do not reside within the same alloca, and at
1986 // least one of them does not escape. This means that we can replace
1987 // memmove with memcpy, and we don't need to worry about all manner of
1988 // downsides to splitting and transforming the operations.
1989
1990 // Compute the relative offset within the transfer.
1991 unsigned IntPtrWidth = TD.getPointerSizeInBits();
1992 APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
1993 : MTO.SourceBegin));
1994
1995 // If this doesn't map cleanly onto the alloca type, and that type isn't
1996 // a single value type, just emit a memcpy.
1997 bool EmitMemCpy
1998 = !VecTy && (BeginOffset != NewAllocaBeginOffset ||
1999 EndOffset != NewAllocaEndOffset ||
2000 !NewAI.getAllocatedType()->isSingleValueType());
2001
2002 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2003 // size hasn't been shrunk based on analysis of the viable range, this is
2004 // a no-op.
2005 if (EmitMemCpy && &OldAI == &NewAI) {
2006 uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
2007 uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
2008 // Ensure the start lines up.
2009 assert(BeginOffset == OrigBegin);
Benjamin Kramerd0807692012-09-14 13:08:09 +00002010 (void)OrigBegin;
Chandler Carruth713aa942012-09-14 09:22:59 +00002011
2012 // Rewrite the size as needed.
2013 if (EndOffset != OrigEnd)
2014 II.setLength(ConstantInt::get(II.getLength()->getType(),
2015 EndOffset - BeginOffset));
2016 return false;
2017 }
2018 // Record this instruction for deletion.
2019 if (Pass.DeadSplitInsts.insert(&II))
2020 Pass.DeadInsts.push_back(&II);
2021
2022 bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
2023 EndOffset < NewAllocaEndOffset);
2024
2025 Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
2026 : II.getRawDest()->getType();
2027 if (!EmitMemCpy)
2028 OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
2029 : NewAI.getType();
2030
2031 // Compute the other pointer, folding as much as possible to produce
2032 // a single, simple GEP in most cases.
2033 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2034 OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
2035 getName("." + OtherPtr->getName()));
2036
2037 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2038 // alloca that should be re-examined after rewriting this instruction.
2039 if (AllocaInst *AI
2040 = dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
2041 Pass.Worklist.insert(AI);
2042
2043 if (EmitMemCpy) {
2044 Value *OurPtr
2045 = getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
2046 : II.getRawSource()->getType());
2047 Type *SizeTy = II.getLength()->getType();
2048 Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
2049
2050 CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
2051 IsDest ? OtherPtr : OurPtr,
2052 Size, II.getAlignment(),
2053 II.isVolatile());
2054 (void)New;
2055 DEBUG(dbgs() << " to: " << *New << "\n");
2056 return false;
2057 }
2058
2059 Value *SrcPtr = OtherPtr;
2060 Value *DstPtr = &NewAI;
2061 if (!IsDest)
2062 std::swap(SrcPtr, DstPtr);
2063
2064 Value *Src;
2065 if (IsVectorElement && !IsDest) {
2066 // We have to extract rather than load.
2067 Src = IRB.CreateExtractElement(IRB.CreateLoad(SrcPtr,
2068 getName(".copyload")),
2069 getIndex(IRB, BeginOffset),
2070 getName(".copyextract"));
2071 } else {
2072 Src = IRB.CreateLoad(SrcPtr, II.isVolatile(), getName(".copyload"));
2073 }
2074
2075 if (IsVectorElement && IsDest) {
2076 // We have to insert into a loaded copy before storing.
2077 Src = IRB.CreateInsertElement(IRB.CreateLoad(&NewAI, getName(".load")),
2078 Src, getIndex(IRB, BeginOffset),
2079 getName(".insert"));
2080 }
2081
2082 Value *Store = IRB.CreateStore(Src, DstPtr, II.isVolatile());
2083 (void)Store;
2084 DEBUG(dbgs() << " to: " << *Store << "\n");
2085 return !II.isVolatile();
2086 }
2087
2088 bool visitIntrinsicInst(IntrinsicInst &II) {
2089 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
2090 II.getIntrinsicID() == Intrinsic::lifetime_end);
2091 DEBUG(dbgs() << " original: " << II << "\n");
2092 IRBuilder<> IRB(&II);
2093 assert(II.getArgOperand(1) == OldPtr);
2094
2095 // Record this instruction for deletion.
2096 if (Pass.DeadSplitInsts.insert(&II))
2097 Pass.DeadInsts.push_back(&II);
2098
2099 ConstantInt *Size
2100 = ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
2101 EndOffset - BeginOffset);
2102 Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
2103 Value *New;
2104 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
2105 New = IRB.CreateLifetimeStart(Ptr, Size);
2106 else
2107 New = IRB.CreateLifetimeEnd(Ptr, Size);
2108
2109 DEBUG(dbgs() << " to: " << *New << "\n");
2110 return true;
2111 }
2112
2113 /// PHI instructions that use an alloca and are subsequently loaded can be
2114 /// rewritten to load both input pointers in the pred blocks and then PHI the
2115 /// results, allowing the load of the alloca to be promoted.
2116 /// From this:
2117 /// %P2 = phi [i32* %Alloca, i32* %Other]
2118 /// %V = load i32* %P2
2119 /// to:
2120 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2121 /// ...
2122 /// %V2 = load i32* %Other
2123 /// ...
2124 /// %V = phi [i32 %V1, i32 %V2]
2125 ///
2126 /// We can do this to a select if its only uses are loads and if the operand
2127 /// to the select can be loaded unconditionally.
2128 ///
2129 /// FIXME: This should be hoisted into a generic utility, likely in
2130 /// Transforms/Util/Local.h
2131 bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
2132 // For now, we can only do this promotion if the load is in the same block
2133 // as the PHI, and if there are no stores between the phi and load.
2134 // TODO: Allow recursive phi users.
2135 // TODO: Allow stores.
2136 BasicBlock *BB = PN.getParent();
2137 unsigned MaxAlign = 0;
2138 for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
2139 UI != UE; ++UI) {
2140 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2141 if (LI == 0 || !LI->isSimple()) return false;
2142
2143 // For now we only allow loads in the same block as the PHI. This is
2144 // a common case that happens when instcombine merges two loads through
2145 // a PHI.
2146 if (LI->getParent() != BB) return false;
2147
2148 // Ensure that there are no instructions between the PHI and the load that
2149 // could store.
2150 for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
2151 if (BBI->mayWriteToMemory())
2152 return false;
2153
2154 MaxAlign = std::max(MaxAlign, LI->getAlignment());
2155 Loads.push_back(LI);
2156 }
2157
2158 // We can only transform this if it is safe to push the loads into the
2159 // predecessor blocks. The only thing to watch out for is that we can't put
2160 // a possibly trapping load in the predecessor if it is a critical edge.
2161 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
2162 ++Idx) {
2163 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
2164 Value *InVal = PN.getIncomingValue(Idx);
2165
2166 // If the value is produced by the terminator of the predecessor (an
2167 // invoke) or it has side-effects, there is no valid place to put a load
2168 // in the predecessor.
2169 if (TI == InVal || TI->mayHaveSideEffects())
2170 return false;
2171
2172 // If the predecessor has a single successor, then the edge isn't
2173 // critical.
2174 if (TI->getNumSuccessors() == 1)
2175 continue;
2176
2177 // If this pointer is always safe to load, or if we can prove that there
2178 // is already a load in the block, then we can move the load to the pred
2179 // block.
2180 if (InVal->isDereferenceablePointer() ||
2181 isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
2182 continue;
2183
2184 return false;
2185 }
2186
2187 return true;
2188 }
2189
2190 bool visitPHINode(PHINode &PN) {
2191 DEBUG(dbgs() << " original: " << PN << "\n");
2192 // We would like to compute a new pointer in only one place, but have it be
2193 // as local as possible to the PHI. To do that, we re-use the location of
2194 // the old pointer, which necessarily must be in the right position to
2195 // dominate the PHI.
2196 IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
2197
2198 SmallVector<LoadInst *, 4> Loads;
2199 if (!isSafePHIToSpeculate(PN, Loads)) {
2200 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2201 // Replace the operands which were using the old pointer.
2202 User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
2203 for (; OI != OE; ++OI)
2204 if (*OI == OldPtr)
2205 *OI = NewPtr;
2206
2207 DEBUG(dbgs() << " to: " << PN << "\n");
2208 deleteIfTriviallyDead(OldPtr);
2209 return false;
2210 }
2211 assert(!Loads.empty());
2212
2213 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
2214 IRBuilder<> PHIBuilder(&PN);
2215 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues());
2216 NewPN->takeName(&PN);
2217
2218 // Get the TBAA tag and alignment to use from one of the loads. It doesn't
2219 // matter which one we get and if any differ, it doesn't matter.
2220 LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
2221 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
2222 unsigned Align = SomeLoad->getAlignment();
2223 Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
2224
2225 // Rewrite all loads of the PN to use the new PHI.
2226 do {
2227 LoadInst *LI = Loads.pop_back_val();
2228 LI->replaceAllUsesWith(NewPN);
2229 Pass.DeadInsts.push_back(LI);
2230 } while (!Loads.empty());
2231
2232 // Inject loads into all of the pred blocks.
2233 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
2234 BasicBlock *Pred = PN.getIncomingBlock(Idx);
2235 TerminatorInst *TI = Pred->getTerminator();
2236 Value *InVal = PN.getIncomingValue(Idx);
2237 IRBuilder<> PredBuilder(TI);
2238
2239 // Map the value to the new alloca pointer if this was the old alloca
2240 // pointer.
2241 bool ThisOperand = InVal == OldPtr;
2242 if (ThisOperand)
2243 InVal = NewPtr;
2244
2245 LoadInst *Load
2246 = PredBuilder.CreateLoad(InVal, getName(".sroa.speculate." +
2247 Pred->getName()));
2248 ++NumLoadsSpeculated;
2249 Load->setAlignment(Align);
2250 if (TBAATag)
2251 Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
2252 NewPN->addIncoming(Load, Pred);
2253
2254 if (ThisOperand)
2255 continue;
2256 Instruction *OtherPtr = dyn_cast<Instruction>(InVal);
2257 if (!OtherPtr)
2258 // No uses to rewrite.
2259 continue;
2260
2261 // Try to lookup and rewrite any partition uses corresponding to this phi
2262 // input.
2263 AllocaPartitioning::iterator PI
2264 = P.findPartitionForPHIOrSelectOperand(PN, OtherPtr);
2265 if (PI != P.end()) {
2266 // If the other pointer is within the partitioning, replace the PHI in
2267 // its uses with the load we just speculated, or add another load for
2268 // it to rewrite if we've already replaced the PHI.
2269 AllocaPartitioning::use_iterator UI
2270 = P.findPartitionUseForPHIOrSelectOperand(PN, OtherPtr);
2271 if (isa<PHINode>(*UI->User))
2272 UI->User = Load;
2273 else {
2274 AllocaPartitioning::PartitionUse OtherUse = *UI;
2275 OtherUse.User = Load;
2276 P.use_insert(PI, std::upper_bound(UI, P.use_end(PI), OtherUse),
2277 OtherUse);
2278 }
2279 }
2280 }
2281 DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
2282 return NewPtr == &NewAI;
2283 }
2284
2285 /// Select instructions that use an alloca and are subsequently loaded can be
2286 /// rewritten to load both input pointers and then select between the result,
2287 /// allowing the load of the alloca to be promoted.
2288 /// From this:
2289 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
2290 /// %V = load i32* %P2
2291 /// to:
2292 /// %V1 = load i32* %Alloca -> will be mem2reg'd
2293 /// %V2 = load i32* %Other
2294 /// %V = select i1 %cond, i32 %V1, i32 %V2
2295 ///
2296 /// We can do this to a select if its only uses are loads and if the operand
2297 /// to the select can be loaded unconditionally.
2298 bool isSafeSelectToSpeculate(SelectInst &SI,
2299 SmallVectorImpl<LoadInst *> &Loads) {
2300 Value *TValue = SI.getTrueValue();
2301 Value *FValue = SI.getFalseValue();
2302 bool TDerefable = TValue->isDereferenceablePointer();
2303 bool FDerefable = FValue->isDereferenceablePointer();
2304
2305 for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
2306 UI != UE; ++UI) {
2307 LoadInst *LI = dyn_cast<LoadInst>(*UI);
2308 if (LI == 0 || !LI->isSimple()) return false;
2309
2310 // Both operands to the select need to be dereferencable, either
2311 // absolutely (e.g. allocas) or at this point because we can see other
2312 // accesses to it.
2313 if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
2314 LI->getAlignment(), &TD))
2315 return false;
2316 if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
2317 LI->getAlignment(), &TD))
2318 return false;
2319 Loads.push_back(LI);
2320 }
2321
2322 return true;
2323 }
2324
2325 bool visitSelectInst(SelectInst &SI) {
2326 DEBUG(dbgs() << " original: " << SI << "\n");
2327 IRBuilder<> IRB(&SI);
2328
2329 // Find the operand we need to rewrite here.
2330 bool IsTrueVal = SI.getTrueValue() == OldPtr;
2331 if (IsTrueVal)
2332 assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
2333 else
2334 assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
2335 Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
2336
2337 // If the select isn't safe to speculate, just use simple logic to emit it.
2338 SmallVector<LoadInst *, 4> Loads;
2339 if (!isSafeSelectToSpeculate(SI, Loads)) {
2340 SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
2341 DEBUG(dbgs() << " to: " << SI << "\n");
2342 deleteIfTriviallyDead(OldPtr);
2343 return false;
2344 }
2345
2346 Value *OtherPtr = IsTrueVal ? SI.getFalseValue() : SI.getTrueValue();
2347 AllocaPartitioning::iterator PI
2348 = P.findPartitionForPHIOrSelectOperand(SI, OtherPtr);
2349 AllocaPartitioning::PartitionUse OtherUse;
2350 if (PI != P.end()) {
2351 // If the other pointer is within the partitioning, remove the select
2352 // from its uses. We'll add in the new loads below.
2353 AllocaPartitioning::use_iterator UI
2354 = P.findPartitionUseForPHIOrSelectOperand(SI, OtherPtr);
2355 OtherUse = *UI;
2356 P.use_erase(PI, UI);
2357 }
2358
2359 Value *TV = IsTrueVal ? NewPtr : SI.getTrueValue();
2360 Value *FV = IsTrueVal ? SI.getFalseValue() : NewPtr;
2361 // Replace the loads of the select with a select of two loads.
2362 while (!Loads.empty()) {
2363 LoadInst *LI = Loads.pop_back_val();
2364
2365 IRB.SetInsertPoint(LI);
2366 LoadInst *TL =
2367 IRB.CreateLoad(TV, getName("." + LI->getName() + ".true"));
2368 LoadInst *FL =
2369 IRB.CreateLoad(FV, getName("." + LI->getName() + ".false"));
2370 NumLoadsSpeculated += 2;
2371 if (PI != P.end()) {
2372 LoadInst *OtherLoad = IsTrueVal ? FL : TL;
2373 assert(OtherUse.Ptr == OtherLoad->getOperand(0));
2374 OtherUse.User = OtherLoad;
2375 P.use_insert(PI, P.use_end(PI), OtherUse);
2376 }
2377
2378 // Transfer alignment and TBAA info if present.
2379 TL->setAlignment(LI->getAlignment());
2380 FL->setAlignment(LI->getAlignment());
2381 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
2382 TL->setMetadata(LLVMContext::MD_tbaa, Tag);
2383 FL->setMetadata(LLVMContext::MD_tbaa, Tag);
2384 }
2385
2386 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL);
2387 V->takeName(LI);
2388 DEBUG(dbgs() << " speculated to: " << *V << "\n");
2389 LI->replaceAllUsesWith(V);
2390 Pass.DeadInsts.push_back(LI);
2391 }
2392 if (PI != P.end())
2393 std::stable_sort(P.use_begin(PI), P.use_end(PI));
2394
2395 deleteIfTriviallyDead(OldPtr);
2396 return NewPtr == &NewAI;
2397 }
2398
2399};
2400}
2401
2402/// \brief Try to find a partition of the aggregate type passed in for a given
2403/// offset and size.
2404///
2405/// This recurses through the aggregate type and tries to compute a subtype
2406/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth6b547a22012-09-14 11:08:31 +00002407/// of an array, it will even compute a new array type for that sub-section,
2408/// and the same for structs.
2409///
2410/// Note that this routine is very strict and tries to find a partition of the
2411/// type which produces the *exact* right offset and size. It is not forgiving
2412/// when the size or offset cause either end of type-based partition to be off.
2413/// Also, this is a best-effort routine. It is reasonable to give up and not
2414/// return a type if necessary.
Chandler Carruth713aa942012-09-14 09:22:59 +00002415static Type *getTypePartition(const TargetData &TD, Type *Ty,
2416 uint64_t Offset, uint64_t Size) {
2417 if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
2418 return Ty;
2419
2420 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
2421 // We can't partition pointers...
2422 if (SeqTy->isPointerTy())
2423 return 0;
2424
2425 Type *ElementTy = SeqTy->getElementType();
2426 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2427 uint64_t NumSkippedElements = Offset / ElementSize;
2428 if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
2429 if (NumSkippedElements >= ArrTy->getNumElements())
2430 return 0;
2431 if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
2432 if (NumSkippedElements >= VecTy->getNumElements())
2433 return 0;
2434 Offset -= NumSkippedElements * ElementSize;
2435
2436 // First check if we need to recurse.
2437 if (Offset > 0 || Size < ElementSize) {
2438 // Bail if the partition ends in a different array element.
2439 if ((Offset + Size) > ElementSize)
2440 return 0;
2441 // Recurse through the element type trying to peel off offset bytes.
2442 return getTypePartition(TD, ElementTy, Offset, Size);
2443 }
2444 assert(Offset == 0);
2445
2446 if (Size == ElementSize)
2447 return ElementTy;
2448 assert(Size > ElementSize);
2449 uint64_t NumElements = Size / ElementSize;
2450 if (NumElements * ElementSize != Size)
2451 return 0;
2452 return ArrayType::get(ElementTy, NumElements);
2453 }
2454
2455 StructType *STy = dyn_cast<StructType>(Ty);
2456 if (!STy)
2457 return 0;
2458
2459 const StructLayout *SL = TD.getStructLayout(STy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002460 if (Offset >= SL->getSizeInBytes())
Chandler Carruth713aa942012-09-14 09:22:59 +00002461 return 0;
2462 uint64_t EndOffset = Offset + Size;
2463 if (EndOffset > SL->getSizeInBytes())
2464 return 0;
2465
2466 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth713aa942012-09-14 09:22:59 +00002467 Offset -= SL->getElementOffset(Index);
2468
2469 Type *ElementTy = STy->getElementType(Index);
2470 uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
2471 if (Offset >= ElementSize)
2472 return 0; // The offset points into alignment padding.
2473
2474 // See if any partition must be contained by the element.
2475 if (Offset > 0 || Size < ElementSize) {
2476 if ((Offset + Size) > ElementSize)
2477 return 0;
Chandler Carruth713aa942012-09-14 09:22:59 +00002478 return getTypePartition(TD, ElementTy, Offset, Size);
2479 }
2480 assert(Offset == 0);
2481
2482 if (Size == ElementSize)
2483 return ElementTy;
2484
2485 StructType::element_iterator EI = STy->element_begin() + Index,
2486 EE = STy->element_end();
2487 if (EndOffset < SL->getSizeInBytes()) {
2488 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
2489 if (Index == EndIndex)
2490 return 0; // Within a single element and its padding.
Chandler Carruth6b547a22012-09-14 11:08:31 +00002491
2492 // Don't try to form "natural" types if the elements don't line up with the
2493 // expected size.
2494 // FIXME: We could potentially recurse down through the last element in the
2495 // sub-struct to find a natural end point.
2496 if (SL->getElementOffset(EndIndex) != EndOffset)
2497 return 0;
2498
Chandler Carruth713aa942012-09-14 09:22:59 +00002499 assert(Index < EndIndex);
Chandler Carruth713aa942012-09-14 09:22:59 +00002500 EE = STy->element_begin() + EndIndex;
2501 }
2502
2503 // Try to build up a sub-structure.
2504 SmallVector<Type *, 4> ElementTys;
2505 do {
2506 ElementTys.push_back(*EI++);
2507 } while (EI != EE);
2508 StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
2509 STy->isPacked());
2510 const StructLayout *SubSL = TD.getStructLayout(SubTy);
Chandler Carruth6b547a22012-09-14 11:08:31 +00002511 if (Size != SubSL->getSizeInBytes())
2512 return 0; // The sub-struct doesn't have quite the size needed.
Chandler Carruth713aa942012-09-14 09:22:59 +00002513
Chandler Carruth6b547a22012-09-14 11:08:31 +00002514 return SubTy;
Chandler Carruth713aa942012-09-14 09:22:59 +00002515}
2516
2517/// \brief Rewrite an alloca partition's users.
2518///
2519/// This routine drives both of the rewriting goals of the SROA pass. It tries
2520/// to rewrite uses of an alloca partition to be conducive for SSA value
2521/// promotion. If the partition needs a new, more refined alloca, this will
2522/// build that new alloca, preserving as much type information as possible, and
2523/// rewrite the uses of the old alloca to point at the new one and have the
2524/// appropriate new offsets. It also evaluates how successful the rewrite was
2525/// at enabling promotion and if it was successful queues the alloca to be
2526/// promoted.
2527bool SROA::rewriteAllocaPartition(AllocaInst &AI,
2528 AllocaPartitioning &P,
2529 AllocaPartitioning::iterator PI) {
2530 uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
2531 if (P.use_begin(PI) == P.use_end(PI))
2532 return false; // No live uses left of this partition.
2533
2534 // Try to compute a friendly type for this partition of the alloca. This
2535 // won't always succeed, in which case we fall back to a legal integer type
2536 // or an i8 array of an appropriate size.
2537 Type *AllocaTy = 0;
2538 if (Type *PartitionTy = P.getCommonType(PI))
2539 if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
2540 AllocaTy = PartitionTy;
2541 if (!AllocaTy)
2542 if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
2543 PI->BeginOffset, AllocaSize))
2544 AllocaTy = PartitionTy;
2545 if ((!AllocaTy ||
2546 (AllocaTy->isArrayTy() &&
2547 AllocaTy->getArrayElementType()->isIntegerTy())) &&
2548 TD->isLegalInteger(AllocaSize * 8))
2549 AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
2550 if (!AllocaTy)
2551 AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
Chandler Carruthb3dd9a12012-09-14 10:26:34 +00002552 assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
Chandler Carruth713aa942012-09-14 09:22:59 +00002553
2554 // Check for the case where we're going to rewrite to a new alloca of the
2555 // exact same type as the original, and with the same access offsets. In that
2556 // case, re-use the existing alloca, but still run through the rewriter to
2557 // performe phi and select speculation.
2558 AllocaInst *NewAI;
2559 if (AllocaTy == AI.getAllocatedType()) {
2560 assert(PI->BeginOffset == 0 &&
2561 "Non-zero begin offset but same alloca type");
2562 assert(PI == P.begin() && "Begin offset is zero on later partition");
2563 NewAI = &AI;
2564 } else {
2565 // FIXME: The alignment here is overly conservative -- we could in many
2566 // cases get away with much weaker alignment constraints.
2567 NewAI = new AllocaInst(AllocaTy, 0, AI.getAlignment(),
2568 AI.getName() + ".sroa." + Twine(PI - P.begin()),
2569 &AI);
2570 ++NumNewAllocas;
2571 }
2572
2573 DEBUG(dbgs() << "Rewriting alloca partition "
2574 << "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
2575 << *NewAI << "\n");
2576
2577 AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
2578 PI->BeginOffset, PI->EndOffset);
2579 DEBUG(dbgs() << " rewriting ");
2580 DEBUG(P.print(dbgs(), PI, ""));
2581 if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
2582 DEBUG(dbgs() << " and queuing for promotion\n");
2583 PromotableAllocas.push_back(NewAI);
2584 } else if (NewAI != &AI) {
2585 // If we can't promote the alloca, iterate on it to check for new
2586 // refinements exposed by splitting the current alloca. Don't iterate on an
2587 // alloca which didn't actually change and didn't get promoted.
2588 Worklist.insert(NewAI);
2589 }
2590 return true;
2591}
2592
2593/// \brief Walks the partitioning of an alloca rewriting uses of each partition.
2594bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
2595 bool Changed = false;
2596 for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
2597 ++PI)
2598 Changed |= rewriteAllocaPartition(AI, P, PI);
2599
2600 return Changed;
2601}
2602
2603/// \brief Analyze an alloca for SROA.
2604///
2605/// This analyzes the alloca to ensure we can reason about it, builds
2606/// a partitioning of the alloca, and then hands it off to be split and
2607/// rewritten as needed.
2608bool SROA::runOnAlloca(AllocaInst &AI) {
2609 DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
2610 ++NumAllocasAnalyzed;
2611
2612 // Special case dead allocas, as they're trivial.
2613 if (AI.use_empty()) {
2614 AI.eraseFromParent();
2615 return true;
2616 }
2617
2618 // Skip alloca forms that this analysis can't handle.
2619 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
2620 TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
2621 return false;
2622
2623 // First check if this is a non-aggregate type that we should simply promote.
2624 if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
2625 DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
2626 PromotableAllocas.push_back(&AI);
2627 return false;
2628 }
2629
2630 // Build the partition set using a recursive instruction-visiting builder.
2631 AllocaPartitioning P(*TD, AI);
2632 DEBUG(P.print(dbgs()));
2633 if (P.isEscaped())
2634 return false;
2635
2636 // No partitions to split. Leave the dead alloca for a later pass to clean up.
2637 if (P.begin() == P.end())
2638 return false;
2639
2640 // Delete all the dead users of this alloca before splitting and rewriting it.
2641 bool Changed = false;
2642 for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
2643 DE = P.dead_user_end();
2644 DI != DE; ++DI) {
2645 Changed = true;
2646 (*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
2647 DeadInsts.push_back(*DI);
2648 }
2649 for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
2650 DE = P.dead_op_end();
2651 DO != DE; ++DO) {
2652 Value *OldV = **DO;
2653 // Clobber the use with an undef value.
2654 **DO = UndefValue::get(OldV->getType());
2655 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
2656 if (isInstructionTriviallyDead(OldI)) {
2657 Changed = true;
2658 DeadInsts.push_back(OldI);
2659 }
2660 }
2661
2662 return splitAlloca(AI, P) || Changed;
2663}
2664
Chandler Carruth8615cd22012-09-14 10:26:38 +00002665/// \brief Delete the dead instructions accumulated in this run.
2666///
2667/// Recursively deletes the dead instructions we've accumulated. This is done
2668/// at the very end to maximize locality of the recursive delete and to
2669/// minimize the problems of invalidated instruction pointers as such pointers
2670/// are used heavily in the intermediate stages of the algorithm.
2671///
2672/// We also record the alloca instructions deleted here so that they aren't
2673/// subsequently handed to mem2reg to promote.
2674void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
Chandler Carruth713aa942012-09-14 09:22:59 +00002675 DeadSplitInsts.clear();
2676 while (!DeadInsts.empty()) {
2677 Instruction *I = DeadInsts.pop_back_val();
2678 DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
2679
2680 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
2681 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
2682 // Zero out the operand and see if it becomes trivially dead.
2683 *OI = 0;
2684 if (isInstructionTriviallyDead(U))
2685 DeadInsts.push_back(U);
2686 }
2687
2688 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2689 DeletedAllocas.insert(AI);
2690
2691 ++NumDeleted;
2692 I->eraseFromParent();
2693 }
2694}
2695
Chandler Carruth1c8db502012-09-15 11:43:14 +00002696/// \brief Promote the allocas, using the best available technique.
2697///
2698/// This attempts to promote whatever allocas have been identified as viable in
2699/// the PromotableAllocas list. If that list is empty, there is nothing to do.
2700/// If there is a domtree available, we attempt to promote using the full power
2701/// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
2702/// based on the SSAUpdater utilities. This function returns whether any
2703/// promotion occured.
2704bool SROA::promoteAllocas(Function &F) {
2705 if (PromotableAllocas.empty())
2706 return false;
2707
2708 NumPromoted += PromotableAllocas.size();
2709
2710 if (DT && !ForceSSAUpdater) {
2711 DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
2712 PromoteMemToReg(PromotableAllocas, *DT);
2713 PromotableAllocas.clear();
2714 return true;
2715 }
2716
2717 DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
2718 SSAUpdater SSA;
2719 DIBuilder DIB(*F.getParent());
2720 SmallVector<Instruction*, 64> Insts;
2721
2722 for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
2723 AllocaInst *AI = PromotableAllocas[Idx];
2724 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
2725 UI != UE;) {
2726 Instruction *I = cast<Instruction>(*UI++);
2727 // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
2728 // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
2729 // leading to them) here. Eventually it should use them to optimize the
2730 // scalar values produced.
2731 if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
2732 assert(onlyUsedByLifetimeMarkers(I) &&
2733 "Found a bitcast used outside of a lifetime marker.");
2734 while (!I->use_empty())
2735 cast<Instruction>(*I->use_begin())->eraseFromParent();
2736 I->eraseFromParent();
2737 continue;
2738 }
2739 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2740 assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
2741 II->getIntrinsicID() == Intrinsic::lifetime_end);
2742 II->eraseFromParent();
2743 continue;
2744 }
2745
2746 Insts.push_back(I);
2747 }
2748 AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
2749 Insts.clear();
2750 }
2751
2752 PromotableAllocas.clear();
2753 return true;
2754}
2755
Chandler Carruth713aa942012-09-14 09:22:59 +00002756namespace {
2757 /// \brief A predicate to test whether an alloca belongs to a set.
2758 class IsAllocaInSet {
2759 typedef SmallPtrSet<AllocaInst *, 4> SetType;
2760 const SetType &Set;
2761
2762 public:
2763 IsAllocaInSet(const SetType &Set) : Set(Set) {}
2764 bool operator()(AllocaInst *AI) { return Set.count(AI); }
2765 };
2766}
2767
2768bool SROA::runOnFunction(Function &F) {
2769 DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
2770 C = &F.getContext();
2771 TD = getAnalysisIfAvailable<TargetData>();
2772 if (!TD) {
2773 DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
2774 return false;
2775 }
Chandler Carruth1c8db502012-09-15 11:43:14 +00002776 DT = getAnalysisIfAvailable<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00002777
2778 BasicBlock &EntryBB = F.getEntryBlock();
2779 for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
2780 I != E; ++I)
2781 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
2782 Worklist.insert(AI);
2783
2784 bool Changed = false;
Chandler Carruth8615cd22012-09-14 10:26:38 +00002785 // A set of deleted alloca instruction pointers which should be removed from
2786 // the list of promotable allocas.
2787 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
2788
Chandler Carruth713aa942012-09-14 09:22:59 +00002789 while (!Worklist.empty()) {
2790 Changed |= runOnAlloca(*Worklist.pop_back_val());
Chandler Carruth8615cd22012-09-14 10:26:38 +00002791 deleteDeadInstructions(DeletedAllocas);
Chandler Carruth713aa942012-09-14 09:22:59 +00002792 if (!DeletedAllocas.empty()) {
2793 PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
2794 PromotableAllocas.end(),
2795 IsAllocaInSet(DeletedAllocas)),
2796 PromotableAllocas.end());
2797 DeletedAllocas.clear();
2798 }
2799 }
2800
Chandler Carruth1c8db502012-09-15 11:43:14 +00002801 Changed |= promoteAllocas(F);
Chandler Carruth713aa942012-09-14 09:22:59 +00002802
2803 return Changed;
2804}
2805
2806void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruth1c8db502012-09-15 11:43:14 +00002807 if (RequiresDomTree)
2808 AU.addRequired<DominatorTree>();
Chandler Carruth713aa942012-09-14 09:22:59 +00002809 AU.setPreservesCFG();
2810}