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