Bug Summary

File:lib/Transforms/Scalar/SROA.cpp
Warning:line 2844, column 54
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SROA.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/lib/Transforms/Scalar -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp -faddrsig
1//===- 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#include "llvm/Transforms/Scalar/SROA.h"
27#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SetVector.h"
33#include "llvm/ADT/SmallBitVector.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/StringRef.h"
38#include "llvm/ADT/Twine.h"
39#include "llvm/ADT/iterator.h"
40#include "llvm/ADT/iterator_range.h"
41#include "llvm/Analysis/AssumptionCache.h"
42#include "llvm/Analysis/GlobalsModRef.h"
43#include "llvm/Analysis/Loads.h"
44#include "llvm/Analysis/PtrUseVisitor.h"
45#include "llvm/Transforms/Utils/Local.h"
46#include "llvm/Config/llvm-config.h"
47#include "llvm/IR/BasicBlock.h"
48#include "llvm/IR/Constant.h"
49#include "llvm/IR/ConstantFolder.h"
50#include "llvm/IR/Constants.h"
51#include "llvm/IR/DIBuilder.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/DebugInfoMetadata.h"
54#include "llvm/IR/DerivedTypes.h"
55#include "llvm/IR/Dominators.h"
56#include "llvm/IR/Function.h"
57#include "llvm/IR/GetElementPtrTypeIterator.h"
58#include "llvm/IR/GlobalAlias.h"
59#include "llvm/IR/IRBuilder.h"
60#include "llvm/IR/InstVisitor.h"
61#include "llvm/IR/InstrTypes.h"
62#include "llvm/IR/Instruction.h"
63#include "llvm/IR/Instructions.h"
64#include "llvm/IR/IntrinsicInst.h"
65#include "llvm/IR/Intrinsics.h"
66#include "llvm/IR/LLVMContext.h"
67#include "llvm/IR/Metadata.h"
68#include "llvm/IR/Module.h"
69#include "llvm/IR/Operator.h"
70#include "llvm/IR/PassManager.h"
71#include "llvm/IR/Type.h"
72#include "llvm/IR/Use.h"
73#include "llvm/IR/User.h"
74#include "llvm/IR/Value.h"
75#include "llvm/Pass.h"
76#include "llvm/Support/Casting.h"
77#include "llvm/Support/CommandLine.h"
78#include "llvm/Support/Compiler.h"
79#include "llvm/Support/Debug.h"
80#include "llvm/Support/ErrorHandling.h"
81#include "llvm/Support/MathExtras.h"
82#include "llvm/Support/raw_ostream.h"
83#include "llvm/Transforms/Scalar.h"
84#include "llvm/Transforms/Utils/PromoteMemToReg.h"
85#include <algorithm>
86#include <cassert>
87#include <chrono>
88#include <cstddef>
89#include <cstdint>
90#include <cstring>
91#include <iterator>
92#include <string>
93#include <tuple>
94#include <utility>
95#include <vector>
96
97#ifndef NDEBUG
98// We only use this for a debug check.
99#include <random>
100#endif
101
102using namespace llvm;
103using namespace llvm::sroa;
104
105#define DEBUG_TYPE"sroa" "sroa"
106
107STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement")static llvm::Statistic NumAllocasAnalyzed = {"sroa", "NumAllocasAnalyzed"
, "Number of allocas analyzed for replacement", {0}, {false}}
;
108STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed")static llvm::Statistic NumAllocaPartitions = {"sroa", "NumAllocaPartitions"
, "Number of alloca partitions formed", {0}, {false}}
;
109STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca")static llvm::Statistic MaxPartitionsPerAlloca = {"sroa", "MaxPartitionsPerAlloca"
, "Maximum number of partitions per alloca", {0}, {false}}
;
110STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten")static llvm::Statistic NumAllocaPartitionUses = {"sroa", "NumAllocaPartitionUses"
, "Number of alloca partition uses rewritten", {0}, {false}}
;
111STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition")static llvm::Statistic MaxUsesPerAllocaPartition = {"sroa", "MaxUsesPerAllocaPartition"
, "Maximum number of uses of a partition", {0}, {false}}
;
112STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced")static llvm::Statistic NumNewAllocas = {"sroa", "NumNewAllocas"
, "Number of new, smaller allocas introduced", {0}, {false}}
;
113STATISTIC(NumPromoted, "Number of allocas promoted to SSA values")static llvm::Statistic NumPromoted = {"sroa", "NumPromoted", "Number of allocas promoted to SSA values"
, {0}, {false}}
;
114STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion")static llvm::Statistic NumLoadsSpeculated = {"sroa", "NumLoadsSpeculated"
, "Number of loads speculated to allow promotion", {0}, {false
}}
;
115STATISTIC(NumDeleted, "Number of instructions deleted")static llvm::Statistic NumDeleted = {"sroa", "NumDeleted", "Number of instructions deleted"
, {0}, {false}}
;
116STATISTIC(NumVectorized, "Number of vectorized aggregates")static llvm::Statistic NumVectorized = {"sroa", "NumVectorized"
, "Number of vectorized aggregates", {0}, {false}}
;
117
118/// Hidden option to enable randomly shuffling the slices to help uncover
119/// instability in their order.
120static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
121 cl::init(false), cl::Hidden);
122
123/// Hidden option to experiment with completely strict handling of inbounds
124/// GEPs.
125static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
126 cl::Hidden);
127
128namespace {
129
130/// A custom IRBuilder inserter which prefixes all names, but only in
131/// Assert builds.
132class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
133 std::string Prefix;
134
135 const Twine getNameWithPrefix(const Twine &Name) const {
136 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
137 }
138
139public:
140 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
141
142protected:
143 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
144 BasicBlock::iterator InsertPt) const {
145 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
146 InsertPt);
147 }
148};
149
150/// Provide a type for IRBuilder that drops names in release builds.
151using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
152
153/// A used slice of an alloca.
154///
155/// This structure represents a slice of an alloca used by some instruction. It
156/// stores both the begin and end offsets of this use, a pointer to the use
157/// itself, and a flag indicating whether we can classify the use as splittable
158/// or not when forming partitions of the alloca.
159class Slice {
160 /// The beginning offset of the range.
161 uint64_t BeginOffset = 0;
162
163 /// The ending offset, not included in the range.
164 uint64_t EndOffset = 0;
165
166 /// Storage for both the use of this slice and whether it can be
167 /// split.
168 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
169
170public:
171 Slice() = default;
172
173 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
174 : BeginOffset(BeginOffset), EndOffset(EndOffset),
175 UseAndIsSplittable(U, IsSplittable) {}
176
177 uint64_t beginOffset() const { return BeginOffset; }
178 uint64_t endOffset() const { return EndOffset; }
179
180 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
181 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
182
183 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
184
185 bool isDead() const { return getUse() == nullptr; }
186 void kill() { UseAndIsSplittable.setPointer(nullptr); }
187
188 /// Support for ordering ranges.
189 ///
190 /// This provides an ordering over ranges such that start offsets are
191 /// always increasing, and within equal start offsets, the end offsets are
192 /// decreasing. Thus the spanning range comes first in a cluster with the
193 /// same start position.
194 bool operator<(const Slice &RHS) const {
195 if (beginOffset() < RHS.beginOffset())
196 return true;
197 if (beginOffset() > RHS.beginOffset())
198 return false;
199 if (isSplittable() != RHS.isSplittable())
200 return !isSplittable();
201 if (endOffset() > RHS.endOffset())
202 return true;
203 return false;
204 }
205
206 /// Support comparison with a single offset to allow binary searches.
207 friend LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) bool operator<(const Slice &LHS,
208 uint64_t RHSOffset) {
209 return LHS.beginOffset() < RHSOffset;
210 }
211 friend LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) bool operator<(uint64_t LHSOffset,
212 const Slice &RHS) {
213 return LHSOffset < RHS.beginOffset();
214 }
215
216 bool operator==(const Slice &RHS) const {
217 return isSplittable() == RHS.isSplittable() &&
218 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
219 }
220 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
221};
222
223} // end anonymous namespace
224
225namespace llvm {
226
227template <typename T> struct isPodLike;
228template <> struct isPodLike<Slice> { static const bool value = true; };
229
230} // end namespace llvm
231
232/// Representation of the alloca slices.
233///
234/// This class represents the slices of an alloca which are formed by its
235/// various uses. If a pointer escapes, we can't fully build a representation
236/// for the slices used and we reflect that in this structure. The uses are
237/// stored, sorted by increasing beginning offset and with unsplittable slices
238/// starting at a particular offset before splittable slices.
239class llvm::sroa::AllocaSlices {
240public:
241 /// Construct the slices of a particular alloca.
242 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
243
244 /// Test whether a pointer to the allocation escapes our analysis.
245 ///
246 /// If this is true, the slices are never fully built and should be
247 /// ignored.
248 bool isEscaped() const { return PointerEscapingInstr; }
249
250 /// Support for iterating over the slices.
251 /// @{
252 using iterator = SmallVectorImpl<Slice>::iterator;
253 using range = iterator_range<iterator>;
254
255 iterator begin() { return Slices.begin(); }
256 iterator end() { return Slices.end(); }
257
258 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
259 using const_range = iterator_range<const_iterator>;
260
261 const_iterator begin() const { return Slices.begin(); }
262 const_iterator end() const { return Slices.end(); }
263 /// @}
264
265 /// Erase a range of slices.
266 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
267
268 /// Insert new slices for this alloca.
269 ///
270 /// This moves the slices into the alloca's slices collection, and re-sorts
271 /// everything so that the usual ordering properties of the alloca's slices
272 /// hold.
273 void insert(ArrayRef<Slice> NewSlices) {
274 int OldSize = Slices.size();
275 Slices.append(NewSlices.begin(), NewSlices.end());
276 auto SliceI = Slices.begin() + OldSize;
277 llvm::sort(SliceI, Slices.end());
278 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
279 }
280
281 // Forward declare the iterator and range accessor for walking the
282 // partitions.
283 class partition_iterator;
284 iterator_range<partition_iterator> partitions();
285
286 /// Access the dead users for this alloca.
287 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
288
289 /// Access the dead operands referring to this alloca.
290 ///
291 /// These are operands which have cannot actually be used to refer to the
292 /// alloca as they are outside its range and the user doesn't correct for
293 /// that. These mostly consist of PHI node inputs and the like which we just
294 /// need to replace with undef.
295 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
296
297#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
298 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
299 void printSlice(raw_ostream &OS, const_iterator I,
300 StringRef Indent = " ") const;
301 void printUse(raw_ostream &OS, const_iterator I,
302 StringRef Indent = " ") const;
303 void print(raw_ostream &OS) const;
304 void dump(const_iterator I) const;
305 void dump() const;
306#endif
307
308private:
309 template <typename DerivedT, typename RetT = void> class BuilderBase;
310 class SliceBuilder;
311
312 friend class AllocaSlices::SliceBuilder;
313
314#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
315 /// Handle to alloca instruction to simplify method interfaces.
316 AllocaInst &AI;
317#endif
318
319 /// The instruction responsible for this alloca not having a known set
320 /// of slices.
321 ///
322 /// When an instruction (potentially) escapes the pointer to the alloca, we
323 /// store a pointer to that here and abort trying to form slices of the
324 /// alloca. This will be null if the alloca slices are analyzed successfully.
325 Instruction *PointerEscapingInstr;
326
327 /// The slices of the alloca.
328 ///
329 /// We store a vector of the slices formed by uses of the alloca here. This
330 /// vector is sorted by increasing begin offset, and then the unsplittable
331 /// slices before the splittable ones. See the Slice inner class for more
332 /// details.
333 SmallVector<Slice, 8> Slices;
334
335 /// Instructions which will become dead if we rewrite the alloca.
336 ///
337 /// Note that these are not separated by slice. This is because we expect an
338 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
339 /// all these instructions can simply be removed and replaced with undef as
340 /// they come from outside of the allocated space.
341 SmallVector<Instruction *, 8> DeadUsers;
342
343 /// Operands which will become dead if we rewrite the alloca.
344 ///
345 /// These are operands that in their particular use can be replaced with
346 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
347 /// to PHI nodes and the like. They aren't entirely dead (there might be
348 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
349 /// want to swap this particular input for undef to simplify the use lists of
350 /// the alloca.
351 SmallVector<Use *, 8> DeadOperands;
352};
353
354/// A partition of the slices.
355///
356/// An ephemeral representation for a range of slices which can be viewed as
357/// a partition of the alloca. This range represents a span of the alloca's
358/// memory which cannot be split, and provides access to all of the slices
359/// overlapping some part of the partition.
360///
361/// Objects of this type are produced by traversing the alloca's slices, but
362/// are only ephemeral and not persistent.
363class llvm::sroa::Partition {
364private:
365 friend class AllocaSlices;
366 friend class AllocaSlices::partition_iterator;
367
368 using iterator = AllocaSlices::iterator;
369
370 /// The beginning and ending offsets of the alloca for this
371 /// partition.
372 uint64_t BeginOffset, EndOffset;
373
374 /// The start and end iterators of this partition.
375 iterator SI, SJ;
376
377 /// A collection of split slice tails overlapping the partition.
378 SmallVector<Slice *, 4> SplitTails;
379
380 /// Raw constructor builds an empty partition starting and ending at
381 /// the given iterator.
382 Partition(iterator SI) : SI(SI), SJ(SI) {}
383
384public:
385 /// The start offset of this partition.
386 ///
387 /// All of the contained slices start at or after this offset.
388 uint64_t beginOffset() const { return BeginOffset; }
389
390 /// The end offset of this partition.
391 ///
392 /// All of the contained slices end at or before this offset.
393 uint64_t endOffset() const { return EndOffset; }
394
395 /// The size of the partition.
396 ///
397 /// Note that this can never be zero.
398 uint64_t size() const {
399 assert(BeginOffset < EndOffset && "Partitions must span some bytes!")(static_cast <bool> (BeginOffset < EndOffset &&
"Partitions must span some bytes!") ? void (0) : __assert_fail
("BeginOffset < EndOffset && \"Partitions must span some bytes!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 399, __extension__ __PRETTY_FUNCTION__))
;
400 return EndOffset - BeginOffset;
401 }
402
403 /// Test whether this partition contains no slices, and merely spans
404 /// a region occupied by split slices.
405 bool empty() const { return SI == SJ; }
406
407 /// \name Iterate slices that start within the partition.
408 /// These may be splittable or unsplittable. They have a begin offset >= the
409 /// partition begin offset.
410 /// @{
411 // FIXME: We should probably define a "concat_iterator" helper and use that
412 // to stitch together pointee_iterators over the split tails and the
413 // contiguous iterators of the partition. That would give a much nicer
414 // interface here. We could then additionally expose filtered iterators for
415 // split, unsplit, and unsplittable splices based on the usage patterns.
416 iterator begin() const { return SI; }
417 iterator end() const { return SJ; }
418 /// @}
419
420 /// Get the sequence of split slice tails.
421 ///
422 /// These tails are of slices which start before this partition but are
423 /// split and overlap into the partition. We accumulate these while forming
424 /// partitions.
425 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
426};
427
428/// An iterator over partitions of the alloca's slices.
429///
430/// This iterator implements the core algorithm for partitioning the alloca's
431/// slices. It is a forward iterator as we don't support backtracking for
432/// efficiency reasons, and re-use a single storage area to maintain the
433/// current set of split slices.
434///
435/// It is templated on the slice iterator type to use so that it can operate
436/// with either const or non-const slice iterators.
437class AllocaSlices::partition_iterator
438 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
439 Partition> {
440 friend class AllocaSlices;
441
442 /// Most of the state for walking the partitions is held in a class
443 /// with a nice interface for examining them.
444 Partition P;
445
446 /// We need to keep the end of the slices to know when to stop.
447 AllocaSlices::iterator SE;
448
449 /// We also need to keep track of the maximum split end offset seen.
450 /// FIXME: Do we really?
451 uint64_t MaxSplitSliceEndOffset = 0;
452
453 /// Sets the partition to be empty at given iterator, and sets the
454 /// end iterator.
455 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
456 : P(SI), SE(SE) {
457 // If not already at the end, advance our state to form the initial
458 // partition.
459 if (SI != SE)
460 advance();
461 }
462
463 /// Advance the iterator to the next partition.
464 ///
465 /// Requires that the iterator not be at the end of the slices.
466 void advance() {
467 assert((P.SI != SE || !P.SplitTails.empty()) &&(static_cast <bool> ((P.SI != SE || !P.SplitTails.empty
()) && "Cannot advance past the end of the slices!") ?
void (0) : __assert_fail ("(P.SI != SE || !P.SplitTails.empty()) && \"Cannot advance past the end of the slices!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 468, __extension__ __PRETTY_FUNCTION__))
468 "Cannot advance past the end of the slices!")(static_cast <bool> ((P.SI != SE || !P.SplitTails.empty
()) && "Cannot advance past the end of the slices!") ?
void (0) : __assert_fail ("(P.SI != SE || !P.SplitTails.empty()) && \"Cannot advance past the end of the slices!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 468, __extension__ __PRETTY_FUNCTION__))
;
469
470 // Clear out any split uses which have ended.
471 if (!P.SplitTails.empty()) {
472 if (P.EndOffset >= MaxSplitSliceEndOffset) {
473 // If we've finished all splits, this is easy.
474 P.SplitTails.clear();
475 MaxSplitSliceEndOffset = 0;
476 } else {
477 // Remove the uses which have ended in the prior partition. This
478 // cannot change the max split slice end because we just checked that
479 // the prior partition ended prior to that max.
480 P.SplitTails.erase(llvm::remove_if(P.SplitTails,
481 [&](Slice *S) {
482 return S->endOffset() <=
483 P.EndOffset;
484 }),
485 P.SplitTails.end());
486 assert(llvm::any_of(P.SplitTails,(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 490, __extension__ __PRETTY_FUNCTION__))
487 [&](Slice *S) {(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 490, __extension__ __PRETTY_FUNCTION__))
488 return S->endOffset() == MaxSplitSliceEndOffset;(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 490, __extension__ __PRETTY_FUNCTION__))
489 }) &&(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 490, __extension__ __PRETTY_FUNCTION__))
490 "Could not find the current max split slice offset!")(static_cast <bool> (llvm::any_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset
; }) && "Could not find the current max split slice offset!"
) ? void (0) : __assert_fail ("llvm::any_of(P.SplitTails, [&](Slice *S) { return S->endOffset() == MaxSplitSliceEndOffset; }) && \"Could not find the current max split slice offset!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 490, __extension__ __PRETTY_FUNCTION__))
;
491 assert(llvm::all_of(P.SplitTails,(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 495, __extension__ __PRETTY_FUNCTION__))
492 [&](Slice *S) {(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 495, __extension__ __PRETTY_FUNCTION__))
493 return S->endOffset() <= MaxSplitSliceEndOffset;(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 495, __extension__ __PRETTY_FUNCTION__))
494 }) &&(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 495, __extension__ __PRETTY_FUNCTION__))
495 "Max split slice end offset is not actually the max!")(static_cast <bool> (llvm::all_of(P.SplitTails, [&]
(Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset
; }) && "Max split slice end offset is not actually the max!"
) ? void (0) : __assert_fail ("llvm::all_of(P.SplitTails, [&](Slice *S) { return S->endOffset() <= MaxSplitSliceEndOffset; }) && \"Max split slice end offset is not actually the max!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 495, __extension__ __PRETTY_FUNCTION__))
;
496 }
497 }
498
499 // If P.SI is already at the end, then we've cleared the split tail and
500 // now have an end iterator.
501 if (P.SI == SE) {
502 assert(P.SplitTails.empty() && "Failed to clear the split slices!")(static_cast <bool> (P.SplitTails.empty() && "Failed to clear the split slices!"
) ? void (0) : __assert_fail ("P.SplitTails.empty() && \"Failed to clear the split slices!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 502, __extension__ __PRETTY_FUNCTION__))
;
503 return;
504 }
505
506 // If we had a non-empty partition previously, set up the state for
507 // subsequent partitions.
508 if (P.SI != P.SJ) {
509 // Accumulate all the splittable slices which started in the old
510 // partition into the split list.
511 for (Slice &S : P)
512 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
513 P.SplitTails.push_back(&S);
514 MaxSplitSliceEndOffset =
515 std::max(S.endOffset(), MaxSplitSliceEndOffset);
516 }
517
518 // Start from the end of the previous partition.
519 P.SI = P.SJ;
520
521 // If P.SI is now at the end, we at most have a tail of split slices.
522 if (P.SI == SE) {
523 P.BeginOffset = P.EndOffset;
524 P.EndOffset = MaxSplitSliceEndOffset;
525 return;
526 }
527
528 // If the we have split slices and the next slice is after a gap and is
529 // not splittable immediately form an empty partition for the split
530 // slices up until the next slice begins.
531 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
532 !P.SI->isSplittable()) {
533 P.BeginOffset = P.EndOffset;
534 P.EndOffset = P.SI->beginOffset();
535 return;
536 }
537 }
538
539 // OK, we need to consume new slices. Set the end offset based on the
540 // current slice, and step SJ past it. The beginning offset of the
541 // partition is the beginning offset of the next slice unless we have
542 // pre-existing split slices that are continuing, in which case we begin
543 // at the prior end offset.
544 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
545 P.EndOffset = P.SI->endOffset();
546 ++P.SJ;
547
548 // There are two strategies to form a partition based on whether the
549 // partition starts with an unsplittable slice or a splittable slice.
550 if (!P.SI->isSplittable()) {
551 // When we're forming an unsplittable region, it must always start at
552 // the first slice and will extend through its end.
553 assert(P.BeginOffset == P.SI->beginOffset())(static_cast <bool> (P.BeginOffset == P.SI->beginOffset
()) ? void (0) : __assert_fail ("P.BeginOffset == P.SI->beginOffset()"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 553, __extension__ __PRETTY_FUNCTION__))
;
554
555 // Form a partition including all of the overlapping slices with this
556 // unsplittable slice.
557 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
558 if (!P.SJ->isSplittable())
559 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
560 ++P.SJ;
561 }
562
563 // We have a partition across a set of overlapping unsplittable
564 // partitions.
565 return;
566 }
567
568 // If we're starting with a splittable slice, then we need to form
569 // a synthetic partition spanning it and any other overlapping splittable
570 // splices.
571 assert(P.SI->isSplittable() && "Forming a splittable partition!")(static_cast <bool> (P.SI->isSplittable() &&
"Forming a splittable partition!") ? void (0) : __assert_fail
("P.SI->isSplittable() && \"Forming a splittable partition!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 571, __extension__ __PRETTY_FUNCTION__))
;
572
573 // Collect all of the overlapping splittable slices.
574 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
575 P.SJ->isSplittable()) {
576 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
577 ++P.SJ;
578 }
579
580 // Back upiP.EndOffset if we ended the span early when encountering an
581 // unsplittable slice. This synthesizes the early end offset of
582 // a partition spanning only splittable slices.
583 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
584 assert(!P.SJ->isSplittable())(static_cast <bool> (!P.SJ->isSplittable()) ? void (
0) : __assert_fail ("!P.SJ->isSplittable()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 584, __extension__ __PRETTY_FUNCTION__))
;
585 P.EndOffset = P.SJ->beginOffset();
586 }
587 }
588
589public:
590 bool operator==(const partition_iterator &RHS) const {
591 assert(SE == RHS.SE &&(static_cast <bool> (SE == RHS.SE && "End iterators don't match between compared partition iterators!"
) ? void (0) : __assert_fail ("SE == RHS.SE && \"End iterators don't match between compared partition iterators!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 592, __extension__ __PRETTY_FUNCTION__))
592 "End iterators don't match between compared partition iterators!")(static_cast <bool> (SE == RHS.SE && "End iterators don't match between compared partition iterators!"
) ? void (0) : __assert_fail ("SE == RHS.SE && \"End iterators don't match between compared partition iterators!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 592, __extension__ __PRETTY_FUNCTION__))
;
593
594 // The observed positions of partitions is marked by the P.SI iterator and
595 // the emptiness of the split slices. The latter is only relevant when
596 // P.SI == SE, as the end iterator will additionally have an empty split
597 // slices list, but the prior may have the same P.SI and a tail of split
598 // slices.
599 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
600 assert(P.SJ == RHS.P.SJ &&(static_cast <bool> (P.SJ == RHS.P.SJ && "Same set of slices formed two different sized partitions!"
) ? void (0) : __assert_fail ("P.SJ == RHS.P.SJ && \"Same set of slices formed two different sized partitions!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 601, __extension__ __PRETTY_FUNCTION__))
601 "Same set of slices formed two different sized partitions!")(static_cast <bool> (P.SJ == RHS.P.SJ && "Same set of slices formed two different sized partitions!"
) ? void (0) : __assert_fail ("P.SJ == RHS.P.SJ && \"Same set of slices formed two different sized partitions!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 601, __extension__ __PRETTY_FUNCTION__))
;
602 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&(static_cast <bool> (P.SplitTails.size() == RHS.P.SplitTails
.size() && "Same slice position with differently sized non-empty split "
"slice tails!") ? void (0) : __assert_fail ("P.SplitTails.size() == RHS.P.SplitTails.size() && \"Same slice position with differently sized non-empty split \" \"slice tails!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 604, __extension__ __PRETTY_FUNCTION__))
603 "Same slice position with differently sized non-empty split "(static_cast <bool> (P.SplitTails.size() == RHS.P.SplitTails
.size() && "Same slice position with differently sized non-empty split "
"slice tails!") ? void (0) : __assert_fail ("P.SplitTails.size() == RHS.P.SplitTails.size() && \"Same slice position with differently sized non-empty split \" \"slice tails!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 604, __extension__ __PRETTY_FUNCTION__))
604 "slice tails!")(static_cast <bool> (P.SplitTails.size() == RHS.P.SplitTails
.size() && "Same slice position with differently sized non-empty split "
"slice tails!") ? void (0) : __assert_fail ("P.SplitTails.size() == RHS.P.SplitTails.size() && \"Same slice position with differently sized non-empty split \" \"slice tails!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 604, __extension__ __PRETTY_FUNCTION__))
;
605 return true;
606 }
607 return false;
608 }
609
610 partition_iterator &operator++() {
611 advance();
612 return *this;
613 }
614
615 Partition &operator*() { return P; }
616};
617
618/// A forward range over the partitions of the alloca's slices.
619///
620/// This accesses an iterator range over the partitions of the alloca's
621/// slices. It computes these partitions on the fly based on the overlapping
622/// offsets of the slices and the ability to split them. It will visit "empty"
623/// partitions to cover regions of the alloca only accessed via split
624/// slices.
625iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
626 return make_range(partition_iterator(begin(), end()),
627 partition_iterator(end(), end()));
628}
629
630static Value *foldSelectInst(SelectInst &SI) {
631 // If the condition being selected on is a constant or the same value is
632 // being selected between, fold the select. Yes this does (rarely) happen
633 // early on.
634 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
635 return SI.getOperand(1 + CI->isZero());
636 if (SI.getOperand(1) == SI.getOperand(2))
637 return SI.getOperand(1);
638
639 return nullptr;
640}
641
642/// A helper that folds a PHI node or a select.
643static Value *foldPHINodeOrSelectInst(Instruction &I) {
644 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
645 // If PN merges together the same value, return that value.
646 return PN->hasConstantValue();
647 }
648 return foldSelectInst(cast<SelectInst>(I));
649}
650
651/// Builder for the alloca slices.
652///
653/// This class builds a set of alloca slices by recursively visiting the uses
654/// of an alloca and making a slice for each load and store at each offset.
655class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
656 friend class PtrUseVisitor<SliceBuilder>;
657 friend class InstVisitor<SliceBuilder>;
658
659 using Base = PtrUseVisitor<SliceBuilder>;
660
661 const uint64_t AllocSize;
662 AllocaSlices &AS;
663
664 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
665 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
666
667 /// Set to de-duplicate dead instructions found in the use walk.
668 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
669
670public:
671 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
672 : PtrUseVisitor<SliceBuilder>(DL),
673 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
674
675private:
676 void markAsDead(Instruction &I) {
677 if (VisitedDeadInsts.insert(&I).second)
678 AS.DeadUsers.push_back(&I);
679 }
680
681 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
682 bool IsSplittable = false) {
683 // Completely skip uses which have a zero size or start either before or
684 // past the end of the allocation.
685 if (Size == 0 || Offset.uge(AllocSize)) {
686 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
687 << Offsetdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
688 << " which has zero size or starts outside of the "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
689 << AllocSize << " byte alloca:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
690 << " alloca: " << AS.AI << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
691 << " use: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte use @" << Offset << " which has zero size or starts outside of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
;
692 return markAsDead(I);
693 }
694
695 uint64_t BeginOffset = Offset.getZExtValue();
696 uint64_t EndOffset = BeginOffset + Size;
697
698 // Clamp the end offset to the end of the allocation. Note that this is
699 // formulated to handle even the case where "BeginOffset + Size" overflows.
700 // This may appear superficially to be something we could ignore entirely,
701 // but that is not so! There may be widened loads or PHI-node uses where
702 // some instructions are dead but not others. We can't completely ignore
703 // them, and so have to record at least the information here.
704 assert(AllocSize >= BeginOffset)(static_cast <bool> (AllocSize >= BeginOffset) ? void
(0) : __assert_fail ("AllocSize >= BeginOffset", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 704, __extension__ __PRETTY_FUNCTION__))
; // Established above.
705 if (Size > AllocSize - BeginOffset) {
706 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
707 << Offset << " to remain within the " << AllocSizedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
708 << " byte alloca:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
709 << " alloca: " << AS.AI << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
710 << " use: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Clamping a " << Size
<< " byte use @" << Offset << " to remain within the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
I << "\n"; } } while (false)
;
711 EndOffset = AllocSize;
712 }
713
714 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
715 }
716
717 void visitBitCastInst(BitCastInst &BC) {
718 if (BC.use_empty())
719 return markAsDead(BC);
720
721 return Base::visitBitCastInst(BC);
722 }
723
724 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
725 if (GEPI.use_empty())
726 return markAsDead(GEPI);
727
728 if (SROAStrictInbounds && GEPI.isInBounds()) {
729 // FIXME: This is a manually un-factored variant of the basic code inside
730 // of GEPs with checking of the inbounds invariant specified in the
731 // langref in a very strict sense. If we ever want to enable
732 // SROAStrictInbounds, this code should be factored cleanly into
733 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
734 // by writing out the code here where we have the underlying allocation
735 // size readily available.
736 APInt GEPOffset = Offset;
737 const DataLayout &DL = GEPI.getModule()->getDataLayout();
738 for (gep_type_iterator GTI = gep_type_begin(GEPI),
739 GTE = gep_type_end(GEPI);
740 GTI != GTE; ++GTI) {
741 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
742 if (!OpC)
743 break;
744
745 // Handle a struct index, which adds its field offset to the pointer.
746 if (StructType *STy = GTI.getStructTypeOrNull()) {
747 unsigned ElementIdx = OpC->getZExtValue();
748 const StructLayout *SL = DL.getStructLayout(STy);
749 GEPOffset +=
750 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
751 } else {
752 // For array or vector indices, scale the index by the size of the
753 // type.
754 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
755 GEPOffset += Index * APInt(Offset.getBitWidth(),
756 DL.getTypeAllocSize(GTI.getIndexedType()));
757 }
758
759 // If this index has computed an intermediate pointer which is not
760 // inbounds, then the result of the GEP is a poison value and we can
761 // delete it and all uses.
762 if (GEPOffset.ugt(AllocSize))
763 return markAsDead(GEPI);
764 }
765 }
766
767 return Base::visitGetElementPtrInst(GEPI);
768 }
769
770 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
771 uint64_t Size, bool IsVolatile) {
772 // We allow splitting of non-volatile loads and stores where the type is an
773 // integer type. These may be used to implement 'memcpy' or other "transfer
774 // of bits" patterns.
775 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
776
777 insertUse(I, Offset, Size, IsSplittable);
778 }
779
780 void visitLoadInst(LoadInst &LI) {
781 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&(static_cast <bool> ((!LI.isSimple() || LI.getType()->
isSingleValueType()) && "All simple FCA loads should have been pre-split"
) ? void (0) : __assert_fail ("(!LI.isSimple() || LI.getType()->isSingleValueType()) && \"All simple FCA loads should have been pre-split\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 782, __extension__ __PRETTY_FUNCTION__))
782 "All simple FCA loads should have been pre-split")(static_cast <bool> ((!LI.isSimple() || LI.getType()->
isSingleValueType()) && "All simple FCA loads should have been pre-split"
) ? void (0) : __assert_fail ("(!LI.isSimple() || LI.getType()->isSingleValueType()) && \"All simple FCA loads should have been pre-split\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 782, __extension__ __PRETTY_FUNCTION__))
;
783
784 if (!IsOffsetKnown)
785 return PI.setAborted(&LI);
786
787 const DataLayout &DL = LI.getModule()->getDataLayout();
788 uint64_t Size = DL.getTypeStoreSize(LI.getType());
789 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
790 }
791
792 void visitStoreInst(StoreInst &SI) {
793 Value *ValOp = SI.getValueOperand();
794 if (ValOp == *U)
795 return PI.setEscapedAndAborted(&SI);
796 if (!IsOffsetKnown)
797 return PI.setAborted(&SI);
798
799 const DataLayout &DL = SI.getModule()->getDataLayout();
800 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
801
802 // If this memory access can be shown to *statically* extend outside the
803 // bounds of the allocation, it's behavior is undefined, so simply
804 // ignore it. Note that this is more strict than the generic clamping
805 // behavior of insertUse. We also try to handle cases which might run the
806 // risk of overflow.
807 // FIXME: We should instead consider the pointer to have escaped if this
808 // function is being instrumented for addressing bugs or race conditions.
809 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
810 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
811 << Offset << " which extends past the end of the "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
812 << AllocSize << " byte alloca:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
813 << " alloca: " << AS.AI << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
814 << " use: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "WARNING: Ignoring " << Size
<< " byte store @" << Offset << " which extends past the end of the "
<< AllocSize << " byte alloca:\n" << " alloca: "
<< AS.AI << "\n" << " use: " <<
SI << "\n"; } } while (false)
;
815 return markAsDead(SI);
816 }
817
818 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&(static_cast <bool> ((!SI.isSimple() || ValOp->getType
()->isSingleValueType()) && "All simple FCA stores should have been pre-split"
) ? void (0) : __assert_fail ("(!SI.isSimple() || ValOp->getType()->isSingleValueType()) && \"All simple FCA stores should have been pre-split\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 819, __extension__ __PRETTY_FUNCTION__))
819 "All simple FCA stores should have been pre-split")(static_cast <bool> ((!SI.isSimple() || ValOp->getType
()->isSingleValueType()) && "All simple FCA stores should have been pre-split"
) ? void (0) : __assert_fail ("(!SI.isSimple() || ValOp->getType()->isSingleValueType()) && \"All simple FCA stores should have been pre-split\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 819, __extension__ __PRETTY_FUNCTION__))
;
820 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
821 }
822
823 void visitMemSetInst(MemSetInst &II) {
824 assert(II.getRawDest() == *U && "Pointer use is not the destination?")(static_cast <bool> (II.getRawDest() == *U && "Pointer use is not the destination?"
) ? void (0) : __assert_fail ("II.getRawDest() == *U && \"Pointer use is not the destination?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 824, __extension__ __PRETTY_FUNCTION__))
;
825 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
826 if ((Length && Length->getValue() == 0) ||
827 (IsOffsetKnown && Offset.uge(AllocSize)))
828 // Zero-length mem transfer intrinsics can be ignored entirely.
829 return markAsDead(II);
830
831 if (!IsOffsetKnown)
832 return PI.setAborted(&II);
833
834 insertUse(II, Offset, Length ? Length->getLimitedValue()
835 : AllocSize - Offset.getLimitedValue(),
836 (bool)Length);
837 }
838
839 void visitMemTransferInst(MemTransferInst &II) {
840 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
841 if (Length && Length->getValue() == 0)
842 // Zero-length mem transfer intrinsics can be ignored entirely.
843 return markAsDead(II);
844
845 // Because we can visit these intrinsics twice, also check to see if the
846 // first time marked this instruction as dead. If so, skip it.
847 if (VisitedDeadInsts.count(&II))
848 return;
849
850 if (!IsOffsetKnown)
851 return PI.setAborted(&II);
852
853 // This side of the transfer is completely out-of-bounds, and so we can
854 // nuke the entire transfer. However, we also need to nuke the other side
855 // if already added to our partitions.
856 // FIXME: Yet another place we really should bypass this when
857 // instrumenting for ASan.
858 if (Offset.uge(AllocSize)) {
859 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
860 MemTransferSliceMap.find(&II);
861 if (MTPI != MemTransferSliceMap.end())
862 AS.Slices[MTPI->second].kill();
863 return markAsDead(II);
864 }
865
866 uint64_t RawOffset = Offset.getLimitedValue();
867 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
868
869 // Check for the special case where the same exact value is used for both
870 // source and dest.
871 if (*U == II.getRawDest() && *U == II.getRawSource()) {
872 // For non-volatile transfers this is a no-op.
873 if (!II.isVolatile())
874 return markAsDead(II);
875
876 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
877 }
878
879 // If we have seen both source and destination for a mem transfer, then
880 // they both point to the same alloca.
881 bool Inserted;
882 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
883 std::tie(MTPI, Inserted) =
884 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
885 unsigned PrevIdx = MTPI->second;
886 if (!Inserted) {
887 Slice &PrevP = AS.Slices[PrevIdx];
888
889 // Check if the begin offsets match and this is a non-volatile transfer.
890 // In that case, we can completely elide the transfer.
891 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
892 PrevP.kill();
893 return markAsDead(II);
894 }
895
896 // Otherwise we have an offset transfer within the same alloca. We can't
897 // split those.
898 PrevP.makeUnsplittable();
899 }
900
901 // Insert the use now that we've fixed up the splittable nature.
902 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
903
904 // Check that we ended up with a valid index in the map.
905 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&(static_cast <bool> (AS.Slices[PrevIdx].getUse()->getUser
() == &II && "Map index doesn't point back to a slice with this user."
) ? void (0) : __assert_fail ("AS.Slices[PrevIdx].getUse()->getUser() == &II && \"Map index doesn't point back to a slice with this user.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 906, __extension__ __PRETTY_FUNCTION__))
906 "Map index doesn't point back to a slice with this user.")(static_cast <bool> (AS.Slices[PrevIdx].getUse()->getUser
() == &II && "Map index doesn't point back to a slice with this user."
) ? void (0) : __assert_fail ("AS.Slices[PrevIdx].getUse()->getUser() == &II && \"Map index doesn't point back to a slice with this user.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 906, __extension__ __PRETTY_FUNCTION__))
;
907 }
908
909 // Disable SRoA for any intrinsics except for lifetime invariants.
910 // FIXME: What about debug intrinsics? This matches old behavior, but
911 // doesn't make sense.
912 void visitIntrinsicInst(IntrinsicInst &II) {
913 if (!IsOffsetKnown)
914 return PI.setAborted(&II);
915
916 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
917 II.getIntrinsicID() == Intrinsic::lifetime_end) {
918 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
919 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
920 Length->getLimitedValue());
921 insertUse(II, Offset, Size, true);
922 return;
923 }
924
925 Base::visitIntrinsicInst(II);
926 }
927
928 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
929 // We consider any PHI or select that results in a direct load or store of
930 // the same offset to be a viable use for slicing purposes. These uses
931 // are considered unsplittable and the size is the maximum loaded or stored
932 // size.
933 SmallPtrSet<Instruction *, 4> Visited;
934 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
935 Visited.insert(Root);
936 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
937 const DataLayout &DL = Root->getModule()->getDataLayout();
938 // If there are no loads or stores, the access is dead. We mark that as
939 // a size zero access.
940 Size = 0;
941 do {
942 Instruction *I, *UsedI;
943 std::tie(UsedI, I) = Uses.pop_back_val();
944
945 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
946 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
947 continue;
948 }
949 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
950 Value *Op = SI->getOperand(0);
951 if (Op == UsedI)
952 return SI;
953 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
954 continue;
955 }
956
957 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
958 if (!GEP->hasAllZeroIndices())
959 return GEP;
960 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
961 !isa<SelectInst>(I)) {
962 return I;
963 }
964
965 for (User *U : I->users())
966 if (Visited.insert(cast<Instruction>(U)).second)
967 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
968 } while (!Uses.empty());
969
970 return nullptr;
971 }
972
973 void visitPHINodeOrSelectInst(Instruction &I) {
974 assert(isa<PHINode>(I) || isa<SelectInst>(I))(static_cast <bool> (isa<PHINode>(I) || isa<SelectInst
>(I)) ? void (0) : __assert_fail ("isa<PHINode>(I) || isa<SelectInst>(I)"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 974, __extension__ __PRETTY_FUNCTION__))
;
975 if (I.use_empty())
976 return markAsDead(I);
977
978 // TODO: We could use SimplifyInstruction here to fold PHINodes and
979 // SelectInsts. However, doing so requires to change the current
980 // dead-operand-tracking mechanism. For instance, suppose neither loading
981 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
982 // trap either. However, if we simply replace %U with undef using the
983 // current dead-operand-tracking mechanism, "load (select undef, undef,
984 // %other)" may trap because the select may return the first operand
985 // "undef".
986 if (Value *Result = foldPHINodeOrSelectInst(I)) {
987 if (Result == *U)
988 // If the result of the constant fold will be the pointer, recurse
989 // through the PHI/select as if we had RAUW'ed it.
990 enqueueUsers(I);
991 else
992 // Otherwise the operand to the PHI/select is dead, and we can replace
993 // it with undef.
994 AS.DeadOperands.push_back(U);
995
996 return;
997 }
998
999 if (!IsOffsetKnown)
1000 return PI.setAborted(&I);
1001
1002 // See if we already have computed info on this node.
1003 uint64_t &Size = PHIOrSelectSizes[&I];
1004 if (!Size) {
1005 // This is a new PHI/Select, check for an unsafe use of it.
1006 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
1007 return PI.setAborted(UnsafeI);
1008 }
1009
1010 // For PHI and select operands outside the alloca, we can't nuke the entire
1011 // phi or select -- the other side might still be relevant, so we special
1012 // case them here and use a separate structure to track the operands
1013 // themselves which should be replaced with undef.
1014 // FIXME: This should instead be escaped in the event we're instrumenting
1015 // for address sanitization.
1016 if (Offset.uge(AllocSize)) {
1017 AS.DeadOperands.push_back(U);
1018 return;
1019 }
1020
1021 insertUse(I, Offset, Size);
1022 }
1023
1024 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1025
1026 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1027
1028 /// Disable SROA entirely if there are unhandled users of the alloca.
1029 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
1030};
1031
1032AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
1033 :
1034#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1035 AI(AI),
1036#endif
1037 PointerEscapingInstr(nullptr) {
1038 SliceBuilder PB(DL, AI, *this);
1039 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1040 if (PtrI.isEscaped() || PtrI.isAborted()) {
1041 // FIXME: We should sink the escape vs. abort info into the caller nicely,
1042 // possibly by just storing the PtrInfo in the AllocaSlices.
1043 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1044 : PtrI.getAbortingInst();
1045 assert(PointerEscapingInstr && "Did not track a bad instruction")(static_cast <bool> (PointerEscapingInstr && "Did not track a bad instruction"
) ? void (0) : __assert_fail ("PointerEscapingInstr && \"Did not track a bad instruction\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1045, __extension__ __PRETTY_FUNCTION__))
;
1046 return;
1047 }
1048
1049 Slices.erase(
1050 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1051 Slices.end());
1052
1053#ifndef NDEBUG
1054 if (SROARandomShuffleSlices) {
1055 std::mt19937 MT(static_cast<unsigned>(
1056 std::chrono::system_clock::now().time_since_epoch().count()));
1057 std::shuffle(Slices.begin(), Slices.end(), MT);
1058 }
1059#endif
1060
1061 // Sort the uses. This arranges for the offsets to be in ascending order,
1062 // and the sizes to be in descending order.
1063 llvm::sort(Slices.begin(), Slices.end());
1064}
1065
1066#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1067
1068void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1069 StringRef Indent) const {
1070 printSlice(OS, I, Indent);
1071 OS << "\n";
1072 printUse(OS, I, Indent);
1073}
1074
1075void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1076 StringRef Indent) const {
1077 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1078 << " slice #" << (I - begin())
1079 << (I->isSplittable() ? " (splittable)" : "");
1080}
1081
1082void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1083 StringRef Indent) const {
1084 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
1085}
1086
1087void AllocaSlices::print(raw_ostream &OS) const {
1088 if (PointerEscapingInstr) {
1089 OS << "Can't analyze slices for alloca: " << AI << "\n"
1090 << " A pointer to this alloca escaped by:\n"
1091 << " " << *PointerEscapingInstr << "\n";
1092 return;
1093 }
1094
1095 OS << "Slices of alloca: " << AI << "\n";
1096 for (const_iterator I = begin(), E = end(); I != E; ++I)
1097 print(OS, I);
1098}
1099
1100LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void AllocaSlices::dump(const_iterator I) const {
1101 print(dbgs(), I);
1102}
1103LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void AllocaSlices::dump() const { print(dbgs()); }
1104
1105#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1106
1107/// Walk the range of a partitioning looking for a common type to cover this
1108/// sequence of slices.
1109static Type *findCommonType(AllocaSlices::const_iterator B,
1110 AllocaSlices::const_iterator E,
1111 uint64_t EndOffset) {
1112 Type *Ty = nullptr;
1113 bool TyIsCommon = true;
1114 IntegerType *ITy = nullptr;
1115
1116 // Note that we need to look at *every* alloca slice's Use to ensure we
1117 // always get consistent results regardless of the order of slices.
1118 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
1119 Use *U = I->getUse();
1120 if (isa<IntrinsicInst>(*U->getUser()))
1121 continue;
1122 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1123 continue;
1124
1125 Type *UserTy = nullptr;
1126 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1127 UserTy = LI->getType();
1128 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1129 UserTy = SI->getValueOperand()->getType();
1130 }
1131
1132 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1133 // If the type is larger than the partition, skip it. We only encounter
1134 // this for split integer operations where we want to use the type of the
1135 // entity causing the split. Also skip if the type is not a byte width
1136 // multiple.
1137 if (UserITy->getBitWidth() % 8 != 0 ||
1138 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
1139 continue;
1140
1141 // Track the largest bitwidth integer type used in this way in case there
1142 // is no common type.
1143 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1144 ITy = UserITy;
1145 }
1146
1147 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1148 // depend on types skipped above.
1149 if (!UserTy || (Ty && Ty != UserTy))
1150 TyIsCommon = false; // Give up on anything but an iN type.
1151 else
1152 Ty = UserTy;
1153 }
1154
1155 return TyIsCommon ? Ty : ITy;
1156}
1157
1158/// PHI instructions that use an alloca and are subsequently loaded can be
1159/// rewritten to load both input pointers in the pred blocks and then PHI the
1160/// results, allowing the load of the alloca to be promoted.
1161/// From this:
1162/// %P2 = phi [i32* %Alloca, i32* %Other]
1163/// %V = load i32* %P2
1164/// to:
1165/// %V1 = load i32* %Alloca -> will be mem2reg'd
1166/// ...
1167/// %V2 = load i32* %Other
1168/// ...
1169/// %V = phi [i32 %V1, i32 %V2]
1170///
1171/// We can do this to a select if its only uses are loads and if the operands
1172/// to the select can be loaded unconditionally.
1173///
1174/// FIXME: This should be hoisted into a generic utility, likely in
1175/// Transforms/Util/Local.h
1176static bool isSafePHIToSpeculate(PHINode &PN) {
1177 // For now, we can only do this promotion if the load is in the same block
1178 // as the PHI, and if there are no stores between the phi and load.
1179 // TODO: Allow recursive phi users.
1180 // TODO: Allow stores.
1181 BasicBlock *BB = PN.getParent();
1182 unsigned MaxAlign = 0;
1183 bool HaveLoad = false;
1184 for (User *U : PN.users()) {
1185 LoadInst *LI = dyn_cast<LoadInst>(U);
1186 if (!LI || !LI->isSimple())
1187 return false;
1188
1189 // For now we only allow loads in the same block as the PHI. This is
1190 // a common case that happens when instcombine merges two loads through
1191 // a PHI.
1192 if (LI->getParent() != BB)
1193 return false;
1194
1195 // Ensure that there are no instructions between the PHI and the load that
1196 // could store.
1197 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
1198 if (BBI->mayWriteToMemory())
1199 return false;
1200
1201 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1202 HaveLoad = true;
1203 }
1204
1205 if (!HaveLoad)
1206 return false;
1207
1208 const DataLayout &DL = PN.getModule()->getDataLayout();
1209
1210 // We can only transform this if it is safe to push the loads into the
1211 // predecessor blocks. The only thing to watch out for is that we can't put
1212 // a possibly trapping load in the predecessor if it is a critical edge.
1213 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1214 TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
1215 Value *InVal = PN.getIncomingValue(Idx);
1216
1217 // If the value is produced by the terminator of the predecessor (an
1218 // invoke) or it has side-effects, there is no valid place to put a load
1219 // in the predecessor.
1220 if (TI == InVal || TI->mayHaveSideEffects())
1221 return false;
1222
1223 // If the predecessor has a single successor, then the edge isn't
1224 // critical.
1225 if (TI->getNumSuccessors() == 1)
1226 continue;
1227
1228 // If this pointer is always safe to load, or if we can prove that there
1229 // is already a load in the block, then we can move the load to the pred
1230 // block.
1231 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
1232 continue;
1233
1234 return false;
1235 }
1236
1237 return true;
1238}
1239
1240static void speculatePHINodeLoads(PHINode &PN) {
1241 LLVM_DEBUG(dbgs() << " original: " << PN << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << PN <<
"\n"; } } while (false)
;
1242
1243 Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
1244 IRBuilderTy PHIBuilder(&PN);
1245 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1246 PN.getName() + ".sroa.speculated");
1247
1248 // Get the AA tags and alignment to use from one of the loads. It doesn't
1249 // matter which one we get and if any differ.
1250 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1251
1252 AAMDNodes AATags;
1253 SomeLoad->getAAMetadata(AATags);
1254 unsigned Align = SomeLoad->getAlignment();
1255
1256 // Rewrite all loads of the PN to use the new PHI.
1257 while (!PN.use_empty()) {
1258 LoadInst *LI = cast<LoadInst>(PN.user_back());
1259 LI->replaceAllUsesWith(NewPN);
1260 LI->eraseFromParent();
1261 }
1262
1263 // Inject loads into all of the pred blocks.
1264 DenseMap<BasicBlock*, Value*> InjectedLoads;
1265 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1266 BasicBlock *Pred = PN.getIncomingBlock(Idx);
1267 Value *InVal = PN.getIncomingValue(Idx);
1268
1269 // A PHI node is allowed to have multiple (duplicated) entries for the same
1270 // basic block, as long as the value is the same. So if we already injected
1271 // a load in the predecessor, then we should reuse the same load for all
1272 // duplicated entries.
1273 if (Value* V = InjectedLoads.lookup(Pred)) {
1274 NewPN->addIncoming(V, Pred);
1275 continue;
1276 }
1277
1278 TerminatorInst *TI = Pred->getTerminator();
1279 IRBuilderTy PredBuilder(TI);
1280
1281 LoadInst *Load = PredBuilder.CreateLoad(
1282 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1283 ++NumLoadsSpeculated;
1284 Load->setAlignment(Align);
1285 if (AATags)
1286 Load->setAAMetadata(AATags);
1287 NewPN->addIncoming(Load, Pred);
1288 InjectedLoads[Pred] = Load;
1289 }
1290
1291 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " speculated to: " <<
*NewPN << "\n"; } } while (false)
;
1292 PN.eraseFromParent();
1293}
1294
1295/// Select instructions that use an alloca and are subsequently loaded can be
1296/// rewritten to load both input pointers and then select between the result,
1297/// allowing the load of the alloca to be promoted.
1298/// From this:
1299/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1300/// %V = load i32* %P2
1301/// to:
1302/// %V1 = load i32* %Alloca -> will be mem2reg'd
1303/// %V2 = load i32* %Other
1304/// %V = select i1 %cond, i32 %V1, i32 %V2
1305///
1306/// We can do this to a select if its only uses are loads and if the operand
1307/// to the select can be loaded unconditionally.
1308static bool isSafeSelectToSpeculate(SelectInst &SI) {
1309 Value *TValue = SI.getTrueValue();
1310 Value *FValue = SI.getFalseValue();
1311 const DataLayout &DL = SI.getModule()->getDataLayout();
1312
1313 for (User *U : SI.users()) {
1314 LoadInst *LI = dyn_cast<LoadInst>(U);
1315 if (!LI || !LI->isSimple())
1316 return false;
1317
1318 // Both operands to the select need to be dereferenceable, either
1319 // absolutely (e.g. allocas) or at this point because we can see other
1320 // accesses to it.
1321 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
1322 return false;
1323 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
1324 return false;
1325 }
1326
1327 return true;
1328}
1329
1330static void speculateSelectInstLoads(SelectInst &SI) {
1331 LLVM_DEBUG(dbgs() << " original: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << SI <<
"\n"; } } while (false)
;
1332
1333 IRBuilderTy IRB(&SI);
1334 Value *TV = SI.getTrueValue();
1335 Value *FV = SI.getFalseValue();
1336 // Replace the loads of the select with a select of two loads.
1337 while (!SI.use_empty()) {
1338 LoadInst *LI = cast<LoadInst>(SI.user_back());
1339 assert(LI->isSimple() && "We only speculate simple loads")(static_cast <bool> (LI->isSimple() && "We only speculate simple loads"
) ? void (0) : __assert_fail ("LI->isSimple() && \"We only speculate simple loads\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1339, __extension__ __PRETTY_FUNCTION__))
;
1340
1341 IRB.SetInsertPoint(LI);
1342 LoadInst *TL =
1343 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
1344 LoadInst *FL =
1345 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
1346 NumLoadsSpeculated += 2;
1347
1348 // Transfer alignment and AA info if present.
1349 TL->setAlignment(LI->getAlignment());
1350 FL->setAlignment(LI->getAlignment());
1351
1352 AAMDNodes Tags;
1353 LI->getAAMetadata(Tags);
1354 if (Tags) {
1355 TL->setAAMetadata(Tags);
1356 FL->setAAMetadata(Tags);
1357 }
1358
1359 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1360 LI->getName() + ".sroa.speculated");
1361
1362 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " speculated to: " <<
*V << "\n"; } } while (false)
;
1363 LI->replaceAllUsesWith(V);
1364 LI->eraseFromParent();
1365 }
1366 SI.eraseFromParent();
1367}
1368
1369/// Build a GEP out of a base pointer and indices.
1370///
1371/// This will return the BasePtr if that is valid, or build a new GEP
1372/// instruction using the IRBuilder if GEP-ing is needed.
1373static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1374 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1375 if (Indices.empty())
1376 return BasePtr;
1377
1378 // A single zero index is a no-op, so check for this and avoid building a GEP
1379 // in that case.
1380 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1381 return BasePtr;
1382
1383 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1384 NamePrefix + "sroa_idx");
1385}
1386
1387/// Get a natural GEP off of the BasePtr walking through Ty toward
1388/// TargetTy without changing the offset of the pointer.
1389///
1390/// This routine assumes we've already established a properly offset GEP with
1391/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1392/// zero-indices down through type layers until we find one the same as
1393/// TargetTy. If we can't find one with the same type, we at least try to use
1394/// one with the same size. If none of that works, we just produce the GEP as
1395/// indicated by Indices to have the correct offset.
1396static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1397 Value *BasePtr, Type *Ty, Type *TargetTy,
1398 SmallVectorImpl<Value *> &Indices,
1399 Twine NamePrefix) {
1400 if (Ty == TargetTy)
1401 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1402
1403 // Pointer size to use for the indices.
1404 unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
1405
1406 // See if we can descend into a struct and locate a field with the correct
1407 // type.
1408 unsigned NumLayers = 0;
1409 Type *ElementTy = Ty;
1410 do {
1411 if (ElementTy->isPointerTy())
1412 break;
1413
1414 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1415 ElementTy = ArrayTy->getElementType();
1416 Indices.push_back(IRB.getIntN(PtrSize, 0));
1417 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1418 ElementTy = VectorTy->getElementType();
1419 Indices.push_back(IRB.getInt32(0));
1420 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1421 if (STy->element_begin() == STy->element_end())
1422 break; // Nothing left to descend into.
1423 ElementTy = *STy->element_begin();
1424 Indices.push_back(IRB.getInt32(0));
1425 } else {
1426 break;
1427 }
1428 ++NumLayers;
1429 } while (ElementTy != TargetTy);
1430 if (ElementTy != TargetTy)
1431 Indices.erase(Indices.end() - NumLayers, Indices.end());
1432
1433 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1434}
1435
1436/// Recursively compute indices for a natural GEP.
1437///
1438/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1439/// element types adding appropriate indices for the GEP.
1440static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1441 Value *Ptr, Type *Ty, APInt &Offset,
1442 Type *TargetTy,
1443 SmallVectorImpl<Value *> &Indices,
1444 Twine NamePrefix) {
1445 if (Offset == 0)
1446 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1447 NamePrefix);
1448
1449 // We can't recurse through pointer types.
1450 if (Ty->isPointerTy())
1451 return nullptr;
1452
1453 // We try to analyze GEPs over vectors here, but note that these GEPs are
1454 // extremely poorly defined currently. The long-term goal is to remove GEPing
1455 // over a vector from the IR completely.
1456 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1457 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1458 if (ElementSizeInBits % 8 != 0) {
1459 // GEPs over non-multiple of 8 size vector elements are invalid.
1460 return nullptr;
1461 }
1462 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1463 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1464 if (NumSkippedElements.ugt(VecTy->getNumElements()))
1465 return nullptr;
1466 Offset -= NumSkippedElements * ElementSize;
1467 Indices.push_back(IRB.getInt(NumSkippedElements));
1468 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1469 Offset, TargetTy, Indices, NamePrefix);
1470 }
1471
1472 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1473 Type *ElementTy = ArrTy->getElementType();
1474 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1475 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1476 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1477 return nullptr;
1478
1479 Offset -= NumSkippedElements * ElementSize;
1480 Indices.push_back(IRB.getInt(NumSkippedElements));
1481 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1482 Indices, NamePrefix);
1483 }
1484
1485 StructType *STy = dyn_cast<StructType>(Ty);
1486 if (!STy)
1487 return nullptr;
1488
1489 const StructLayout *SL = DL.getStructLayout(STy);
1490 uint64_t StructOffset = Offset.getZExtValue();
1491 if (StructOffset >= SL->getSizeInBytes())
1492 return nullptr;
1493 unsigned Index = SL->getElementContainingOffset(StructOffset);
1494 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1495 Type *ElementTy = STy->getElementType(Index);
1496 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1497 return nullptr; // The offset points into alignment padding.
1498
1499 Indices.push_back(IRB.getInt32(Index));
1500 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1501 Indices, NamePrefix);
1502}
1503
1504/// Get a natural GEP from a base pointer to a particular offset and
1505/// resulting in a particular type.
1506///
1507/// The goal is to produce a "natural" looking GEP that works with the existing
1508/// composite types to arrive at the appropriate offset and element type for
1509/// a pointer. TargetTy is the element type the returned GEP should point-to if
1510/// possible. We recurse by decreasing Offset, adding the appropriate index to
1511/// Indices, and setting Ty to the result subtype.
1512///
1513/// If no natural GEP can be constructed, this function returns null.
1514static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1515 Value *Ptr, APInt Offset, Type *TargetTy,
1516 SmallVectorImpl<Value *> &Indices,
1517 Twine NamePrefix) {
1518 PointerType *Ty = cast<PointerType>(Ptr->getType());
1519
1520 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1521 // an i8.
1522 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
1523 return nullptr;
1524
1525 Type *ElementTy = Ty->getElementType();
1526 if (!ElementTy->isSized())
1527 return nullptr; // We can't GEP through an unsized element.
1528 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1529 if (ElementSize == 0)
1530 return nullptr; // Zero-length arrays can't help us build a natural GEP.
1531 APInt NumSkippedElements = Offset.sdiv(ElementSize);
1532
1533 Offset -= NumSkippedElements * ElementSize;
1534 Indices.push_back(IRB.getInt(NumSkippedElements));
1535 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1536 Indices, NamePrefix);
1537}
1538
1539/// Compute an adjusted pointer from Ptr by Offset bytes where the
1540/// resulting pointer has PointerTy.
1541///
1542/// This tries very hard to compute a "natural" GEP which arrives at the offset
1543/// and produces the pointer type desired. Where it cannot, it will try to use
1544/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1545/// fails, it will try to use an existing i8* and GEP to the byte offset and
1546/// bitcast to the type.
1547///
1548/// The strategy for finding the more natural GEPs is to peel off layers of the
1549/// pointer, walking back through bit casts and GEPs, searching for a base
1550/// pointer from which we can compute a natural GEP with the desired
1551/// properties. The algorithm tries to fold as many constant indices into
1552/// a single GEP as possible, thus making each GEP more independent of the
1553/// surrounding code.
1554static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1555 APInt Offset, Type *PointerTy, Twine NamePrefix) {
1556 // Even though we don't look through PHI nodes, we could be called on an
1557 // instruction in an unreachable block, which may be on a cycle.
1558 SmallPtrSet<Value *, 4> Visited;
1559 Visited.insert(Ptr);
1560 SmallVector<Value *, 4> Indices;
1561
1562 // We may end up computing an offset pointer that has the wrong type. If we
1563 // never are able to compute one directly that has the correct type, we'll
1564 // fall back to it, so keep it and the base it was computed from around here.
1565 Value *OffsetPtr = nullptr;
1566 Value *OffsetBasePtr;
1567
1568 // Remember any i8 pointer we come across to re-use if we need to do a raw
1569 // byte offset.
1570 Value *Int8Ptr = nullptr;
1571 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1572
1573 Type *TargetTy = PointerTy->getPointerElementType();
1574
1575 do {
1576 // First fold any existing GEPs into the offset.
1577 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1578 APInt GEPOffset(Offset.getBitWidth(), 0);
1579 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1580 break;
1581 Offset += GEPOffset;
1582 Ptr = GEP->getPointerOperand();
1583 if (!Visited.insert(Ptr).second)
1584 break;
1585 }
1586
1587 // See if we can perform a natural GEP here.
1588 Indices.clear();
1589 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1590 Indices, NamePrefix)) {
1591 // If we have a new natural pointer at the offset, clear out any old
1592 // offset pointer we computed. Unless it is the base pointer or
1593 // a non-instruction, we built a GEP we don't need. Zap it.
1594 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1595 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1596 assert(I->use_empty() && "Built a GEP with uses some how!")(static_cast <bool> (I->use_empty() && "Built a GEP with uses some how!"
) ? void (0) : __assert_fail ("I->use_empty() && \"Built a GEP with uses some how!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1596, __extension__ __PRETTY_FUNCTION__))
;
1597 I->eraseFromParent();
1598 }
1599 OffsetPtr = P;
1600 OffsetBasePtr = Ptr;
1601 // If we also found a pointer of the right type, we're done.
1602 if (P->getType() == PointerTy)
1603 return P;
1604 }
1605
1606 // Stash this pointer if we've found an i8*.
1607 if (Ptr->getType()->isIntegerTy(8)) {
1608 Int8Ptr = Ptr;
1609 Int8PtrOffset = Offset;
1610 }
1611
1612 // Peel off a layer of the pointer and update the offset appropriately.
1613 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1614 Ptr = cast<Operator>(Ptr)->getOperand(0);
1615 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1616 if (GA->isInterposable())
1617 break;
1618 Ptr = GA->getAliasee();
1619 } else {
1620 break;
1621 }
1622 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!")(static_cast <bool> (Ptr->getType()->isPointerTy(
) && "Unexpected operand type!") ? void (0) : __assert_fail
("Ptr->getType()->isPointerTy() && \"Unexpected operand type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1622, __extension__ __PRETTY_FUNCTION__))
;
1623 } while (Visited.insert(Ptr).second);
1624
1625 if (!OffsetPtr) {
1626 if (!Int8Ptr) {
1627 Int8Ptr = IRB.CreateBitCast(
1628 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1629 NamePrefix + "sroa_raw_cast");
1630 Int8PtrOffset = Offset;
1631 }
1632
1633 OffsetPtr = Int8PtrOffset == 0
1634 ? Int8Ptr
1635 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1636 IRB.getInt(Int8PtrOffset),
1637 NamePrefix + "sroa_raw_idx");
1638 }
1639 Ptr = OffsetPtr;
1640
1641 // On the off chance we were targeting i8*, guard the bitcast here.
1642 if (Ptr->getType() != PointerTy)
1643 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
1644
1645 return Ptr;
1646}
1647
1648/// Compute the adjusted alignment for a load or store from an offset.
1649static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1650 const DataLayout &DL) {
1651 unsigned Alignment;
1652 Type *Ty;
1653 if (auto *LI = dyn_cast<LoadInst>(I)) {
1654 Alignment = LI->getAlignment();
1655 Ty = LI->getType();
1656 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1657 Alignment = SI->getAlignment();
1658 Ty = SI->getValueOperand()->getType();
1659 } else {
1660 llvm_unreachable("Only loads and stores are allowed!")::llvm::llvm_unreachable_internal("Only loads and stores are allowed!"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1660)
;
1661 }
1662
1663 if (!Alignment)
1664 Alignment = DL.getABITypeAlignment(Ty);
1665
1666 return MinAlign(Alignment, Offset);
1667}
1668
1669/// Test whether we can convert a value from the old to the new type.
1670///
1671/// This predicate should be used to guard calls to convertValue in order to
1672/// ensure that we only try to convert viable values. The strategy is that we
1673/// will peel off single element struct and array wrappings to get to an
1674/// underlying value, and convert that value.
1675static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1676 if (OldTy == NewTy)
1677 return true;
1678
1679 // For integer types, we can't handle any bit-width differences. This would
1680 // break both vector conversions with extension and introduce endianness
1681 // issues when in conjunction with loads and stores.
1682 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1683 assert(cast<IntegerType>(OldTy)->getBitWidth() !=(static_cast <bool> (cast<IntegerType>(OldTy)->
getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth
() && "We can't have the same bitwidth for different int types"
) ? void (0) : __assert_fail ("cast<IntegerType>(OldTy)->getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth() && \"We can't have the same bitwidth for different int types\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1685, __extension__ __PRETTY_FUNCTION__))
1684 cast<IntegerType>(NewTy)->getBitWidth() &&(static_cast <bool> (cast<IntegerType>(OldTy)->
getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth
() && "We can't have the same bitwidth for different int types"
) ? void (0) : __assert_fail ("cast<IntegerType>(OldTy)->getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth() && \"We can't have the same bitwidth for different int types\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1685, __extension__ __PRETTY_FUNCTION__))
1685 "We can't have the same bitwidth for different int types")(static_cast <bool> (cast<IntegerType>(OldTy)->
getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth
() && "We can't have the same bitwidth for different int types"
) ? void (0) : __assert_fail ("cast<IntegerType>(OldTy)->getBitWidth() != cast<IntegerType>(NewTy)->getBitWidth() && \"We can't have the same bitwidth for different int types\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1685, __extension__ __PRETTY_FUNCTION__))
;
1686 return false;
1687 }
1688
1689 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1690 return false;
1691 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1692 return false;
1693
1694 // We can convert pointers to integers and vice-versa. Same for vectors
1695 // of pointers and integers.
1696 OldTy = OldTy->getScalarType();
1697 NewTy = NewTy->getScalarType();
1698 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
1699 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1700 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1701 cast<PointerType>(OldTy)->getPointerAddressSpace();
1702 }
1703
1704 // We can convert integers to integral pointers, but not to non-integral
1705 // pointers.
1706 if (OldTy->isIntegerTy())
1707 return !DL.isNonIntegralPointerType(NewTy);
1708
1709 // We can convert integral pointers to integers, but non-integral pointers
1710 // need to remain pointers.
1711 if (!DL.isNonIntegralPointerType(OldTy))
1712 return NewTy->isIntegerTy();
1713
1714 return false;
1715 }
1716
1717 return true;
1718}
1719
1720/// Generic routine to convert an SSA value to a value of a different
1721/// type.
1722///
1723/// This will try various different casting techniques, such as bitcasts,
1724/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1725/// two types for viability with this routine.
1726static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1727 Type *NewTy) {
1728 Type *OldTy = V->getType();
1729 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type")(static_cast <bool> (canConvertValue(DL, OldTy, NewTy) &&
"Value not convertable to type") ? void (0) : __assert_fail (
"canConvertValue(DL, OldTy, NewTy) && \"Value not convertable to type\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1729, __extension__ __PRETTY_FUNCTION__))
;
1730
1731 if (OldTy == NewTy)
1732 return V;
1733
1734 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&(static_cast <bool> (!(isa<IntegerType>(OldTy) &&
isa<IntegerType>(NewTy)) && "Integer types must be the exact same to convert."
) ? void (0) : __assert_fail ("!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) && \"Integer types must be the exact same to convert.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1735, __extension__ __PRETTY_FUNCTION__))
1735 "Integer types must be the exact same to convert.")(static_cast <bool> (!(isa<IntegerType>(OldTy) &&
isa<IntegerType>(NewTy)) && "Integer types must be the exact same to convert."
) ? void (0) : __assert_fail ("!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) && \"Integer types must be the exact same to convert.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1735, __extension__ __PRETTY_FUNCTION__))
;
1736
1737 // See if we need inttoptr for this type pair. A cast involving both scalars
1738 // and vectors requires and additional bitcast.
1739 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
1740 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1741 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1742 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1743 NewTy);
1744
1745 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1746 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1747 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1748 NewTy);
1749
1750 return IRB.CreateIntToPtr(V, NewTy);
1751 }
1752
1753 // See if we need ptrtoint for this type pair. A cast involving both scalars
1754 // and vectors requires and additional bitcast.
1755 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
1756 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1757 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1758 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1759 NewTy);
1760
1761 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1762 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1763 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1764 NewTy);
1765
1766 return IRB.CreatePtrToInt(V, NewTy);
1767 }
1768
1769 return IRB.CreateBitCast(V, NewTy);
1770}
1771
1772/// Test whether the given slice use can be promoted to a vector.
1773///
1774/// This function is called to test each entry in a partition which is slated
1775/// for a single slice.
1776static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1777 VectorType *Ty,
1778 uint64_t ElementSize,
1779 const DataLayout &DL) {
1780 // First validate the slice offsets.
1781 uint64_t BeginOffset =
1782 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
1783 uint64_t BeginIndex = BeginOffset / ElementSize;
1784 if (BeginIndex * ElementSize != BeginOffset ||
1785 BeginIndex >= Ty->getNumElements())
1786 return false;
1787 uint64_t EndOffset =
1788 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
1789 uint64_t EndIndex = EndOffset / ElementSize;
1790 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1791 return false;
1792
1793 assert(EndIndex > BeginIndex && "Empty vector!")(static_cast <bool> (EndIndex > BeginIndex &&
"Empty vector!") ? void (0) : __assert_fail ("EndIndex > BeginIndex && \"Empty vector!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1793, __extension__ __PRETTY_FUNCTION__))
;
1794 uint64_t NumElements = EndIndex - BeginIndex;
1795 Type *SliceTy = (NumElements == 1)
1796 ? Ty->getElementType()
1797 : VectorType::get(Ty->getElementType(), NumElements);
1798
1799 Type *SplitIntTy =
1800 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1801
1802 Use *U = S.getUse();
1803
1804 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1805 if (MI->isVolatile())
1806 return false;
1807 if (!S.isSplittable())
1808 return false; // Skip any unsplittable intrinsics.
1809 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1810 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1811 II->getIntrinsicID() != Intrinsic::lifetime_end)
1812 return false;
1813 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1814 // Disable vector promotion when there are loads or stores of an FCA.
1815 return false;
1816 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1817 if (LI->isVolatile())
1818 return false;
1819 Type *LTy = LI->getType();
1820 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1821 assert(LTy->isIntegerTy())(static_cast <bool> (LTy->isIntegerTy()) ? void (0) :
__assert_fail ("LTy->isIntegerTy()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1821, __extension__ __PRETTY_FUNCTION__))
;
1822 LTy = SplitIntTy;
1823 }
1824 if (!canConvertValue(DL, SliceTy, LTy))
1825 return false;
1826 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1827 if (SI->isVolatile())
1828 return false;
1829 Type *STy = SI->getValueOperand()->getType();
1830 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1831 assert(STy->isIntegerTy())(static_cast <bool> (STy->isIntegerTy()) ? void (0) :
__assert_fail ("STy->isIntegerTy()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1831, __extension__ __PRETTY_FUNCTION__))
;
1832 STy = SplitIntTy;
1833 }
1834 if (!canConvertValue(DL, STy, SliceTy))
1835 return false;
1836 } else {
1837 return false;
1838 }
1839
1840 return true;
1841}
1842
1843/// Test whether the given alloca partitioning and range of slices can be
1844/// promoted to a vector.
1845///
1846/// This is a quick test to check whether we can rewrite a particular alloca
1847/// partition (and its newly formed alloca) into a vector alloca with only
1848/// whole-vector loads and stores such that it could be promoted to a vector
1849/// SSA value. We only can ensure this for a limited set of operations, and we
1850/// don't want to do the rewrites unless we are confident that the result will
1851/// be promotable, so we have an early test here.
1852static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
1853 // Collect the candidate types for vector-based promotion. Also track whether
1854 // we have different element types.
1855 SmallVector<VectorType *, 4> CandidateTys;
1856 Type *CommonEltTy = nullptr;
1857 bool HaveCommonEltTy = true;
1858 auto CheckCandidateType = [&](Type *Ty) {
1859 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1860 CandidateTys.push_back(VTy);
1861 if (!CommonEltTy)
1862 CommonEltTy = VTy->getElementType();
1863 else if (CommonEltTy != VTy->getElementType())
1864 HaveCommonEltTy = false;
1865 }
1866 };
1867 // Consider any loads or stores that are the exact size of the slice.
1868 for (const Slice &S : P)
1869 if (S.beginOffset() == P.beginOffset() &&
1870 S.endOffset() == P.endOffset()) {
1871 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1872 CheckCandidateType(LI->getType());
1873 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1874 CheckCandidateType(SI->getValueOperand()->getType());
1875 }
1876
1877 // If we didn't find a vector type, nothing to do here.
1878 if (CandidateTys.empty())
1879 return nullptr;
1880
1881 // Remove non-integer vector types if we had multiple common element types.
1882 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1883 // do that until all the backends are known to produce good code for all
1884 // integer vector types.
1885 if (!HaveCommonEltTy) {
1886 CandidateTys.erase(
1887 llvm::remove_if(CandidateTys,
1888 [](VectorType *VTy) {
1889 return !VTy->getElementType()->isIntegerTy();
1890 }),
1891 CandidateTys.end());
1892
1893 // If there were no integer vector types, give up.
1894 if (CandidateTys.empty())
1895 return nullptr;
1896
1897 // Rank the remaining candidate vector types. This is easy because we know
1898 // they're all integer vectors. We sort by ascending number of elements.
1899 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1900 (void)DL;
1901 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&(static_cast <bool> (DL.getTypeSizeInBits(RHSTy) == DL.
getTypeSizeInBits(LHSTy) && "Cannot have vector types of different sizes!"
) ? void (0) : __assert_fail ("DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) && \"Cannot have vector types of different sizes!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1902, __extension__ __PRETTY_FUNCTION__))
1902 "Cannot have vector types of different sizes!")(static_cast <bool> (DL.getTypeSizeInBits(RHSTy) == DL.
getTypeSizeInBits(LHSTy) && "Cannot have vector types of different sizes!"
) ? void (0) : __assert_fail ("DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) && \"Cannot have vector types of different sizes!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1902, __extension__ __PRETTY_FUNCTION__))
;
1903 assert(RHSTy->getElementType()->isIntegerTy() &&(static_cast <bool> (RHSTy->getElementType()->isIntegerTy
() && "All non-integer types eliminated!") ? void (0)
: __assert_fail ("RHSTy->getElementType()->isIntegerTy() && \"All non-integer types eliminated!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1904, __extension__ __PRETTY_FUNCTION__))
1904 "All non-integer types eliminated!")(static_cast <bool> (RHSTy->getElementType()->isIntegerTy
() && "All non-integer types eliminated!") ? void (0)
: __assert_fail ("RHSTy->getElementType()->isIntegerTy() && \"All non-integer types eliminated!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1904, __extension__ __PRETTY_FUNCTION__))
;
1905 assert(LHSTy->getElementType()->isIntegerTy() &&(static_cast <bool> (LHSTy->getElementType()->isIntegerTy
() && "All non-integer types eliminated!") ? void (0)
: __assert_fail ("LHSTy->getElementType()->isIntegerTy() && \"All non-integer types eliminated!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1906, __extension__ __PRETTY_FUNCTION__))
1906 "All non-integer types eliminated!")(static_cast <bool> (LHSTy->getElementType()->isIntegerTy
() && "All non-integer types eliminated!") ? void (0)
: __assert_fail ("LHSTy->getElementType()->isIntegerTy() && \"All non-integer types eliminated!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1906, __extension__ __PRETTY_FUNCTION__))
;
1907 return RHSTy->getNumElements() < LHSTy->getNumElements();
1908 };
1909 llvm::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
1910 CandidateTys.erase(
1911 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1912 CandidateTys.end());
1913 } else {
1914// The only way to have the same element type in every vector type is to
1915// have the same vector type. Check that and remove all but one.
1916#ifndef NDEBUG
1917 for (VectorType *VTy : CandidateTys) {
1918 assert(VTy->getElementType() == CommonEltTy &&(static_cast <bool> (VTy->getElementType() == CommonEltTy
&& "Unaccounted for element type!") ? void (0) : __assert_fail
("VTy->getElementType() == CommonEltTy && \"Unaccounted for element type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1919, __extension__ __PRETTY_FUNCTION__))
1919 "Unaccounted for element type!")(static_cast <bool> (VTy->getElementType() == CommonEltTy
&& "Unaccounted for element type!") ? void (0) : __assert_fail
("VTy->getElementType() == CommonEltTy && \"Unaccounted for element type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1919, __extension__ __PRETTY_FUNCTION__))
;
1920 assert(VTy == CandidateTys[0] &&(static_cast <bool> (VTy == CandidateTys[0] && "Different vector types with the same element type!"
) ? void (0) : __assert_fail ("VTy == CandidateTys[0] && \"Different vector types with the same element type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1921, __extension__ __PRETTY_FUNCTION__))
1921 "Different vector types with the same element type!")(static_cast <bool> (VTy == CandidateTys[0] && "Different vector types with the same element type!"
) ? void (0) : __assert_fail ("VTy == CandidateTys[0] && \"Different vector types with the same element type!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1921, __extension__ __PRETTY_FUNCTION__))
;
1922 }
1923#endif
1924 CandidateTys.resize(1);
1925 }
1926
1927 // Try each vector type, and return the one which works.
1928 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1929 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1930
1931 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1932 // that aren't byte sized.
1933 if (ElementSize % 8)
1934 return false;
1935 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&(static_cast <bool> ((DL.getTypeSizeInBits(VTy) % 8) ==
0 && "vector size not a multiple of element size?") ?
void (0) : __assert_fail ("(DL.getTypeSizeInBits(VTy) % 8) == 0 && \"vector size not a multiple of element size?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1936, __extension__ __PRETTY_FUNCTION__))
1936 "vector size not a multiple of element size?")(static_cast <bool> ((DL.getTypeSizeInBits(VTy) % 8) ==
0 && "vector size not a multiple of element size?") ?
void (0) : __assert_fail ("(DL.getTypeSizeInBits(VTy) % 8) == 0 && \"vector size not a multiple of element size?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 1936, __extension__ __PRETTY_FUNCTION__))
;
1937 ElementSize /= 8;
1938
1939 for (const Slice &S : P)
1940 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
1941 return false;
1942
1943 for (const Slice *S : P.splitSliceTails())
1944 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
1945 return false;
1946
1947 return true;
1948 };
1949 for (VectorType *VTy : CandidateTys)
1950 if (CheckVectorTypeForPromotion(VTy))
1951 return VTy;
1952
1953 return nullptr;
1954}
1955
1956/// Test whether a slice of an alloca is valid for integer widening.
1957///
1958/// This implements the necessary checking for the \c isIntegerWideningViable
1959/// test below on a single slice of the alloca.
1960static bool isIntegerWideningViableForSlice(const Slice &S,
1961 uint64_t AllocBeginOffset,
1962 Type *AllocaTy,
1963 const DataLayout &DL,
1964 bool &WholeAllocaOp) {
1965 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1966
1967 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1968 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
1969
1970 // We can't reasonably handle cases where the load or store extends past
1971 // the end of the alloca's type and into its padding.
1972 if (RelEnd > Size)
1973 return false;
1974
1975 Use *U = S.getUse();
1976
1977 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1978 if (LI->isVolatile())
1979 return false;
1980 // We can't handle loads that extend past the allocated memory.
1981 if (DL.getTypeStoreSize(LI->getType()) > Size)
1982 return false;
1983 // So far, AllocaSliceRewriter does not support widening split slice tails
1984 // in rewriteIntegerLoad.
1985 if (S.beginOffset() < AllocBeginOffset)
1986 return false;
1987 // Note that we don't count vector loads or stores as whole-alloca
1988 // operations which enable integer widening because we would prefer to use
1989 // vector widening instead.
1990 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
1991 WholeAllocaOp = true;
1992 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
1993 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
1994 return false;
1995 } else if (RelBegin != 0 || RelEnd != Size ||
1996 !canConvertValue(DL, AllocaTy, LI->getType())) {
1997 // Non-integer loads need to be convertible from the alloca type so that
1998 // they are promotable.
1999 return false;
2000 }
2001 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2002 Type *ValueTy = SI->getValueOperand()->getType();
2003 if (SI->isVolatile())
2004 return false;
2005 // We can't handle stores that extend past the allocated memory.
2006 if (DL.getTypeStoreSize(ValueTy) > Size)
2007 return false;
2008 // So far, AllocaSliceRewriter does not support widening split slice tails
2009 // in rewriteIntegerStore.
2010 if (S.beginOffset() < AllocBeginOffset)
2011 return false;
2012 // Note that we don't count vector loads or stores as whole-alloca
2013 // operations which enable integer widening because we would prefer to use
2014 // vector widening instead.
2015 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
2016 WholeAllocaOp = true;
2017 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2018 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2019 return false;
2020 } else if (RelBegin != 0 || RelEnd != Size ||
2021 !canConvertValue(DL, ValueTy, AllocaTy)) {
2022 // Non-integer stores need to be convertible to the alloca type so that
2023 // they are promotable.
2024 return false;
2025 }
2026 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2027 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2028 return false;
2029 if (!S.isSplittable())
2030 return false; // Skip any unsplittable intrinsics.
2031 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2032 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2033 II->getIntrinsicID() != Intrinsic::lifetime_end)
2034 return false;
2035 } else {
2036 return false;
2037 }
2038
2039 return true;
2040}
2041
2042/// Test whether the given alloca partition's integer operations can be
2043/// widened to promotable ones.
2044///
2045/// This is a quick test to check whether we can rewrite the integer loads and
2046/// stores to a particular alloca into wider loads and stores and be able to
2047/// promote the resulting alloca.
2048static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
2049 const DataLayout &DL) {
2050 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
2051 // Don't create integer types larger than the maximum bitwidth.
2052 if (SizeInBits > IntegerType::MAX_INT_BITS)
2053 return false;
2054
2055 // Don't try to handle allocas with bit-padding.
2056 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
2057 return false;
2058
2059 // We need to ensure that an integer type with the appropriate bitwidth can
2060 // be converted to the alloca type, whatever that is. We don't want to force
2061 // the alloca itself to have an integer type if there is a more suitable one.
2062 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2063 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2064 !canConvertValue(DL, IntTy, AllocaTy))
2065 return false;
2066
2067 // While examining uses, we ensure that the alloca has a covering load or
2068 // store. We don't want to widen the integer operations only to fail to
2069 // promote due to some other unsplittable entry (which we may make splittable
2070 // later). However, if there are only splittable uses, go ahead and assume
2071 // that we cover the alloca.
2072 // FIXME: We shouldn't consider split slices that happen to start in the
2073 // partition here...
2074 bool WholeAllocaOp =
2075 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
2076
2077 for (const Slice &S : P)
2078 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2079 WholeAllocaOp))
2080 return false;
2081
2082 for (const Slice *S : P.splitSliceTails())
2083 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2084 WholeAllocaOp))
2085 return false;
2086
2087 return WholeAllocaOp;
2088}
2089
2090static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2091 IntegerType *Ty, uint64_t Offset,
2092 const Twine &Name) {
2093 LLVM_DEBUG(dbgs() << " start: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " start: " << *V <<
"\n"; } } while (false)
;
2094 IntegerType *IntTy = cast<IntegerType>(V->getType());
2095 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&(static_cast <bool> (DL.getTypeStoreSize(Ty) + Offset <=
DL.getTypeStoreSize(IntTy) && "Element extends past full value"
) ? void (0) : __assert_fail ("DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) && \"Element extends past full value\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2096, __extension__ __PRETTY_FUNCTION__))
2096 "Element extends past full value")(static_cast <bool> (DL.getTypeStoreSize(Ty) + Offset <=
DL.getTypeStoreSize(IntTy) && "Element extends past full value"
) ? void (0) : __assert_fail ("DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) && \"Element extends past full value\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2096, __extension__ __PRETTY_FUNCTION__))
;
2097 uint64_t ShAmt = 8 * Offset;
2098 if (DL.isBigEndian())
2099 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2100 if (ShAmt) {
2101 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2102 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " shifted: " << *V <<
"\n"; } } while (false)
;
2103 }
2104 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&(static_cast <bool> (Ty->getBitWidth() <= IntTy->
getBitWidth() && "Cannot extract to a larger integer!"
) ? void (0) : __assert_fail ("Ty->getBitWidth() <= IntTy->getBitWidth() && \"Cannot extract to a larger integer!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2105, __extension__ __PRETTY_FUNCTION__))
2105 "Cannot extract to a larger integer!")(static_cast <bool> (Ty->getBitWidth() <= IntTy->
getBitWidth() && "Cannot extract to a larger integer!"
) ? void (0) : __assert_fail ("Ty->getBitWidth() <= IntTy->getBitWidth() && \"Cannot extract to a larger integer!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2105, __extension__ __PRETTY_FUNCTION__))
;
2106 if (Ty != IntTy) {
2107 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2108 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " trunced: " << *V <<
"\n"; } } while (false)
;
2109 }
2110 return V;
2111}
2112
2113static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2114 Value *V, uint64_t Offset, const Twine &Name) {
2115 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2116 IntegerType *Ty = cast<IntegerType>(V->getType());
2117 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&(static_cast <bool> (Ty->getBitWidth() <= IntTy->
getBitWidth() && "Cannot insert a larger integer!") ?
void (0) : __assert_fail ("Ty->getBitWidth() <= IntTy->getBitWidth() && \"Cannot insert a larger integer!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2118, __extension__ __PRETTY_FUNCTION__))
2118 "Cannot insert a larger integer!")(static_cast <bool> (Ty->getBitWidth() <= IntTy->
getBitWidth() && "Cannot insert a larger integer!") ?
void (0) : __assert_fail ("Ty->getBitWidth() <= IntTy->getBitWidth() && \"Cannot insert a larger integer!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2118, __extension__ __PRETTY_FUNCTION__))
;
2119 LLVM_DEBUG(dbgs() << " start: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " start: " << *V <<
"\n"; } } while (false)
;
2120 if (Ty != IntTy) {
2121 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2122 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " extended: " << *V <<
"\n"; } } while (false)
;
2123 }
2124 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&(static_cast <bool> (DL.getTypeStoreSize(Ty) + Offset <=
DL.getTypeStoreSize(IntTy) && "Element store outside of alloca store"
) ? void (0) : __assert_fail ("DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) && \"Element store outside of alloca store\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2125, __extension__ __PRETTY_FUNCTION__))
2125 "Element store outside of alloca store")(static_cast <bool> (DL.getTypeStoreSize(Ty) + Offset <=
DL.getTypeStoreSize(IntTy) && "Element store outside of alloca store"
) ? void (0) : __assert_fail ("DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) && \"Element store outside of alloca store\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2125, __extension__ __PRETTY_FUNCTION__))
;
2126 uint64_t ShAmt = 8 * Offset;
2127 if (DL.isBigEndian())
2128 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2129 if (ShAmt) {
2130 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2131 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " shifted: " << *V <<
"\n"; } } while (false)
;
2132 }
2133
2134 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2135 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2136 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2137 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " masked: " << *Old <<
"\n"; } } while (false)
;
2138 V = IRB.CreateOr(Old, V, Name + ".insert");
2139 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " inserted: " << *V <<
"\n"; } } while (false)
;
2140 }
2141 return V;
2142}
2143
2144static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2145 unsigned EndIndex, const Twine &Name) {
2146 VectorType *VecTy = cast<VectorType>(V->getType());
2147 unsigned NumElements = EndIndex - BeginIndex;
2148 assert(NumElements <= VecTy->getNumElements() && "Too many elements!")(static_cast <bool> (NumElements <= VecTy->getNumElements
() && "Too many elements!") ? void (0) : __assert_fail
("NumElements <= VecTy->getNumElements() && \"Too many elements!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2148, __extension__ __PRETTY_FUNCTION__))
;
2149
2150 if (NumElements == VecTy->getNumElements())
2151 return V;
2152
2153 if (NumElements == 1) {
2154 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2155 Name + ".extract");
2156 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " extract: " << *V <<
"\n"; } } while (false)
;
2157 return V;
2158 }
2159
2160 SmallVector<Constant *, 8> Mask;
2161 Mask.reserve(NumElements);
2162 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2163 Mask.push_back(IRB.getInt32(i));
2164 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2165 ConstantVector::get(Mask), Name + ".extract");
2166 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " shuffle: " << *V <<
"\n"; } } while (false)
;
2167 return V;
2168}
2169
2170static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2171 unsigned BeginIndex, const Twine &Name) {
2172 VectorType *VecTy = cast<VectorType>(Old->getType());
2173 assert(VecTy && "Can only insert a vector into a vector")(static_cast <bool> (VecTy && "Can only insert a vector into a vector"
) ? void (0) : __assert_fail ("VecTy && \"Can only insert a vector into a vector\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2173, __extension__ __PRETTY_FUNCTION__))
;
2174
2175 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2176 if (!Ty) {
2177 // Single element to insert.
2178 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2179 Name + ".insert");
2180 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " insert: " << *V <<
"\n"; } } while (false)
;
2181 return V;
2182 }
2183
2184 assert(Ty->getNumElements() <= VecTy->getNumElements() &&(static_cast <bool> (Ty->getNumElements() <= VecTy
->getNumElements() && "Too many elements!") ? void
(0) : __assert_fail ("Ty->getNumElements() <= VecTy->getNumElements() && \"Too many elements!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2185, __extension__ __PRETTY_FUNCTION__))
2185 "Too many elements!")(static_cast <bool> (Ty->getNumElements() <= VecTy
->getNumElements() && "Too many elements!") ? void
(0) : __assert_fail ("Ty->getNumElements() <= VecTy->getNumElements() && \"Too many elements!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2185, __extension__ __PRETTY_FUNCTION__))
;
2186 if (Ty->getNumElements() == VecTy->getNumElements()) {
2187 assert(V->getType() == VecTy && "Vector type mismatch")(static_cast <bool> (V->getType() == VecTy &&
"Vector type mismatch") ? void (0) : __assert_fail ("V->getType() == VecTy && \"Vector type mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2187, __extension__ __PRETTY_FUNCTION__))
;
2188 return V;
2189 }
2190 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2191
2192 // When inserting a smaller vector into the larger to store, we first
2193 // use a shuffle vector to widen it with undef elements, and then
2194 // a second shuffle vector to select between the loaded vector and the
2195 // incoming vector.
2196 SmallVector<Constant *, 8> Mask;
2197 Mask.reserve(VecTy->getNumElements());
2198 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2199 if (i >= BeginIndex && i < EndIndex)
2200 Mask.push_back(IRB.getInt32(i - BeginIndex));
2201 else
2202 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2203 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2204 ConstantVector::get(Mask), Name + ".expand");
2205 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " shuffle: " << *V <<
"\n"; } } while (false)
;
2206
2207 Mask.clear();
2208 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2209 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2210
2211 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2212
2213 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " blend: " << *V <<
"\n"; } } while (false)
;
2214 return V;
2215}
2216
2217/// Visitor to rewrite instructions using p particular slice of an alloca
2218/// to use a new alloca.
2219///
2220/// Also implements the rewriting to vector-based accesses when the partition
2221/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2222/// lives here.
2223class llvm::sroa::AllocaSliceRewriter
2224 : public InstVisitor<AllocaSliceRewriter, bool> {
2225 // Befriend the base class so it can delegate to private visit methods.
2226 friend class InstVisitor<AllocaSliceRewriter, bool>;
2227
2228 using Base = InstVisitor<AllocaSliceRewriter, bool>;
2229
2230 const DataLayout &DL;
2231 AllocaSlices &AS;
2232 SROA &Pass;
2233 AllocaInst &OldAI, &NewAI;
2234 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2235 Type *NewAllocaTy;
2236
2237 // This is a convenience and flag variable that will be null unless the new
2238 // alloca's integer operations should be widened to this integer type due to
2239 // passing isIntegerWideningViable above. If it is non-null, the desired
2240 // integer type will be stored here for easy access during rewriting.
2241 IntegerType *IntTy;
2242
2243 // If we are rewriting an alloca partition which can be written as pure
2244 // vector operations, we stash extra information here. When VecTy is
2245 // non-null, we have some strict guarantees about the rewritten alloca:
2246 // - The new alloca is exactly the size of the vector type here.
2247 // - The accesses all either map to the entire vector or to a single
2248 // element.
2249 // - The set of accessing instructions is only one of those handled above
2250 // in isVectorPromotionViable. Generally these are the same access kinds
2251 // which are promotable via mem2reg.
2252 VectorType *VecTy;
2253 Type *ElementTy;
2254 uint64_t ElementSize;
2255
2256 // The original offset of the slice currently being rewritten relative to
2257 // the original alloca.
2258 uint64_t BeginOffset = 0;
2259 uint64_t EndOffset = 0;
2260
2261 // The new offsets of the slice currently being rewritten relative to the
2262 // original alloca.
2263 uint64_t NewBeginOffset, NewEndOffset;
2264
2265 uint64_t SliceSize;
2266 bool IsSplittable = false;
2267 bool IsSplit = false;
2268 Use *OldUse = nullptr;
2269 Instruction *OldPtr = nullptr;
2270
2271 // Track post-rewrite users which are PHI nodes and Selects.
2272 SmallSetVector<PHINode *, 8> &PHIUsers;
2273 SmallSetVector<SelectInst *, 8> &SelectUsers;
2274
2275 // Utility IR builder, whose name prefix is setup for each visited use, and
2276 // the insertion point is set to point to the user.
2277 IRBuilderTy IRB;
2278
2279public:
2280 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2281 AllocaInst &OldAI, AllocaInst &NewAI,
2282 uint64_t NewAllocaBeginOffset,
2283 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2284 VectorType *PromotableVecTy,
2285 SmallSetVector<PHINode *, 8> &PHIUsers,
2286 SmallSetVector<SelectInst *, 8> &SelectUsers)
2287 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2288 NewAllocaBeginOffset(NewAllocaBeginOffset),
2289 NewAllocaEndOffset(NewAllocaEndOffset),
2290 NewAllocaTy(NewAI.getAllocatedType()),
2291 IntTy(IsIntegerPromotable
2292 ? Type::getIntNTy(
2293 NewAI.getContext(),
2294 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2295 : nullptr),
2296 VecTy(PromotableVecTy),
2297 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2298 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2299 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2300 IRB(NewAI.getContext(), ConstantFolder()) {
2301 if (VecTy) {
2302 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&(static_cast <bool> ((DL.getTypeSizeInBits(ElementTy) %
8) == 0 && "Only multiple-of-8 sized vector elements are viable"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(ElementTy) % 8) == 0 && \"Only multiple-of-8 sized vector elements are viable\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2303, __extension__ __PRETTY_FUNCTION__))
2303 "Only multiple-of-8 sized vector elements are viable")(static_cast <bool> ((DL.getTypeSizeInBits(ElementTy) %
8) == 0 && "Only multiple-of-8 sized vector elements are viable"
) ? void (0) : __assert_fail ("(DL.getTypeSizeInBits(ElementTy) % 8) == 0 && \"Only multiple-of-8 sized vector elements are viable\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2303, __extension__ __PRETTY_FUNCTION__))
;
2304 ++NumVectorized;
2305 }
2306 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy))(static_cast <bool> ((!IntTy && !VecTy) || (IntTy
&& !VecTy) || (!IntTy && VecTy)) ? void (0) :
__assert_fail ("(!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy)"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2306, __extension__ __PRETTY_FUNCTION__))
;
2307 }
2308
2309 bool visit(AllocaSlices::const_iterator I) {
2310 bool CanSROA = true;
2311 BeginOffset = I->beginOffset();
2312 EndOffset = I->endOffset();
2313 IsSplittable = I->isSplittable();
2314 IsSplit =
2315 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
2316 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " rewriting " << (IsSplit ?
"split " : ""); } } while (false)
;
2317 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { AS.printSlice(dbgs(), I, ""); } } while (false)
;
2318 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "\n"; } } while (false)
;
2319
2320 // Compute the intersecting offset range.
2321 assert(BeginOffset < NewAllocaEndOffset)(static_cast <bool> (BeginOffset < NewAllocaEndOffset
) ? void (0) : __assert_fail ("BeginOffset < NewAllocaEndOffset"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2321, __extension__ __PRETTY_FUNCTION__))
;
2322 assert(EndOffset > NewAllocaBeginOffset)(static_cast <bool> (EndOffset > NewAllocaBeginOffset
) ? void (0) : __assert_fail ("EndOffset > NewAllocaBeginOffset"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2322, __extension__ __PRETTY_FUNCTION__))
;
2323 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2324 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2325
2326 SliceSize = NewEndOffset - NewBeginOffset;
2327
2328 OldUse = I->getUse();
2329 OldPtr = cast<Instruction>(OldUse->get());
2330
2331 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2332 IRB.SetInsertPoint(OldUserI);
2333 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2334 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2335
2336 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2337 if (VecTy || IntTy)
2338 assert(CanSROA)(static_cast <bool> (CanSROA) ? void (0) : __assert_fail
("CanSROA", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2338, __extension__ __PRETTY_FUNCTION__))
;
2339 return CanSROA;
2340 }
2341
2342private:
2343 // Make sure the other visit overloads are visible.
2344 using Base::visit;
2345
2346 // Every instruction which can end up as a user must have a rewrite rule.
2347 bool visitInstruction(Instruction &I) {
2348 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " !!!! Cannot rewrite: " <<
I << "\n"; } } while (false)
;
2349 llvm_unreachable("No rewrite rule for this instruction!")::llvm::llvm_unreachable_internal("No rewrite rule for this instruction!"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2349)
;
2350 }
2351
2352 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2353 // Note that the offset computation can use BeginOffset or NewBeginOffset
2354 // interchangeably for unsplit slices.
2355 assert(IsSplit || BeginOffset == NewBeginOffset)(static_cast <bool> (IsSplit || BeginOffset == NewBeginOffset
) ? void (0) : __assert_fail ("IsSplit || BeginOffset == NewBeginOffset"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2355, __extension__ __PRETTY_FUNCTION__))
;
2356 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2357
2358#ifndef NDEBUG
2359 StringRef OldName = OldPtr->getName();
2360 // Skip through the last '.sroa.' component of the name.
2361 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2362 if (LastSROAPrefix != StringRef::npos) {
2363 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2364 // Look for an SROA slice index.
2365 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2366 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2367 // Strip the index and look for the offset.
2368 OldName = OldName.substr(IndexEnd + 1);
2369 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2370 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2371 // Strip the offset.
2372 OldName = OldName.substr(OffsetEnd + 1);
2373 }
2374 }
2375 // Strip any SROA suffixes as well.
2376 OldName = OldName.substr(0, OldName.find(".sroa_"));
2377#endif
2378
2379 return getAdjustedPtr(IRB, DL, &NewAI,
2380 APInt(DL.getPointerTypeSizeInBits(PointerTy), Offset),
2381 PointerTy,
2382#ifndef NDEBUG
2383 Twine(OldName) + "."
2384#else
2385 Twine()
2386#endif
2387 );
2388 }
2389
2390 /// Compute suitable alignment to access this slice of the *new*
2391 /// alloca.
2392 ///
2393 /// You can optionally pass a type to this routine and if that type's ABI
2394 /// alignment is itself suitable, this will return zero.
2395 unsigned getSliceAlign(Type *Ty = nullptr) {
2396 unsigned NewAIAlign = NewAI.getAlignment();
2397 if (!NewAIAlign)
2398 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2399 unsigned Align =
2400 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2401 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
2402 }
2403
2404 unsigned getIndex(uint64_t Offset) {
2405 assert(VecTy && "Can only call getIndex when rewriting a vector")(static_cast <bool> (VecTy && "Can only call getIndex when rewriting a vector"
) ? void (0) : __assert_fail ("VecTy && \"Can only call getIndex when rewriting a vector\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2405, __extension__ __PRETTY_FUNCTION__))
;
2406 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2407 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds")(static_cast <bool> (RelOffset / ElementSize < (4294967295U
) && "Index out of bounds") ? void (0) : __assert_fail
("RelOffset / ElementSize < UINT32_MAX && \"Index out of bounds\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2407, __extension__ __PRETTY_FUNCTION__))
;
2408 uint32_t Index = RelOffset / ElementSize;
2409 assert(Index * ElementSize == RelOffset)(static_cast <bool> (Index * ElementSize == RelOffset) ?
void (0) : __assert_fail ("Index * ElementSize == RelOffset"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2409, __extension__ __PRETTY_FUNCTION__))
;
2410 return Index;
2411 }
2412
2413 void deleteIfTriviallyDead(Value *V) {
2414 Instruction *I = cast<Instruction>(V);
2415 if (isInstructionTriviallyDead(I))
2416 Pass.DeadInsts.insert(I);
2417 }
2418
2419 Value *rewriteVectorizedLoadInst() {
2420 unsigned BeginIndex = getIndex(NewBeginOffset);
2421 unsigned EndIndex = getIndex(NewEndOffset);
2422 assert(EndIndex > BeginIndex && "Empty vector!")(static_cast <bool> (EndIndex > BeginIndex &&
"Empty vector!") ? void (0) : __assert_fail ("EndIndex > BeginIndex && \"Empty vector!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2422, __extension__ __PRETTY_FUNCTION__))
;
2423
2424 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2425 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2426 }
2427
2428 Value *rewriteIntegerLoad(LoadInst &LI) {
2429 assert(IntTy && "We cannot insert an integer to the alloca")(static_cast <bool> (IntTy && "We cannot insert an integer to the alloca"
) ? void (0) : __assert_fail ("IntTy && \"We cannot insert an integer to the alloca\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2429, __extension__ __PRETTY_FUNCTION__))
;
2430 assert(!LI.isVolatile())(static_cast <bool> (!LI.isVolatile()) ? void (0) : __assert_fail
("!LI.isVolatile()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2430, __extension__ __PRETTY_FUNCTION__))
;
2431 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2432 V = convertValue(DL, IRB, V, IntTy);
2433 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset")(static_cast <bool> (NewBeginOffset >= NewAllocaBeginOffset
&& "Out of bounds offset") ? void (0) : __assert_fail
("NewBeginOffset >= NewAllocaBeginOffset && \"Out of bounds offset\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2433, __extension__ __PRETTY_FUNCTION__))
;
2434 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2435 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2436 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2437 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2438 }
2439 // It is possible that the extracted type is not the load type. This
2440 // happens if there is a load past the end of the alloca, and as
2441 // a consequence the slice is narrower but still a candidate for integer
2442 // lowering. To handle this case, we just zero extend the extracted
2443 // integer.
2444 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&(static_cast <bool> (cast<IntegerType>(LI.getType
())->getBitWidth() >= SliceSize * 8 && "Can only handle an extract for an overly wide load"
) ? void (0) : __assert_fail ("cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 && \"Can only handle an extract for an overly wide load\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2445, __extension__ __PRETTY_FUNCTION__))
2445 "Can only handle an extract for an overly wide load")(static_cast <bool> (cast<IntegerType>(LI.getType
())->getBitWidth() >= SliceSize * 8 && "Can only handle an extract for an overly wide load"
) ? void (0) : __assert_fail ("cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 && \"Can only handle an extract for an overly wide load\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2445, __extension__ __PRETTY_FUNCTION__))
;
2446 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2447 V = IRB.CreateZExt(V, LI.getType());
2448 return V;
2449 }
2450
2451 bool visitLoadInst(LoadInst &LI) {
2452 LLVM_DEBUG(dbgs() << " original: " << LI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << LI <<
"\n"; } } while (false)
;
2453 Value *OldOp = LI.getOperand(0);
2454 assert(OldOp == OldPtr)(static_cast <bool> (OldOp == OldPtr) ? void (0) : __assert_fail
("OldOp == OldPtr", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2454, __extension__ __PRETTY_FUNCTION__))
;
2455
2456 AAMDNodes AATags;
2457 LI.getAAMetadata(AATags);
2458
2459 unsigned AS = LI.getPointerAddressSpace();
2460
2461 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
2462 : LI.getType();
2463 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
2464 bool IsPtrAdjusted = false;
2465 Value *V;
2466 if (VecTy) {
2467 V = rewriteVectorizedLoadInst();
2468 } else if (IntTy && LI.getType()->isIntegerTy()) {
2469 V = rewriteIntegerLoad(LI);
2470 } else if (NewBeginOffset == NewAllocaBeginOffset &&
2471 NewEndOffset == NewAllocaEndOffset &&
2472 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2473 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2474 TargetTy->isIntegerTy()))) {
2475 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2476 LI.isVolatile(), LI.getName());
2477 if (AATags)
2478 NewLI->setAAMetadata(AATags);
2479 if (LI.isVolatile())
2480 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2481
2482 // Any !nonnull metadata or !range metadata on the old load is also valid
2483 // on the new load. This is even true in some cases even when the loads
2484 // are different types, for example by mapping !nonnull metadata to
2485 // !range metadata by modeling the null pointer constant converted to the
2486 // integer type.
2487 // FIXME: Add support for range metadata here. Currently the utilities
2488 // for this don't propagate range metadata in trivial cases from one
2489 // integer load to another, don't handle non-addrspace-0 null pointers
2490 // correctly, and don't have any support for mapping ranges as the
2491 // integer type becomes winder or narrower.
2492 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2493 copyNonnullMetadata(LI, N, *NewLI);
2494
2495 // Try to preserve nonnull metadata
2496 V = NewLI;
2497
2498 // If this is an integer load past the end of the slice (which means the
2499 // bytes outside the slice are undef or this load is dead) just forcibly
2500 // fix the integer size with correct handling of endianness.
2501 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2502 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2503 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2504 V = IRB.CreateZExt(V, TITy, "load.ext");
2505 if (DL.isBigEndian())
2506 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2507 "endian_shift");
2508 }
2509 } else {
2510 Type *LTy = TargetTy->getPointerTo(AS);
2511 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2512 getSliceAlign(TargetTy),
2513 LI.isVolatile(), LI.getName());
2514 if (AATags)
2515 NewLI->setAAMetadata(AATags);
2516 if (LI.isVolatile())
2517 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2518
2519 V = NewLI;
2520 IsPtrAdjusted = true;
2521 }
2522 V = convertValue(DL, IRB, V, TargetTy);
2523
2524 if (IsSplit) {
2525 assert(!LI.isVolatile())(static_cast <bool> (!LI.isVolatile()) ? void (0) : __assert_fail
("!LI.isVolatile()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2525, __extension__ __PRETTY_FUNCTION__))
;
2526 assert(LI.getType()->isIntegerTy() &&(static_cast <bool> (LI.getType()->isIntegerTy() &&
"Only integer type loads and stores are split") ? void (0) :
__assert_fail ("LI.getType()->isIntegerTy() && \"Only integer type loads and stores are split\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2527, __extension__ __PRETTY_FUNCTION__))
2527 "Only integer type loads and stores are split")(static_cast <bool> (LI.getType()->isIntegerTy() &&
"Only integer type loads and stores are split") ? void (0) :
__assert_fail ("LI.getType()->isIntegerTy() && \"Only integer type loads and stores are split\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2527, __extension__ __PRETTY_FUNCTION__))
;
2528 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&(static_cast <bool> (SliceSize < DL.getTypeStoreSize
(LI.getType()) && "Split load isn't smaller than original load"
) ? void (0) : __assert_fail ("SliceSize < DL.getTypeStoreSize(LI.getType()) && \"Split load isn't smaller than original load\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2529, __extension__ __PRETTY_FUNCTION__))
2529 "Split load isn't smaller than original load")(static_cast <bool> (SliceSize < DL.getTypeStoreSize
(LI.getType()) && "Split load isn't smaller than original load"
) ? void (0) : __assert_fail ("SliceSize < DL.getTypeStoreSize(LI.getType()) && \"Split load isn't smaller than original load\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2529, __extension__ __PRETTY_FUNCTION__))
;
2530 assert(LI.getType()->getIntegerBitWidth() ==(static_cast <bool> (LI.getType()->getIntegerBitWidth
() == DL.getTypeStoreSizeInBits(LI.getType()) && "Non-byte-multiple bit width"
) ? void (0) : __assert_fail ("LI.getType()->getIntegerBitWidth() == DL.getTypeStoreSizeInBits(LI.getType()) && \"Non-byte-multiple bit width\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2532, __extension__ __PRETTY_FUNCTION__))
2531 DL.getTypeStoreSizeInBits(LI.getType()) &&(static_cast <bool> (LI.getType()->getIntegerBitWidth
() == DL.getTypeStoreSizeInBits(LI.getType()) && "Non-byte-multiple bit width"
) ? void (0) : __assert_fail ("LI.getType()->getIntegerBitWidth() == DL.getTypeStoreSizeInBits(LI.getType()) && \"Non-byte-multiple bit width\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2532, __extension__ __PRETTY_FUNCTION__))
2532 "Non-byte-multiple bit width")(static_cast <bool> (LI.getType()->getIntegerBitWidth
() == DL.getTypeStoreSizeInBits(LI.getType()) && "Non-byte-multiple bit width"
) ? void (0) : __assert_fail ("LI.getType()->getIntegerBitWidth() == DL.getTypeStoreSizeInBits(LI.getType()) && \"Non-byte-multiple bit width\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2532, __extension__ __PRETTY_FUNCTION__))
;
2533 // Move the insertion point just past the load so that we can refer to it.
2534 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
2535 // Create a placeholder value with the same type as LI to use as the
2536 // basis for the new value. This allows us to replace the uses of LI with
2537 // the computed value, and then replace the placeholder with LI, leaving
2538 // LI only used for this computation.
2539 Value *Placeholder =
2540 new LoadInst(UndefValue::get(LI.getType()->getPointerTo(AS)));
2541 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2542 "insert");
2543 LI.replaceAllUsesWith(V);
2544 Placeholder->replaceAllUsesWith(&LI);
2545 Placeholder->deleteValue();
2546 } else {
2547 LI.replaceAllUsesWith(V);
2548 }
2549
2550 Pass.DeadInsts.insert(&LI);
2551 deleteIfTriviallyDead(OldOp);
2552 LLVM_DEBUG(dbgs() << " to: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *V <<
"\n"; } } while (false)
;
2553 return !LI.isVolatile() && !IsPtrAdjusted;
2554 }
2555
2556 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2557 AAMDNodes AATags) {
2558 if (V->getType() != VecTy) {
2559 unsigned BeginIndex = getIndex(NewBeginOffset);
2560 unsigned EndIndex = getIndex(NewEndOffset);
2561 assert(EndIndex > BeginIndex && "Empty vector!")(static_cast <bool> (EndIndex > BeginIndex &&
"Empty vector!") ? void (0) : __assert_fail ("EndIndex > BeginIndex && \"Empty vector!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2561, __extension__ __PRETTY_FUNCTION__))
;
2562 unsigned NumElements = EndIndex - BeginIndex;
2563 assert(NumElements <= VecTy->getNumElements() && "Too many elements!")(static_cast <bool> (NumElements <= VecTy->getNumElements
() && "Too many elements!") ? void (0) : __assert_fail
("NumElements <= VecTy->getNumElements() && \"Too many elements!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2563, __extension__ __PRETTY_FUNCTION__))
;
2564 Type *SliceTy = (NumElements == 1)
2565 ? ElementTy
2566 : VectorType::get(ElementTy, NumElements);
2567 if (V->getType() != SliceTy)
2568 V = convertValue(DL, IRB, V, SliceTy);
2569
2570 // Mix in the existing elements.
2571 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2572 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2573 }
2574 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2575 if (AATags)
2576 Store->setAAMetadata(AATags);
2577 Pass.DeadInsts.insert(&SI);
2578
2579 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Store <<
"\n"; } } while (false)
;
2580 return true;
2581 }
2582
2583 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
2584 assert(IntTy && "We cannot extract an integer from the alloca")(static_cast <bool> (IntTy && "We cannot extract an integer from the alloca"
) ? void (0) : __assert_fail ("IntTy && \"We cannot extract an integer from the alloca\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2584, __extension__ __PRETTY_FUNCTION__))
;
2585 assert(!SI.isVolatile())(static_cast <bool> (!SI.isVolatile()) ? void (0) : __assert_fail
("!SI.isVolatile()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2585, __extension__ __PRETTY_FUNCTION__))
;
2586 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2587 Value *Old =
2588 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2589 Old = convertValue(DL, IRB, Old, IntTy);
2590 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset")(static_cast <bool> (BeginOffset >= NewAllocaBeginOffset
&& "Out of bounds offset") ? void (0) : __assert_fail
("BeginOffset >= NewAllocaBeginOffset && \"Out of bounds offset\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2590, __extension__ __PRETTY_FUNCTION__))
;
2591 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2592 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2593 }
2594 V = convertValue(DL, IRB, V, NewAllocaTy);
2595 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2596 Store->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
2597 if (AATags)
2598 Store->setAAMetadata(AATags);
2599 Pass.DeadInsts.insert(&SI);
2600 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Store <<
"\n"; } } while (false)
;
2601 return true;
2602 }
2603
2604 bool visitStoreInst(StoreInst &SI) {
2605 LLVM_DEBUG(dbgs() << " original: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << SI <<
"\n"; } } while (false)
;
2606 Value *OldOp = SI.getOperand(1);
2607 assert(OldOp == OldPtr)(static_cast <bool> (OldOp == OldPtr) ? void (0) : __assert_fail
("OldOp == OldPtr", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2607, __extension__ __PRETTY_FUNCTION__))
;
2608
2609 AAMDNodes AATags;
2610 SI.getAAMetadata(AATags);
2611
2612 Value *V = SI.getValueOperand();
2613
2614 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2615 // alloca that should be re-examined after promoting this alloca.
2616 if (V->getType()->isPointerTy())
2617 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2618 Pass.PostPromotionWorklist.insert(AI);
2619
2620 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2621 assert(!SI.isVolatile())(static_cast <bool> (!SI.isVolatile()) ? void (0) : __assert_fail
("!SI.isVolatile()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2621, __extension__ __PRETTY_FUNCTION__))
;
2622 assert(V->getType()->isIntegerTy() &&(static_cast <bool> (V->getType()->isIntegerTy() &&
"Only integer type loads and stores are split") ? void (0) :
__assert_fail ("V->getType()->isIntegerTy() && \"Only integer type loads and stores are split\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2623, __extension__ __PRETTY_FUNCTION__))
2623 "Only integer type loads and stores are split")(static_cast <bool> (V->getType()->isIntegerTy() &&
"Only integer type loads and stores are split") ? void (0) :
__assert_fail ("V->getType()->isIntegerTy() && \"Only integer type loads and stores are split\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2623, __extension__ __PRETTY_FUNCTION__))
;
2624 assert(V->getType()->getIntegerBitWidth() ==(static_cast <bool> (V->getType()->getIntegerBitWidth
() == DL.getTypeStoreSizeInBits(V->getType()) && "Non-byte-multiple bit width"
) ? void (0) : __assert_fail ("V->getType()->getIntegerBitWidth() == DL.getTypeStoreSizeInBits(V->getType()) && \"Non-byte-multiple bit width\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2626, __extension__ __PRETTY_FUNCTION__))
2625 DL.getTypeStoreSizeInBits(V->getType()) &&(static_cast <bool> (V->getType()->getIntegerBitWidth
() == DL.getTypeStoreSizeInBits(V->getType()) && "Non-byte-multiple bit width"
) ? void (0) : __assert_fail ("V->getType()->getIntegerBitWidth() == DL.getTypeStoreSizeInBits(V->getType()) && \"Non-byte-multiple bit width\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2626, __extension__ __PRETTY_FUNCTION__))
2626 "Non-byte-multiple bit width")(static_cast <bool> (V->getType()->getIntegerBitWidth
() == DL.getTypeStoreSizeInBits(V->getType()) && "Non-byte-multiple bit width"
) ? void (0) : __assert_fail ("V->getType()->getIntegerBitWidth() == DL.getTypeStoreSizeInBits(V->getType()) && \"Non-byte-multiple bit width\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2626, __extension__ __PRETTY_FUNCTION__))
;
2627 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2628 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2629 "extract");
2630 }
2631
2632 if (VecTy)
2633 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
2634 if (IntTy && V->getType()->isIntegerTy())
2635 return rewriteIntegerStore(V, SI, AATags);
2636
2637 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
2638 StoreInst *NewSI;
2639 if (NewBeginOffset == NewAllocaBeginOffset &&
2640 NewEndOffset == NewAllocaEndOffset &&
2641 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2642 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2643 V->getType()->isIntegerTy()))) {
2644 // If this is an integer store past the end of slice (and thus the bytes
2645 // past that point are irrelevant or this is unreachable), truncate the
2646 // value prior to storing.
2647 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2648 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2649 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2650 if (DL.isBigEndian())
2651 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2652 "endian_shift");
2653 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2654 }
2655
2656 V = convertValue(DL, IRB, V, NewAllocaTy);
2657 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2658 SI.isVolatile());
2659 } else {
2660 unsigned AS = SI.getPointerAddressSpace();
2661 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
2662 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2663 SI.isVolatile());
2664 }
2665 NewSI->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
2666 if (AATags)
2667 NewSI->setAAMetadata(AATags);
2668 if (SI.isVolatile())
2669 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
2670 Pass.DeadInsts.insert(&SI);
2671 deleteIfTriviallyDead(OldOp);
2672
2673 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *NewSI <<
"\n"; } } while (false)
;
2674 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
2675 }
2676
2677 /// Compute an integer value from splatting an i8 across the given
2678 /// number of bytes.
2679 ///
2680 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2681 /// call this routine.
2682 /// FIXME: Heed the advice above.
2683 ///
2684 /// \param V The i8 value to splat.
2685 /// \param Size The number of bytes in the output (assuming i8 is one byte)
2686 Value *getIntegerSplat(Value *V, unsigned Size) {
2687 assert(Size > 0 && "Expected a positive number of bytes.")(static_cast <bool> (Size > 0 && "Expected a positive number of bytes."
) ? void (0) : __assert_fail ("Size > 0 && \"Expected a positive number of bytes.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2687, __extension__ __PRETTY_FUNCTION__))
;
2688 IntegerType *VTy = cast<IntegerType>(V->getType());
2689 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte")(static_cast <bool> (VTy->getBitWidth() == 8 &&
"Expected an i8 value for the byte") ? void (0) : __assert_fail
("VTy->getBitWidth() == 8 && \"Expected an i8 value for the byte\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2689, __extension__ __PRETTY_FUNCTION__))
;
2690 if (Size == 1)
2691 return V;
2692
2693 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2694 V = IRB.CreateMul(
2695 IRB.CreateZExt(V, SplatIntTy, "zext"),
2696 ConstantExpr::getUDiv(
2697 Constant::getAllOnesValue(SplatIntTy),
2698 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2699 SplatIntTy)),
2700 "isplat");
2701 return V;
2702 }
2703
2704 /// Compute a vector splat for a given element value.
2705 Value *getVectorSplat(Value *V, unsigned NumElements) {
2706 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2707 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " splat: " << *V <<
"\n"; } } while (false)
;
2708 return V;
2709 }
2710
2711 bool visitMemSetInst(MemSetInst &II) {
2712 LLVM_DEBUG(dbgs() << " original: " << II << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << II <<
"\n"; } } while (false)
;
2713 assert(II.getRawDest() == OldPtr)(static_cast <bool> (II.getRawDest() == OldPtr) ? void (
0) : __assert_fail ("II.getRawDest() == OldPtr", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2713, __extension__ __PRETTY_FUNCTION__))
;
2714
2715 AAMDNodes AATags;
2716 II.getAAMetadata(AATags);
2717
2718 // If the memset has a variable size, it cannot be split, just adjust the
2719 // pointer to the new alloca.
2720 if (!isa<Constant>(II.getLength())) {
2721 assert(!IsSplit)(static_cast <bool> (!IsSplit) ? void (0) : __assert_fail
("!IsSplit", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2721, __extension__ __PRETTY_FUNCTION__))
;
2722 assert(NewBeginOffset == BeginOffset)(static_cast <bool> (NewBeginOffset == BeginOffset) ? void
(0) : __assert_fail ("NewBeginOffset == BeginOffset", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2722, __extension__ __PRETTY_FUNCTION__))
;
2723 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2724 II.setDestAlignment(getSliceAlign());
2725
2726 deleteIfTriviallyDead(OldPtr);
2727 return false;
2728 }
2729
2730 // Record this instruction for deletion.
2731 Pass.DeadInsts.insert(&II);
2732
2733 Type *AllocaTy = NewAI.getAllocatedType();
2734 Type *ScalarTy = AllocaTy->getScalarType();
2735
2736 // If this doesn't map cleanly onto the alloca type, and that type isn't
2737 // a single value type, just emit a memset.
2738 if (!VecTy && !IntTy &&
2739 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2740 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
2741 !AllocaTy->isSingleValueType() ||
2742 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
2743 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
2744 Type *SizeTy = II.getLength()->getType();
2745 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2746 CallInst *New = IRB.CreateMemSet(
2747 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2748 getSliceAlign(), II.isVolatile());
2749 if (AATags)
2750 New->setAAMetadata(AATags);
2751 LLVM_DEBUG(dbgs() << " to: " << *New << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *New <<
"\n"; } } while (false)
;
2752 return false;
2753 }
2754
2755 // If we can represent this as a simple value, we have to build the actual
2756 // value to store, which requires expanding the byte present in memset to
2757 // a sensible representation for the alloca type. This is essentially
2758 // splatting the byte to a sufficiently wide integer, splatting it across
2759 // any desired vector width, and bitcasting to the final type.
2760 Value *V;
2761
2762 if (VecTy) {
2763 // If this is a memset of a vectorized alloca, insert it.
2764 assert(ElementTy == ScalarTy)(static_cast <bool> (ElementTy == ScalarTy) ? void (0) :
__assert_fail ("ElementTy == ScalarTy", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2764, __extension__ __PRETTY_FUNCTION__))
;
2765
2766 unsigned BeginIndex = getIndex(NewBeginOffset);
2767 unsigned EndIndex = getIndex(NewEndOffset);
2768 assert(EndIndex > BeginIndex && "Empty vector!")(static_cast <bool> (EndIndex > BeginIndex &&
"Empty vector!") ? void (0) : __assert_fail ("EndIndex > BeginIndex && \"Empty vector!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2768, __extension__ __PRETTY_FUNCTION__))
;
2769 unsigned NumElements = EndIndex - BeginIndex;
2770 assert(NumElements <= VecTy->getNumElements() && "Too many elements!")(static_cast <bool> (NumElements <= VecTy->getNumElements
() && "Too many elements!") ? void (0) : __assert_fail
("NumElements <= VecTy->getNumElements() && \"Too many elements!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2770, __extension__ __PRETTY_FUNCTION__))
;
2771
2772 Value *Splat =
2773 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2774 Splat = convertValue(DL, IRB, Splat, ElementTy);
2775 if (NumElements > 1)
2776 Splat = getVectorSplat(Splat, NumElements);
2777
2778 Value *Old =
2779 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2780 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2781 } else if (IntTy) {
2782 // If this is a memset on an alloca where we can widen stores, insert the
2783 // set integer.
2784 assert(!II.isVolatile())(static_cast <bool> (!II.isVolatile()) ? void (0) : __assert_fail
("!II.isVolatile()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2784, __extension__ __PRETTY_FUNCTION__))
;
2785
2786 uint64_t Size = NewEndOffset - NewBeginOffset;
2787 V = getIntegerSplat(II.getValue(), Size);
2788
2789 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2790 EndOffset != NewAllocaBeginOffset)) {
2791 Value *Old =
2792 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2793 Old = convertValue(DL, IRB, Old, IntTy);
2794 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2795 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2796 } else {
2797 assert(V->getType() == IntTy &&(static_cast <bool> (V->getType() == IntTy &&
"Wrong type for an alloca wide integer!") ? void (0) : __assert_fail
("V->getType() == IntTy && \"Wrong type for an alloca wide integer!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2798, __extension__ __PRETTY_FUNCTION__))
2798 "Wrong type for an alloca wide integer!")(static_cast <bool> (V->getType() == IntTy &&
"Wrong type for an alloca wide integer!") ? void (0) : __assert_fail
("V->getType() == IntTy && \"Wrong type for an alloca wide integer!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2798, __extension__ __PRETTY_FUNCTION__))
;
2799 }
2800 V = convertValue(DL, IRB, V, AllocaTy);
2801 } else {
2802 // Established these invariants above.
2803 assert(NewBeginOffset == NewAllocaBeginOffset)(static_cast <bool> (NewBeginOffset == NewAllocaBeginOffset
) ? void (0) : __assert_fail ("NewBeginOffset == NewAllocaBeginOffset"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2803, __extension__ __PRETTY_FUNCTION__))
;
2804 assert(NewEndOffset == NewAllocaEndOffset)(static_cast <bool> (NewEndOffset == NewAllocaEndOffset
) ? void (0) : __assert_fail ("NewEndOffset == NewAllocaEndOffset"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2804, __extension__ __PRETTY_FUNCTION__))
;
2805
2806 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2807 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2808 V = getVectorSplat(V, AllocaVecTy->getNumElements());
2809
2810 V = convertValue(DL, IRB, V, AllocaTy);
2811 }
2812
2813 StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2814 II.isVolatile());
2815 if (AATags)
2816 New->setAAMetadata(AATags);
2817 LLVM_DEBUG(dbgs() << " to: " << *New << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *New <<
"\n"; } } while (false)
;
2818 return !II.isVolatile();
2819 }
2820
2821 bool visitMemTransferInst(MemTransferInst &II) {
2822 // Rewriting of memory transfer instructions can be a bit tricky. We break
2823 // them into two categories: split intrinsics and unsplit intrinsics.
2824
2825 LLVM_DEBUG(dbgs() << " original: " << II << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << II <<
"\n"; } } while (false)
;
2826
2827 AAMDNodes AATags;
2828 II.getAAMetadata(AATags);
2829
2830 bool IsDest = &II.getRawDestUse() == OldUse;
2831 assert((IsDest && II.getRawDest() == OldPtr) ||(static_cast <bool> ((IsDest && II.getRawDest()
== OldPtr) || (!IsDest && II.getRawSource() == OldPtr
)) ? void (0) : __assert_fail ("(IsDest && II.getRawDest() == OldPtr) || (!IsDest && II.getRawSource() == OldPtr)"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2832, __extension__ __PRETTY_FUNCTION__))
1
Within the expansion of the macro 'assert':
a
Assuming 'IsDest' is 0
b
Assuming pointer value is null
2832 (!IsDest && II.getRawSource() == OldPtr))(static_cast <bool> ((IsDest && II.getRawDest()
== OldPtr) || (!IsDest && II.getRawSource() == OldPtr
)) ? void (0) : __assert_fail ("(IsDest && II.getRawDest() == OldPtr) || (!IsDest && II.getRawSource() == OldPtr)"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2832, __extension__ __PRETTY_FUNCTION__))
;
2833
2834 unsigned SliceAlign = getSliceAlign();
2835
2836 // For unsplit intrinsics, we simply modify the source and destination
2837 // pointers in place. This isn't just an optimization, it is a matter of
2838 // correctness. With unsplit intrinsics we may be dealing with transfers
2839 // within a single alloca before SROA ran, or with transfers that have
2840 // a variable length. We may also be dealing with memmove instead of
2841 // memcpy, and so simply updating the pointers is the necessary for us to
2842 // update both source and dest of a single call.
2843 if (!IsSplittable) {
2
Assuming the condition is true
3
Taking true branch
2844 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
4
Called C++ object pointer is null
2845 if (IsDest) {
2846 II.setDest(AdjustedPtr);
2847 II.setDestAlignment(SliceAlign);
2848 }
2849 else {
2850 II.setSource(AdjustedPtr);
2851 II.setSourceAlignment(SliceAlign);
2852 }
2853
2854 LLVM_DEBUG(dbgs() << " to: " << II << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << II <<
"\n"; } } while (false)
;
2855 deleteIfTriviallyDead(OldPtr);
2856 return false;
2857 }
2858 // For split transfer intrinsics we have an incredibly useful assurance:
2859 // the source and destination do not reside within the same alloca, and at
2860 // least one of them does not escape. This means that we can replace
2861 // memmove with memcpy, and we don't need to worry about all manner of
2862 // downsides to splitting and transforming the operations.
2863
2864 // If this doesn't map cleanly onto the alloca type, and that type isn't
2865 // a single value type, just emit a memcpy.
2866 bool EmitMemCpy =
2867 !VecTy && !IntTy &&
2868 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2869 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2870 !NewAI.getAllocatedType()->isSingleValueType());
2871
2872 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2873 // size hasn't been shrunk based on analysis of the viable range, this is
2874 // a no-op.
2875 if (EmitMemCpy && &OldAI == &NewAI) {
2876 // Ensure the start lines up.
2877 assert(NewBeginOffset == BeginOffset)(static_cast <bool> (NewBeginOffset == BeginOffset) ? void
(0) : __assert_fail ("NewBeginOffset == BeginOffset", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2877, __extension__ __PRETTY_FUNCTION__))
;
2878
2879 // Rewrite the size as needed.
2880 if (NewEndOffset != EndOffset)
2881 II.setLength(ConstantInt::get(II.getLength()->getType(),
2882 NewEndOffset - NewBeginOffset));
2883 return false;
2884 }
2885 // Record this instruction for deletion.
2886 Pass.DeadInsts.insert(&II);
2887
2888 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2889 // alloca that should be re-examined after rewriting this instruction.
2890 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
2891 if (AllocaInst *AI =
2892 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2893 assert(AI != &OldAI && AI != &NewAI &&(static_cast <bool> (AI != &OldAI && AI != &
NewAI && "Splittable transfers cannot reach the same alloca on both ends."
) ? void (0) : __assert_fail ("AI != &OldAI && AI != &NewAI && \"Splittable transfers cannot reach the same alloca on both ends.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2894, __extension__ __PRETTY_FUNCTION__))
2894 "Splittable transfers cannot reach the same alloca on both ends.")(static_cast <bool> (AI != &OldAI && AI != &
NewAI && "Splittable transfers cannot reach the same alloca on both ends."
) ? void (0) : __assert_fail ("AI != &OldAI && AI != &NewAI && \"Splittable transfers cannot reach the same alloca on both ends.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 2894, __extension__ __PRETTY_FUNCTION__))
;
2895 Pass.Worklist.insert(AI);
2896 }
2897
2898 Type *OtherPtrTy = OtherPtr->getType();
2899 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2900
2901 // Compute the relative offset for the other pointer within the transfer.
2902 unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
2903 APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
2904 unsigned OtherAlign =
2905 IsDest ? II.getSourceAlignment() : II.getDestAlignment();
2906 OtherAlign = MinAlign(OtherAlign ? OtherAlign : 1,
2907 OtherOffset.zextOrTrunc(64).getZExtValue());
2908
2909 if (EmitMemCpy) {
2910 // Compute the other pointer, folding as much as possible to produce
2911 // a single, simple GEP in most cases.
2912 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2913 OtherPtr->getName() + ".");
2914
2915 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2916 Type *SizeTy = II.getLength()->getType();
2917 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2918
2919 Value *DestPtr, *SrcPtr;
2920 unsigned DestAlign, SrcAlign;
2921 // Note: IsDest is true iff we're copying into the new alloca slice
2922 if (IsDest) {
2923 DestPtr = OurPtr;
2924 DestAlign = SliceAlign;
2925 SrcPtr = OtherPtr;
2926 SrcAlign = OtherAlign;
2927 } else {
2928 DestPtr = OtherPtr;
2929 DestAlign = OtherAlign;
2930 SrcPtr = OurPtr;
2931 SrcAlign = SliceAlign;
2932 }
2933 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2934 Size, II.isVolatile());
2935 if (AATags)
2936 New->setAAMetadata(AATags);
2937 LLVM_DEBUG(dbgs() << " to: " << *New << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *New <<
"\n"; } } while (false)
;
2938 return false;
2939 }
2940
2941 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2942 NewEndOffset == NewAllocaEndOffset;
2943 uint64_t Size = NewEndOffset - NewBeginOffset;
2944 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2945 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
2946 unsigned NumElements = EndIndex - BeginIndex;
2947 IntegerType *SubIntTy =
2948 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
2949
2950 // Reset the other pointer type to match the register type we're going to
2951 // use, but using the address space of the original other pointer.
2952 if (VecTy && !IsWholeAlloca) {
2953 if (NumElements == 1)
2954 OtherPtrTy = VecTy->getElementType();
2955 else
2956 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2957
2958 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
2959 } else if (IntTy && !IsWholeAlloca) {
2960 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2961 } else {
2962 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
2963 }
2964
2965 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2966 OtherPtr->getName() + ".");
2967 unsigned SrcAlign = OtherAlign;
2968 Value *DstPtr = &NewAI;
2969 unsigned DstAlign = SliceAlign;
2970 if (!IsDest) {
2971 std::swap(SrcPtr, DstPtr);
2972 std::swap(SrcAlign, DstAlign);
2973 }
2974
2975 Value *Src;
2976 if (VecTy && !IsWholeAlloca && !IsDest) {
2977 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2978 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
2979 } else if (IntTy && !IsWholeAlloca && !IsDest) {
2980 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
2981 Src = convertValue(DL, IRB, Src, IntTy);
2982 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2983 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
2984 } else {
2985 LoadInst *Load = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
2986 "copyload");
2987 if (AATags)
2988 Load->setAAMetadata(AATags);
2989 Src = Load;
2990 }
2991
2992 if (VecTy && !IsWholeAlloca && IsDest) {
2993 Value *Old =
2994 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2995 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
2996 } else if (IntTy && !IsWholeAlloca && IsDest) {
2997 Value *Old =
2998 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
2999 Old = convertValue(DL, IRB, Old, IntTy);
3000 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3001 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3002 Src = convertValue(DL, IRB, Src, NewAllocaTy);
3003 }
3004
3005 StoreInst *Store = cast<StoreInst>(
3006 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
3007 if (AATags)
3008 Store->setAAMetadata(AATags);
3009 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Store <<
"\n"; } } while (false)
;
3010 return !II.isVolatile();
3011 }
3012
3013 bool visitIntrinsicInst(IntrinsicInst &II) {
3014 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||(static_cast <bool> (II.getIntrinsicID() == Intrinsic::
lifetime_start || II.getIntrinsicID() == Intrinsic::lifetime_end
) ? void (0) : __assert_fail ("II.getIntrinsicID() == Intrinsic::lifetime_start || II.getIntrinsicID() == Intrinsic::lifetime_end"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3015, __extension__ __PRETTY_FUNCTION__))
3015 II.getIntrinsicID() == Intrinsic::lifetime_end)(static_cast <bool> (II.getIntrinsicID() == Intrinsic::
lifetime_start || II.getIntrinsicID() == Intrinsic::lifetime_end
) ? void (0) : __assert_fail ("II.getIntrinsicID() == Intrinsic::lifetime_start || II.getIntrinsicID() == Intrinsic::lifetime_end"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3015, __extension__ __PRETTY_FUNCTION__))
;
3016 LLVM_DEBUG(dbgs() << " original: " << II << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << II <<
"\n"; } } while (false)
;
3017 assert(II.getArgOperand(1) == OldPtr)(static_cast <bool> (II.getArgOperand(1) == OldPtr) ? void
(0) : __assert_fail ("II.getArgOperand(1) == OldPtr", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3017, __extension__ __PRETTY_FUNCTION__))
;
3018
3019 // Record this instruction for deletion.
3020 Pass.DeadInsts.insert(&II);
3021
3022 // Lifetime intrinsics are only promotable if they cover the whole alloca.
3023 // Therefore, we drop lifetime intrinsics which don't cover the whole
3024 // alloca.
3025 // (In theory, intrinsics which partially cover an alloca could be
3026 // promoted, but PromoteMemToReg doesn't handle that case.)
3027 // FIXME: Check whether the alloca is promotable before dropping the
3028 // lifetime intrinsics?
3029 if (NewBeginOffset != NewAllocaBeginOffset ||
3030 NewEndOffset != NewAllocaEndOffset)
3031 return true;
3032
3033 ConstantInt *Size =
3034 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3035 NewEndOffset - NewBeginOffset);
3036 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3037 Value *New;
3038 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3039 New = IRB.CreateLifetimeStart(Ptr, Size);
3040 else
3041 New = IRB.CreateLifetimeEnd(Ptr, Size);
3042
3043 (void)New;
3044 LLVM_DEBUG(dbgs() << " to: " << *New << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *New <<
"\n"; } } while (false)
;
3045
3046 return true;
3047 }
3048
3049 bool visitPHINode(PHINode &PN) {
3050 LLVM_DEBUG(dbgs() << " original: " << PN << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << PN <<
"\n"; } } while (false)
;
3051 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable")(static_cast <bool> (BeginOffset >= NewAllocaBeginOffset
&& "PHIs are unsplittable") ? void (0) : __assert_fail
("BeginOffset >= NewAllocaBeginOffset && \"PHIs are unsplittable\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3051, __extension__ __PRETTY_FUNCTION__))
;
3052 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable")(static_cast <bool> (EndOffset <= NewAllocaEndOffset
&& "PHIs are unsplittable") ? void (0) : __assert_fail
("EndOffset <= NewAllocaEndOffset && \"PHIs are unsplittable\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3052, __extension__ __PRETTY_FUNCTION__))
;
3053
3054 // We would like to compute a new pointer in only one place, but have it be
3055 // as local as possible to the PHI. To do that, we re-use the location of
3056 // the old pointer, which necessarily must be in the right position to
3057 // dominate the PHI.
3058 IRBuilderTy PtrBuilder(IRB);
3059 if (isa<PHINode>(OldPtr))
3060 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
3061 else
3062 PtrBuilder.SetInsertPoint(OldPtr);
3063 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
3064
3065 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
3066 // Replace the operands which were using the old pointer.
3067 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3068
3069 LLVM_DEBUG(dbgs() << " to: " << PN << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << PN <<
"\n"; } } while (false)
;
3070 deleteIfTriviallyDead(OldPtr);
3071
3072 // PHIs can't be promoted on their own, but often can be speculated. We
3073 // check the speculation outside of the rewriter so that we see the
3074 // fully-rewritten alloca.
3075 PHIUsers.insert(&PN);
3076 return true;
3077 }
3078
3079 bool visitSelectInst(SelectInst &SI) {
3080 LLVM_DEBUG(dbgs() << " original: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << SI <<
"\n"; } } while (false)
;
3081 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&(static_cast <bool> ((SI.getTrueValue() == OldPtr || SI
.getFalseValue() == OldPtr) && "Pointer isn't an operand!"
) ? void (0) : __assert_fail ("(SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) && \"Pointer isn't an operand!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3082, __extension__ __PRETTY_FUNCTION__))
3082 "Pointer isn't an operand!")(static_cast <bool> ((SI.getTrueValue() == OldPtr || SI
.getFalseValue() == OldPtr) && "Pointer isn't an operand!"
) ? void (0) : __assert_fail ("(SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) && \"Pointer isn't an operand!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3082, __extension__ __PRETTY_FUNCTION__))
;
3083 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable")(static_cast <bool> (BeginOffset >= NewAllocaBeginOffset
&& "Selects are unsplittable") ? void (0) : __assert_fail
("BeginOffset >= NewAllocaBeginOffset && \"Selects are unsplittable\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3083, __extension__ __PRETTY_FUNCTION__))
;
3084 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable")(static_cast <bool> (EndOffset <= NewAllocaEndOffset
&& "Selects are unsplittable") ? void (0) : __assert_fail
("EndOffset <= NewAllocaEndOffset && \"Selects are unsplittable\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3084, __extension__ __PRETTY_FUNCTION__))
;
3085
3086 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3087 // Replace the operands which were using the old pointer.
3088 if (SI.getOperand(1) == OldPtr)
3089 SI.setOperand(1, NewPtr);
3090 if (SI.getOperand(2) == OldPtr)
3091 SI.setOperand(2, NewPtr);
3092
3093 LLVM_DEBUG(dbgs() << " to: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << SI <<
"\n"; } } while (false)
;
3094 deleteIfTriviallyDead(OldPtr);
3095
3096 // Selects can't be promoted on their own, but often can be speculated. We
3097 // check the speculation outside of the rewriter so that we see the
3098 // fully-rewritten alloca.
3099 SelectUsers.insert(&SI);
3100 return true;
3101 }
3102};
3103
3104namespace {
3105
3106/// Visitor to rewrite aggregate loads and stores as scalar.
3107///
3108/// This pass aggressively rewrites all aggregate loads and stores on
3109/// a particular pointer (or any pointer derived from it which we can identify)
3110/// with scalar loads and stores.
3111class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3112 // Befriend the base class so it can delegate to private visit methods.
3113 friend class InstVisitor<AggLoadStoreRewriter, bool>;
3114
3115 /// Queue of pointer uses to analyze and potentially rewrite.
3116 SmallVector<Use *, 8> Queue;
3117
3118 /// Set to prevent us from cycling with phi nodes and loops.
3119 SmallPtrSet<User *, 8> Visited;
3120
3121 /// The current pointer use being rewritten. This is used to dig up the used
3122 /// value (as opposed to the user).
3123 Use *U;
3124
3125public:
3126 /// Rewrite loads and stores through a pointer and all pointers derived from
3127 /// it.
3128 bool rewrite(Instruction &I) {
3129 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Rewriting FCA loads and stores...\n"
; } } while (false)
;
3130 enqueueUsers(I);
3131 bool Changed = false;
3132 while (!Queue.empty()) {
3133 U = Queue.pop_back_val();
3134 Changed |= visit(cast<Instruction>(U->getUser()));
3135 }
3136 return Changed;
3137 }
3138
3139private:
3140 /// Enqueue all the users of the given instruction for further processing.
3141 /// This uses a set to de-duplicate users.
3142 void enqueueUsers(Instruction &I) {
3143 for (Use &U : I.uses())
3144 if (Visited.insert(U.getUser()).second)
3145 Queue.push_back(&U);
3146 }
3147
3148 // Conservative default is to not rewrite anything.
3149 bool visitInstruction(Instruction &I) { return false; }
3150
3151 /// Generic recursive split emission class.
3152 template <typename Derived> class OpSplitter {
3153 protected:
3154 /// The builder used to form new instructions.
3155 IRBuilderTy IRB;
3156
3157 /// The indices which to be used with insert- or extractvalue to select the
3158 /// appropriate value within the aggregate.
3159 SmallVector<unsigned, 4> Indices;
3160
3161 /// The indices to a GEP instruction which will move Ptr to the correct slot
3162 /// within the aggregate.
3163 SmallVector<Value *, 4> GEPIndices;
3164
3165 /// The base pointer of the original op, used as a base for GEPing the
3166 /// split operations.
3167 Value *Ptr;
3168
3169 /// Initialize the splitter with an insertion point, Ptr and start with a
3170 /// single zero GEP index.
3171 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
3172 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
3173
3174 public:
3175 /// Generic recursive split emission routine.
3176 ///
3177 /// This method recursively splits an aggregate op (load or store) into
3178 /// scalar or vector ops. It splits recursively until it hits a single value
3179 /// and emits that single value operation via the template argument.
3180 ///
3181 /// The logic of this routine relies on GEPs and insertvalue and
3182 /// extractvalue all operating with the same fundamental index list, merely
3183 /// formatted differently (GEPs need actual values).
3184 ///
3185 /// \param Ty The type being split recursively into smaller ops.
3186 /// \param Agg The aggregate value being built up or stored, depending on
3187 /// whether this is splitting a load or a store respectively.
3188 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3189 if (Ty->isSingleValueType())
3190 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
3191
3192 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3193 unsigned OldSize = Indices.size();
3194 (void)OldSize;
3195 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3196 ++Idx) {
3197 assert(Indices.size() == OldSize && "Did not return to the old size")(static_cast <bool> (Indices.size() == OldSize &&
"Did not return to the old size") ? void (0) : __assert_fail
("Indices.size() == OldSize && \"Did not return to the old size\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3197, __extension__ __PRETTY_FUNCTION__))
;
3198 Indices.push_back(Idx);
3199 GEPIndices.push_back(IRB.getInt32(Idx));
3200 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3201 GEPIndices.pop_back();
3202 Indices.pop_back();
3203 }
3204 return;
3205 }
3206
3207 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3208 unsigned OldSize = Indices.size();
3209 (void)OldSize;
3210 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3211 ++Idx) {
3212 assert(Indices.size() == OldSize && "Did not return to the old size")(static_cast <bool> (Indices.size() == OldSize &&
"Did not return to the old size") ? void (0) : __assert_fail
("Indices.size() == OldSize && \"Did not return to the old size\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3212, __extension__ __PRETTY_FUNCTION__))
;
3213 Indices.push_back(Idx);
3214 GEPIndices.push_back(IRB.getInt32(Idx));
3215 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3216 GEPIndices.pop_back();
3217 Indices.pop_back();
3218 }
3219 return;
3220 }
3221
3222 llvm_unreachable("Only arrays and structs are aggregate loadable types")::llvm::llvm_unreachable_internal("Only arrays and structs are aggregate loadable types"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3222)
;
3223 }
3224 };
3225
3226 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3227 AAMDNodes AATags;
3228
3229 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, AAMDNodes AATags)
3230 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr), AATags(AATags) {}
3231
3232 /// Emit a leaf load of a single value. This is called at the leaves of the
3233 /// recursive emission to actually load values.
3234 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3235 assert(Ty->isSingleValueType())(static_cast <bool> (Ty->isSingleValueType()) ? void
(0) : __assert_fail ("Ty->isSingleValueType()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3235, __extension__ __PRETTY_FUNCTION__))
;
3236 // Load the single value and insert it using the indices.
3237 Value *GEP =
3238 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
3239 LoadInst *Load = IRB.CreateLoad(GEP, Name + ".load");
3240 if (AATags)
3241 Load->setAAMetadata(AATags);
3242 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3243 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Load <<
"\n"; } } while (false)
;
3244 }
3245 };
3246
3247 bool visitLoadInst(LoadInst &LI) {
3248 assert(LI.getPointerOperand() == *U)(static_cast <bool> (LI.getPointerOperand() == *U) ? void
(0) : __assert_fail ("LI.getPointerOperand() == *U", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3248, __extension__ __PRETTY_FUNCTION__))
;
3249 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3250 return false;
3251
3252 // We have an aggregate being loaded, split it apart.
3253 LLVM_DEBUG(dbgs() << " original: " << LI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << LI <<
"\n"; } } while (false)
;
3254 AAMDNodes AATags;
3255 LI.getAAMetadata(AATags);
3256 LoadOpSplitter Splitter(&LI, *U, AATags);
3257 Value *V = UndefValue::get(LI.getType());
3258 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3259 LI.replaceAllUsesWith(V);
3260 LI.eraseFromParent();
3261 return true;
3262 }
3263
3264 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3265 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, AAMDNodes AATags)
3266 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr), AATags(AATags) {}
3267 AAMDNodes AATags;
3268
3269 /// Emit a leaf store of a single value. This is called at the leaves of the
3270 /// recursive emission to actually produce stores.
3271 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
3272 assert(Ty->isSingleValueType())(static_cast <bool> (Ty->isSingleValueType()) ? void
(0) : __assert_fail ("Ty->isSingleValueType()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3272, __extension__ __PRETTY_FUNCTION__))
;
3273 // Extract the single value and store it using the indices.
3274 //
3275 // The gep and extractvalue values are factored out of the CreateStore
3276 // call to make the output independent of the argument evaluation order.
3277 Value *ExtractValue =
3278 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3279 Value *InBoundsGEP =
3280 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
3281 StoreInst *Store = IRB.CreateStore(ExtractValue, InBoundsGEP);
3282 if (AATags)
3283 Store->setAAMetadata(AATags);
3284 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " to: " << *Store <<
"\n"; } } while (false)
;
3285 }
3286 };
3287
3288 bool visitStoreInst(StoreInst &SI) {
3289 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3290 return false;
3291 Value *V = SI.getValueOperand();
3292 if (V->getType()->isSingleValueType())
3293 return false;
3294
3295 // We have an aggregate being stored, split it apart.
3296 LLVM_DEBUG(dbgs() << " original: " << SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " original: " << SI <<
"\n"; } } while (false)
;
3297 AAMDNodes AATags;
3298 SI.getAAMetadata(AATags);
3299 StoreOpSplitter Splitter(&SI, *U, AATags);
3300 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3301 SI.eraseFromParent();
3302 return true;
3303 }
3304
3305 bool visitBitCastInst(BitCastInst &BC) {
3306 enqueueUsers(BC);
3307 return false;
3308 }
3309
3310 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3311 enqueueUsers(GEPI);
3312 return false;
3313 }
3314
3315 bool visitPHINode(PHINode &PN) {
3316 enqueueUsers(PN);
3317 return false;
3318 }
3319
3320 bool visitSelectInst(SelectInst &SI) {
3321 enqueueUsers(SI);
3322 return false;
3323 }
3324};
3325
3326} // end anonymous namespace
3327
3328/// Strip aggregate type wrapping.
3329///
3330/// This removes no-op aggregate types wrapping an underlying type. It will
3331/// strip as many layers of types as it can without changing either the type
3332/// size or the allocated size.
3333static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3334 if (Ty->isSingleValueType())
3335 return Ty;
3336
3337 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3338 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3339
3340 Type *InnerTy;
3341 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3342 InnerTy = ArrTy->getElementType();
3343 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3344 const StructLayout *SL = DL.getStructLayout(STy);
3345 unsigned Index = SL->getElementContainingOffset(0);
3346 InnerTy = STy->getElementType(Index);
3347 } else {
3348 return Ty;
3349 }
3350
3351 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3352 TypeSize > DL.getTypeSizeInBits(InnerTy))
3353 return Ty;
3354
3355 return stripAggregateTypeWrapping(DL, InnerTy);
3356}
3357
3358/// Try to find a partition of the aggregate type passed in for a given
3359/// offset and size.
3360///
3361/// This recurses through the aggregate type and tries to compute a subtype
3362/// based on the offset and size. When the offset and size span a sub-section
3363/// of an array, it will even compute a new array type for that sub-section,
3364/// and the same for structs.
3365///
3366/// Note that this routine is very strict and tries to find a partition of the
3367/// type which produces the *exact* right offset and size. It is not forgiving
3368/// when the size or offset cause either end of type-based partition to be off.
3369/// Also, this is a best-effort routine. It is reasonable to give up and not
3370/// return a type if necessary.
3371static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3372 uint64_t Size) {
3373 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3374 return stripAggregateTypeWrapping(DL, Ty);
3375 if (Offset > DL.getTypeAllocSize(Ty) ||
3376 (DL.getTypeAllocSize(Ty) - Offset) < Size)
3377 return nullptr;
3378
3379 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3380 Type *ElementTy = SeqTy->getElementType();
3381 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3382 uint64_t NumSkippedElements = Offset / ElementSize;
3383 if (NumSkippedElements >= SeqTy->getNumElements())
3384 return nullptr;
3385 Offset -= NumSkippedElements * ElementSize;
3386
3387 // First check if we need to recurse.
3388 if (Offset > 0 || Size < ElementSize) {
3389 // Bail if the partition ends in a different array element.
3390 if ((Offset + Size) > ElementSize)
3391 return nullptr;
3392 // Recurse through the element type trying to peel off offset bytes.
3393 return getTypePartition(DL, ElementTy, Offset, Size);
3394 }
3395 assert(Offset == 0)(static_cast <bool> (Offset == 0) ? void (0) : __assert_fail
("Offset == 0", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3395, __extension__ __PRETTY_FUNCTION__))
;
3396
3397 if (Size == ElementSize)
3398 return stripAggregateTypeWrapping(DL, ElementTy);
3399 assert(Size > ElementSize)(static_cast <bool> (Size > ElementSize) ? void (0) :
__assert_fail ("Size > ElementSize", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3399, __extension__ __PRETTY_FUNCTION__))
;
3400 uint64_t NumElements = Size / ElementSize;
3401 if (NumElements * ElementSize != Size)
3402 return nullptr;
3403 return ArrayType::get(ElementTy, NumElements);
3404 }
3405
3406 StructType *STy = dyn_cast<StructType>(Ty);
3407 if (!STy)
3408 return nullptr;
3409
3410 const StructLayout *SL = DL.getStructLayout(STy);
3411 if (Offset >= SL->getSizeInBytes())
3412 return nullptr;
3413 uint64_t EndOffset = Offset + Size;
3414 if (EndOffset > SL->getSizeInBytes())
3415 return nullptr;
3416
3417 unsigned Index = SL->getElementContainingOffset(Offset);
3418 Offset -= SL->getElementOffset(Index);
3419
3420 Type *ElementTy = STy->getElementType(Index);
3421 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3422 if (Offset >= ElementSize)
3423 return nullptr; // The offset points into alignment padding.
3424
3425 // See if any partition must be contained by the element.
3426 if (Offset > 0 || Size < ElementSize) {
3427 if ((Offset + Size) > ElementSize)
3428 return nullptr;
3429 return getTypePartition(DL, ElementTy, Offset, Size);
3430 }
3431 assert(Offset == 0)(static_cast <bool> (Offset == 0) ? void (0) : __assert_fail
("Offset == 0", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3431, __extension__ __PRETTY_FUNCTION__))
;
3432
3433 if (Size == ElementSize)
3434 return stripAggregateTypeWrapping(DL, ElementTy);
3435
3436 StructType::element_iterator EI = STy->element_begin() + Index,
3437 EE = STy->element_end();
3438 if (EndOffset < SL->getSizeInBytes()) {
3439 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3440 if (Index == EndIndex)
3441 return nullptr; // Within a single element and its padding.
3442
3443 // Don't try to form "natural" types if the elements don't line up with the
3444 // expected size.
3445 // FIXME: We could potentially recurse down through the last element in the
3446 // sub-struct to find a natural end point.
3447 if (SL->getElementOffset(EndIndex) != EndOffset)
3448 return nullptr;
3449
3450 assert(Index < EndIndex)(static_cast <bool> (Index < EndIndex) ? void (0) : __assert_fail
("Index < EndIndex", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3450, __extension__ __PRETTY_FUNCTION__))
;
3451 EE = STy->element_begin() + EndIndex;
3452 }
3453
3454 // Try to build up a sub-structure.
3455 StructType *SubTy =
3456 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3457 const StructLayout *SubSL = DL.getStructLayout(SubTy);
3458 if (Size != SubSL->getSizeInBytes())
3459 return nullptr; // The sub-struct doesn't have quite the size needed.
3460
3461 return SubTy;
3462}
3463
3464/// Pre-split loads and stores to simplify rewriting.
3465///
3466/// We want to break up the splittable load+store pairs as much as
3467/// possible. This is important to do as a preprocessing step, as once we
3468/// start rewriting the accesses to partitions of the alloca we lose the
3469/// necessary information to correctly split apart paired loads and stores
3470/// which both point into this alloca. The case to consider is something like
3471/// the following:
3472///
3473/// %a = alloca [12 x i8]
3474/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3475/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3476/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3477/// %iptr1 = bitcast i8* %gep1 to i64*
3478/// %iptr2 = bitcast i8* %gep2 to i64*
3479/// %fptr1 = bitcast i8* %gep1 to float*
3480/// %fptr2 = bitcast i8* %gep2 to float*
3481/// %fptr3 = bitcast i8* %gep3 to float*
3482/// store float 0.0, float* %fptr1
3483/// store float 1.0, float* %fptr2
3484/// %v = load i64* %iptr1
3485/// store i64 %v, i64* %iptr2
3486/// %f1 = load float* %fptr2
3487/// %f2 = load float* %fptr3
3488///
3489/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3490/// promote everything so we recover the 2 SSA values that should have been
3491/// there all along.
3492///
3493/// \returns true if any changes are made.
3494bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3495 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Pre-splitting loads and stores\n"
; } } while (false)
;
3496
3497 // Track the loads and stores which are candidates for pre-splitting here, in
3498 // the order they first appear during the partition scan. These give stable
3499 // iteration order and a basis for tracking which loads and stores we
3500 // actually split.
3501 SmallVector<LoadInst *, 4> Loads;
3502 SmallVector<StoreInst *, 4> Stores;
3503
3504 // We need to accumulate the splits required of each load or store where we
3505 // can find them via a direct lookup. This is important to cross-check loads
3506 // and stores against each other. We also track the slice so that we can kill
3507 // all the slices that end up split.
3508 struct SplitOffsets {
3509 Slice *S;
3510 std::vector<uint64_t> Splits;
3511 };
3512 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3513
3514 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3515 // This is important as we also cannot pre-split stores of those loads!
3516 // FIXME: This is all pretty gross. It means that we can be more aggressive
3517 // in pre-splitting when the load feeding the store happens to come from
3518 // a separate alloca. Put another way, the effectiveness of SROA would be
3519 // decreased by a frontend which just concatenated all of its local allocas
3520 // into one big flat alloca. But defeating such patterns is exactly the job
3521 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3522 // change store pre-splitting to actually force pre-splitting of the load
3523 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3524 // maybe it would make it more principled?
3525 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3526
3527 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Searching for candidate loads and stores\n"
; } } while (false)
;
3528 for (auto &P : AS.partitions()) {
3529 for (Slice &S : P) {
3530 Instruction *I = cast<Instruction>(S.getUse()->getUser());
3531 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3532 // If this is a load we have to track that it can't participate in any
3533 // pre-splitting. If this is a store of a load we have to track that
3534 // that load also can't participate in any pre-splitting.
3535 if (auto *LI = dyn_cast<LoadInst>(I))
3536 UnsplittableLoads.insert(LI);
3537 else if (auto *SI = dyn_cast<StoreInst>(I))
3538 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3539 UnsplittableLoads.insert(LI);
3540 continue;
3541 }
3542 assert(P.endOffset() > S.beginOffset() &&(static_cast <bool> (P.endOffset() > S.beginOffset()
&& "Empty or backwards partition!") ? void (0) : __assert_fail
("P.endOffset() > S.beginOffset() && \"Empty or backwards partition!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3543, __extension__ __PRETTY_FUNCTION__))
3543 "Empty or backwards partition!")(static_cast <bool> (P.endOffset() > S.beginOffset()
&& "Empty or backwards partition!") ? void (0) : __assert_fail
("P.endOffset() > S.beginOffset() && \"Empty or backwards partition!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3543, __extension__ __PRETTY_FUNCTION__))
;
3544
3545 // Determine if this is a pre-splittable slice.
3546 if (auto *LI = dyn_cast<LoadInst>(I)) {
3547 assert(!LI->isVolatile() && "Cannot split volatile loads!")(static_cast <bool> (!LI->isVolatile() && "Cannot split volatile loads!"
) ? void (0) : __assert_fail ("!LI->isVolatile() && \"Cannot split volatile loads!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3547, __extension__ __PRETTY_FUNCTION__))
;
3548
3549 // The load must be used exclusively to store into other pointers for
3550 // us to be able to arbitrarily pre-split it. The stores must also be
3551 // simple to avoid changing semantics.
3552 auto IsLoadSimplyStored = [](LoadInst *LI) {
3553 for (User *LU : LI->users()) {
3554 auto *SI = dyn_cast<StoreInst>(LU);
3555 if (!SI || !SI->isSimple())
3556 return false;
3557 }
3558 return true;
3559 };
3560 if (!IsLoadSimplyStored(LI)) {
3561 UnsplittableLoads.insert(LI);
3562 continue;
3563 }
3564
3565 Loads.push_back(LI);
3566 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3567 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3568 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
3569 continue;
3570 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3571 if (!StoredLoad || !StoredLoad->isSimple())
3572 continue;
3573 assert(!SI->isVolatile() && "Cannot split volatile stores!")(static_cast <bool> (!SI->isVolatile() && "Cannot split volatile stores!"
) ? void (0) : __assert_fail ("!SI->isVolatile() && \"Cannot split volatile stores!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3573, __extension__ __PRETTY_FUNCTION__))
;
3574
3575 Stores.push_back(SI);
3576 } else {
3577 // Other uses cannot be pre-split.
3578 continue;
3579 }
3580
3581 // Record the initial split.
3582 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Candidate: " << *I <<
"\n"; } } while (false)
;
3583 auto &Offsets = SplitOffsetsMap[I];
3584 assert(Offsets.Splits.empty() &&(static_cast <bool> (Offsets.Splits.empty() && "Should not have splits the first time we see an instruction!"
) ? void (0) : __assert_fail ("Offsets.Splits.empty() && \"Should not have splits the first time we see an instruction!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3585, __extension__ __PRETTY_FUNCTION__))
3585 "Should not have splits the first time we see an instruction!")(static_cast <bool> (Offsets.Splits.empty() && "Should not have splits the first time we see an instruction!"
) ? void (0) : __assert_fail ("Offsets.Splits.empty() && \"Should not have splits the first time we see an instruction!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3585, __extension__ __PRETTY_FUNCTION__))
;
3586 Offsets.S = &S;
3587 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3588 }
3589
3590 // Now scan the already split slices, and add a split for any of them which
3591 // we're going to pre-split.
3592 for (Slice *S : P.splitSliceTails()) {
3593 auto SplitOffsetsMapI =
3594 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3595 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3596 continue;
3597 auto &Offsets = SplitOffsetsMapI->second;
3598
3599 assert(Offsets.S == S && "Found a mismatched slice!")(static_cast <bool> (Offsets.S == S && "Found a mismatched slice!"
) ? void (0) : __assert_fail ("Offsets.S == S && \"Found a mismatched slice!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3599, __extension__ __PRETTY_FUNCTION__))
;
3600 assert(!Offsets.Splits.empty() &&(static_cast <bool> (!Offsets.Splits.empty() &&
"Cannot have an empty set of splits on the second partition!"
) ? void (0) : __assert_fail ("!Offsets.Splits.empty() && \"Cannot have an empty set of splits on the second partition!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3601, __extension__ __PRETTY_FUNCTION__))
3601 "Cannot have an empty set of splits on the second partition!")(static_cast <bool> (!Offsets.Splits.empty() &&
"Cannot have an empty set of splits on the second partition!"
) ? void (0) : __assert_fail ("!Offsets.Splits.empty() && \"Cannot have an empty set of splits on the second partition!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3601, __extension__ __PRETTY_FUNCTION__))
;
3602 assert(Offsets.Splits.back() ==(static_cast <bool> (Offsets.Splits.back() == P.beginOffset
() - Offsets.S->beginOffset() && "Previous split does not end where this one begins!"
) ? void (0) : __assert_fail ("Offsets.Splits.back() == P.beginOffset() - Offsets.S->beginOffset() && \"Previous split does not end where this one begins!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3604, __extension__ __PRETTY_FUNCTION__))
3603 P.beginOffset() - Offsets.S->beginOffset() &&(static_cast <bool> (Offsets.Splits.back() == P.beginOffset
() - Offsets.S->beginOffset() && "Previous split does not end where this one begins!"
) ? void (0) : __assert_fail ("Offsets.Splits.back() == P.beginOffset() - Offsets.S->beginOffset() && \"Previous split does not end where this one begins!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3604, __extension__ __PRETTY_FUNCTION__))
3604 "Previous split does not end where this one begins!")(static_cast <bool> (Offsets.Splits.back() == P.beginOffset
() - Offsets.S->beginOffset() && "Previous split does not end where this one begins!"
) ? void (0) : __assert_fail ("Offsets.Splits.back() == P.beginOffset() - Offsets.S->beginOffset() && \"Previous split does not end where this one begins!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3604, __extension__ __PRETTY_FUNCTION__))
;
3605
3606 // Record each split. The last partition's end isn't needed as the size
3607 // of the slice dictates that.
3608 if (S->endOffset() > P.endOffset())
3609 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
3610 }
3611 }
3612
3613 // We may have split loads where some of their stores are split stores. For
3614 // such loads and stores, we can only pre-split them if their splits exactly
3615 // match relative to their starting offset. We have to verify this prior to
3616 // any rewriting.
3617 Stores.erase(
3618 llvm::remove_if(Stores,
3619 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3620 // Lookup the load we are storing in our map of split
3621 // offsets.
3622 auto *LI = cast<LoadInst>(SI->getValueOperand());
3623 // If it was completely unsplittable, then we're done,
3624 // and this store can't be pre-split.
3625 if (UnsplittableLoads.count(LI))
3626 return true;
3627
3628 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3629 if (LoadOffsetsI == SplitOffsetsMap.end())
3630 return false; // Unrelated loads are definitely safe.
3631 auto &LoadOffsets = LoadOffsetsI->second;
3632
3633 // Now lookup the store's offsets.
3634 auto &StoreOffsets = SplitOffsetsMap[SI];
3635
3636 // If the relative offsets of each split in the load and
3637 // store match exactly, then we can split them and we
3638 // don't need to remove them here.
3639 if (LoadOffsets.Splits == StoreOffsets.Splits)
3640 return false;
3641
3642 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Mismatched splits for load and store:\n"
<< " " << *LI << "\n" << " "
<< *SI << "\n"; } } while (false)
3643 dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Mismatched splits for load and store:\n"
<< " " << *LI << "\n" << " "
<< *SI << "\n"; } } while (false)
3644 << " Mismatched splits for load and store:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Mismatched splits for load and store:\n"
<< " " << *LI << "\n" << " "
<< *SI << "\n"; } } while (false)
3645 << " " << *LI << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Mismatched splits for load and store:\n"
<< " " << *LI << "\n" << " "
<< *SI << "\n"; } } while (false)
3646 << " " << *SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Mismatched splits for load and store:\n"
<< " " << *LI << "\n" << " "
<< *SI << "\n"; } } while (false)
;
3647
3648 // We've found a store and load that we need to split
3649 // with mismatched relative splits. Just give up on them
3650 // and remove both instructions from our list of
3651 // candidates.
3652 UnsplittableLoads.insert(LI);
3653 return true;
3654 }),
3655 Stores.end());
3656 // Now we have to go *back* through all the stores, because a later store may
3657 // have caused an earlier store's load to become unsplittable and if it is
3658 // unsplittable for the later store, then we can't rely on it being split in
3659 // the earlier store either.
3660 Stores.erase(llvm::remove_if(Stores,
3661 [&UnsplittableLoads](StoreInst *SI) {
3662 auto *LI =
3663 cast<LoadInst>(SI->getValueOperand());
3664 return UnsplittableLoads.count(LI);
3665 }),
3666 Stores.end());
3667 // Once we've established all the loads that can't be split for some reason,
3668 // filter any that made it into our list out.
3669 Loads.erase(llvm::remove_if(Loads,
3670 [&UnsplittableLoads](LoadInst *LI) {
3671 return UnsplittableLoads.count(LI);
3672 }),
3673 Loads.end());
3674
3675 // If no loads or stores are left, there is no pre-splitting to be done for
3676 // this alloca.
3677 if (Loads.empty() && Stores.empty())
3678 return false;
3679
3680 // From here on, we can't fail and will be building new accesses, so rig up
3681 // an IR builder.
3682 IRBuilderTy IRB(&AI);
3683
3684 // Collect the new slices which we will merge into the alloca slices.
3685 SmallVector<Slice, 4> NewSlices;
3686
3687 // Track any allocas we end up splitting loads and stores for so we iterate
3688 // on them.
3689 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3690
3691 // At this point, we have collected all of the loads and stores we can
3692 // pre-split, and the specific splits needed for them. We actually do the
3693 // splitting in a specific order in order to handle when one of the loads in
3694 // the value operand to one of the stores.
3695 //
3696 // First, we rewrite all of the split loads, and just accumulate each split
3697 // load in a parallel structure. We also build the slices for them and append
3698 // them to the alloca slices.
3699 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3700 std::vector<LoadInst *> SplitLoads;
3701 const DataLayout &DL = AI.getModule()->getDataLayout();
3702 for (LoadInst *LI : Loads) {
3703 SplitLoads.clear();
3704
3705 IntegerType *Ty = cast<IntegerType>(LI->getType());
3706 uint64_t LoadSize = Ty->getBitWidth() / 8;
3707 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!")(static_cast <bool> (LoadSize > 0 && "Cannot have a zero-sized integer load!"
) ? void (0) : __assert_fail ("LoadSize > 0 && \"Cannot have a zero-sized integer load!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3707, __extension__ __PRETTY_FUNCTION__))
;
3708
3709 auto &Offsets = SplitOffsetsMap[LI];
3710 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&(static_cast <bool> (LoadSize == Offsets.S->endOffset
() - Offsets.S->beginOffset() && "Slice size should always match load size exactly!"
) ? void (0) : __assert_fail ("LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && \"Slice size should always match load size exactly!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3711, __extension__ __PRETTY_FUNCTION__))
3711 "Slice size should always match load size exactly!")(static_cast <bool> (LoadSize == Offsets.S->endOffset
() - Offsets.S->beginOffset() && "Slice size should always match load size exactly!"
) ? void (0) : __assert_fail ("LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && \"Slice size should always match load size exactly!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3711, __extension__ __PRETTY_FUNCTION__))
;
3712 uint64_t BaseOffset = Offsets.S->beginOffset();
3713 assert(BaseOffset + LoadSize > BaseOffset &&(static_cast <bool> (BaseOffset + LoadSize > BaseOffset
&& "Cannot represent alloca access size using 64-bit integers!"
) ? void (0) : __assert_fail ("BaseOffset + LoadSize > BaseOffset && \"Cannot represent alloca access size using 64-bit integers!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3714, __extension__ __PRETTY_FUNCTION__))
3714 "Cannot represent alloca access size using 64-bit integers!")(static_cast <bool> (BaseOffset + LoadSize > BaseOffset
&& "Cannot represent alloca access size using 64-bit integers!"
) ? void (0) : __assert_fail ("BaseOffset + LoadSize > BaseOffset && \"Cannot represent alloca access size using 64-bit integers!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3714, __extension__ __PRETTY_FUNCTION__))
;
3715
3716 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3717 IRB.SetInsertPoint(LI);
3718
3719 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Splitting load: " << *LI
<< "\n"; } } while (false)
;
3720
3721 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3722 int Idx = 0, Size = Offsets.Splits.size();
3723 for (;;) {
3724 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3725 auto AS = LI->getPointerAddressSpace();
3726 auto *PartPtrTy = PartTy->getPointerTo(AS);
3727 LoadInst *PLoad = IRB.CreateAlignedLoad(
3728 getAdjustedPtr(IRB, DL, BasePtr,
3729 APInt(DL.getIndexSizeInBits(AS), PartOffset),
3730 PartPtrTy, BasePtr->getName() + "."),
3731 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3732 LI->getName());
3733 PLoad->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
3734
3735 // Append this load onto the list of split loads so we can find it later
3736 // to rewrite the stores.
3737 SplitLoads.push_back(PLoad);
3738
3739 // Now build a new slice for the alloca.
3740 NewSlices.push_back(
3741 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3742 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
3743 /*IsSplittable*/ false));
3744 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PLoad << "\n"; } }
while (false)
3745 << ", " << NewSlices.back().endOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PLoad << "\n"; } }
while (false)
3746 << "): " << *PLoad << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PLoad << "\n"; } }
while (false)
;
3747
3748 // See if we've handled all the splits.
3749 if (Idx >= Size)
3750 break;
3751
3752 // Setup the next partition.
3753 PartOffset = Offsets.Splits[Idx];
3754 ++Idx;
3755 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3756 }
3757
3758 // Now that we have the split loads, do the slow walk over all uses of the
3759 // load and rewrite them as split stores, or save the split loads to use
3760 // below if the store is going to be split there anyways.
3761 bool DeferredStores = false;
3762 for (User *LU : LI->users()) {
3763 StoreInst *SI = cast<StoreInst>(LU);
3764 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3765 DeferredStores = true;
3766 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Deferred splitting of store: "
<< *SI << "\n"; } } while (false)
3767 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Deferred splitting of store: "
<< *SI << "\n"; } } while (false)
;
3768 continue;
3769 }
3770
3771 Value *StoreBasePtr = SI->getPointerOperand();
3772 IRB.SetInsertPoint(SI);
3773
3774 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Splitting store of load: " <<
*SI << "\n"; } } while (false)
;
3775
3776 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3777 LoadInst *PLoad = SplitLoads[Idx];
3778 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
3779 auto *PartPtrTy =
3780 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
3781
3782 auto AS = SI->getPointerAddressSpace();
3783 StoreInst *PStore = IRB.CreateAlignedStore(
3784 PLoad,
3785 getAdjustedPtr(IRB, DL, StoreBasePtr,
3786 APInt(DL.getIndexSizeInBits(AS), PartOffset),
3787 PartPtrTy, StoreBasePtr->getName() + "."),
3788 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3789 PStore->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
3790 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " +" << PartOffset <<
":" << *PStore << "\n"; } } while (false)
;
3791 }
3792
3793 // We want to immediately iterate on any allocas impacted by splitting
3794 // this store, and we have to track any promotable alloca (indicated by
3795 // a direct store) as needing to be resplit because it is no longer
3796 // promotable.
3797 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3798 ResplitPromotableAllocas.insert(OtherAI);
3799 Worklist.insert(OtherAI);
3800 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3801 StoreBasePtr->stripInBoundsOffsets())) {
3802 Worklist.insert(OtherAI);
3803 }
3804
3805 // Mark the original store as dead.
3806 DeadInsts.insert(SI);
3807 }
3808
3809 // Save the split loads if there are deferred stores among the users.
3810 if (DeferredStores)
3811 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3812
3813 // Mark the original load as dead and kill the original slice.
3814 DeadInsts.insert(LI);
3815 Offsets.S->kill();
3816 }
3817
3818 // Second, we rewrite all of the split stores. At this point, we know that
3819 // all loads from this alloca have been split already. For stores of such
3820 // loads, we can simply look up the pre-existing split loads. For stores of
3821 // other loads, we split those loads first and then write split stores of
3822 // them.
3823 for (StoreInst *SI : Stores) {
3824 auto *LI = cast<LoadInst>(SI->getValueOperand());
3825 IntegerType *Ty = cast<IntegerType>(LI->getType());
3826 uint64_t StoreSize = Ty->getBitWidth() / 8;
3827 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!")(static_cast <bool> (StoreSize > 0 && "Cannot have a zero-sized integer store!"
) ? void (0) : __assert_fail ("StoreSize > 0 && \"Cannot have a zero-sized integer store!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3827, __extension__ __PRETTY_FUNCTION__))
;
3828
3829 auto &Offsets = SplitOffsetsMap[SI];
3830 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&(static_cast <bool> (StoreSize == Offsets.S->endOffset
() - Offsets.S->beginOffset() && "Slice size should always match load size exactly!"
) ? void (0) : __assert_fail ("StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && \"Slice size should always match load size exactly!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3831, __extension__ __PRETTY_FUNCTION__))
3831 "Slice size should always match load size exactly!")(static_cast <bool> (StoreSize == Offsets.S->endOffset
() - Offsets.S->beginOffset() && "Slice size should always match load size exactly!"
) ? void (0) : __assert_fail ("StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() && \"Slice size should always match load size exactly!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3831, __extension__ __PRETTY_FUNCTION__))
;
3832 uint64_t BaseOffset = Offsets.S->beginOffset();
3833 assert(BaseOffset + StoreSize > BaseOffset &&(static_cast <bool> (BaseOffset + StoreSize > BaseOffset
&& "Cannot represent alloca access size using 64-bit integers!"
) ? void (0) : __assert_fail ("BaseOffset + StoreSize > BaseOffset && \"Cannot represent alloca access size using 64-bit integers!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3834, __extension__ __PRETTY_FUNCTION__))
3834 "Cannot represent alloca access size using 64-bit integers!")(static_cast <bool> (BaseOffset + StoreSize > BaseOffset
&& "Cannot represent alloca access size using 64-bit integers!"
) ? void (0) : __assert_fail ("BaseOffset + StoreSize > BaseOffset && \"Cannot represent alloca access size using 64-bit integers!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3834, __extension__ __PRETTY_FUNCTION__))
;
3835
3836 Value *LoadBasePtr = LI->getPointerOperand();
3837 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3838
3839 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Splitting store: " << *SI
<< "\n"; } } while (false)
;
3840
3841 // Check whether we have an already split load.
3842 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3843 std::vector<LoadInst *> *SplitLoads = nullptr;
3844 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3845 SplitLoads = &SplitLoadsMapI->second;
3846 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&(static_cast <bool> (SplitLoads->size() == Offsets.Splits
.size() + 1 && "Too few split loads for the number of splits in the store!"
) ? void (0) : __assert_fail ("SplitLoads->size() == Offsets.Splits.size() + 1 && \"Too few split loads for the number of splits in the store!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3847, __extension__ __PRETTY_FUNCTION__))
3847 "Too few split loads for the number of splits in the store!")(static_cast <bool> (SplitLoads->size() == Offsets.Splits
.size() + 1 && "Too few split loads for the number of splits in the store!"
) ? void (0) : __assert_fail ("SplitLoads->size() == Offsets.Splits.size() + 1 && \"Too few split loads for the number of splits in the store!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3847, __extension__ __PRETTY_FUNCTION__))
;
3848 } else {
3849 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " of load: " << *LI
<< "\n"; } } while (false)
;
3850 }
3851
3852 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3853 int Idx = 0, Size = Offsets.Splits.size();
3854 for (;;) {
3855 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3856 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3857 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3858
3859 // Either lookup a split load or create one.
3860 LoadInst *PLoad;
3861 if (SplitLoads) {
3862 PLoad = (*SplitLoads)[Idx];
3863 } else {
3864 IRB.SetInsertPoint(LI);
3865 auto AS = LI->getPointerAddressSpace();
3866 PLoad = IRB.CreateAlignedLoad(
3867 getAdjustedPtr(IRB, DL, LoadBasePtr,
3868 APInt(DL.getIndexSizeInBits(AS), PartOffset),
3869 LoadPartPtrTy, LoadBasePtr->getName() + "."),
3870 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3871 LI->getName());
3872 }
3873
3874 // And store this partition.
3875 IRB.SetInsertPoint(SI);
3876 auto AS = SI->getPointerAddressSpace();
3877 StoreInst *PStore = IRB.CreateAlignedStore(
3878 PLoad,
3879 getAdjustedPtr(IRB, DL, StoreBasePtr,
3880 APInt(DL.getIndexSizeInBits(AS), PartOffset),
3881 StorePartPtrTy, StoreBasePtr->getName() + "."),
3882 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3883
3884 // Now build a new slice for the alloca.
3885 NewSlices.push_back(
3886 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3887 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
3888 /*IsSplittable*/ false));
3889 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PStore << "\n"; }
} while (false)
3890 << ", " << NewSlices.back().endOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PStore << "\n"; }
} while (false)
3891 << "): " << *PStore << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " new slice [" << NewSlices
.back().beginOffset() << ", " << NewSlices.back()
.endOffset() << "): " << *PStore << "\n"; }
} while (false)
;
3892 if (!SplitLoads) {
3893 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " of split load: " << *
PLoad << "\n"; } } while (false)
;
3894 }
3895
3896 // See if we've finished all the splits.
3897 if (Idx >= Size)
3898 break;
3899
3900 // Setup the next partition.
3901 PartOffset = Offsets.Splits[Idx];
3902 ++Idx;
3903 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3904 }
3905
3906 // We want to immediately iterate on any allocas impacted by splitting
3907 // this load, which is only relevant if it isn't a load of this alloca and
3908 // thus we didn't already split the loads above. We also have to keep track
3909 // of any promotable allocas we split loads on as they can no longer be
3910 // promoted.
3911 if (!SplitLoads) {
3912 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3913 assert(OtherAI != &AI && "We can't re-split our own alloca!")(static_cast <bool> (OtherAI != &AI && "We can't re-split our own alloca!"
) ? void (0) : __assert_fail ("OtherAI != &AI && \"We can't re-split our own alloca!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3913, __extension__ __PRETTY_FUNCTION__))
;
3914 ResplitPromotableAllocas.insert(OtherAI);
3915 Worklist.insert(OtherAI);
3916 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3917 LoadBasePtr->stripInBoundsOffsets())) {
3918 assert(OtherAI != &AI && "We can't re-split our own alloca!")(static_cast <bool> (OtherAI != &AI && "We can't re-split our own alloca!"
) ? void (0) : __assert_fail ("OtherAI != &AI && \"We can't re-split our own alloca!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3918, __extension__ __PRETTY_FUNCTION__))
;
3919 Worklist.insert(OtherAI);
3920 }
3921 }
3922
3923 // Mark the original store as dead now that we've split it up and kill its
3924 // slice. Note that we leave the original load in place unless this store
3925 // was its only use. It may in turn be split up if it is an alloca load
3926 // for some other alloca, but it may be a normal load. This may introduce
3927 // redundant loads, but where those can be merged the rest of the optimizer
3928 // should handle the merging, and this uncovers SSA splits which is more
3929 // important. In practice, the original loads will almost always be fully
3930 // split and removed eventually, and the splits will be merged by any
3931 // trivial CSE, including instcombine.
3932 if (LI->hasOneUse()) {
3933 assert(*LI->user_begin() == SI && "Single use isn't this store!")(static_cast <bool> (*LI->user_begin() == SI &&
"Single use isn't this store!") ? void (0) : __assert_fail (
"*LI->user_begin() == SI && \"Single use isn't this store!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3933, __extension__ __PRETTY_FUNCTION__))
;
3934 DeadInsts.insert(LI);
3935 }
3936 DeadInsts.insert(SI);
3937 Offsets.S->kill();
3938 }
3939
3940 // Remove the killed slices that have ben pre-split.
3941 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
3942 AS.end());
3943
3944 // Insert our new slices. This will sort and merge them into the sorted
3945 // sequence.
3946 AS.insert(NewSlices);
3947
3948 LLVM_DEBUG(dbgs() << " Pre-split slices:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Pre-split slices:\n"; } } while
(false)
;
3949#ifndef NDEBUG
3950 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
3951 LLVM_DEBUG(AS.print(dbgs(), I, " "))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { AS.print(dbgs(), I, " "); } } while (false)
;
3952#endif
3953
3954 // Finally, don't try to promote any allocas that new require re-splitting.
3955 // They have already been added to the worklist above.
3956 PromotableAllocas.erase(
3957 llvm::remove_if(
3958 PromotableAllocas,
3959 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
3960 PromotableAllocas.end());
3961
3962 return true;
3963}
3964
3965/// Rewrite an alloca partition's users.
3966///
3967/// This routine drives both of the rewriting goals of the SROA pass. It tries
3968/// to rewrite uses of an alloca partition to be conducive for SSA value
3969/// promotion. If the partition needs a new, more refined alloca, this will
3970/// build that new alloca, preserving as much type information as possible, and
3971/// rewrite the uses of the old alloca to point at the new one and have the
3972/// appropriate new offsets. It also evaluates how successful the rewrite was
3973/// at enabling promotion and if it was successful queues the alloca to be
3974/// promoted.
3975AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
3976 Partition &P) {
3977 // Try to compute a friendly type for this partition of the alloca. This
3978 // won't always succeed, in which case we fall back to a legal integer type
3979 // or an i8 array of an appropriate size.
3980 Type *SliceTy = nullptr;
3981 const DataLayout &DL = AI.getModule()->getDataLayout();
3982 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
3983 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
3984 SliceTy = CommonUseTy;
3985 if (!SliceTy)
3986 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
3987 P.beginOffset(), P.size()))
3988 SliceTy = TypePartitionTy;
3989 if ((!SliceTy || (SliceTy->isArrayTy() &&
3990 SliceTy->getArrayElementType()->isIntegerTy())) &&
3991 DL.isLegalInteger(P.size() * 8))
3992 SliceTy = Type::getIntNTy(*C, P.size() * 8);
3993 if (!SliceTy)
3994 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
3995 assert(DL.getTypeAllocSize(SliceTy) >= P.size())(static_cast <bool> (DL.getTypeAllocSize(SliceTy) >=
P.size()) ? void (0) : __assert_fail ("DL.getTypeAllocSize(SliceTy) >= P.size()"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 3995, __extension__ __PRETTY_FUNCTION__))
;
3996
3997 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
3998
3999 VectorType *VecTy =
4000 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
4001 if (VecTy)
4002 SliceTy = VecTy;
4003
4004 // Check for the case where we're going to rewrite to a new alloca of the
4005 // exact same type as the original, and with the same access offsets. In that
4006 // case, re-use the existing alloca, but still run through the rewriter to
4007 // perform phi and select speculation.
4008 // P.beginOffset() can be non-zero even with the same type in a case with
4009 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
4010 AllocaInst *NewAI;
4011 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
4012 NewAI = &AI;
4013 // FIXME: We should be able to bail at this point with "nothing changed".
4014 // FIXME: We might want to defer PHI speculation until after here.
4015 // FIXME: return nullptr;
4016 } else {
4017 unsigned Alignment = AI.getAlignment();
4018 if (!Alignment) {
4019 // The minimum alignment which users can rely on when the explicit
4020 // alignment is omitted or zero is that required by the ABI for this
4021 // type.
4022 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
4023 }
4024 Alignment = MinAlign(Alignment, P.beginOffset());
4025 // If we will get at least this much alignment from the type alone, leave
4026 // the alloca's alignment unconstrained.
4027 if (Alignment <= DL.getABITypeAlignment(SliceTy))
4028 Alignment = 0;
4029 NewAI = new AllocaInst(
4030 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
4031 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
4032 // Copy the old AI debug location over to the new one.
4033 NewAI->setDebugLoc(AI.getDebugLoc());
4034 ++NumNewAllocas;
4035 }
4036
4037 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Rewriting alloca partition " <<
"[" << P.beginOffset() << "," << P.endOffset
() << ") to: " << *NewAI << "\n"; } } while
(false)
4038 << "[" << P.beginOffset() << "," << P.endOffset()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Rewriting alloca partition " <<
"[" << P.beginOffset() << "," << P.endOffset
() << ") to: " << *NewAI << "\n"; } } while
(false)
4039 << ") to: " << *NewAI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Rewriting alloca partition " <<
"[" << P.beginOffset() << "," << P.endOffset
() << ") to: " << *NewAI << "\n"; } } while
(false)
;
4040
4041 // Track the high watermark on the worklist as it is only relevant for
4042 // promoted allocas. We will reset it to this point if the alloca is not in
4043 // fact scheduled for promotion.
4044 unsigned PPWOldSize = PostPromotionWorklist.size();
4045 unsigned NumUses = 0;
4046 SmallSetVector<PHINode *, 8> PHIUsers;
4047 SmallSetVector<SelectInst *, 8> SelectUsers;
4048
4049 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
4050 P.endOffset(), IsIntegerPromotable, VecTy,
4051 PHIUsers, SelectUsers);
4052 bool Promotable = true;
4053 for (Slice *S : P.splitSliceTails()) {
4054 Promotable &= Rewriter.visit(S);
4055 ++NumUses;
4056 }
4057 for (Slice &S : P) {
4058 Promotable &= Rewriter.visit(&S);
4059 ++NumUses;
4060 }
4061
4062 NumAllocaPartitionUses += NumUses;
4063 MaxUsesPerAllocaPartition.updateMax(NumUses);
4064
4065 // Now that we've processed all the slices in the new partition, check if any
4066 // PHIs or Selects would block promotion.
4067 for (PHINode *PHI : PHIUsers)
4068 if (!isSafePHIToSpeculate(*PHI)) {
4069 Promotable = false;
4070 PHIUsers.clear();
4071 SelectUsers.clear();
4072 break;
4073 }
4074
4075 for (SelectInst *Sel : SelectUsers)
4076 if (!isSafeSelectToSpeculate(*Sel)) {
4077 Promotable = false;
4078 PHIUsers.clear();
4079 SelectUsers.clear();
4080 break;
4081 }
4082
4083 if (Promotable) {
4084 if (PHIUsers.empty() && SelectUsers.empty()) {
4085 // Promote the alloca.
4086 PromotableAllocas.push_back(NewAI);
4087 } else {
4088 // If we have either PHIs or Selects to speculate, add them to those
4089 // worklists and re-queue the new alloca so that we promote in on the
4090 // next iteration.
4091 for (PHINode *PHIUser : PHIUsers)
4092 SpeculatablePHIs.insert(PHIUser);
4093 for (SelectInst *SelectUser : SelectUsers)
4094 SpeculatableSelects.insert(SelectUser);
4095 Worklist.insert(NewAI);
4096 }
4097 } else {
4098 // Drop any post-promotion work items if promotion didn't happen.
4099 while (PostPromotionWorklist.size() > PPWOldSize)
4100 PostPromotionWorklist.pop_back();
4101
4102 // We couldn't promote and we didn't create a new partition, nothing
4103 // happened.
4104 if (NewAI == &AI)
4105 return nullptr;
4106
4107 // If we can't promote the alloca, iterate on it to check for new
4108 // refinements exposed by splitting the current alloca. Don't iterate on an
4109 // alloca which didn't actually change and didn't get promoted.
4110 Worklist.insert(NewAI);
4111 }
4112
4113 return NewAI;
4114}
4115
4116/// Walks the slices of an alloca and form partitions based on them,
4117/// rewriting each of their uses.
4118bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4119 if (AS.begin() == AS.end())
4120 return false;
4121
4122 unsigned NumPartitions = 0;
4123 bool Changed = false;
4124 const DataLayout &DL = AI.getModule()->getDataLayout();
4125
4126 // First try to pre-split loads and stores.
4127 Changed |= presplitLoadsAndStores(AI, AS);
4128
4129 // Now that we have identified any pre-splitting opportunities,
4130 // mark loads and stores unsplittable except for the following case.
4131 // We leave a slice splittable if all other slices are disjoint or fully
4132 // included in the slice, such as whole-alloca loads and stores.
4133 // If we fail to split these during pre-splitting, we want to force them
4134 // to be rewritten into a partition.
4135 bool IsSorted = true;
4136
4137 uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType());
4138 const uint64_t MaxBitVectorSize = 1024;
4139 if (AllocaSize <= MaxBitVectorSize) {
4140 // If a byte boundary is included in any load or store, a slice starting or
4141 // ending at the boundary is not splittable.
4142 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4143 for (Slice &S : AS)
4144 for (unsigned O = S.beginOffset() + 1;
4145 O < S.endOffset() && O < AllocaSize; O++)
4146 SplittableOffset.reset(O);
4147
4148 for (Slice &S : AS) {
4149 if (!S.isSplittable())
4150 continue;
4151
4152 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4153 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4154 continue;
4155
4156 if (isa<LoadInst>(S.getUse()->getUser()) ||
4157 isa<StoreInst>(S.getUse()->getUser())) {
4158 S.makeUnsplittable();
4159 IsSorted = false;
4160 }
4161 }
4162 }
4163 else {
4164 // We only allow whole-alloca splittable loads and stores
4165 // for a large alloca to avoid creating too large BitVector.
4166 for (Slice &S : AS) {
4167 if (!S.isSplittable())
4168 continue;
4169
4170 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4171 continue;
4172
4173 if (isa<LoadInst>(S.getUse()->getUser()) ||
4174 isa<StoreInst>(S.getUse()->getUser())) {
4175 S.makeUnsplittable();
4176 IsSorted = false;
4177 }
4178 }
4179 }
4180
4181 if (!IsSorted)
4182 llvm::sort(AS.begin(), AS.end());
4183
4184 /// Describes the allocas introduced by rewritePartition in order to migrate
4185 /// the debug info.
4186 struct Fragment {
4187 AllocaInst *Alloca;
4188 uint64_t Offset;
4189 uint64_t Size;
4190 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
4191 : Alloca(AI), Offset(O), Size(S) {}
4192 };
4193 SmallVector<Fragment, 4> Fragments;
4194
4195 // Rewrite each partition.
4196 for (auto &P : AS.partitions()) {
4197 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4198 Changed = true;
4199 if (NewAI != &AI) {
4200 uint64_t SizeOfByte = 8;
4201 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
4202 // Don't include any padding.
4203 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4204 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
4205 }
4206 }
4207 ++NumPartitions;
4208 }
4209
4210 NumAllocaPartitions += NumPartitions;
4211 MaxPartitionsPerAlloca.updateMax(NumPartitions);
4212
4213 // Migrate debug information from the old alloca to the new alloca(s)
4214 // and the individual partitions.
4215 TinyPtrVector<DbgInfoIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
4216 if (!DbgDeclares.empty()) {
4217 auto *Var = DbgDeclares.front()->getVariable();
4218 auto *Expr = DbgDeclares.front()->getExpression();
4219 auto VarSize = Var->getSizeInBits();
4220 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
4221 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
4222 for (auto Fragment : Fragments) {
4223 // Create a fragment expression describing the new partition or reuse AI's
4224 // expression if there is only one partition.
4225 auto *FragmentExpr = Expr;
4226 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
4227 // If this alloca is already a scalar replacement of a larger aggregate,
4228 // Fragment.Offset describes the offset inside the scalar.
4229 auto ExprFragment = Expr->getFragmentInfo();
4230 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
4231 uint64_t Start = Offset + Fragment.Offset;
4232 uint64_t Size = Fragment.Size;
4233 if (ExprFragment) {
4234 uint64_t AbsEnd =
4235 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
4236 if (Start >= AbsEnd)
4237 // No need to describe a SROAed padding.
4238 continue;
4239 Size = std::min(Size, AbsEnd - Start);
4240 }
4241 // The new, smaller fragment is stenciled out from the old fragment.
4242 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4243 assert(Start >= OrigFragment->OffsetInBits &&(static_cast <bool> (Start >= OrigFragment->OffsetInBits
&& "new fragment is outside of original fragment") ?
void (0) : __assert_fail ("Start >= OrigFragment->OffsetInBits && \"new fragment is outside of original fragment\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 4244, __extension__ __PRETTY_FUNCTION__))
4244 "new fragment is outside of original fragment")(static_cast <bool> (Start >= OrigFragment->OffsetInBits
&& "new fragment is outside of original fragment") ?
void (0) : __assert_fail ("Start >= OrigFragment->OffsetInBits && \"new fragment is outside of original fragment\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Transforms/Scalar/SROA.cpp"
, 4244, __extension__ __PRETTY_FUNCTION__))
;
4245 Start -= OrigFragment->OffsetInBits;
4246 }
4247
4248 // The alloca may be larger than the variable.
4249 if (VarSize) {
4250 if (Size > *VarSize)
4251 Size = *VarSize;
4252 if (Size == 0 || Start + Size > *VarSize)
4253 continue;
4254 }
4255
4256 // Avoid creating a fragment expression that covers the entire variable.
4257 if (!VarSize || *VarSize != Size) {
4258 if (auto E =
4259 DIExpression::createFragmentExpression(Expr, Start, Size))
4260 FragmentExpr = *E;
4261 else
4262 continue;
4263 }
4264 }
4265
4266 // Remove any existing intrinsics describing the same alloca.
4267 for (DbgInfoIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
4268 OldDII->eraseFromParent();
4269
4270 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
4271 DbgDeclares.front()->getDebugLoc(), &AI);
4272 }
4273 }
4274 return Changed;
4275}
4276
4277/// Clobber a use with undef, deleting the used value if it becomes dead.
4278void SROA::clobberUse(Use &U) {
4279 Value *OldV = U;
4280 // Replace the use with an undef value.
4281 U = UndefValue::get(OldV->getType());
4282
4283 // Check for this making an instruction dead. We have to garbage collect
4284 // all the dead instructions to ensure the uses of any alloca end up being
4285 // minimal.
4286 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4287 if (isInstructionTriviallyDead(OldI)) {
4288 DeadInsts.insert(OldI);
4289 }
4290}
4291
4292/// Analyze an alloca for SROA.
4293///
4294/// This analyzes the alloca to ensure we can reason about it, builds
4295/// the slices of the alloca, and then hands it off to be split and
4296/// rewritten as needed.
4297bool SROA::runOnAlloca(AllocaInst &AI) {
4298 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "SROA alloca: " << AI <<
"\n"; } } while (false)
;
4299 ++NumAllocasAnalyzed;
4300
4301 // Special case dead allocas, as they're trivial.
4302 if (AI.use_empty()) {
4303 AI.eraseFromParent();
4304 return true;
4305 }
4306 const DataLayout &DL = AI.getModule()->getDataLayout();
4307
4308 // Skip alloca forms that this analysis can't handle.
4309 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
4310 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
4311 return false;
4312
4313 bool Changed = false;
4314
4315 // First, split any FCA loads and stores touching this alloca to promote
4316 // better splitting and promotion opportunities.
4317 AggLoadStoreRewriter AggRewriter;
4318 Changed |= AggRewriter.rewrite(AI);
4319
4320 // Build the slices using a recursive instruction-visiting builder.
4321 AllocaSlices AS(DL, AI);
4322 LLVM_DEBUG(AS.print(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { AS.print(dbgs()); } } while (false)
;
4323 if (AS.isEscaped())
4324 return Changed;
4325
4326 // Delete all the dead users of this alloca before splitting and rewriting it.
4327 for (Instruction *DeadUser : AS.getDeadUsers()) {
4328 // Free up everything used by this instruction.
4329 for (Use &DeadOp : DeadUser->operands())
4330 clobberUse(DeadOp);
4331
4332 // Now replace the uses of this instruction.
4333 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4334
4335 // And mark it for deletion.
4336 DeadInsts.insert(DeadUser);
4337 Changed = true;
4338 }
4339 for (Use *DeadOp : AS.getDeadOperands()) {
4340 clobberUse(*DeadOp);
4341 Changed = true;
4342 }
4343
4344 // No slices to split. Leave the dead alloca for a later pass to clean up.
4345 if (AS.begin() == AS.end())
4346 return Changed;
4347
4348 Changed |= splitAlloca(AI, AS);
4349
4350 LLVM_DEBUG(dbgs() << " Speculating PHIs\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Speculating PHIs\n"; } } while
(false)
;
4351 while (!SpeculatablePHIs.empty())
4352 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4353
4354 LLVM_DEBUG(dbgs() << " Speculating Selects\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << " Speculating Selects\n"; } } while
(false)
;
4355 while (!SpeculatableSelects.empty())
4356 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4357
4358 return Changed;
4359}
4360
4361/// Delete the dead instructions accumulated in this run.
4362///
4363/// Recursively deletes the dead instructions we've accumulated. This is done
4364/// at the very end to maximize locality of the recursive delete and to
4365/// minimize the problems of invalidated instruction pointers as such pointers
4366/// are used heavily in the intermediate stages of the algorithm.
4367///
4368/// We also record the alloca instructions deleted here so that they aren't
4369/// subsequently handed to mem2reg to promote.
4370bool SROA::deleteDeadInstructions(
4371 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4372 bool Changed = false;
4373 while (!DeadInsts.empty()) {
4374 Instruction *I = DeadInsts.pop_back_val();
4375 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Deleting dead instruction: " <<
*I << "\n"; } } while (false)
;
4376
4377 // If the instruction is an alloca, find the possible dbg.declare connected
4378 // to it, and remove it too. We must do this before calling RAUW or we will
4379 // not be able to find it.
4380 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4381 DeletedAllocas.insert(AI);
4382 for (DbgInfoIntrinsic *OldDII : FindDbgAddrUses(AI))
4383 OldDII->eraseFromParent();
4384 }
4385
4386 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4387
4388 for (Use &Operand : I->operands())
4389 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4390 // Zero out the operand and see if it becomes trivially dead.
4391 Operand = nullptr;
4392 if (isInstructionTriviallyDead(U))
4393 DeadInsts.insert(U);
4394 }
4395
4396 ++NumDeleted;
4397 I->eraseFromParent();
4398 Changed = true;
4399 }
4400 return Changed;
4401}
4402
4403/// Promote the allocas, using the best available technique.
4404///
4405/// This attempts to promote whatever allocas have been identified as viable in
4406/// the PromotableAllocas list. If that list is empty, there is nothing to do.
4407/// This function returns whether any promotion occurred.
4408bool SROA::promoteAllocas(Function &F) {
4409 if (PromotableAllocas.empty())
4410 return false;
4411
4412 NumPromoted += PromotableAllocas.size();
4413
4414 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "Promoting allocas with mem2reg...\n"
; } } while (false)
;
4415 PromoteMemToReg(PromotableAllocas, *DT, AC);
4416 PromotableAllocas.clear();
4417 return true;
4418}
4419
4420PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4421 AssumptionCache &RunAC) {
4422 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("sroa")) { dbgs() << "SROA function: " << F.getName
() << "\n"; } } while (false)
;
4423 C = &F.getContext();
4424 DT = &RunDT;
4425 AC = &RunAC;
4426
4427 BasicBlock &EntryBB = F.getEntryBlock();
4428 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4429 I != E; ++I) {
4430 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4431 Worklist.insert(AI);
4432 }
4433
4434 bool Changed = false;
4435 // A set of deleted alloca instruction pointers which should be removed from
4436 // the list of promotable allocas.
4437 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4438
4439 do {
4440 while (!Worklist.empty()) {
4441 Changed |= runOnAlloca(*Worklist.pop_back_val());
4442 Changed |= deleteDeadInstructions(DeletedAllocas);
4443
4444 // Remove the deleted allocas from various lists so that we don't try to
4445 // continue processing them.
4446 if (!DeletedAllocas.empty()) {
4447 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4448 Worklist.remove_if(IsInSet);
4449 PostPromotionWorklist.remove_if(IsInSet);
4450 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
4451 PromotableAllocas.end());
4452 DeletedAllocas.clear();
4453 }
4454 }
4455
4456 Changed |= promoteAllocas(F);
4457
4458 Worklist = PostPromotionWorklist;
4459 PostPromotionWorklist.clear();
4460 } while (!Worklist.empty());
4461
4462 if (!Changed)
4463 return PreservedAnalyses::all();
4464
4465 PreservedAnalyses PA;
4466 PA.preserveSet<CFGAnalyses>();
4467 PA.preserve<GlobalsAA>();
4468 return PA;
4469}
4470
4471PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
4472 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4473 AM.getResult<AssumptionAnalysis>(F));
4474}
4475
4476/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4477///
4478/// This is in the llvm namespace purely to allow it to be a friend of the \c
4479/// SROA pass.
4480class llvm::sroa::SROALegacyPass : public FunctionPass {
4481 /// The SROA implementation.
4482 SROA Impl;
4483
4484public:
4485 static char ID;
4486
4487 SROALegacyPass() : FunctionPass(ID) {
4488 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4489 }
4490
4491 bool runOnFunction(Function &F) override {
4492 if (skipFunction(F))
4493 return false;
4494
4495 auto PA = Impl.runImpl(
4496 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4497 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4498 return !PA.areAllPreserved();
4499 }
4500
4501 void getAnalysisUsage(AnalysisUsage &AU) const override {
4502 AU.addRequired<AssumptionCacheTracker>();
4503 AU.addRequired<DominatorTreeWrapperPass>();
4504 AU.addPreserved<GlobalsAAWrapperPass>();
4505 AU.setPreservesCFG();
4506 }
4507
4508 StringRef getPassName() const override { return "SROA"; }
4509};
4510
4511char SROALegacyPass::ID = 0;
4512
4513FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4514
4515INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",static void *initializeSROALegacyPassPassOnce(PassRegistry &
Registry) {
4516 "Scalar Replacement Of Aggregates", false, false)static void *initializeSROALegacyPassPassOnce(PassRegistry &
Registry) {
4517INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
4518INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
4519INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",PassInfo *PI = new PassInfo( "Scalar Replacement Of Aggregates"
, "sroa", &SROALegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<SROALegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeSROALegacyPassPassFlag
; void llvm::initializeSROALegacyPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeSROALegacyPassPassFlag, initializeSROALegacyPassPassOnce
, std::ref(Registry)); }
4520 false, false)PassInfo *PI = new PassInfo( "Scalar Replacement Of Aggregates"
, "sroa", &SROALegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<SROALegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeSROALegacyPassPassFlag
; void llvm::initializeSROALegacyPassPass(PassRegistry &Registry
) { llvm::call_once(InitializeSROALegacyPassPassFlag, initializeSROALegacyPassPassOnce
, std::ref(Registry)); }