blob: a8b9ee566395a3b6cabc74ba05eaa2afef4795ad [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation implements the well known scalar replacement of
11/// aggregates transformation. It tries to identify promotable elements of an
12/// aggregate alloca, and promote them to registers. It will also try to
13/// convert uses of an element (or set of elements) of an alloca into a vector
14/// or bitfield-style integer scalar if appropriate.
15///
16/// It works to do this with minimal slicing of the alloca so that regions
17/// which are merely transferred in and out of external memory remain unchanged
18/// and are not decomposed to scalar code.
19///
20/// Because this also performs alloca promotion, it can be thought of as also
21/// serving the purpose of SSA formation. The algorithm iterates on the
22/// function until all opportunities for promotion have been realized.
23///
24//===----------------------------------------------------------------------===//
25
Chandler Carruth29a18a42015-09-12 09:09:14 +000026#include "llvm/Transforms/Scalar/SROA.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000027#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/PointerIntPair.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/STLExtras.h"
Davide Italiano81a26da2017-04-27 23:09:01 +000032#include "llvm/ADT/SetVector.h"
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +000033#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000034#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/Statistic.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000037#include "llvm/ADT/StringRef.h"
38#include "llvm/ADT/Twine.h"
39#include "llvm/ADT/iterator.h"
40#include "llvm/ADT/iterator_range.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000041#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000042#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000044#include "llvm/Analysis/PtrUseVisitor.h"
David Blaikie31b98d22018-06-04 21:23:21 +000045#include "llvm/Transforms/Utils/Local.h"
Nico Weber432a3882018-04-30 14:59:11 +000046#include "llvm/Config/llvm-config.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000047#include "llvm/IR/BasicBlock.h"
48#include "llvm/IR/Constant.h"
49#include "llvm/IR/ConstantFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000051#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/DataLayout.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000053#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000055#include "llvm/IR/Dominators.h"
56#include "llvm/IR/Function.h"
57#include "llvm/IR/GetElementPtrTypeIterator.h"
58#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000060#include "llvm/IR/InstVisitor.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000061#include "llvm/IR/InstrTypes.h"
62#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000063#include "llvm/IR/Instructions.h"
64#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000065#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000066#include "llvm/IR/LLVMContext.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000067#include "llvm/IR/Metadata.h"
68#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000069#include "llvm/IR/Operator.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000070#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"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000075#include "llvm/Pass.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000076#include "llvm/Support/Casting.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000077#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000078#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000079#include "llvm/Support/Debug.h"
80#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000081#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000082#include "llvm/Support/raw_ostream.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000083#include "llvm/Transforms/Scalar.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000084#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000085#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>
Chandler Carruth83cee772014-02-25 03:59:29 +000096
Hal Finkel29f51312016-03-28 11:13:03 +000097#ifndef NDEBUG
98// We only use this for a debug check.
Chandler Carruth83cee772014-02-25 03:59:29 +000099#include <random>
100#endif
101
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000102using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000103using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000104
Chandler Carruth964daaa2014-04-22 02:55:47 +0000105#define DEBUG_TYPE "sroa"
106
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000107STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000108STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +0000109STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
110STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
111STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000112STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
113STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000114STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000115STATISTIC(NumDeleted, "Number of instructions deleted");
116STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000117
Chandler Carruth83cee772014-02-25 03:59:29 +0000118/// 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
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000123/// Hidden option to experiment with completely strict handling of inbounds
124/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +0000125static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
126 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000127
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000128namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000129
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000130/// A custom IRBuilder inserter which prefixes all names, but only in
Mehdi Amini1e9c9252016-03-11 17:15:34 +0000131/// Assert builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000132class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000133 std::string Prefix;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000134
Zachary Turner41a9ee92017-10-11 23:54:34 +0000135 const Twine getNameWithPrefix(const Twine &Name) const {
136 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
137 }
138
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000139public:
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 {
Zachary Turner41a9ee92017-10-11 23:54:34 +0000145 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
146 InsertPt);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000147 }
148};
149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000150/// Provide a type for IRBuilder that drops names in release builds.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000151using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
Chandler Carruthd177f862013-03-20 07:30:36 +0000152
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000153/// A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000154///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000155/// 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 {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000160 /// The beginning offset of the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000161 uint64_t BeginOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000162
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000163 /// The ending offset, not included in the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000164 uint64_t EndOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000165
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000166 /// Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000167 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000168 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000169
170public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000171 Slice() = default;
172
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000173 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000174 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000175 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000176
177 uint64_t beginOffset() const { return BeginOffset; }
178 uint64_t endOffset() const { return EndOffset; }
179
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000180 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
181 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000182
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000183 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000184
Craig Topperf40110f2014-04-25 05:29:35 +0000185 bool isDead() const { return getUse() == nullptr; }
186 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000187
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000188 /// Support for ordering ranges.
Chandler Carruthf74654d2013-03-18 08:36:46 +0000189 ///
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.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000194 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000195 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;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000203 return false;
204 }
205
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000206 /// Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000207 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000208 uint64_t RHSOffset) {
209 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000210 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000211 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000212 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000213 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000214 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000215
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000216 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000217 return isSplittable() == RHS.isSplittable() &&
218 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000219 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000220 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000221};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000222
Chandler Carruthf0546402013-07-18 07:15:00 +0000223} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000224
225namespace llvm {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000226
Chandler Carruthf0546402013-07-18 07:15:00 +0000227template <typename T> struct isPodLike;
Chandler Carruth113dc642014-12-20 02:39:18 +0000228template <> struct isPodLike<Slice> { static const bool value = true; };
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000229
230} // end namespace llvm
Chandler Carruthf74654d2013-03-18 08:36:46 +0000231
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000232/// Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000233///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000234/// 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.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000239class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000240public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000241 /// Construct the slices of a particular alloca.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000242 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000243
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000244 /// Test whether a pointer to the allocation escapes our analysis.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000245 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000246 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000247 /// ignored.
248 bool isEscaped() const { return PointerEscapingInstr; }
249
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000250 /// Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000251 /// @{
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000252 using iterator = SmallVectorImpl<Slice>::iterator;
253 using range = iterator_range<iterator>;
254
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000255 iterator begin() { return Slices.begin(); }
256 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000257
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000258 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
259 using const_range = iterator_range<const_iterator>;
260
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000261 const_iterator begin() const { return Slices.begin(); }
262 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000263 /// @}
264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000265 /// Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000266 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000267
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000268 /// Insert new slices for this alloca.
Chandler Carruth0715cba2015-01-01 11:54:38 +0000269 ///
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();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000275 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000276 auto SliceI = Slices.begin() + OldSize;
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000277 llvm::sort(SliceI, Slices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000278 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
279 }
280
Chandler Carruth29a18a42015-09-12 09:09:14 +0000281 // Forward declare the iterator and range accessor for walking the
282 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000283 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000284 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000285
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000286 /// Access the dead users for this alloca.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000287 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000288
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000289 /// Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000290 ///
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.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000295 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000296
Aaron Ballman615eb472017-10-15 14:32:27 +0000297#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000298 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000299 void printSlice(raw_ostream &OS, const_iterator I,
300 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000301 void printUse(raw_ostream &OS, const_iterator I,
302 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000303 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000304 void dump(const_iterator I) const;
305 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000306#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000307
308private:
309 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000310 class SliceBuilder;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000311
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000312 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000313
Aaron Ballman615eb472017-10-15 14:32:27 +0000314#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000315 /// Handle to alloca instruction to simplify method interfaces.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000316 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000317#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000319 /// The instruction responsible for this alloca not having a known set
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000320 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000321 ///
322 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000323 /// 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.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000325 Instruction *PointerEscapingInstr;
326
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000327 /// The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000328 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000329 /// 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;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000334
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000335 /// Instructions which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000336 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000337 /// 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.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000341 SmallVector<Instruction *, 8> DeadUsers;
342
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000343 /// Operands which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000344 ///
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;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000352};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000353
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000354/// A partition of the slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000355///
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
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000368 using iterator = AllocaSlices::iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000369
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000370 /// The beginning and ending offsets of the alloca for this
Chandler Carruth29a18a42015-09-12 09:09:14 +0000371 /// partition.
372 uint64_t BeginOffset, EndOffset;
373
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000374 /// The start and end iterators of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000375 iterator SI, SJ;
376
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000377 /// A collection of split slice tails overlapping the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000378 SmallVector<Slice *, 4> SplitTails;
379
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000380 /// Raw constructor builds an empty partition starting and ending at
Chandler Carruth29a18a42015-09-12 09:09:14 +0000381 /// the given iterator.
382 Partition(iterator SI) : SI(SI), SJ(SI) {}
383
384public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000385 /// The start offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000386 ///
387 /// All of the contained slices start at or after this offset.
388 uint64_t beginOffset() const { return BeginOffset; }
389
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000390 /// The end offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000391 ///
392 /// All of the contained slices end at or before this offset.
393 uint64_t endOffset() const { return EndOffset; }
394
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000395 /// The size of the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000396 ///
397 /// Note that this can never be zero.
398 uint64_t size() const {
399 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
400 return EndOffset - BeginOffset;
401 }
402
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000403 /// Test whether this partition contains no slices, and merely spans
Chandler Carruth29a18a42015-09-12 09:09:14 +0000404 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000420 /// Get the sequence of split slice tails.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000421 ///
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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000428/// An iterator over partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000429///
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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000442 /// Most of the state for walking the partitions is held in a class
Chandler Carruth29a18a42015-09-12 09:09:14 +0000443 /// with a nice interface for examining them.
444 Partition P;
445
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000446 /// We need to keep the end of the slices to know when to stop.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000447 AllocaSlices::iterator SE;
448
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000449 /// We also need to keep track of the maximum split end offset seen.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000450 /// FIXME: Do we really?
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000451 uint64_t MaxSplitSliceEndOffset = 0;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000452
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000453 /// Sets the partition to be empty at given iterator, and sets the
Chandler Carruth29a18a42015-09-12 09:09:14 +0000454 /// end iterator.
455 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000456 : P(SI), SE(SE) {
Chandler Carruth29a18a42015-09-12 09:09:14 +0000457 // If not already at the end, advance our state to form the initial
458 // partition.
459 if (SI != SE)
460 advance();
461 }
462
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000463 /// Advance the iterator to the next partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000464 ///
465 /// Requires that the iterator not be at the end of the slices.
466 void advance() {
467 assert((P.SI != SE || !P.SplitTails.empty()) &&
468 "Cannot advance past the end of the slices!");
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.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000480 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,
487 [&](Slice *S) {
488 return S->endOffset() == MaxSplitSliceEndOffset;
489 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000490 "Could not find the current max split slice offset!");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000491 assert(llvm::all_of(P.SplitTails,
492 [&](Slice *S) {
493 return S->endOffset() <= MaxSplitSliceEndOffset;
494 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000495 "Max split slice end offset is not actually the max!");
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!");
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());
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!");
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());
585 P.EndOffset = P.SJ->beginOffset();
586 }
587 }
588
589public:
590 bool operator==(const partition_iterator &RHS) const {
591 assert(SE == RHS.SE &&
592 "End iterators don't match between compared partition iterators!");
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 &&
601 "Same set of slices formed two different sized partitions!");
602 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
603 "Same slice position with differently sized non-empty split "
604 "slice tails!");
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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000618/// A forward range over the partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000619///
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()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000628}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000629
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000630static 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()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000635 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000636 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000637 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000638
Craig Topperf40110f2014-04-25 05:29:35 +0000639 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000640}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000641
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000642/// A helper that folds a PHI node or a select.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000643static 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000651/// Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000652///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000653/// 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>;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000658
659 using Base = PtrUseVisitor<SliceBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000660
661 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000662 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000663
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000664 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000665 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
666
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000667 /// Set to de-duplicate dead instructions found in the use walk.
Chandler Carruthf0546402013-07-18 07:15:00 +0000668 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000669
670public:
Chandler Carruth83934062014-10-16 21:11:55 +0000671 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000672 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000673 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000674
675private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000676 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000677 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000678 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000679 }
680
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000681 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000682 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000683 // Completely skip uses which have a zero size or start either before or
684 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000685 if (Size == 0 || Offset.uge(AllocSize)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000686 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
687 << Offset
688 << " which has zero size or starts outside of the "
689 << AllocSize << " byte alloca:\n"
690 << " alloca: " << AS.AI << "\n"
691 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000692 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000693 }
694
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000695 uint64_t BeginOffset = Offset.getZExtValue();
696 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000697
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.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000700 // 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.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000704 assert(AllocSize >= BeginOffset); // Established above.
705 if (Size > AllocSize - BeginOffset) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000706 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
707 << Offset << " to remain within the " << AllocSize
708 << " byte alloca:\n"
709 << " alloca: " << AS.AI << "\n"
710 << " use: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000711 EndOffset = AllocSize;
712 }
713
Chandler Carruth83934062014-10-16 21:11:55 +0000714 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000715 }
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
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000728 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
Hal Finkel5c83a092016-03-28 11:23:21 +0000734 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000735 // size readily available.
736 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000737 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000738 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.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000746 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000747 unsigned ElementIdx = OpC->getZExtValue();
748 const StructLayout *SL = DL.getStructLayout(STy);
749 GEPOffset +=
750 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
751 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000752 // For array or vector indices, scale the index by the size of the
753 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000754 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
Chandler Carruthf0546402013-07-18 07:15:00 +0000767 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000768 }
769
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000770 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000771 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000772 // 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;
Chandler Carruth58d05562012-10-25 04:37:07 +0000776
777 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000778 }
779
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000780 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000781 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
782 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000783
784 if (!IsOffsetKnown)
785 return PI.setAborted(&LI);
786
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000787 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000788 uint64_t Size = DL.getTypeStoreSize(LI.getType());
789 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000790 }
791
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000792 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000793 Value *ValOp = SI.getValueOperand();
794 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000795 return PI.setEscapedAndAborted(&SI);
796 if (!IsOffsetKnown)
797 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000798
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000799 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000800 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
801
802 // If this memory access can be shown to *statically* extend outside the
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000803 // bounds of the allocation, it's behavior is undefined, so simply
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000804 // 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.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000809 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000810 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
811 << Offset << " which extends past the end of the "
812 << AllocSize << " byte alloca:\n"
813 << " alloca: " << AS.AI << "\n"
814 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000815 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000816 }
817
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000818 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
819 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000820 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000821 }
822
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000823 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000824 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000825 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000826 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000827 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000828 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000829 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000830
831 if (!IsOffsetKnown)
832 return PI.setAborted(&II);
833
Chandler Carruth113dc642014-12-20 02:39:18 +0000834 insertUse(II, Offset, Length ? Length->getLimitedValue()
835 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000836 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000837 }
838
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000839 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000840 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000841 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000842 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000843 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000844
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000845 // 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
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000850 if (!IsOffsetKnown)
851 return PI.setAborted(&II);
852
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000853 // 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.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000858 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000859 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
860 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000861 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000862 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000863 return markAsDead(II);
864 }
865
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000866 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000867 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000868
Chandler Carruthf0546402013-07-18 07:15:00 +0000869 // 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);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000875
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000876 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000877 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000878
Chandler Carruthf0546402013-07-18 07:15:00 +0000879 // 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;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000883 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000884 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000885 unsigned PrevIdx = MTPI->second;
886 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000887 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000888
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000889 // Check if the begin offsets match and this is a non-volatile transfer.
890 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000891 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
892 PrevP.kill();
893 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000894 }
895
896 // Otherwise we have an offset transfer within the same alloca. We can't
897 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000898 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000899 }
900
Chandler Carruthe3899f22013-07-15 17:36:21 +0000901 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000902 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000903
Chandler Carruthf0546402013-07-18 07:15:00 +0000904 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000905 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000906 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000907 }
908
909 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000910 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000911 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000912 void visitIntrinsicInst(IntrinsicInst &II) {
913 if (!IsOffsetKnown)
914 return PI.setAborted(&II);
915
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000916 if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
917 II.getIntrinsicID() == Intrinsic::lifetime_end) {
918 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000919 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
920 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000921 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000922 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000923 }
924
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000925 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000926 }
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
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000930 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000931 // 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));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000937 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000938 // If there are no loads or stores, the access is dead. We mark that as
939 // a size zero access.
940 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000941 do {
942 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000943 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000944
945 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000946 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000947 continue;
948 }
949 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
950 Value *Op = SI->getOperand(0);
951 if (Op == UsedI)
952 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000953 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000954 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
Chandler Carruthcdf47882014-03-09 03:16:01 +0000965 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000966 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000967 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000968 } while (!Uses.empty());
969
Craig Topperf40110f2014-04-25 05:29:35 +0000970 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000971 }
972
Jingyue Wuec33fa92014-08-22 22:45:57 +0000973 void visitPHINodeOrSelectInst(Instruction &I) {
974 assert(isa<PHINode>(I) || isa<SelectInst>(I));
975 if (I.use_empty())
976 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000977
Jingyue Wuec33fa92014-08-22 22:45:57 +0000978 // 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)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000987 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000988 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000989 // through the PHI/select as if we had RAUW'ed it.
990 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000991 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000992 // Otherwise the operand to the PHI/select is dead, and we can replace
993 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000994 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000995
996 return;
997 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000998
Chandler Carruthf0546402013-07-18 07:15:00 +0000999 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +00001000 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001001
Chandler Carruthf0546402013-07-18 07:15:00 +00001002 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +00001003 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))
Chandler Carruthf0546402013-07-18 07:15:00 +00001007 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.
Chandler Carruth6aedc102014-02-26 03:14:14 +00001016 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +00001017 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +00001018 return;
1019 }
1020
Jingyue Wuec33fa92014-08-22 22:45:57 +00001021 insertUse(I, Offset, Size);
1022 }
1023
Chandler Carruth113dc642014-12-20 02:39:18 +00001024 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001025
Chandler Carruth113dc642014-12-20 02:39:18 +00001026 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001027
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001028 /// Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +00001029 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001030};
1031
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001032AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001033 :
Aaron Ballman615eb472017-10-15 14:32:27 +00001034#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001035 AI(AI),
1036#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001037 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001038 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001039 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001040 if (PtrI.isEscaped() || PtrI.isAborted()) {
1041 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001042 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001043 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1044 : PtrI.getAbortingInst();
1045 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001046 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001047 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001048
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001049 Slices.erase(
1050 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1051 Slices.end());
Benjamin Kramer08e50702013-07-20 08:38:34 +00001052
Hal Finkel29f51312016-03-28 11:13:03 +00001053#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001054 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001055 std::mt19937 MT(static_cast<unsigned>(
1056 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001057 std::shuffle(Slices.begin(), Slices.end(), MT);
1058 }
1059#endif
1060
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001061 // Sort the uses. This arranges for the offsets to be in ascending order,
1062 // and the sizes to be in descending order.
Fangrui Song0cac7262018-09-27 02:13:45 +00001063 llvm::sort(Slices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001064}
1065
Aaron Ballman615eb472017-10-15 14:32:27 +00001066#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001067
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001068void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1069 StringRef Indent) const {
1070 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001071 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001072 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001073}
1074
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001075void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1076 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001077 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001078 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001079 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001080}
1081
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001082void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1083 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001084 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001085}
1086
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001087void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001088 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001089 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001090 << " A pointer to this alloca escaped by:\n"
1091 << " " << *PointerEscapingInstr << "\n";
1092 return;
1093 }
1094
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001095 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001096 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001097 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001098}
1099
Alp Tokerf929e092014-01-04 22:47:48 +00001100LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1101 print(dbgs(), I);
1102}
1103LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001104
Aaron Ballman615eb472017-10-15 14:32:27 +00001105#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001106
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001107/// 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,
Chandler Carruthf0546402013-07-18 07:15:00 +00001111 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001112 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001113 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001114 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001115
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.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001118 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001119 Use *U = I->getUse();
1120 if (isa<IntrinsicInst>(*U->getUser()))
1121 continue;
1122 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1123 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001124
Craig Topperf40110f2014-04-25 05:29:35 +00001125 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001126 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001127 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001128 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001129 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001130 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001131
Chandler Carruth4de31542014-01-21 23:16:05 +00001132 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001133 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001134 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001135 // entity causing the split. Also skip if the type is not a byte width
1136 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001137 if (UserITy->getBitWidth() % 8 != 0 ||
1138 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001139 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001140
Chandler Carruth4de31542014-01-21 23:16:05 +00001141 // 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;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001145 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001146
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;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001153 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001154
1155 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001156}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001157
Chandler Carruthf0546402013-07-18 07:15:00 +00001158/// 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
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001176static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001177 // 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;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001184 for (User *U : PN.users()) {
1185 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001186 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001187 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001188
Chandler Carruthf0546402013-07-18 07:15:00 +00001189 // 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;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001194
Chandler Carruthf0546402013-07-18 07:15:00 +00001195 // Ensure that there are no instructions between the PHI and the load that
1196 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001197 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001198 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001199 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001200
Chandler Carruthf0546402013-07-18 07:15:00 +00001201 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1202 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001203 }
1204
Chandler Carruthf0546402013-07-18 07:15:00 +00001205 if (!HaveLoad)
1206 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001207
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001208 const DataLayout &DL = PN.getModule()->getDataLayout();
1209
Chandler Carruthf0546402013-07-18 07:15:00 +00001210 // 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) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001214 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001215 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001216
Chandler Carruthf0546402013-07-18 07:15:00 +00001217 // 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;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001222
Chandler Carruthf0546402013-07-18 07:15:00 +00001223 // If the predecessor has a single successor, then the edge isn't
1224 // critical.
1225 if (TI->getNumSuccessors() == 1)
1226 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001227
Chandler Carruthf0546402013-07-18 07:15:00 +00001228 // 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.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001231 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001232 continue;
1233
1234 return false;
1235 }
1236
1237 return true;
1238}
1239
1240static void speculatePHINodeLoads(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001241 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001242
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
Hal Finkelcc39b672014-07-24 12:16:19 +00001248 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001249 // matter which one we get and if any differ.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001250 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001251
1252 AAMDNodes AATags;
1253 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001254 unsigned Align = SomeLoad->getAlignment();
1255
1256 // Rewrite all loads of the PN to use the new PHI.
1257 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001258 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001259 LI->replaceAllUsesWith(NewPN);
1260 LI->eraseFromParent();
1261 }
1262
1263 // Inject loads into all of the pred blocks.
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001264 DenseMap<BasicBlock*, Value*> InjectedLoads;
Chandler Carruthf0546402013-07-18 07:15:00 +00001265 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1266 BasicBlock *Pred = PN.getIncomingBlock(Idx);
Chandler Carruthf0546402013-07-18 07:15:00 +00001267 Value *InVal = PN.getIncomingValue(Idx);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001268
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
Chandler Carruthedb12a82018-10-15 10:04:59 +00001278 Instruction *TI = Pred->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001279 IRBuilderTy PredBuilder(TI);
1280
1281 LoadInst *Load = PredBuilder.CreateLoad(
1282 InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1283 ++NumLoadsSpeculated;
1284 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001285 if (AATags)
1286 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001287 NewPN->addIncoming(Load, Pred);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001288 InjectedLoads[Pred] = Load;
Chandler Carruthf0546402013-07-18 07:15:00 +00001289 }
1290
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001291 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001292 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.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001308static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001309 Value *TValue = SI.getTrueValue();
1310 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001311 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001312
Chandler Carruthcdf47882014-03-09 03:16:01 +00001313 for (User *U : SI.users()) {
1314 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001315 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001316 return false;
1317
Hiroshi Inoueb3008242017-06-24 15:43:33 +00001318 // Both operands to the select need to be dereferenceable, either
Chandler Carruthf0546402013-07-18 07:15:00 +00001319 // absolutely (e.g. allocas) or at this point because we can see other
1320 // accesses to it.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001321 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001322 return false;
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001323 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001324 return false;
1325 }
1326
1327 return true;
1328}
1329
1330static void speculateSelectInstLoads(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001331 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001332
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()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001338 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001339 assert(LI->isSimple() && "We only speculate simple loads");
1340
1341 IRB.SetInsertPoint(LI);
1342 LoadInst *TL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001343 IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
Chandler Carruthf0546402013-07-18 07:15:00 +00001344 LoadInst *FL =
Chandler Carruthe3899f22013-07-15 17:36:21 +00001345 IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001346 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001347
Hal Finkelcc39b672014-07-24 12:16:19 +00001348 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001349 TL->setAlignment(LI->getAlignment());
1350 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001351
1352 AAMDNodes Tags;
1353 LI->getAAMetadata(Tags);
1354 if (Tags) {
1355 TL->setAAMetadata(Tags);
1356 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001357 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001358
1359 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1360 LI->getName() + ".sroa.speculated");
1361
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001362 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001363 LI->replaceAllUsesWith(V);
1364 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001365 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001366 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001367}
1368
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001369/// Build a GEP out of a base pointer and indices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001370///
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.
Chandler Carruthd177f862013-03-20 07:30:36 +00001373static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001374 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001375 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
David Blaikieaa41cd52015-04-03 21:33:42 +00001383 return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
1384 NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001385}
1386
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001387/// Get a natural GEP off of the BasePtr walking through Ty toward
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001388/// 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.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001396static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001397 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001398 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001399 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001400 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001401 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001402
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001403 // Offset size to use for the indices.
1404 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001405
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001406 // 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;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001413
1414 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1415 ElementTy = ArrayTy->getElementType();
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001416 Indices.push_back(IRB.getIntN(OffsetSize, 0));
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001417 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1418 ElementTy = VectorTy->getElementType();
1419 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001420 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001421 if (STy->element_begin() == STy->element_end())
1422 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001423 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
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001433 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001434}
1435
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001436/// Recursively compute indices for a natural GEP.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001437///
1438/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1439/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001440static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001441 Value *Ptr, Type *Ty, APInt &Offset,
1442 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001443 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001444 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001445 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001446 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1447 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001448
1449 // We can't recurse through pointer types.
1450 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001451 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001452
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001453 // 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.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001456 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001457 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001458 if (ElementSizeInBits % 8 != 0) {
1459 // GEPs over non-multiple of 8 size vector elements are invalid.
1460 return nullptr;
1461 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001462 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001463 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001464 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001465 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001466 Offset -= NumSkippedElements * ElementSize;
1467 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001468 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001469 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001470 }
1471
1472 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1473 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001474 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001475 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001476 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001477 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001478
1479 Offset -= NumSkippedElements * ElementSize;
1480 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001481 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001482 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001483 }
1484
1485 StructType *STy = dyn_cast<StructType>(Ty);
1486 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001487 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001488
Chandler Carruth90a735d2013-07-19 07:21:28 +00001489 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001490 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001491 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001492 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001493 unsigned Index = SL->getElementContainingOffset(StructOffset);
1494 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1495 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001496 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001497 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001498
1499 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001500 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001501 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001502}
1503
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001504/// Get a natural GEP from a base pointer to a particular offset and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001505/// 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///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001513/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001514static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001515 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001516 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001517 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001518 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.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001522 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001523 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001524
1525 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001526 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001527 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001528 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001529 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001530 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001531 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001532
1533 Offset -= NumSkippedElements * ElementSize;
1534 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001535 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001536 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001537}
1538
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001539/// Compute an adjusted pointer from Ptr by Offset bytes where the
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001540/// 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
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001551/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001552/// a single GEP as possible, thus making each GEP more independent of the
1553/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001554static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001555 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001556 // 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
Chandler Carruth5986b542015-01-02 02:47:38 +00001564 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001565 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001566 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001567
1568 // Remember any i8 pointer we come across to re-use if we need to do a raw
1569 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001570 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001571 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);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001579 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001580 break;
1581 Offset += GEPOffset;
1582 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001583 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001584 break;
1585 }
1586
1587 // See if we can perform a natural GEP here.
1588 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001589 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001590 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001591 // 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!");
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)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001603 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001604 }
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)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001616 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001617 break;
1618 Ptr = GA->getAliasee();
1619 } else {
1620 break;
1621 }
1622 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001623 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001624
1625 if (!OffsetPtr) {
1626 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001627 Int8Ptr = IRB.CreateBitCast(
1628 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1629 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001630 Int8PtrOffset = Offset;
1631 }
1632
Chandler Carruth113dc642014-12-20 02:39:18 +00001633 OffsetPtr = Int8PtrOffset == 0
1634 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001635 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1636 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001637 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001638 }
1639 Ptr = OffsetPtr;
1640
1641 // On the off chance we were targeting i8*, guard the bitcast here.
1642 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001643 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001644
1645 return Ptr;
1646}
1647
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001648/// Compute the adjusted alignment for a load or store from an offset.
Chandler Carruth0715cba2015-01-01 11:54:38 +00001649static 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!");
1661 }
1662
1663 if (!Alignment)
1664 Alignment = DL.getABITypeAlignment(Ty);
1665
1666 return MinAlign(Alignment, Offset);
1667}
1668
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001669/// Test whether we can convert a value from the old to the new type.
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001670///
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;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001678
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() !=
1684 cast<IntegerType>(NewTy)->getBitWidth() &&
1685 "We can't have the same bitwidth for different int types");
1686 return false;
1687 }
1688
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001689 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1690 return false;
1691 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1692 return false;
1693
Benjamin Kramer56262592013-09-22 11:24:58 +00001694 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001695 // of pointers and integers.
1696 OldTy = OldTy->getScalarType();
1697 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001698 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001699 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1700 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1701 cast<PointerType>(OldTy)->getPointerAddressSpace();
1702 }
Sanjoy Dasb70ddd82017-06-17 20:28:13 +00001703
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
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001714 return false;
1715 }
1716
1717 return true;
1718}
1719
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001720/// Generic routine to convert an SSA value to a value of a different
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001721/// 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.
Chandler Carruthd177f862013-03-20 07:30:36 +00001726static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001727 Type *NewTy) {
1728 Type *OldTy = V->getType();
1729 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1730
1731 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001732 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001733
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001734 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1735 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001736
Benjamin Kramer90901a32013-09-21 20:36:04 +00001737 // See if we need inttoptr for this type pair. A cast involving both scalars
1738 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001739 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001740 // 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.
Craig Topper95d23472017-07-09 07:04:00 +00001755 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001756 // 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);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001770}
1771
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001772/// Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001773///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001774/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001775/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001776static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1777 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001778 uint64_t ElementSize,
1779 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001780 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001781 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001782 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001783 uint64_t BeginIndex = BeginOffset / ElementSize;
1784 if (BeginIndex * ElementSize != BeginOffset ||
1785 BeginIndex >= Ty->getNumElements())
1786 return false;
1787 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001788 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001789 uint64_t EndIndex = EndOffset / ElementSize;
1790 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1791 return false;
1792
1793 assert(EndIndex > BeginIndex && "Empty vector!");
1794 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001795 Type *SliceTy = (NumElements == 1)
1796 ? Ty->getElementType()
1797 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001798
1799 Type *SplitIntTy =
1800 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1801
Chandler Carruthc659df92014-10-16 20:24:07 +00001802 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001803
1804 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1805 if (MI->isVolatile())
1806 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001807 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001808 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001809 } 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;
Chandler Carruthf0546402013-07-18 07:15:00 +00001813 } 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();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001820 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001821 assert(LTy->isIntegerTy());
1822 LTy = SplitIntTy;
1823 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001824 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001825 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();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001830 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001831 assert(STy->isIntegerTy());
1832 STy = SplitIntTy;
1833 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001834 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001835 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001836 } else {
1837 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001838 }
1839
1840 return true;
1841}
1842
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001843/// Test whether the given alloca partitioning and range of slices can be
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001844/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001845///
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.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001852static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001853 // 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 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001867 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001868 for (const Slice &S : P)
1869 if (S.beginOffset() == P.beginOffset() &&
1870 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001871 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 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001876
Chandler Carruth2dc96822014-10-18 00:44:02 +00001877 // If we didn't find a vector type, nothing to do here.
1878 if (CandidateTys.empty())
1879 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001880
Chandler Carruth2dc96822014-10-18 00:44:02 +00001881 // 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) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001886 CandidateTys.erase(
1887 llvm::remove_if(CandidateTys,
1888 [](VectorType *VTy) {
1889 return !VTy->getElementType()->isIntegerTy();
1890 }),
1891 CandidateTys.end());
Chandler Carruth2dc96822014-10-18 00:44:02 +00001892
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) {
David L. Jones41cecba2017-01-13 21:02:41 +00001900 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001901 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1902 "Cannot have vector types of different sizes!");
1903 assert(RHSTy->getElementType()->isIntegerTy() &&
1904 "All non-integer types eliminated!");
1905 assert(LHSTy->getElementType()->isIntegerTy() &&
1906 "All non-integer types eliminated!");
1907 return RHSTy->getNumElements() < LHSTy->getNumElements();
1908 };
Fangrui Song0cac7262018-09-27 02:13:45 +00001909 llvm::sort(CandidateTys, RankVectorTypes);
Chandler Carruth2dc96822014-10-18 00:44:02 +00001910 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 &&
1919 "Unaccounted for element type!");
1920 assert(VTy == CandidateTys[0] &&
1921 "Different vector types with the same element type!");
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 &&
1936 "vector size not a multiple of element size?");
1937 ElementSize /= 8;
1938
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001939 for (const Slice &S : P)
1940 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001941 return false;
1942
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001943 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001944 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001945 return false;
1946
1947 return true;
1948 };
1949 for (VectorType *VTy : CandidateTys)
1950 if (CheckVectorTypeForPromotion(VTy))
1951 return VTy;
1952
1953 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001954}
1955
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001956/// Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001957///
1958/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001959/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001960static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001961 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001962 Type *AllocaTy,
1963 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001964 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001965 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1966
Chandler Carruthc659df92014-10-16 20:24:07 +00001967 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1968 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001969
1970 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001971 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00001972 if (RelEnd > Size)
1973 return false;
1974
Chandler Carruthc659df92014-10-16 20:24:07 +00001975 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001976
1977 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1978 if (LI->isVolatile())
1979 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001980 // We can't handle loads that extend past the allocated memory.
1981 if (DL.getTypeStoreSize(LI->getType()) > Size)
1982 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00001983 // So far, AllocaSliceRewriter does not support widening split slice tails
1984 // in rewriteIntegerLoad.
1985 if (S.beginOffset() < AllocBeginOffset)
1986 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001987 // 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)
Chandler Carruthf0546402013-07-18 07:15:00 +00001991 WholeAllocaOp = true;
1992 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001993 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001994 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001995 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001996 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001997 // Non-integer loads need to be convertible from the alloca type so that
1998 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001999 return false;
2000 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002001 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2002 Type *ValueTy = SI->getValueOperand()->getType();
2003 if (SI->isVolatile())
2004 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002005 // We can't handle stores that extend past the allocated memory.
2006 if (DL.getTypeStoreSize(ValueTy) > Size)
2007 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00002008 // So far, AllocaSliceRewriter does not support widening split slice tails
2009 // in rewriteIntegerStore.
2010 if (S.beginOffset() < AllocBeginOffset)
2011 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002012 // 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)
Chandler Carruthf0546402013-07-18 07:15:00 +00002016 WholeAllocaOp = true;
2017 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002018 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002019 return false;
2020 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002021 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002022 // 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;
Chandler Carruthc659df92014-10-16 20:24:07 +00002029 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002030 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;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002037 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002038
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002039 return true;
2040}
2041
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002042/// Test whether the given alloca partition's integer operations can be
Chandler Carruth435c4e02012-10-15 08:40:30 +00002043/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002044///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002045/// 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.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002048static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002049 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002050 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002051 // Don't create integer types larger than the maximum bitwidth.
2052 if (SizeInBits > IntegerType::MAX_INT_BITS)
2053 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002054
2055 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002056 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002057 return false;
2058
Chandler Carruth58d05562012-10-25 04:37:07 +00002059 // 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);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002063 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2064 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002065 return false;
2066
Chandler Carruthf0546402013-07-18 07:15:00 +00002067 // 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
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002070 // later). However, if there are only splittable uses, go ahead and assume
2071 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002072 // FIXME: We shouldn't consider split slices that happen to start in the
2073 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002074 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002075 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002076
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002077 for (const Slice &S : P)
2078 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2079 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002080 return false;
2081
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002082 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002083 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2084 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002085 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002086
Chandler Carruth92924fd2012-09-24 00:34:20 +00002087 return WholeAllocaOp;
2088}
2089
Chandler Carruthd177f862013-03-20 07:30:36 +00002090static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002091 IntegerType *Ty, uint64_t Offset,
2092 const Twine &Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002093 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002094 IntegerType *IntTy = cast<IntegerType>(V->getType());
2095 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2096 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002097 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002098 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002099 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002100 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002101 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002102 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002103 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002104 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2105 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002106 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002107 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002108 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002109 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002110 return V;
2111}
2112
Chandler Carruthd177f862013-03-20 07:30:36 +00002113static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002114 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() &&
2118 "Cannot insert a larger integer!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002119 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002120 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002121 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002122 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002123 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002124 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2125 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002126 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002127 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002128 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002129 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002130 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002131 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002132 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002133
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");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002137 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002138 V = IRB.CreateOr(Old, V, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002139 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002140 }
2141 return V;
2142}
2143
Chandler Carruth113dc642014-12-20 02:39:18 +00002144static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2145 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002146 VectorType *VecTy = cast<VectorType>(V->getType());
2147 unsigned NumElements = EndIndex - BeginIndex;
2148 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
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");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002156 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002157 return V;
2158 }
2159
Chandler Carruth113dc642014-12-20 02:39:18 +00002160 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002161 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()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002165 ConstantVector::get(Mask), Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002166 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002167 return V;
2168}
2169
Chandler Carruthd177f862013-03-20 07:30:36 +00002170static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002171 unsigned BeginIndex, const Twine &Name) {
2172 VectorType *VecTy = cast<VectorType>(Old->getType());
2173 assert(VecTy && "Can only insert a vector into a vector");
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");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002180 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002181 return V;
2182 }
2183
2184 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2185 "Too many elements!");
2186 if (Ty->getNumElements() == VecTy->getNumElements()) {
2187 assert(V->getType() == VecTy && "Vector type mismatch");
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.
Chandler Carruth113dc642014-12-20 02:39:18 +00002196 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002197 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()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002204 ConstantVector::get(Mask), Name + ".expand");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002205 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002206
2207 Mask.clear();
2208 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002209 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2210
2211 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2212
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002213 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002214 return V;
2215}
2216
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002217/// Visitor to rewrite instructions using p particular slice of an alloca
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002218/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002219///
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.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002223class llvm::sroa::AllocaSliceRewriter
2224 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002225 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002226 friend class InstVisitor<AllocaSliceRewriter, bool>;
2227
2228 using Base = InstVisitor<AllocaSliceRewriter, bool>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002229
Chandler Carruth90a735d2013-07-19 07:21:28 +00002230 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002231 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002232 SROA &Pass;
2233 AllocaInst &OldAI, &NewAI;
2234 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002235 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002236
Chandler Carruth2dc96822014-10-18 00:44:02 +00002237 // 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
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002243 // If we are rewriting an alloca partition which can be written as pure
2244 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002245 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002246 // - 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
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002256 // The original offset of the slice currently being rewritten relative to
2257 // the original alloca.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002258 uint64_t BeginOffset = 0;
2259 uint64_t EndOffset = 0;
2260
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002261 // 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;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002266 bool IsSplittable = false;
2267 bool IsSplit = false;
2268 Use *OldUse = nullptr;
2269 Instruction *OldPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002270
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002271 // Track post-rewrite users which are PHI nodes and Selects.
Davide Italiano81a26da2017-04-27 23:09:01 +00002272 SmallSetVector<PHINode *, 8> &PHIUsers;
2273 SmallSetVector<SelectInst *, 8> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002274
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002275 // 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;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002278
2279public:
Chandler Carruth83934062014-10-16 21:11:55 +00002280 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002281 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002282 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002283 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2284 VectorType *PromotableVecTy,
Davide Italiano81a26da2017-04-27 23:09:01 +00002285 SmallSetVector<PHINode *, 8> &PHIUsers,
2286 SmallSetVector<SelectInst *, 8> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002287 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002288 NewAllocaBeginOffset(NewAllocaBeginOffset),
2289 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002290 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002291 IntTy(IsIntegerPromotable
2292 ? Type::getIntNTy(
2293 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002294 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002295 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002296 VecTy(PromotableVecTy),
2297 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2298 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002299 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002300 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002301 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002302 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002303 "Only multiple-of-8 sized vector elements are viable");
2304 ++NumVectorized;
2305 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002306 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002307 }
2308
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002309 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002310 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002311 BeginOffset = I->beginOffset();
2312 EndOffset = I->endOffset();
2313 IsSplittable = I->isSplittable();
2314 IsSplit =
2315 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002316 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2317 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2318 LLVM_DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002319
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002320 // Compute the intersecting offset range.
2321 assert(BeginOffset < NewAllocaEndOffset);
2322 assert(EndOffset > NewAllocaBeginOffset);
2323 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2324 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2325
2326 SliceSize = NewEndOffset - NewBeginOffset;
2327
Chandler Carruthf0546402013-07-18 07:15:00 +00002328 OldUse = I->getUse();
2329 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002330
Chandler Carruthf0546402013-07-18 07:15:00 +00002331 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)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002338 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002339 return CanSROA;
2340 }
2341
2342private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002343 // Make sure the other visit overloads are visible.
2344 using Base::visit;
2345
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002346 // Every instruction which can end up as a user must have a rewrite rule.
2347 bool visitInstruction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002348 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002349 llvm_unreachable("No rewrite rule for this instruction!");
2350 }
2351
Chandler Carruth47954c82014-02-26 05:12:43 +00002352 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);
2356 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2357
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002358#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
Chandler Carruth47954c82014-02-26 05:12:43 +00002378
2379 return getAdjustedPtr(IRB, DL, &NewAI,
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002380 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002381 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002382#ifndef NDEBUG
2383 Twine(OldName) + "."
2384#else
2385 Twine()
2386#endif
2387 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002388 }
2389
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002390 /// Compute suitable alignment to access this slice of the *new*
Chandler Carruth113dc642014-12-20 02:39:18 +00002391 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002392 ///
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.
Craig Topperf40110f2014-04-25 05:29:35 +00002395 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002396 unsigned NewAIAlign = NewAI.getAlignment();
2397 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002398 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002399 unsigned Align =
2400 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002401 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002402 }
2403
Chandler Carruth845b73c2012-11-21 08:16:30 +00002404 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002405 assert(VecTy && "Can only call getIndex when rewriting a vector");
2406 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2407 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2408 uint32_t Index = RelOffset / ElementSize;
2409 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002410 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002411 }
2412
2413 void deleteIfTriviallyDead(Value *V) {
2414 Instruction *I = cast<Instruction>(V);
2415 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002416 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002417 }
2418
Chandler Carruthea27cf02014-02-26 04:25:04 +00002419 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002420 unsigned BeginIndex = getIndex(NewBeginOffset);
2421 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002422 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002423
Chandler Carruth113dc642014-12-20 02:39:18 +00002424 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002425 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002426 }
2427
Chandler Carruthea27cf02014-02-26 04:25:04 +00002428 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002429 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002430 assert(!LI.isVolatile());
Chandler Carruth113dc642014-12-20 02:39:18 +00002431 Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002432 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002433 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2434 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002435 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 &&
2445 "Can only handle an extract for an overly wide load");
2446 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2447 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002448 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002449 }
2450
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002451 bool visitLoadInst(LoadInst &LI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002452 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002453 Value *OldOp = LI.getOperand(0);
2454 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002455
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002456 AAMDNodes AATags;
2457 LI.getAAMetadata(AATags);
2458
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002459 unsigned AS = LI.getPointerAddressSpace();
2460
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002461 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002462 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002463 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002464 bool IsPtrAdjusted = false;
2465 Value *V;
2466 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002467 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002468 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002469 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002470 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002471 NewEndOffset == NewAllocaEndOffset &&
2472 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2473 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2474 TargetTy->isIntegerTy()))) {
David Majnemer62690b12015-07-14 06:19:58 +00002475 LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
2476 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002477 if (AATags)
2478 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002479 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002480 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Luqman Aden3f807c92017-03-22 19:16:39 +00002481
Chandler Carruth3f81d802017-06-27 08:32:03 +00002482 // 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.
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002487 // 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.
Chandler Carruth3f81d802017-06-27 08:32:03 +00002492 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2493 copyNonnullMetadata(LI, N, *NewLI);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002494
2495 // Try to preserve nonnull metadata
David Majnemer62690b12015-07-14 06:19:58 +00002496 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002497
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 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002509 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002510 Type *LTy = TargetTy->getPointerTo(AS);
David Majnemer62690b12015-07-14 06:19:58 +00002511 LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
2512 getSliceAlign(TargetTy),
2513 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002514 if (AATags)
2515 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002516 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002517 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002518
2519 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002520 IsPtrAdjusted = true;
2521 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002522 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002523
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002524 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002525 assert(!LI.isVolatile());
2526 assert(LI.getType()->isIntegerTy() &&
2527 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002528 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002529 "Split load isn't smaller than original load");
Chandler Carruth58d05562012-10-25 04:37:07 +00002530 assert(LI.getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002531 DL.getTypeStoreSizeInBits(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002532 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002533 // Move the insertion point just past the load so that we can refer to it.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00002534 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002535 // 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.
Chandler Carruth113dc642014-12-20 02:39:18 +00002539 Value *Placeholder =
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002540 new LoadInst(UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002541 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2542 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002543 LI.replaceAllUsesWith(V);
2544 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002545 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002546 } else {
2547 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002548 }
2549
Chandler Carruth18db7952012-11-20 01:12:50 +00002550 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002551 deleteIfTriviallyDead(OldOp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002552 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002553 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002554 }
2555
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002556 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2557 AAMDNodes AATags) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002558 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002559 unsigned BeginIndex = getIndex(NewBeginOffset);
2560 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002561 assert(EndIndex > BeginIndex && "Empty vector!");
2562 unsigned NumElements = EndIndex - BeginIndex;
2563 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002564 Type *SliceTy = (NumElements == 1)
2565 ? ElementTy
2566 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002567 if (V->getType() != SliceTy)
2568 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002569
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002570 // Mix in the existing elements.
Chandler Carruth113dc642014-12-20 02:39:18 +00002571 Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002572 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2573 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002574 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002575 if (AATags)
2576 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002577 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002578
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002579 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002580 return true;
2581 }
2582
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002583 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002584 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002585 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002586 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002587 Value *Old =
2588 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002589 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002590 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2591 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002592 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002593 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002594 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002595 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002596 Store->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002597 if (AATags)
2598 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002599 Pass.DeadInsts.insert(&SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002600 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002601 return true;
2602 }
2603
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002604 bool visitStoreInst(StoreInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002605 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002606 Value *OldOp = SI.getOperand(1);
2607 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002608
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002609 AAMDNodes AATags;
2610 SI.getAAMetadata(AATags);
2611
Chandler Carruth18db7952012-11-20 01:12:50 +00002612 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002613
Chandler Carruthac8317f2012-10-04 12:33:50 +00002614 // 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.
Chandler Carruth18db7952012-11-20 01:12:50 +00002616 if (V->getType()->isPointerTy())
2617 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002618 Pass.PostPromotionWorklist.insert(AI);
2619
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002620 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002621 assert(!SI.isVolatile());
2622 assert(V->getType()->isIntegerTy() &&
2623 "Only integer type loads and stores are split");
2624 assert(V->getType()->getIntegerBitWidth() ==
Chandler Carruth113dc642014-12-20 02:39:18 +00002625 DL.getTypeStoreSizeInBits(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002626 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002627 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002628 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2629 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002630 }
2631
Chandler Carruth18db7952012-11-20 01:12:50 +00002632 if (VecTy)
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002633 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002634 if (IntTy && V->getType()->isIntegerTy())
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002635 return rewriteIntegerStore(V, SI, AATags);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002636
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002637 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002638 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002639 if (NewBeginOffset == NewAllocaBeginOffset &&
2640 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002641 (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
Chandler Carruth90a735d2013-07-19 07:21:28 +00002656 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002657 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2658 SI.isVolatile());
2659 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002660 unsigned AS = SI.getPointerAddressSpace();
2661 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002662 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2663 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002664 }
Dorit Nuzmand1247a62016-09-22 07:56:23 +00002665 NewSI->copyMetadata(SI, LLVMContext::MD_mem_parallel_loop_access);
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002666 if (AATags)
2667 NewSI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002668 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002669 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002670 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002671 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002672
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002673 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002674 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002675 }
2676
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002677 /// Compute an integer value from splatting an i8 across the given
Chandler Carruth514f34f2012-12-17 04:07:30 +00002678 /// 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.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002682 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002683 ///
2684 /// \param V The i8 value to splat.
2685 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002686 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002687 assert(Size > 0 && "Expected a positive number of bytes.");
2688 IntegerType *VTy = cast<IntegerType>(V->getType());
2689 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2690 if (Size == 1)
2691 return V;
2692
Chandler Carruth113dc642014-12-20 02:39:18 +00002693 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");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002701 return V;
2702 }
2703
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002704 /// Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002705 Value *getVectorSplat(Value *V, unsigned NumElements) {
2706 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002707 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
Chandler Carruthccca5042012-12-17 04:07:37 +00002708 return V;
2709 }
2710
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002711 bool visitMemSetInst(MemSetInst &II) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002712 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002713 assert(II.getRawDest() == OldPtr);
2714
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002715 AAMDNodes AATags;
2716 II.getAAMetadata(AATags);
2717
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002718 // 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())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002721 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002722 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002723 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Daniel Neilson41e781d2018-03-13 14:25:33 +00002724 II.setDestAlignment(getSliceAlign());
Chandler Carruth208124f2012-09-26 10:59:22 +00002725
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002726 deleteIfTriviallyDead(OldPtr);
2727 return false;
2728 }
2729
2730 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002731 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002732
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.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002738 if (!VecTy && !IntTy &&
Chandler Carruth113dc642014-12-20 02:39:18 +00002739 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002740 SliceSize != DL.getTypeStoreSize(AllocaTy) ||
Chandler Carruth9d966a22012-10-15 10:24:40 +00002741 !AllocaTy->isSingleValueType() ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002742 !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
Chandler Carruth113dc642014-12-20 02:39:18 +00002743 DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002744 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002745 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2746 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002747 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2748 getSliceAlign(), II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002749 if (AATags)
2750 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002751 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002752 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
Chandler Carruthccca5042012-12-17 04:07:37 +00002758 // splatting the byte to a sufficiently wide integer, splatting it across
2759 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002760 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002761
Chandler Carruthccca5042012-12-17 04:07:37 +00002762 if (VecTy) {
2763 // If this is a memset of a vectorized alloca, insert it.
2764 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002765
Chandler Carruthf0546402013-07-18 07:15:00 +00002766 unsigned BeginIndex = getIndex(NewBeginOffset);
2767 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002768 assert(EndIndex > BeginIndex && "Empty vector!");
2769 unsigned NumElements = EndIndex - BeginIndex;
2770 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2771
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002772 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002773 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2774 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002775 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002776 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002777
Chandler Carruth113dc642014-12-20 02:39:18 +00002778 Value *Old =
2779 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002780 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002781 } else if (IntTy) {
2782 // If this is a memset on an alloca where we can widen stores, insert the
2783 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002784 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002785
Chandler Carruthf0546402013-07-18 07:15:00 +00002786 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002787 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002788
2789 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2790 EndOffset != NewAllocaBeginOffset)) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002791 Value *Old =
2792 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002793 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002794 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002795 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002796 } else {
2797 assert(V->getType() == IntTy &&
2798 "Wrong type for an alloca wide integer!");
2799 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002800 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002801 } else {
2802 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002803 assert(NewBeginOffset == NewAllocaBeginOffset);
2804 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002805
Chandler Carruth90a735d2013-07-19 07:21:28 +00002806 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002807 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002808 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002809
Chandler Carruth90a735d2013-07-19 07:21:28 +00002810 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002811 }
2812
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002813 StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2814 II.isVolatile());
2815 if (AATags)
2816 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002817 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002818 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
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002825 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002826
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002827 AAMDNodes AATags;
2828 II.getAAMetadata(AATags);
2829
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002830 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002831 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002832 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002833
Chandler Carruthaa72b932014-02-26 07:29:54 +00002834 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002835
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002836 // 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.
Chandler Carruthf0546402013-07-18 07:15:00 +00002843 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002844 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Daniel Neilson41e781d2018-03-13 14:25:33 +00002845 if (IsDest) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002846 II.setDest(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002847 II.setDestAlignment(SliceAlign);
2848 }
2849 else {
Chandler Carruth8183a502014-02-25 11:08:02 +00002850 II.setSource(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002851 II.setSourceAlignment(SliceAlign);
Chandler Carruth181ed052014-02-26 05:33:36 +00002852 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002853
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002854 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002855 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002856 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
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002864 // If this doesn't map cleanly onto the alloca type, and that type isn't
2865 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002866 bool EmitMemCpy =
2867 !VecTy && !IntTy &&
2868 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2869 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2870 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002871
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) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002876 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002877 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002878
2879 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002880 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002881 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002882 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002883 return false;
2884 }
2885 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002886 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002887
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002888 // 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.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002890 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002891 if (AllocaInst *AI =
2892 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002893 assert(AI != &OldAI && AI != &NewAI &&
2894 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002895 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002896 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002897
Chandler Carruth286d87e2014-02-26 08:25:02 +00002898 Type *OtherPtrTy = OtherPtr->getType();
2899 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2900
Chandler Carruth181ed052014-02-26 05:33:36 +00002901 // Compute the relative offset for the other pointer within the transfer.
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002902 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2903 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002904 unsigned OtherAlign =
2905 IsDest ? II.getSourceAlignment() : II.getDestAlignment();
2906 OtherAlign = MinAlign(OtherAlign ? OtherAlign : 1,
2907 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002908
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002909 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002910 // Compute the other pointer, folding as much as possible to produce
2911 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002912 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002913 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002914
Chandler Carruth47954c82014-02-26 05:12:43 +00002915 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002916 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002917 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002918
Daniel Neilson41e781d2018-03-13 14:25:33 +00002919 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());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002935 if (AATags)
2936 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002937 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002938 return false;
2939 }
2940
Chandler Carruthf0546402013-07-18 07:15:00 +00002941 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;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002946 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002947 IntegerType *SubIntTy =
2948 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002949
Chandler Carruth286d87e2014-02-26 08:25:02 +00002950 // 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.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002952 if (VecTy && !IsWholeAlloca) {
2953 if (NumElements == 1)
2954 OtherPtrTy = VecTy->getElementType();
2955 else
2956 OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
2957
Chandler Carruth286d87e2014-02-26 08:25:02 +00002958 OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002959 } else if (IntTy && !IsWholeAlloca) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00002960 OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
2961 } else {
2962 OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002963 }
2964
Chandler Carruth181ed052014-02-26 05:33:36 +00002965 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002966 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002967 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002968 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002969 unsigned DstAlign = SliceAlign;
2970 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002971 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002972 std::swap(SrcAlign, DstAlign);
2973 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002974
2975 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002976 if (VecTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002977 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002978 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002979 } else if (IntTy && !IsWholeAlloca && !IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002980 Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002981 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002982 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002983 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002984 } else {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002985 LoadInst *Load = IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(),
2986 "copyload");
2987 if (AATags)
2988 Load->setAAMetadata(AATags);
2989 Src = Load;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002990 }
2991
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002992 if (VecTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002993 Value *Old =
2994 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002995 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002996 } else if (IntTy && !IsWholeAlloca && IsDest) {
Chandler Carruth113dc642014-12-20 02:39:18 +00002997 Value *Old =
2998 IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002999 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003000 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003001 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3002 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003003 }
3004
Chandler Carruth871ba722012-09-26 10:27:46 +00003005 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00003006 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003007 if (AATags)
3008 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003009 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003010 return !II.isVolatile();
3011 }
3012
3013 bool visitIntrinsicInst(IntrinsicInst &II) {
3014 assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
3015 II.getIntrinsicID() == Intrinsic::lifetime_end);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003016 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003017 assert(II.getArgOperand(1) == OldPtr);
3018
3019 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003020 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003021
Eli Friedman50967752016-11-28 21:50:34 +00003022 // 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
Chandler Carruth113dc642014-12-20 02:39:18 +00003033 ConstantInt *Size =
3034 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003035 NewEndOffset - NewBeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00003036 Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003037 Value *New;
3038 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3039 New = IRB.CreateLifetimeStart(Ptr, Size);
3040 else
3041 New = IRB.CreateLifetimeEnd(Ptr, Size);
3042
Edwin Vane82f80d42013-01-29 17:42:24 +00003043 (void)New;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003044 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00003045
Eli Friedman50967752016-11-28 21:50:34 +00003046 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003047 }
3048
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003049 void fixLoadStoreAlign(Instruction &Root) {
3050 // This algorithm implements the same visitor loop as
3051 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3052 // or store found.
3053 SmallPtrSet<Instruction *, 4> Visited;
3054 SmallVector<Instruction *, 4> Uses;
3055 Visited.insert(&Root);
3056 Uses.push_back(&Root);
3057 do {
3058 Instruction *I = Uses.pop_back_val();
3059
3060 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3061 unsigned LoadAlign = LI->getAlignment();
3062 if (!LoadAlign)
3063 LoadAlign = DL.getABITypeAlignment(LI->getType());
3064 LI->setAlignment(std::min(LoadAlign, getSliceAlign()));
3065 continue;
3066 }
3067 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3068 unsigned StoreAlign = SI->getAlignment();
3069 if (!StoreAlign) {
3070 Value *Op = SI->getOperand(0);
3071 StoreAlign = DL.getABITypeAlignment(Op->getType());
3072 }
3073 SI->setAlignment(std::min(StoreAlign, getSliceAlign()));
3074 continue;
3075 }
3076
3077 assert(isa<BitCastInst>(I) || isa<PHINode>(I) ||
3078 isa<SelectInst>(I) || isa<GetElementPtrInst>(I));
3079 for (User *U : I->users())
3080 if (Visited.insert(cast<Instruction>(U)).second)
3081 Uses.push_back(cast<Instruction>(U));
3082 } while (!Uses.empty());
3083 }
3084
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003085 bool visitPHINode(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003086 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003087 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3088 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003089
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003090 // We would like to compute a new pointer in only one place, but have it be
3091 // as local as possible to the PHI. To do that, we re-use the location of
3092 // the old pointer, which necessarily must be in the right position to
3093 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003094 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003095 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003096 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00003097 else
3098 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003099 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003100
Chandler Carruth47954c82014-02-26 05:12:43 +00003101 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003102 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003103 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003104
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003105 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00003106 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003107
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003108 // Fix the alignment of any loads or stores using this PHI node.
3109 fixLoadStoreAlign(PN);
3110
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003111 // PHIs can't be promoted on their own, but often can be speculated. We
3112 // check the speculation outside of the rewriter so that we see the
3113 // fully-rewritten alloca.
3114 PHIUsers.insert(&PN);
3115 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003116 }
3117
3118 bool visitSelectInst(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003119 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003120 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3121 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003122 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3123 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003124
Chandler Carruth47954c82014-02-26 05:12:43 +00003125 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003126 // Replace the operands which were using the old pointer.
3127 if (SI.getOperand(1) == OldPtr)
3128 SI.setOperand(1, NewPtr);
3129 if (SI.getOperand(2) == OldPtr)
3130 SI.setOperand(2, NewPtr);
3131
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003132 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003133 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003134
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003135 // Fix the alignment of any loads or stores using this select.
3136 fixLoadStoreAlign(SI);
3137
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003138 // Selects can't be promoted on their own, but often can be speculated. We
3139 // check the speculation outside of the rewriter so that we see the
3140 // fully-rewritten alloca.
3141 SelectUsers.insert(&SI);
3142 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003143 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003144};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003145
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003146namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003147
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003148/// Visitor to rewrite aggregate loads and stores as scalar.
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003149///
3150/// This pass aggressively rewrites all aggregate loads and stores on
3151/// a particular pointer (or any pointer derived from it which we can identify)
3152/// with scalar loads and stores.
3153class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3154 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003155 friend class InstVisitor<AggLoadStoreRewriter, bool>;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003156
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003157 /// Queue of pointer uses to analyze and potentially rewrite.
3158 SmallVector<Use *, 8> Queue;
3159
3160 /// Set to prevent us from cycling with phi nodes and loops.
3161 SmallPtrSet<User *, 8> Visited;
3162
3163 /// The current pointer use being rewritten. This is used to dig up the used
3164 /// value (as opposed to the user).
3165 Use *U;
3166
3167public:
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003168 /// Rewrite loads and stores through a pointer and all pointers derived from
3169 /// it.
3170 bool rewrite(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003171 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003172 enqueueUsers(I);
3173 bool Changed = false;
3174 while (!Queue.empty()) {
3175 U = Queue.pop_back_val();
3176 Changed |= visit(cast<Instruction>(U->getUser()));
3177 }
3178 return Changed;
3179 }
3180
3181private:
3182 /// Enqueue all the users of the given instruction for further processing.
3183 /// This uses a set to de-duplicate users.
3184 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003185 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003186 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003187 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003188 }
3189
3190 // Conservative default is to not rewrite anything.
3191 bool visitInstruction(Instruction &I) { return false; }
3192
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003193 /// Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003194 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003195 protected:
3196 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003197 IRBuilderTy IRB;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003198
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003199 /// The indices which to be used with insert- or extractvalue to select the
3200 /// appropriate value within the aggregate.
3201 SmallVector<unsigned, 4> Indices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003202
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003203 /// The indices to a GEP instruction which will move Ptr to the correct slot
3204 /// within the aggregate.
3205 SmallVector<Value *, 4> GEPIndices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003206
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003207 /// The base pointer of the original op, used as a base for GEPing the
3208 /// split operations.
3209 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003210
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003211 /// Initialize the splitter with an insertion point, Ptr and start with a
3212 /// single zero GEP index.
3213 OpSplitter(Instruction *InsertionPoint, Value *Ptr)
Chandler Carruth113dc642014-12-20 02:39:18 +00003214 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003215
3216 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003217 /// Generic recursive split emission routine.
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003218 ///
3219 /// This method recursively splits an aggregate op (load or store) into
3220 /// scalar or vector ops. It splits recursively until it hits a single value
3221 /// and emits that single value operation via the template argument.
3222 ///
3223 /// The logic of this routine relies on GEPs and insertvalue and
3224 /// extractvalue all operating with the same fundamental index list, merely
3225 /// formatted differently (GEPs need actual values).
3226 ///
3227 /// \param Ty The type being split recursively into smaller ops.
3228 /// \param Agg The aggregate value being built up or stored, depending on
3229 /// whether this is splitting a load or a store respectively.
3230 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3231 if (Ty->isSingleValueType())
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003232 return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003233
3234 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3235 unsigned OldSize = Indices.size();
3236 (void)OldSize;
3237 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3238 ++Idx) {
3239 assert(Indices.size() == OldSize && "Did not return to the old size");
3240 Indices.push_back(Idx);
3241 GEPIndices.push_back(IRB.getInt32(Idx));
3242 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3243 GEPIndices.pop_back();
3244 Indices.pop_back();
3245 }
3246 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003247 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003248
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003249 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3250 unsigned OldSize = Indices.size();
3251 (void)OldSize;
3252 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3253 ++Idx) {
3254 assert(Indices.size() == OldSize && "Did not return to the old size");
3255 Indices.push_back(Idx);
3256 GEPIndices.push_back(IRB.getInt32(Idx));
3257 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3258 GEPIndices.pop_back();
3259 Indices.pop_back();
3260 }
3261 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003262 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003263
3264 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003265 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003266 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003267
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003268 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003269 AAMDNodes AATags;
3270
3271 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, AAMDNodes AATags)
3272 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr), AATags(AATags) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003273
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003274 /// Emit a leaf load of a single value. This is called at the leaves of the
3275 /// recursive emission to actually load values.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003276 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003277 assert(Ty->isSingleValueType());
3278 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003279 Value *GEP =
3280 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003281 LoadInst *Load = IRB.CreateLoad(GEP, Name + ".load");
3282 if (AATags)
3283 Load->setAAMetadata(AATags);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003284 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003285 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003286 }
3287 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003288
3289 bool visitLoadInst(LoadInst &LI) {
3290 assert(LI.getPointerOperand() == *U);
3291 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3292 return false;
3293
3294 // We have an aggregate being loaded, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003295 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003296 AAMDNodes AATags;
3297 LI.getAAMetadata(AATags);
3298 LoadOpSplitter Splitter(&LI, *U, AATags);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003299 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003300 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003301 LI.replaceAllUsesWith(V);
3302 LI.eraseFromParent();
3303 return true;
3304 }
3305
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003306 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003307 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, AAMDNodes AATags)
3308 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr), AATags(AATags) {}
3309 AAMDNodes AATags;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003310
3311 /// Emit a leaf store of a single value. This is called at the leaves of the
3312 /// recursive emission to actually produce stores.
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003313 void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003314 assert(Ty->isSingleValueType());
3315 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003316 //
3317 // The gep and extractvalue values are factored out of the CreateStore
3318 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003319 Value *ExtractValue =
3320 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3321 Value *InBoundsGEP =
3322 IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003323 StoreInst *Store = IRB.CreateStore(ExtractValue, InBoundsGEP);
3324 if (AATags)
3325 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003326 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003327 }
3328 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003329
3330 bool visitStoreInst(StoreInst &SI) {
3331 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3332 return false;
3333 Value *V = SI.getValueOperand();
3334 if (V->getType()->isSingleValueType())
3335 return false;
3336
3337 // We have an aggregate being stored, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003338 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003339 AAMDNodes AATags;
3340 SI.getAAMetadata(AATags);
3341 StoreOpSplitter Splitter(&SI, *U, AATags);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003342 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003343 SI.eraseFromParent();
3344 return true;
3345 }
3346
3347 bool visitBitCastInst(BitCastInst &BC) {
3348 enqueueUsers(BC);
3349 return false;
3350 }
3351
3352 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3353 enqueueUsers(GEPI);
3354 return false;
3355 }
3356
3357 bool visitPHINode(PHINode &PN) {
3358 enqueueUsers(PN);
3359 return false;
3360 }
3361
3362 bool visitSelectInst(SelectInst &SI) {
3363 enqueueUsers(SI);
3364 return false;
3365 }
3366};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003367
3368} // end anonymous namespace
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003369
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003370/// Strip aggregate type wrapping.
Chandler Carruthba931992012-10-13 10:49:33 +00003371///
3372/// This removes no-op aggregate types wrapping an underlying type. It will
3373/// strip as many layers of types as it can without changing either the type
3374/// size or the allocated size.
3375static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3376 if (Ty->isSingleValueType())
3377 return Ty;
3378
3379 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3380 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3381
3382 Type *InnerTy;
3383 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3384 InnerTy = ArrTy->getElementType();
3385 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3386 const StructLayout *SL = DL.getStructLayout(STy);
3387 unsigned Index = SL->getElementContainingOffset(0);
3388 InnerTy = STy->getElementType(Index);
3389 } else {
3390 return Ty;
3391 }
3392
3393 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3394 TypeSize > DL.getTypeSizeInBits(InnerTy))
3395 return Ty;
3396
3397 return stripAggregateTypeWrapping(DL, InnerTy);
3398}
3399
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003400/// Try to find a partition of the aggregate type passed in for a given
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003401/// offset and size.
3402///
3403/// This recurses through the aggregate type and tries to compute a subtype
3404/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003405/// of an array, it will even compute a new array type for that sub-section,
3406/// and the same for structs.
3407///
3408/// Note that this routine is very strict and tries to find a partition of the
3409/// type which produces the *exact* right offset and size. It is not forgiving
3410/// when the size or offset cause either end of type-based partition to be off.
3411/// Also, this is a best-effort routine. It is reasonable to give up and not
3412/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003413static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3414 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003415 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3416 return stripAggregateTypeWrapping(DL, Ty);
3417 if (Offset > DL.getTypeAllocSize(Ty) ||
3418 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003419 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003420
3421 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003422 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003423 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003424 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003425 if (NumSkippedElements >= SeqTy->getNumElements())
3426 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003427 Offset -= NumSkippedElements * ElementSize;
3428
3429 // First check if we need to recurse.
3430 if (Offset > 0 || Size < ElementSize) {
3431 // Bail if the partition ends in a different array element.
3432 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003433 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003434 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003435 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003436 }
3437 assert(Offset == 0);
3438
3439 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003440 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003441 assert(Size > ElementSize);
3442 uint64_t NumElements = Size / ElementSize;
3443 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003444 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003445 return ArrayType::get(ElementTy, NumElements);
3446 }
3447
3448 StructType *STy = dyn_cast<StructType>(Ty);
3449 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003450 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003451
Chandler Carruth90a735d2013-07-19 07:21:28 +00003452 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003453 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003454 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003455 uint64_t EndOffset = Offset + Size;
3456 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003457 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003458
3459 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003460 Offset -= SL->getElementOffset(Index);
3461
3462 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003463 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003464 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003465 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003466
3467 // See if any partition must be contained by the element.
3468 if (Offset > 0 || Size < ElementSize) {
3469 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003470 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003471 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003472 }
3473 assert(Offset == 0);
3474
3475 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003476 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003477
3478 StructType::element_iterator EI = STy->element_begin() + Index,
3479 EE = STy->element_end();
3480 if (EndOffset < SL->getSizeInBytes()) {
3481 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3482 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003483 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003484
3485 // Don't try to form "natural" types if the elements don't line up with the
3486 // expected size.
3487 // FIXME: We could potentially recurse down through the last element in the
3488 // sub-struct to find a natural end point.
3489 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003490 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003491
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003492 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003493 EE = STy->element_begin() + EndIndex;
3494 }
3495
3496 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003497 StructType *SubTy =
3498 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003499 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003500 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003501 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003502
Chandler Carruth054a40a2012-09-14 11:08:31 +00003503 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003504}
3505
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003506/// Pre-split loads and stores to simplify rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003507///
3508/// We want to break up the splittable load+store pairs as much as
3509/// possible. This is important to do as a preprocessing step, as once we
3510/// start rewriting the accesses to partitions of the alloca we lose the
3511/// necessary information to correctly split apart paired loads and stores
3512/// which both point into this alloca. The case to consider is something like
3513/// the following:
3514///
3515/// %a = alloca [12 x i8]
3516/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3517/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3518/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3519/// %iptr1 = bitcast i8* %gep1 to i64*
3520/// %iptr2 = bitcast i8* %gep2 to i64*
3521/// %fptr1 = bitcast i8* %gep1 to float*
3522/// %fptr2 = bitcast i8* %gep2 to float*
3523/// %fptr3 = bitcast i8* %gep3 to float*
3524/// store float 0.0, float* %fptr1
3525/// store float 1.0, float* %fptr2
3526/// %v = load i64* %iptr1
3527/// store i64 %v, i64* %iptr2
3528/// %f1 = load float* %fptr2
3529/// %f2 = load float* %fptr3
3530///
3531/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3532/// promote everything so we recover the 2 SSA values that should have been
3533/// there all along.
3534///
3535/// \returns true if any changes are made.
3536bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003537 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003538
3539 // Track the loads and stores which are candidates for pre-splitting here, in
3540 // the order they first appear during the partition scan. These give stable
3541 // iteration order and a basis for tracking which loads and stores we
3542 // actually split.
3543 SmallVector<LoadInst *, 4> Loads;
3544 SmallVector<StoreInst *, 4> Stores;
3545
3546 // We need to accumulate the splits required of each load or store where we
3547 // can find them via a direct lookup. This is important to cross-check loads
3548 // and stores against each other. We also track the slice so that we can kill
3549 // all the slices that end up split.
3550 struct SplitOffsets {
3551 Slice *S;
3552 std::vector<uint64_t> Splits;
3553 };
3554 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3555
Chandler Carruth73b01642015-01-05 04:17:53 +00003556 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3557 // This is important as we also cannot pre-split stores of those loads!
3558 // FIXME: This is all pretty gross. It means that we can be more aggressive
3559 // in pre-splitting when the load feeding the store happens to come from
3560 // a separate alloca. Put another way, the effectiveness of SROA would be
3561 // decreased by a frontend which just concatenated all of its local allocas
3562 // into one big flat alloca. But defeating such patterns is exactly the job
3563 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3564 // change store pre-splitting to actually force pre-splitting of the load
3565 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3566 // maybe it would make it more principled?
3567 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3568
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003569 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003570 for (auto &P : AS.partitions()) {
3571 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003572 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003573 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3574 // If this is a load we have to track that it can't participate in any
3575 // pre-splitting. If this is a store of a load we have to track that
3576 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003577 if (auto *LI = dyn_cast<LoadInst>(I))
3578 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003579 else if (auto *SI = dyn_cast<StoreInst>(I))
3580 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3581 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003582 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003583 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003584 assert(P.endOffset() > S.beginOffset() &&
3585 "Empty or backwards partition!");
3586
3587 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003588 if (auto *LI = dyn_cast<LoadInst>(I)) {
3589 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3590
3591 // The load must be used exclusively to store into other pointers for
3592 // us to be able to arbitrarily pre-split it. The stores must also be
3593 // simple to avoid changing semantics.
3594 auto IsLoadSimplyStored = [](LoadInst *LI) {
3595 for (User *LU : LI->users()) {
3596 auto *SI = dyn_cast<StoreInst>(LU);
3597 if (!SI || !SI->isSimple())
3598 return false;
3599 }
3600 return true;
3601 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003602 if (!IsLoadSimplyStored(LI)) {
3603 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003604 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003605 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003606
3607 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003608 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3609 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3610 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003611 continue;
3612 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3613 if (!StoredLoad || !StoredLoad->isSimple())
3614 continue;
3615 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003616
Chandler Carruth994cde82015-01-01 12:01:03 +00003617 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003618 } else {
3619 // Other uses cannot be pre-split.
3620 continue;
3621 }
3622
3623 // Record the initial split.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003624 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003625 auto &Offsets = SplitOffsetsMap[I];
3626 assert(Offsets.Splits.empty() &&
3627 "Should not have splits the first time we see an instruction!");
3628 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003629 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003630 }
3631
3632 // Now scan the already split slices, and add a split for any of them which
3633 // we're going to pre-split.
3634 for (Slice *S : P.splitSliceTails()) {
3635 auto SplitOffsetsMapI =
3636 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3637 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3638 continue;
3639 auto &Offsets = SplitOffsetsMapI->second;
3640
3641 assert(Offsets.S == S && "Found a mismatched slice!");
3642 assert(!Offsets.Splits.empty() &&
3643 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003644 assert(Offsets.Splits.back() ==
3645 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003646 "Previous split does not end where this one begins!");
3647
3648 // Record each split. The last partition's end isn't needed as the size
3649 // of the slice dictates that.
3650 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003651 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003652 }
3653 }
3654
3655 // We may have split loads where some of their stores are split stores. For
3656 // such loads and stores, we can only pre-split them if their splits exactly
3657 // match relative to their starting offset. We have to verify this prior to
3658 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003659 Stores.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003660 llvm::remove_if(Stores,
3661 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3662 // Lookup the load we are storing in our map of split
3663 // offsets.
3664 auto *LI = cast<LoadInst>(SI->getValueOperand());
3665 // If it was completely unsplittable, then we're done,
3666 // and this store can't be pre-split.
3667 if (UnsplittableLoads.count(LI))
3668 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003669
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003670 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3671 if (LoadOffsetsI == SplitOffsetsMap.end())
3672 return false; // Unrelated loads are definitely safe.
3673 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003674
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003675 // Now lookup the store's offsets.
3676 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003677
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003678 // If the relative offsets of each split in the load and
3679 // store match exactly, then we can split them and we
3680 // don't need to remove them here.
3681 if (LoadOffsets.Splits == StoreOffsets.Splits)
3682 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003683
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003684 LLVM_DEBUG(
3685 dbgs()
3686 << " Mismatched splits for load and store:\n"
3687 << " " << *LI << "\n"
3688 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003689
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003690 // We've found a store and load that we need to split
3691 // with mismatched relative splits. Just give up on them
3692 // and remove both instructions from our list of
3693 // candidates.
3694 UnsplittableLoads.insert(LI);
3695 return true;
3696 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003697 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003698 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003699 // have caused an earlier store's load to become unsplittable and if it is
3700 // unsplittable for the later store, then we can't rely on it being split in
3701 // the earlier store either.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003702 Stores.erase(llvm::remove_if(Stores,
3703 [&UnsplittableLoads](StoreInst *SI) {
3704 auto *LI =
3705 cast<LoadInst>(SI->getValueOperand());
3706 return UnsplittableLoads.count(LI);
3707 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003708 Stores.end());
3709 // Once we've established all the loads that can't be split for some reason,
3710 // filter any that made it into our list out.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003711 Loads.erase(llvm::remove_if(Loads,
3712 [&UnsplittableLoads](LoadInst *LI) {
3713 return UnsplittableLoads.count(LI);
3714 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003715 Loads.end());
3716
3717 // If no loads or stores are left, there is no pre-splitting to be done for
3718 // this alloca.
3719 if (Loads.empty() && Stores.empty())
3720 return false;
3721
3722 // From here on, we can't fail and will be building new accesses, so rig up
3723 // an IR builder.
3724 IRBuilderTy IRB(&AI);
3725
3726 // Collect the new slices which we will merge into the alloca slices.
3727 SmallVector<Slice, 4> NewSlices;
3728
3729 // Track any allocas we end up splitting loads and stores for so we iterate
3730 // on them.
3731 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3732
3733 // At this point, we have collected all of the loads and stores we can
3734 // pre-split, and the specific splits needed for them. We actually do the
3735 // splitting in a specific order in order to handle when one of the loads in
3736 // the value operand to one of the stores.
3737 //
3738 // First, we rewrite all of the split loads, and just accumulate each split
3739 // load in a parallel structure. We also build the slices for them and append
3740 // them to the alloca slices.
3741 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3742 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003743 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003744 for (LoadInst *LI : Loads) {
3745 SplitLoads.clear();
3746
3747 IntegerType *Ty = cast<IntegerType>(LI->getType());
3748 uint64_t LoadSize = Ty->getBitWidth() / 8;
3749 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3750
3751 auto &Offsets = SplitOffsetsMap[LI];
3752 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3753 "Slice size should always match load size exactly!");
3754 uint64_t BaseOffset = Offsets.S->beginOffset();
3755 assert(BaseOffset + LoadSize > BaseOffset &&
3756 "Cannot represent alloca access size using 64-bit integers!");
3757
3758 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003759 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003760
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003761 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003762
3763 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3764 int Idx = 0, Size = Offsets.Splits.size();
3765 for (;;) {
3766 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003767 auto AS = LI->getPointerAddressSpace();
3768 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003769 LoadInst *PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003770 getAdjustedPtr(IRB, DL, BasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003771 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003772 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003773 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003774 LI->getName());
Fangrui Songf78650a2018-07-30 19:41:25 +00003775 PLoad->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003776
3777 // Append this load onto the list of split loads so we can find it later
3778 // to rewrite the stores.
3779 SplitLoads.push_back(PLoad);
3780
3781 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003782 NewSlices.push_back(
3783 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3784 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003785 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003786 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3787 << ", " << NewSlices.back().endOffset()
3788 << "): " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003789
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003790 // See if we've handled all the splits.
3791 if (Idx >= Size)
3792 break;
3793
Chandler Carruth0715cba2015-01-01 11:54:38 +00003794 // Setup the next partition.
3795 PartOffset = Offsets.Splits[Idx];
3796 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003797 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3798 }
3799
3800 // Now that we have the split loads, do the slow walk over all uses of the
3801 // load and rewrite them as split stores, or save the split loads to use
3802 // below if the store is going to be split there anyways.
3803 bool DeferredStores = false;
3804 for (User *LU : LI->users()) {
3805 StoreInst *SI = cast<StoreInst>(LU);
3806 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3807 DeferredStores = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003808 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
3809 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003810 continue;
3811 }
3812
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003813 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003814 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003815
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003816 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003817
3818 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3819 LoadInst *PLoad = SplitLoads[Idx];
3820 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003821 auto *PartPtrTy =
3822 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003823
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003824 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003825 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003826 PLoad,
3827 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003828 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003829 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003830 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Dorit Nuzmand1247a62016-09-22 07:56:23 +00003831 PStore->copyMetadata(*LI, LLVMContext::MD_mem_parallel_loop_access);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003832 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003833 }
3834
3835 // We want to immediately iterate on any allocas impacted by splitting
3836 // this store, and we have to track any promotable alloca (indicated by
3837 // a direct store) as needing to be resplit because it is no longer
3838 // promotable.
3839 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3840 ResplitPromotableAllocas.insert(OtherAI);
3841 Worklist.insert(OtherAI);
3842 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3843 StoreBasePtr->stripInBoundsOffsets())) {
3844 Worklist.insert(OtherAI);
3845 }
3846
3847 // Mark the original store as dead.
3848 DeadInsts.insert(SI);
3849 }
3850
3851 // Save the split loads if there are deferred stores among the users.
3852 if (DeferredStores)
3853 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3854
3855 // Mark the original load as dead and kill the original slice.
3856 DeadInsts.insert(LI);
3857 Offsets.S->kill();
3858 }
3859
3860 // Second, we rewrite all of the split stores. At this point, we know that
3861 // all loads from this alloca have been split already. For stores of such
3862 // loads, we can simply look up the pre-existing split loads. For stores of
3863 // other loads, we split those loads first and then write split stores of
3864 // them.
3865 for (StoreInst *SI : Stores) {
3866 auto *LI = cast<LoadInst>(SI->getValueOperand());
3867 IntegerType *Ty = cast<IntegerType>(LI->getType());
3868 uint64_t StoreSize = Ty->getBitWidth() / 8;
3869 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3870
3871 auto &Offsets = SplitOffsetsMap[SI];
3872 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3873 "Slice size should always match load size exactly!");
3874 uint64_t BaseOffset = Offsets.S->beginOffset();
3875 assert(BaseOffset + StoreSize > BaseOffset &&
3876 "Cannot represent alloca access size using 64-bit integers!");
3877
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003878 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003879 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3880
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003881 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003882
3883 // Check whether we have an already split load.
3884 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3885 std::vector<LoadInst *> *SplitLoads = nullptr;
3886 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3887 SplitLoads = &SplitLoadsMapI->second;
3888 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3889 "Too few split loads for the number of splits in the store!");
3890 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003891 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003892 }
3893
Chandler Carruth0715cba2015-01-01 11:54:38 +00003894 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3895 int Idx = 0, Size = Offsets.Splits.size();
3896 for (;;) {
3897 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003898 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3899 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003900
3901 // Either lookup a split load or create one.
3902 LoadInst *PLoad;
3903 if (SplitLoads) {
3904 PLoad = (*SplitLoads)[Idx];
3905 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003906 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003907 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003908 PLoad = IRB.CreateAlignedLoad(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003909 getAdjustedPtr(IRB, DL, LoadBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003910 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00003911 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003912 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003913 LI->getName());
3914 }
3915
3916 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003917 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003918 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003919 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003920 PLoad,
3921 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003922 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003923 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003924 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003925
3926 // Now build a new slice for the alloca.
3927 NewSlices.push_back(
3928 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3929 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003930 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003931 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3932 << ", " << NewSlices.back().endOffset()
3933 << "): " << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003934 if (!SplitLoads) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003935 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003936 }
3937
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003938 // See if we've finished all the splits.
3939 if (Idx >= Size)
3940 break;
3941
Chandler Carruth0715cba2015-01-01 11:54:38 +00003942 // Setup the next partition.
3943 PartOffset = Offsets.Splits[Idx];
3944 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003945 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3946 }
3947
3948 // We want to immediately iterate on any allocas impacted by splitting
3949 // this load, which is only relevant if it isn't a load of this alloca and
3950 // thus we didn't already split the loads above. We also have to keep track
3951 // of any promotable allocas we split loads on as they can no longer be
3952 // promoted.
3953 if (!SplitLoads) {
3954 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3955 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3956 ResplitPromotableAllocas.insert(OtherAI);
3957 Worklist.insert(OtherAI);
3958 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3959 LoadBasePtr->stripInBoundsOffsets())) {
3960 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3961 Worklist.insert(OtherAI);
3962 }
3963 }
3964
3965 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00003966 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003967 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00003968 // for some other alloca, but it may be a normal load. This may introduce
3969 // redundant loads, but where those can be merged the rest of the optimizer
3970 // should handle the merging, and this uncovers SSA splits which is more
3971 // important. In practice, the original loads will almost always be fully
3972 // split and removed eventually, and the splits will be merged by any
3973 // trivial CSE, including instcombine.
3974 if (LI->hasOneUse()) {
3975 assert(*LI->user_begin() == SI && "Single use isn't this store!");
3976 DeadInsts.insert(LI);
3977 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003978 DeadInsts.insert(SI);
3979 Offsets.S->kill();
3980 }
3981
Chandler Carruth24ac8302015-01-02 03:55:54 +00003982 // Remove the killed slices that have ben pre-split.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003983 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
3984 AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003985
Chandler Carruth24ac8302015-01-02 03:55:54 +00003986 // Insert our new slices. This will sort and merge them into the sorted
3987 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003988 AS.insert(NewSlices);
3989
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003990 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003991#ifndef NDEBUG
3992 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003993 LLVM_DEBUG(AS.print(dbgs(), I, " "));
Chandler Carruth0715cba2015-01-01 11:54:38 +00003994#endif
3995
3996 // Finally, don't try to promote any allocas that new require re-splitting.
3997 // They have already been added to the worklist above.
3998 PromotableAllocas.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003999 llvm::remove_if(
David Majnemerc7004902016-08-12 04:32:37 +00004000 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00004001 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
4002 PromotableAllocas.end());
4003
4004 return true;
4005}
4006
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004007/// Rewrite an alloca partition's users.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004008///
4009/// This routine drives both of the rewriting goals of the SROA pass. It tries
4010/// to rewrite uses of an alloca partition to be conducive for SSA value
4011/// promotion. If the partition needs a new, more refined alloca, this will
4012/// build that new alloca, preserving as much type information as possible, and
4013/// rewrite the uses of the old alloca to point at the new one and have the
4014/// appropriate new offsets. It also evaluates how successful the rewrite was
4015/// at enabling promotion and if it was successful queues the alloca to be
4016/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00004017AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00004018 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004019 // Try to compute a friendly type for this partition of the alloca. This
4020 // won't always succeed, in which case we fall back to a legal integer type
4021 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00004022 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004023 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004024 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004025 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004026 SliceTy = CommonUseTy;
4027 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004028 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004029 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004030 SliceTy = TypePartitionTy;
4031 if ((!SliceTy || (SliceTy->isArrayTy() &&
4032 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004033 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004034 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004035 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004036 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004037 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00004038
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004039 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00004040
Chandler Carruth2dc96822014-10-18 00:44:02 +00004041 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004042 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00004043 if (VecTy)
4044 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004045
4046 // Check for the case where we're going to rewrite to a new alloca of the
4047 // exact same type as the original, and with the same access offsets. In that
4048 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00004049 // perform phi and select speculation.
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004050 // P.beginOffset() can be non-zero even with the same type in a case with
4051 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004052 AllocaInst *NewAI;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004053 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004054 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00004055 // FIXME: We should be able to bail at this point with "nothing changed".
4056 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00004057 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004058 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00004059 unsigned Alignment = AI.getAlignment();
4060 if (!Alignment) {
4061 // The minimum alignment which users can rely on when the explicit
4062 // alignment is omitted or zero is that required by the ABI for this
4063 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004064 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00004065 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004066 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00004067 // If we will get at least this much alignment from the type alone, leave
4068 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004069 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00004070 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004071 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004072 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004073 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Anastasis Grammenos425df222018-06-28 18:58:30 +00004074 // Copy the old AI debug location over to the new one.
4075 NewAI->setDebugLoc(AI.getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004076 ++NumNewAllocas;
4077 }
4078
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004079 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4080 << "[" << P.beginOffset() << "," << P.endOffset()
4081 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004082
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004083 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00004084 // promoted allocas. We will reset it to this point if the alloca is not in
4085 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004086 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00004087 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00004088 SmallSetVector<PHINode *, 8> PHIUsers;
4089 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00004090
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004091 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004092 P.endOffset(), IsIntegerPromotable, VecTy,
4093 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00004094 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00004095 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004096 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004097 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004098 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004099 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004100 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004101 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004102 }
4103
Chandler Carruth6c321c12013-07-19 10:57:36 +00004104 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00004105 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004106
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004107 // Now that we've processed all the slices in the new partition, check if any
4108 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00004109 for (PHINode *PHI : PHIUsers)
4110 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004111 Promotable = false;
4112 PHIUsers.clear();
4113 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004114 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004115 }
Davide Italiano81a26da2017-04-27 23:09:01 +00004116
4117 for (SelectInst *Sel : SelectUsers)
4118 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004119 Promotable = false;
4120 PHIUsers.clear();
4121 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004122 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004123 }
4124
4125 if (Promotable) {
4126 if (PHIUsers.empty() && SelectUsers.empty()) {
4127 // Promote the alloca.
4128 PromotableAllocas.push_back(NewAI);
4129 } else {
4130 // If we have either PHIs or Selects to speculate, add them to those
4131 // worklists and re-queue the new alloca so that we promote in on the
4132 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004133 for (PHINode *PHIUser : PHIUsers)
4134 SpeculatablePHIs.insert(PHIUser);
4135 for (SelectInst *SelectUser : SelectUsers)
4136 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004137 Worklist.insert(NewAI);
4138 }
4139 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004140 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004141 while (PostPromotionWorklist.size() > PPWOldSize)
4142 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00004143
4144 // We couldn't promote and we didn't create a new partition, nothing
4145 // happened.
4146 if (NewAI == &AI)
4147 return nullptr;
4148
4149 // If we can't promote the alloca, iterate on it to check for new
4150 // refinements exposed by splitting the current alloca. Don't iterate on an
4151 // alloca which didn't actually change and didn't get promoted.
4152 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00004153 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004154
Adrian Prantl565cc182015-01-20 19:42:22 +00004155 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004156}
4157
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004158/// Walks the slices of an alloca and form partitions based on them,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004159/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004160bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4161 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004162 return false;
4163
Chandler Carruth6c321c12013-07-19 10:57:36 +00004164 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004165 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004166 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004167
Chandler Carruth24ac8302015-01-02 03:55:54 +00004168 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004169 Changed |= presplitLoadsAndStores(AI, AS);
4170
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004171 // Now that we have identified any pre-splitting opportunities,
4172 // mark loads and stores unsplittable except for the following case.
4173 // We leave a slice splittable if all other slices are disjoint or fully
4174 // included in the slice, such as whole-alloca loads and stores.
4175 // If we fail to split these during pre-splitting, we want to force them
4176 // to be rewritten into a partition.
Chandler Carruth24ac8302015-01-02 03:55:54 +00004177 bool IsSorted = true;
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004178
4179 uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType());
4180 const uint64_t MaxBitVectorSize = 1024;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004181 if (AllocaSize <= MaxBitVectorSize) {
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004182 // If a byte boundary is included in any load or store, a slice starting or
4183 // ending at the boundary is not splittable.
4184 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4185 for (Slice &S : AS)
4186 for (unsigned O = S.beginOffset() + 1;
4187 O < S.endOffset() && O < AllocaSize; O++)
4188 SplittableOffset.reset(O);
4189
4190 for (Slice &S : AS) {
4191 if (!S.isSplittable())
4192 continue;
4193
4194 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4195 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4196 continue;
4197
4198 if (isa<LoadInst>(S.getUse()->getUser()) ||
4199 isa<StoreInst>(S.getUse()->getUser())) {
4200 S.makeUnsplittable();
4201 IsSorted = false;
4202 }
Chandler Carruth24ac8302015-01-02 03:55:54 +00004203 }
4204 }
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004205 else {
4206 // We only allow whole-alloca splittable loads and stores
4207 // for a large alloca to avoid creating too large BitVector.
4208 for (Slice &S : AS) {
4209 if (!S.isSplittable())
4210 continue;
4211
4212 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4213 continue;
4214
4215 if (isa<LoadInst>(S.getUse()->getUser()) ||
4216 isa<StoreInst>(S.getUse()->getUser())) {
4217 S.makeUnsplittable();
4218 IsSorted = false;
4219 }
4220 }
4221 }
4222
Chandler Carruth24ac8302015-01-02 03:55:54 +00004223 if (!IsSorted)
Fangrui Song0cac7262018-09-27 02:13:45 +00004224 llvm::sort(AS);
Chandler Carruth24ac8302015-01-02 03:55:54 +00004225
Adrian Prantl941fa752016-12-05 18:04:47 +00004226 /// Describes the allocas introduced by rewritePartition in order to migrate
4227 /// the debug info.
4228 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004229 AllocaInst *Alloca;
4230 uint64_t Offset;
4231 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004232 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004233 : Alloca(AI), Offset(O), Size(S) {}
4234 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004235 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004236
Chandler Carruth0715cba2015-01-01 11:54:38 +00004237 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004238 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004239 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4240 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004241 if (NewAI != &AI) {
4242 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004243 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004244 // Don't include any padding.
4245 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004246 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004247 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004248 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004249 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004250 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004251
Chandler Carruth6c321c12013-07-19 10:57:36 +00004252 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004253 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004254
Adrian Prantl565cc182015-01-20 19:42:22 +00004255 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004256 // and the individual partitions.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004257 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004258 if (!DbgDeclares.empty()) {
4259 auto *Var = DbgDeclares.front()->getVariable();
4260 auto *Expr = DbgDeclares.front()->getExpression();
Adrian Prantld7f6f162017-11-28 00:57:53 +00004261 auto VarSize = Var->getSizeInBits();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004262 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004263 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004264 for (auto Fragment : Fragments) {
4265 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004266 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004267 auto *FragmentExpr = Expr;
4268 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004269 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004270 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004271 auto ExprFragment = Expr->getFragmentInfo();
4272 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004273 uint64_t Start = Offset + Fragment.Offset;
4274 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004275 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004276 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004277 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004278 if (Start >= AbsEnd)
4279 // No need to describe a SROAed padding.
4280 continue;
4281 Size = std::min(Size, AbsEnd - Start);
4282 }
Adrian Prantlb192b542017-08-30 20:04:17 +00004283 // The new, smaller fragment is stenciled out from the old fragment.
4284 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4285 assert(Start >= OrigFragment->OffsetInBits &&
4286 "new fragment is outside of original fragment");
4287 Start -= OrigFragment->OffsetInBits;
4288 }
Adrian Prantl77d90b02017-11-28 21:30:38 +00004289
4290 // The alloca may be larger than the variable.
4291 if (VarSize) {
4292 if (Size > *VarSize)
4293 Size = *VarSize;
4294 if (Size == 0 || Start + Size > *VarSize)
4295 continue;
4296 }
4297
Adrian Prantld7f6f162017-11-28 00:57:53 +00004298 // Avoid creating a fragment expression that covers the entire variable.
4299 if (!VarSize || *VarSize != Size) {
4300 if (auto E =
4301 DIExpression::createFragmentExpression(Expr, Start, Size))
4302 FragmentExpr = *E;
4303 else
4304 continue;
4305 }
Adrian Prantl152ac392015-02-01 00:58:04 +00004306 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004307
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004308 // Remove any existing intrinsics describing the same alloca.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004309 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004310 OldDII->eraseFromParent();
Adrian Prantl565cc182015-01-20 19:42:22 +00004311
Adrian Prantl941fa752016-12-05 18:04:47 +00004312 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004313 DbgDeclares.front()->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004314 }
4315 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004316 return Changed;
4317}
4318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004319/// Clobber a use with undef, deleting the used value if it becomes dead.
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004320void SROA::clobberUse(Use &U) {
4321 Value *OldV = U;
4322 // Replace the use with an undef value.
4323 U = UndefValue::get(OldV->getType());
4324
4325 // Check for this making an instruction dead. We have to garbage collect
4326 // all the dead instructions to ensure the uses of any alloca end up being
4327 // minimal.
4328 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4329 if (isInstructionTriviallyDead(OldI)) {
4330 DeadInsts.insert(OldI);
4331 }
4332}
4333
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004334/// Analyze an alloca for SROA.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004335///
4336/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004337/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004338/// rewritten as needed.
4339bool SROA::runOnAlloca(AllocaInst &AI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004340 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004341 ++NumAllocasAnalyzed;
4342
4343 // Special case dead allocas, as they're trivial.
4344 if (AI.use_empty()) {
4345 AI.eraseFromParent();
4346 return true;
4347 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004348 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004349
4350 // Skip alloca forms that this analysis can't handle.
4351 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004352 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004353 return false;
4354
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004355 bool Changed = false;
4356
4357 // First, split any FCA loads and stores touching this alloca to promote
4358 // better splitting and promotion opportunities.
Benjamin Kramer6db33382015-10-15 15:08:58 +00004359 AggLoadStoreRewriter AggRewriter;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004360 Changed |= AggRewriter.rewrite(AI);
4361
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004362 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004363 AllocaSlices AS(DL, AI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004364 LLVM_DEBUG(AS.print(dbgs()));
Chandler Carruth83934062014-10-16 21:11:55 +00004365 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004366 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004367
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004368 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004369 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004370 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004371 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004372 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004373
4374 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004375 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004376
4377 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004378 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004379 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004380 }
Chandler Carruth83934062014-10-16 21:11:55 +00004381 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004382 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004383 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004384 }
4385
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004386 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004387 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004388 return Changed;
4389
Chandler Carruth83934062014-10-16 21:11:55 +00004390 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004391
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004392 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004393 while (!SpeculatablePHIs.empty())
4394 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4395
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004396 LLVM_DEBUG(dbgs() << " Speculating Selects\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004397 while (!SpeculatableSelects.empty())
4398 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4399
4400 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004401}
4402
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004403/// Delete the dead instructions accumulated in this run.
Chandler Carruth19450da2012-09-14 10:26:38 +00004404///
4405/// Recursively deletes the dead instructions we've accumulated. This is done
4406/// at the very end to maximize locality of the recursive delete and to
4407/// minimize the problems of invalidated instruction pointers as such pointers
4408/// are used heavily in the intermediate stages of the algorithm.
4409///
4410/// We also record the alloca instructions deleted here so that they aren't
4411/// subsequently handed to mem2reg to promote.
Teresa Johnson33090022017-11-20 18:33:38 +00004412bool SROA::deleteDeadInstructions(
Chandler Carruth113dc642014-12-20 02:39:18 +00004413 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Teresa Johnson33090022017-11-20 18:33:38 +00004414 bool Changed = false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004415 while (!DeadInsts.empty()) {
4416 Instruction *I = DeadInsts.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004417 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004418
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004419 // If the instruction is an alloca, find the possible dbg.declare connected
4420 // to it, and remove it too. We must do this before calling RAUW or we will
4421 // not be able to find it.
4422 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4423 DeletedAllocas.insert(AI);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004424 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004425 OldDII->eraseFromParent();
4426 }
4427
Chandler Carruth58d05562012-10-25 04:37:07 +00004428 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4429
Chandler Carruth1583e992014-03-03 10:42:58 +00004430 for (Use &Operand : I->operands())
4431 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004432 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004433 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004434 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004435 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004436 }
4437
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004438 ++NumDeleted;
4439 I->eraseFromParent();
Teresa Johnson33090022017-11-20 18:33:38 +00004440 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004441 }
Teresa Johnson33090022017-11-20 18:33:38 +00004442 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004443}
4444
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004445/// Promote the allocas, using the best available technique.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004446///
4447/// This attempts to promote whatever allocas have been identified as viable in
4448/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004449/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004450bool SROA::promoteAllocas(Function &F) {
4451 if (PromotableAllocas.empty())
4452 return false;
4453
4454 NumPromoted += PromotableAllocas.size();
4455
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004456 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004457 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004458 PromotableAllocas.clear();
4459 return true;
4460}
4461
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004462PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4463 AssumptionCache &RunAC) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004464 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004465 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004466 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004467 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004468
4469 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004470 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004471 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004472 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4473 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004474 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004475
4476 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004477 // A set of deleted alloca instruction pointers which should be removed from
4478 // the list of promotable allocas.
4479 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4480
Chandler Carruthac8317f2012-10-04 12:33:50 +00004481 do {
4482 while (!Worklist.empty()) {
4483 Changed |= runOnAlloca(*Worklist.pop_back_val());
Teresa Johnson33090022017-11-20 18:33:38 +00004484 Changed |= deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004485
Chandler Carruthac8317f2012-10-04 12:33:50 +00004486 // Remove the deleted allocas from various lists so that we don't try to
4487 // continue processing them.
4488 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004489 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004490 Worklist.remove_if(IsInSet);
4491 PostPromotionWorklist.remove_if(IsInSet);
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004492 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004493 PromotableAllocas.end());
4494 DeletedAllocas.clear();
4495 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004496 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004497
Chandler Carruthac8317f2012-10-04 12:33:50 +00004498 Changed |= promoteAllocas(F);
4499
4500 Worklist = PostPromotionWorklist;
4501 PostPromotionWorklist.clear();
4502 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004503
Davide Italiano16e96d42016-06-07 13:21:17 +00004504 if (!Changed)
4505 return PreservedAnalyses::all();
4506
Davide Italiano16e96d42016-06-07 13:21:17 +00004507 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004508 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004509 PA.preserve<GlobalsAA>();
4510 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004511}
4512
Sean Silva36e0d012016-08-09 00:28:15 +00004513PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004514 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4515 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004516}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004517
4518/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4519///
4520/// This is in the llvm namespace purely to allow it to be a friend of the \c
4521/// SROA pass.
4522class llvm::sroa::SROALegacyPass : public FunctionPass {
4523 /// The SROA implementation.
4524 SROA Impl;
4525
4526public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004527 static char ID;
4528
Chandler Carruth29a18a42015-09-12 09:09:14 +00004529 SROALegacyPass() : FunctionPass(ID) {
4530 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4531 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004532
Chandler Carruth29a18a42015-09-12 09:09:14 +00004533 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004534 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004535 return false;
4536
4537 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004538 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4539 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004540 return !PA.areAllPreserved();
4541 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004542
Chandler Carruth29a18a42015-09-12 09:09:14 +00004543 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004544 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004545 AU.addRequired<DominatorTreeWrapperPass>();
4546 AU.addPreserved<GlobalsAAWrapperPass>();
4547 AU.setPreservesCFG();
4548 }
4549
Mehdi Amini117296c2016-10-01 02:56:57 +00004550 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004551};
4552
4553char SROALegacyPass::ID = 0;
4554
4555FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4556
4557INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4558 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004559INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004560INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4561INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4562 false, false)