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