blob: c1e935fda7f8603761ddbc9c3448268c905eeee2 [file] [log] [blame]
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruth1b398ae2012-09-14 09:22:59 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This transformation implements the well known scalar replacement of
10/// aggregates transformation. It tries to identify promotable elements of an
11/// aggregate alloca, and promote them to registers. It will also try to
12/// convert uses of an element (or set of elements) of an alloca into a vector
13/// or bitfield-style integer scalar if appropriate.
14///
15/// It works to do this with minimal slicing of the alloca so that regions
16/// which are merely transferred in and out of external memory remain unchanged
17/// and are not decomposed to scalar code.
18///
19/// Because this also performs alloca promotion, it can be thought of as also
20/// serving the purpose of SSA formation. The algorithm iterates on the
21/// function until all opportunities for promotion have been realized.
22///
23//===----------------------------------------------------------------------===//
24
Chandler Carruth29a18a42015-09-12 09:09:14 +000025#include "llvm/Transforms/Scalar/SROA.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000026#include "llvm/ADT/APInt.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/PointerIntPair.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/STLExtras.h"
Davide Italiano81a26da2017-04-27 23:09:01 +000031#include "llvm/ADT/SetVector.h"
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +000032#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Statistic.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000036#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/Twine.h"
38#include "llvm/ADT/iterator.h"
39#include "llvm/ADT/iterator_range.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000040#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000041#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/Analysis/Loads.h"
Chandler Carruthe41e7b72012-12-10 08:28:39 +000043#include "llvm/Analysis/PtrUseVisitor.h"
David Blaikie31b98d22018-06-04 21:23:21 +000044#include "llvm/Transforms/Utils/Local.h"
Nico Weber432a3882018-04-30 14:59:11 +000045#include "llvm/Config/llvm-config.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000046#include "llvm/IR/BasicBlock.h"
47#include "llvm/IR/Constant.h"
48#include "llvm/IR/ConstantFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000050#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/DataLayout.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000052#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000054#include "llvm/IR/Dominators.h"
55#include "llvm/IR/Function.h"
56#include "llvm/IR/GetElementPtrTypeIterator.h"
57#include "llvm/IR/GlobalAlias.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000059#include "llvm/IR/InstVisitor.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/IR/InstrTypes.h"
61#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000062#include "llvm/IR/Instructions.h"
63#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000064#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000065#include "llvm/IR/LLVMContext.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000066#include "llvm/IR/Metadata.h"
67#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000068#include "llvm/IR/Operator.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000069#include "llvm/IR/PassManager.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000074#include "llvm/Pass.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000075#include "llvm/Support/Casting.h"
Chandler Carruth70b44c52012-09-15 11:43:14 +000076#include "llvm/Support/CommandLine.h"
Chandler Carruthf0546402013-07-18 07:15:00 +000077#include "llvm/Support/Compiler.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000078#include "llvm/Support/Debug.h"
79#include "llvm/Support/ErrorHandling.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000080#include "llvm/Support/MathExtras.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000081#include "llvm/Support/raw_ostream.h"
Chandler Carruth29a18a42015-09-12 09:09:14 +000082#include "llvm/Transforms/Scalar.h"
Chandler Carruth1b398ae2012-09-14 09:22:59 +000083#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000084#include <algorithm>
85#include <cassert>
86#include <chrono>
87#include <cstddef>
88#include <cstdint>
89#include <cstring>
90#include <iterator>
91#include <string>
92#include <tuple>
93#include <utility>
94#include <vector>
Chandler Carruth83cee772014-02-25 03:59:29 +000095
Hal Finkel29f51312016-03-28 11:13:03 +000096#ifndef NDEBUG
97// We only use this for a debug check.
Chandler Carruth83cee772014-02-25 03:59:29 +000098#include <random>
99#endif
100
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000101using namespace llvm;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000102using namespace llvm::sroa;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000103
Chandler Carruth964daaa2014-04-22 02:55:47 +0000104#define DEBUG_TYPE "sroa"
105
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000106STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000107STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
Chandler Carruth6c321c12013-07-19 10:57:36 +0000108STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
109STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
110STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000111STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
112STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000113STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
Chandler Carruth5f5b6162013-03-20 06:30:46 +0000114STATISTIC(NumDeleted, "Number of instructions deleted");
115STATISTIC(NumVectorized, "Number of vectorized aggregates");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000116
Chandler Carruth83cee772014-02-25 03:59:29 +0000117/// Hidden option to enable randomly shuffling the slices to help uncover
118/// instability in their order.
119static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
120 cl::init(false), cl::Hidden);
121
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000122/// Hidden option to experiment with completely strict handling of inbounds
123/// GEPs.
Chandler Carruth113dc642014-12-20 02:39:18 +0000124static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
125 cl::Hidden);
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000126
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000127namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000128
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000129/// A custom IRBuilder inserter which prefixes all names, but only in
Mehdi Amini1e9c9252016-03-11 17:15:34 +0000130/// Assert builds.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000131class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000132 std::string Prefix;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000133
Zachary Turner41a9ee92017-10-11 23:54:34 +0000134 const Twine getNameWithPrefix(const Twine &Name) const {
135 return Name.isTriviallyEmpty() ? Name : Prefix + Name;
136 }
137
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000138public:
139 void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
140
141protected:
142 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
143 BasicBlock::iterator InsertPt) const {
Zachary Turner41a9ee92017-10-11 23:54:34 +0000144 IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
145 InsertPt);
Chandler Carruth34f0c7f2013-03-21 09:52:18 +0000146 }
147};
148
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000149/// Provide a type for IRBuilder that drops names in release builds.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000150using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
Chandler Carruthd177f862013-03-20 07:30:36 +0000151
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000152/// A used slice of an alloca.
Chandler Carruthf0546402013-07-18 07:15:00 +0000153///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000154/// This structure represents a slice of an alloca used by some instruction. It
155/// stores both the begin and end offsets of this use, a pointer to the use
156/// itself, and a flag indicating whether we can classify the use as splittable
157/// or not when forming partitions of the alloca.
158class Slice {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000159 /// The beginning offset of the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000160 uint64_t BeginOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000161
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000162 /// The ending offset, not included in the range.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000163 uint64_t EndOffset = 0;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000164
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000165 /// Storage for both the use of this slice and whether it can be
Chandler Carruthf0546402013-07-18 07:15:00 +0000166 /// split.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000167 PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
Chandler Carruthf0546402013-07-18 07:15:00 +0000168
169public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000170 Slice() = default;
171
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000172 Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
Chandler Carruthf0546402013-07-18 07:15:00 +0000173 : BeginOffset(BeginOffset), EndOffset(EndOffset),
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000174 UseAndIsSplittable(U, IsSplittable) {}
Chandler Carruthf0546402013-07-18 07:15:00 +0000175
176 uint64_t beginOffset() const { return BeginOffset; }
177 uint64_t endOffset() const { return EndOffset; }
178
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000179 bool isSplittable() const { return UseAndIsSplittable.getInt(); }
180 void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000181
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000182 Use *getUse() const { return UseAndIsSplittable.getPointer(); }
Chandler Carruthf0546402013-07-18 07:15:00 +0000183
Craig Topperf40110f2014-04-25 05:29:35 +0000184 bool isDead() const { return getUse() == nullptr; }
185 void kill() { UseAndIsSplittable.setPointer(nullptr); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000186
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000187 /// Support for ordering ranges.
Chandler Carruthf74654d2013-03-18 08:36:46 +0000188 ///
189 /// This provides an ordering over ranges such that start offsets are
190 /// always increasing, and within equal start offsets, the end offsets are
191 /// decreasing. Thus the spanning range comes first in a cluster with the
192 /// same start position.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000193 bool operator<(const Slice &RHS) const {
Chandler Carruth113dc642014-12-20 02:39:18 +0000194 if (beginOffset() < RHS.beginOffset())
195 return true;
196 if (beginOffset() > RHS.beginOffset())
197 return false;
198 if (isSplittable() != RHS.isSplittable())
199 return !isSplittable();
200 if (endOffset() > RHS.endOffset())
201 return true;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000202 return false;
203 }
204
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000205 /// Support comparison with a single offset to allow binary searches.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000206 friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
Chandler Carruthf0546402013-07-18 07:15:00 +0000207 uint64_t RHSOffset) {
208 return LHS.beginOffset() < RHSOffset;
Chandler Carruthf74654d2013-03-18 08:36:46 +0000209 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000210 friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000211 const Slice &RHS) {
Chandler Carruthf0546402013-07-18 07:15:00 +0000212 return LHSOffset < RHS.beginOffset();
Chandler Carruthf74654d2013-03-18 08:36:46 +0000213 }
Chandler Carruthe3899f22013-07-15 17:36:21 +0000214
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000215 bool operator==(const Slice &RHS) const {
Chandler Carruthf0546402013-07-18 07:15:00 +0000216 return isSplittable() == RHS.isSplittable() &&
217 beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
Chandler Carruthe3899f22013-07-15 17:36:21 +0000218 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000219 bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
Chandler Carruthf74654d2013-03-18 08:36:46 +0000220};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000221
Chandler Carruthf0546402013-07-18 07:15:00 +0000222} // end anonymous namespace
Chandler Carruthf74654d2013-03-18 08:36:46 +0000223
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000224/// Representation of the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000225///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000226/// This class represents the slices of an alloca which are formed by its
227/// various uses. If a pointer escapes, we can't fully build a representation
228/// for the slices used and we reflect that in this structure. The uses are
229/// stored, sorted by increasing beginning offset and with unsplittable slices
230/// starting at a particular offset before splittable slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000231class llvm::sroa::AllocaSlices {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000232public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000233 /// Construct the slices of a particular alloca.
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000234 AllocaSlices(const DataLayout &DL, AllocaInst &AI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000235
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000236 /// Test whether a pointer to the allocation escapes our analysis.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000237 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000238 /// If this is true, the slices are never fully built and should be
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000239 /// ignored.
240 bool isEscaped() const { return PointerEscapingInstr; }
241
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000242 /// Support for iterating over the slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000243 /// @{
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000244 using iterator = SmallVectorImpl<Slice>::iterator;
245 using range = iterator_range<iterator>;
246
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000247 iterator begin() { return Slices.begin(); }
248 iterator end() { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000249
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000250 using const_iterator = SmallVectorImpl<Slice>::const_iterator;
251 using const_range = iterator_range<const_iterator>;
252
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000253 const_iterator begin() const { return Slices.begin(); }
254 const_iterator end() const { return Slices.end(); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000255 /// @}
256
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000257 /// Erase a range of slices.
Chandler Carruth994cde82015-01-01 12:01:03 +0000258 void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
Chandler Carruth0715cba2015-01-01 11:54:38 +0000259
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000260 /// Insert new slices for this alloca.
Chandler Carruth0715cba2015-01-01 11:54:38 +0000261 ///
262 /// This moves the slices into the alloca's slices collection, and re-sorts
263 /// everything so that the usual ordering properties of the alloca's slices
264 /// hold.
265 void insert(ArrayRef<Slice> NewSlices) {
266 int OldSize = Slices.size();
Benjamin Kramer4f6ac162015-02-28 10:11:12 +0000267 Slices.append(NewSlices.begin(), NewSlices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000268 auto SliceI = Slices.begin() + OldSize;
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000269 llvm::sort(SliceI, Slices.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +0000270 std::inplace_merge(Slices.begin(), SliceI, Slices.end());
271 }
272
Chandler Carruth29a18a42015-09-12 09:09:14 +0000273 // Forward declare the iterator and range accessor for walking the
274 // partitions.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000275 class partition_iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000276 iterator_range<partition_iterator> partitions();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +0000277
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000278 /// Access the dead users for this alloca.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000279 ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000280
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000281 /// Access the dead operands referring to this alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000282 ///
283 /// These are operands which have cannot actually be used to refer to the
284 /// alloca as they are outside its range and the user doesn't correct for
285 /// that. These mostly consist of PHI node inputs and the like which we just
286 /// need to replace with undef.
Chandler Carruth57d4cae2014-10-16 20:42:08 +0000287 ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000288
Aaron Ballman615eb472017-10-15 14:32:27 +0000289#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000290 void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000291 void printSlice(raw_ostream &OS, const_iterator I,
292 StringRef Indent = " ") const;
Chandler Carruthf0546402013-07-18 07:15:00 +0000293 void printUse(raw_ostream &OS, const_iterator I,
294 StringRef Indent = " ") const;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000295 void print(raw_ostream &OS) const;
Alp Tokerf929e092014-01-04 22:47:48 +0000296 void dump(const_iterator I) const;
297 void dump() const;
Chandler Carruth25fb23d2012-09-14 10:18:51 +0000298#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000299
300private:
301 template <typename DerivedT, typename RetT = void> class BuilderBase;
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000302 class SliceBuilder;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000303
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000304 friend class AllocaSlices::SliceBuilder;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000305
Aaron Ballman615eb472017-10-15 14:32:27 +0000306#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000307 /// Handle to alloca instruction to simplify method interfaces.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000308 AllocaInst &AI;
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000309#endif
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000311 /// The instruction responsible for this alloca not having a known set
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000312 /// of slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000313 ///
314 /// When an instruction (potentially) escapes the pointer to the alloca, we
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000315 /// store a pointer to that here and abort trying to form slices of the
316 /// alloca. This will be null if the alloca slices are analyzed successfully.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000317 Instruction *PointerEscapingInstr;
318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000319 /// The slices of the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000320 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000321 /// We store a vector of the slices formed by uses of the alloca here. This
322 /// vector is sorted by increasing begin offset, and then the unsplittable
323 /// slices before the splittable ones. See the Slice inner class for more
324 /// details.
325 SmallVector<Slice, 8> Slices;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000326
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000327 /// Instructions which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000328 ///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000329 /// Note that these are not separated by slice. This is because we expect an
330 /// alloca to be completely rewritten or not rewritten at all. If rewritten,
331 /// all these instructions can simply be removed and replaced with undef as
332 /// they come from outside of the allocated space.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000333 SmallVector<Instruction *, 8> DeadUsers;
334
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000335 /// Operands which will become dead if we rewrite the alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000336 ///
337 /// These are operands that in their particular use can be replaced with
338 /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
339 /// to PHI nodes and the like. They aren't entirely dead (there might be
340 /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
341 /// want to swap this particular input for undef to simplify the use lists of
342 /// the alloca.
343 SmallVector<Use *, 8> DeadOperands;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000344};
Chandler Carruth29a18a42015-09-12 09:09:14 +0000345
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000346/// A partition of the slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000347///
348/// An ephemeral representation for a range of slices which can be viewed as
349/// a partition of the alloca. This range represents a span of the alloca's
350/// memory which cannot be split, and provides access to all of the slices
351/// overlapping some part of the partition.
352///
353/// Objects of this type are produced by traversing the alloca's slices, but
354/// are only ephemeral and not persistent.
355class llvm::sroa::Partition {
356private:
357 friend class AllocaSlices;
358 friend class AllocaSlices::partition_iterator;
359
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000360 using iterator = AllocaSlices::iterator;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000361
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000362 /// The beginning and ending offsets of the alloca for this
Chandler Carruth29a18a42015-09-12 09:09:14 +0000363 /// partition.
364 uint64_t BeginOffset, EndOffset;
365
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000366 /// The start and end iterators of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000367 iterator SI, SJ;
368
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000369 /// A collection of split slice tails overlapping the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000370 SmallVector<Slice *, 4> SplitTails;
371
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000372 /// Raw constructor builds an empty partition starting and ending at
Chandler Carruth29a18a42015-09-12 09:09:14 +0000373 /// the given iterator.
374 Partition(iterator SI) : SI(SI), SJ(SI) {}
375
376public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000377 /// The start offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000378 ///
379 /// All of the contained slices start at or after this offset.
380 uint64_t beginOffset() const { return BeginOffset; }
381
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000382 /// The end offset of this partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000383 ///
384 /// All of the contained slices end at or before this offset.
385 uint64_t endOffset() const { return EndOffset; }
386
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000387 /// The size of the partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000388 ///
389 /// Note that this can never be zero.
390 uint64_t size() const {
391 assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
392 return EndOffset - BeginOffset;
393 }
394
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000395 /// Test whether this partition contains no slices, and merely spans
Chandler Carruth29a18a42015-09-12 09:09:14 +0000396 /// a region occupied by split slices.
397 bool empty() const { return SI == SJ; }
398
399 /// \name Iterate slices that start within the partition.
400 /// These may be splittable or unsplittable. They have a begin offset >= the
401 /// partition begin offset.
402 /// @{
403 // FIXME: We should probably define a "concat_iterator" helper and use that
404 // to stitch together pointee_iterators over the split tails and the
405 // contiguous iterators of the partition. That would give a much nicer
406 // interface here. We could then additionally expose filtered iterators for
407 // split, unsplit, and unsplittable splices based on the usage patterns.
408 iterator begin() const { return SI; }
409 iterator end() const { return SJ; }
410 /// @}
411
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000412 /// Get the sequence of split slice tails.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000413 ///
414 /// These tails are of slices which start before this partition but are
415 /// split and overlap into the partition. We accumulate these while forming
416 /// partitions.
417 ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
418};
419
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000420/// An iterator over partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000421///
422/// This iterator implements the core algorithm for partitioning the alloca's
423/// slices. It is a forward iterator as we don't support backtracking for
424/// efficiency reasons, and re-use a single storage area to maintain the
425/// current set of split slices.
426///
427/// It is templated on the slice iterator type to use so that it can operate
428/// with either const or non-const slice iterators.
429class AllocaSlices::partition_iterator
430 : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
431 Partition> {
432 friend class AllocaSlices;
433
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000434 /// Most of the state for walking the partitions is held in a class
Chandler Carruth29a18a42015-09-12 09:09:14 +0000435 /// with a nice interface for examining them.
436 Partition P;
437
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000438 /// We need to keep the end of the slices to know when to stop.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000439 AllocaSlices::iterator SE;
440
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000441 /// We also need to keep track of the maximum split end offset seen.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000442 /// FIXME: Do we really?
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000443 uint64_t MaxSplitSliceEndOffset = 0;
Chandler Carruth29a18a42015-09-12 09:09:14 +0000444
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000445 /// Sets the partition to be empty at given iterator, and sets the
Chandler Carruth29a18a42015-09-12 09:09:14 +0000446 /// end iterator.
447 partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000448 : P(SI), SE(SE) {
Chandler Carruth29a18a42015-09-12 09:09:14 +0000449 // If not already at the end, advance our state to form the initial
450 // partition.
451 if (SI != SE)
452 advance();
453 }
454
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000455 /// Advance the iterator to the next partition.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000456 ///
457 /// Requires that the iterator not be at the end of the slices.
458 void advance() {
459 assert((P.SI != SE || !P.SplitTails.empty()) &&
460 "Cannot advance past the end of the slices!");
461
462 // Clear out any split uses which have ended.
463 if (!P.SplitTails.empty()) {
464 if (P.EndOffset >= MaxSplitSliceEndOffset) {
465 // If we've finished all splits, this is easy.
466 P.SplitTails.clear();
467 MaxSplitSliceEndOffset = 0;
468 } else {
469 // Remove the uses which have ended in the prior partition. This
470 // cannot change the max split slice end because we just checked that
471 // the prior partition ended prior to that max.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000472 P.SplitTails.erase(llvm::remove_if(P.SplitTails,
473 [&](Slice *S) {
474 return S->endOffset() <=
475 P.EndOffset;
476 }),
477 P.SplitTails.end());
478 assert(llvm::any_of(P.SplitTails,
479 [&](Slice *S) {
480 return S->endOffset() == MaxSplitSliceEndOffset;
481 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000482 "Could not find the current max split slice offset!");
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000483 assert(llvm::all_of(P.SplitTails,
484 [&](Slice *S) {
485 return S->endOffset() <= MaxSplitSliceEndOffset;
486 }) &&
Chandler Carruth29a18a42015-09-12 09:09:14 +0000487 "Max split slice end offset is not actually the max!");
488 }
489 }
490
491 // If P.SI is already at the end, then we've cleared the split tail and
492 // now have an end iterator.
493 if (P.SI == SE) {
494 assert(P.SplitTails.empty() && "Failed to clear the split slices!");
495 return;
496 }
497
498 // If we had a non-empty partition previously, set up the state for
499 // subsequent partitions.
500 if (P.SI != P.SJ) {
501 // Accumulate all the splittable slices which started in the old
502 // partition into the split list.
503 for (Slice &S : P)
504 if (S.isSplittable() && S.endOffset() > P.EndOffset) {
505 P.SplitTails.push_back(&S);
506 MaxSplitSliceEndOffset =
507 std::max(S.endOffset(), MaxSplitSliceEndOffset);
508 }
509
510 // Start from the end of the previous partition.
511 P.SI = P.SJ;
512
513 // If P.SI is now at the end, we at most have a tail of split slices.
514 if (P.SI == SE) {
515 P.BeginOffset = P.EndOffset;
516 P.EndOffset = MaxSplitSliceEndOffset;
517 return;
518 }
519
520 // If the we have split slices and the next slice is after a gap and is
521 // not splittable immediately form an empty partition for the split
522 // slices up until the next slice begins.
523 if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
524 !P.SI->isSplittable()) {
525 P.BeginOffset = P.EndOffset;
526 P.EndOffset = P.SI->beginOffset();
527 return;
528 }
529 }
530
531 // OK, we need to consume new slices. Set the end offset based on the
532 // current slice, and step SJ past it. The beginning offset of the
533 // partition is the beginning offset of the next slice unless we have
534 // pre-existing split slices that are continuing, in which case we begin
535 // at the prior end offset.
536 P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
537 P.EndOffset = P.SI->endOffset();
538 ++P.SJ;
539
540 // There are two strategies to form a partition based on whether the
541 // partition starts with an unsplittable slice or a splittable slice.
542 if (!P.SI->isSplittable()) {
543 // When we're forming an unsplittable region, it must always start at
544 // the first slice and will extend through its end.
545 assert(P.BeginOffset == P.SI->beginOffset());
546
547 // Form a partition including all of the overlapping slices with this
548 // unsplittable slice.
549 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
550 if (!P.SJ->isSplittable())
551 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
552 ++P.SJ;
553 }
554
555 // We have a partition across a set of overlapping unsplittable
556 // partitions.
557 return;
558 }
559
560 // If we're starting with a splittable slice, then we need to form
561 // a synthetic partition spanning it and any other overlapping splittable
562 // splices.
563 assert(P.SI->isSplittable() && "Forming a splittable partition!");
564
565 // Collect all of the overlapping splittable slices.
566 while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
567 P.SJ->isSplittable()) {
568 P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
569 ++P.SJ;
570 }
571
572 // Back upiP.EndOffset if we ended the span early when encountering an
573 // unsplittable slice. This synthesizes the early end offset of
574 // a partition spanning only splittable slices.
575 if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
576 assert(!P.SJ->isSplittable());
577 P.EndOffset = P.SJ->beginOffset();
578 }
579 }
580
581public:
582 bool operator==(const partition_iterator &RHS) const {
583 assert(SE == RHS.SE &&
584 "End iterators don't match between compared partition iterators!");
585
586 // The observed positions of partitions is marked by the P.SI iterator and
587 // the emptiness of the split slices. The latter is only relevant when
588 // P.SI == SE, as the end iterator will additionally have an empty split
589 // slices list, but the prior may have the same P.SI and a tail of split
590 // slices.
591 if (P.SI == RHS.P.SI && P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
592 assert(P.SJ == RHS.P.SJ &&
593 "Same set of slices formed two different sized partitions!");
594 assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
595 "Same slice position with differently sized non-empty split "
596 "slice tails!");
597 return true;
598 }
599 return false;
600 }
601
602 partition_iterator &operator++() {
603 advance();
604 return *this;
605 }
606
607 Partition &operator*() { return P; }
608};
609
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000610/// A forward range over the partitions of the alloca's slices.
Chandler Carruth29a18a42015-09-12 09:09:14 +0000611///
612/// This accesses an iterator range over the partitions of the alloca's
613/// slices. It computes these partitions on the fly based on the overlapping
614/// offsets of the slices and the ability to split them. It will visit "empty"
615/// partitions to cover regions of the alloca only accessed via split
616/// slices.
617iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
618 return make_range(partition_iterator(begin(), end()),
619 partition_iterator(end(), end()));
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000620}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000621
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000622static Value *foldSelectInst(SelectInst &SI) {
623 // If the condition being selected on is a constant or the same value is
624 // being selected between, fold the select. Yes this does (rarely) happen
625 // early on.
626 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
Chandler Carruth113dc642014-12-20 02:39:18 +0000627 return SI.getOperand(1 + CI->isZero());
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000628 if (SI.getOperand(1) == SI.getOperand(2))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000629 return SI.getOperand(1);
Jakub Staszak3c6583a2013-02-19 22:14:45 +0000630
Craig Topperf40110f2014-04-25 05:29:35 +0000631 return nullptr;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000632}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000633
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000634/// A helper that folds a PHI node or a select.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000635static Value *foldPHINodeOrSelectInst(Instruction &I) {
636 if (PHINode *PN = dyn_cast<PHINode>(&I)) {
637 // If PN merges together the same value, return that value.
638 return PN->hasConstantValue();
639 }
640 return foldSelectInst(cast<SelectInst>(I));
641}
642
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000643/// Builder for the alloca slices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000644///
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000645/// This class builds a set of alloca slices by recursively visiting the uses
646/// of an alloca and making a slice for each load and store at each offset.
647class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
648 friend class PtrUseVisitor<SliceBuilder>;
649 friend class InstVisitor<SliceBuilder>;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000650
651 using Base = PtrUseVisitor<SliceBuilder>;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000652
653 const uint64_t AllocSize;
Chandler Carruth83934062014-10-16 21:11:55 +0000654 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000655
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000656 SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
Chandler Carruthf0546402013-07-18 07:15:00 +0000657 SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
658
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000659 /// Set to de-duplicate dead instructions found in the use walk.
Chandler Carruthf0546402013-07-18 07:15:00 +0000660 SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000661
662public:
Chandler Carruth83934062014-10-16 21:11:55 +0000663 SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000664 : PtrUseVisitor<SliceBuilder>(DL),
Chandler Carruth83934062014-10-16 21:11:55 +0000665 AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000666
667private:
Chandler Carruthf0546402013-07-18 07:15:00 +0000668 void markAsDead(Instruction &I) {
David Blaikie70573dc2014-11-19 07:49:26 +0000669 if (VisitedDeadInsts.insert(&I).second)
Chandler Carruth83934062014-10-16 21:11:55 +0000670 AS.DeadUsers.push_back(&I);
Chandler Carruthf0546402013-07-18 07:15:00 +0000671 }
672
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000673 void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
Chandler Carruth97121172012-09-16 19:39:50 +0000674 bool IsSplittable = false) {
Chandler Carruthf02b8bf2012-12-03 10:59:55 +0000675 // Completely skip uses which have a zero size or start either before or
676 // past the end of the allocation.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000677 if (Size == 0 || Offset.uge(AllocSize)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000678 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
679 << Offset
680 << " which has zero size or starts outside of the "
681 << AllocSize << " byte alloca:\n"
682 << " alloca: " << AS.AI << "\n"
683 << " use: " << I << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000684 return markAsDead(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000685 }
686
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000687 uint64_t BeginOffset = Offset.getZExtValue();
688 uint64_t EndOffset = BeginOffset + Size;
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000689
690 // Clamp the end offset to the end of the allocation. Note that this is
691 // formulated to handle even the case where "BeginOffset + Size" overflows.
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000692 // This may appear superficially to be something we could ignore entirely,
693 // but that is not so! There may be widened loads or PHI-node uses where
694 // some instructions are dead but not others. We can't completely ignore
695 // them, and so have to record at least the information here.
Chandler Carruthe7a1ba52012-09-23 11:43:14 +0000696 assert(AllocSize >= BeginOffset); // Established above.
697 if (Size > AllocSize - BeginOffset) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000698 LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
699 << Offset << " to remain within the " << AllocSize
700 << " byte alloca:\n"
701 << " alloca: " << AS.AI << "\n"
702 << " use: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000703 EndOffset = AllocSize;
704 }
705
Chandler Carruth83934062014-10-16 21:11:55 +0000706 AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
Chandler Carruthf0546402013-07-18 07:15:00 +0000707 }
708
709 void visitBitCastInst(BitCastInst &BC) {
710 if (BC.use_empty())
711 return markAsDead(BC);
712
713 return Base::visitBitCastInst(BC);
714 }
715
Matt Arsenault282dac72019-06-14 21:38:31 +0000716 void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
717 if (ASC.use_empty())
718 return markAsDead(ASC);
719
720 return Base::visitAddrSpaceCastInst(ASC);
721 }
722
Chandler Carruthf0546402013-07-18 07:15:00 +0000723 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
724 if (GEPI.use_empty())
725 return markAsDead(GEPI);
726
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000727 if (SROAStrictInbounds && GEPI.isInBounds()) {
728 // FIXME: This is a manually un-factored variant of the basic code inside
729 // of GEPs with checking of the inbounds invariant specified in the
730 // langref in a very strict sense. If we ever want to enable
731 // SROAStrictInbounds, this code should be factored cleanly into
732 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
Hal Finkel5c83a092016-03-28 11:23:21 +0000733 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000734 // size readily available.
735 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000736 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000737 for (gep_type_iterator GTI = gep_type_begin(GEPI),
738 GTE = gep_type_end(GEPI);
739 GTI != GTE; ++GTI) {
740 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
741 if (!OpC)
742 break;
743
744 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000745 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000746 unsigned ElementIdx = OpC->getZExtValue();
747 const StructLayout *SL = DL.getStructLayout(STy);
748 GEPOffset +=
749 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
750 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000751 // For array or vector indices, scale the index by the size of the
752 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000753 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
754 GEPOffset += Index * APInt(Offset.getBitWidth(),
755 DL.getTypeAllocSize(GTI.getIndexedType()));
756 }
757
758 // If this index has computed an intermediate pointer which is not
759 // inbounds, then the result of the GEP is a poison value and we can
760 // delete it and all uses.
761 if (GEPOffset.ugt(AllocSize))
762 return markAsDead(GEPI);
763 }
764 }
765
Chandler Carruthf0546402013-07-18 07:15:00 +0000766 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000767 }
768
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000769 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000770 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000771 // We allow splitting of non-volatile loads and stores where the type is an
772 // integer type. These may be used to implement 'memcpy' or other "transfer
773 // of bits" patterns.
774 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000775
776 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000777 }
778
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000779 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000780 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
781 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000782
783 if (!IsOffsetKnown)
784 return PI.setAborted(&LI);
785
Matt Arsenault282dac72019-06-14 21:38:31 +0000786 if (LI.isVolatile() &&
787 LI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
788 return PI.setAborted(&LI);
789
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000790 uint64_t Size = DL.getTypeStoreSize(LI.getType());
791 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000792 }
793
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000794 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000795 Value *ValOp = SI.getValueOperand();
796 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000797 return PI.setEscapedAndAborted(&SI);
798 if (!IsOffsetKnown)
799 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000800
Matt Arsenault282dac72019-06-14 21:38:31 +0000801 if (SI.isVolatile() &&
802 SI.getPointerAddressSpace() != DL.getAllocaAddrSpace())
803 return PI.setAborted(&SI);
804
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000805 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
806
807 // If this memory access can be shown to *statically* extend outside the
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000808 // bounds of the allocation, it's behavior is undefined, so simply
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000809 // ignore it. Note that this is more strict than the generic clamping
810 // behavior of insertUse. We also try to handle cases which might run the
811 // risk of overflow.
812 // FIXME: We should instead consider the pointer to have escaped if this
813 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000814 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000815 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
816 << Offset << " which extends past the end of the "
817 << AllocSize << " byte alloca:\n"
818 << " alloca: " << AS.AI << "\n"
819 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000820 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000821 }
822
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000823 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
824 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000825 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000826 }
827
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000828 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000829 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000830 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000831 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000832 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000833 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000834 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000835
836 if (!IsOffsetKnown)
837 return PI.setAborted(&II);
838
Matt Arsenault282dac72019-06-14 21:38:31 +0000839 // Don't replace this with a store with a different address space. TODO:
840 // Use a store with the casted new alloca?
841 if (II.isVolatile() && II.getDestAddressSpace() != DL.getAllocaAddrSpace())
842 return PI.setAborted(&II);
843
Chandler Carruth113dc642014-12-20 02:39:18 +0000844 insertUse(II, Offset, Length ? Length->getLimitedValue()
845 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000846 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000847 }
848
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000849 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000850 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000851 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000852 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000853 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000854
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000855 // Because we can visit these intrinsics twice, also check to see if the
856 // first time marked this instruction as dead. If so, skip it.
857 if (VisitedDeadInsts.count(&II))
858 return;
859
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000860 if (!IsOffsetKnown)
861 return PI.setAborted(&II);
862
Matt Arsenault282dac72019-06-14 21:38:31 +0000863 // Don't replace this with a load/store with a different address space.
864 // TODO: Use a store with the casted new alloca?
865 if (II.isVolatile() &&
866 (II.getDestAddressSpace() != DL.getAllocaAddrSpace() ||
867 II.getSourceAddressSpace() != DL.getAllocaAddrSpace()))
868 return PI.setAborted(&II);
869
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000870 // This side of the transfer is completely out-of-bounds, and so we can
871 // nuke the entire transfer. However, we also need to nuke the other side
872 // if already added to our partitions.
873 // FIXME: Yet another place we really should bypass this when
874 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000875 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000876 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
877 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000878 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000879 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000880 return markAsDead(II);
881 }
882
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000883 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000884 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000885
Chandler Carruthf0546402013-07-18 07:15:00 +0000886 // Check for the special case where the same exact value is used for both
887 // source and dest.
888 if (*U == II.getRawDest() && *U == II.getRawSource()) {
889 // For non-volatile transfers this is a no-op.
890 if (!II.isVolatile())
891 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000892
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000893 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000894 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000895
Chandler Carruthf0546402013-07-18 07:15:00 +0000896 // If we have seen both source and destination for a mem transfer, then
897 // they both point to the same alloca.
898 bool Inserted;
899 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000900 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000901 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000902 unsigned PrevIdx = MTPI->second;
903 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000904 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000905
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000906 // Check if the begin offsets match and this is a non-volatile transfer.
907 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000908 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
909 PrevP.kill();
910 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000911 }
912
913 // Otherwise we have an offset transfer within the same alloca. We can't
914 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000915 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000916 }
917
Chandler Carruthe3899f22013-07-15 17:36:21 +0000918 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000919 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000920
Chandler Carruthf0546402013-07-18 07:15:00 +0000921 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000922 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000923 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000924 }
925
926 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000927 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000928 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000929 void visitIntrinsicInst(IntrinsicInst &II) {
930 if (!IsOffsetKnown)
931 return PI.setAborted(&II);
932
Vedant Kumarb264d692018-12-21 21:49:40 +0000933 if (II.isLifetimeStartOrEnd()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000934 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000935 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
936 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000937 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000938 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000939 }
940
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000941 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000942 }
943
944 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
945 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000946 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000947 // are considered unsplittable and the size is the maximum loaded or stored
948 // size.
949 SmallPtrSet<Instruction *, 4> Visited;
950 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
951 Visited.insert(Root);
952 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000953 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000954 // If there are no loads or stores, the access is dead. We mark that as
955 // a size zero access.
956 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000957 do {
958 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000959 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000960
961 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000962 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000963 continue;
964 }
965 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
966 Value *Op = SI->getOperand(0);
967 if (Op == UsedI)
968 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000969 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000970 continue;
971 }
972
973 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
974 if (!GEP->hasAllZeroIndices())
975 return GEP;
976 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
Matt Arsenault282dac72019-06-14 21:38:31 +0000977 !isa<SelectInst>(I) && !isa<AddrSpaceCastInst>(I)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000978 return I;
979 }
980
Chandler Carruthcdf47882014-03-09 03:16:01 +0000981 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000982 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000983 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000984 } while (!Uses.empty());
985
Craig Topperf40110f2014-04-25 05:29:35 +0000986 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000987 }
988
Jingyue Wuec33fa92014-08-22 22:45:57 +0000989 void visitPHINodeOrSelectInst(Instruction &I) {
990 assert(isa<PHINode>(I) || isa<SelectInst>(I));
991 if (I.use_empty())
992 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000993
Jingyue Wuec33fa92014-08-22 22:45:57 +0000994 // TODO: We could use SimplifyInstruction here to fold PHINodes and
995 // SelectInsts. However, doing so requires to change the current
996 // dead-operand-tracking mechanism. For instance, suppose neither loading
997 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
998 // trap either. However, if we simply replace %U with undef using the
999 // current dead-operand-tracking mechanism, "load (select undef, undef,
1000 // %other)" may trap because the select may return the first operand
1001 // "undef".
1002 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001003 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001004 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +00001005 // through the PHI/select as if we had RAUW'ed it.
1006 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001007 else
Jingyue Wuec33fa92014-08-22 22:45:57 +00001008 // Otherwise the operand to the PHI/select is dead, and we can replace
1009 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +00001010 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001011
1012 return;
1013 }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001014
Chandler Carruthf0546402013-07-18 07:15:00 +00001015 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +00001016 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001017
Chandler Carruthf0546402013-07-18 07:15:00 +00001018 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +00001019 uint64_t &Size = PHIOrSelectSizes[&I];
1020 if (!Size) {
1021 // This is a new PHI/Select, check for an unsafe use of it.
1022 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +00001023 return PI.setAborted(UnsafeI);
1024 }
1025
1026 // For PHI and select operands outside the alloca, we can't nuke the entire
1027 // phi or select -- the other side might still be relevant, so we special
1028 // case them here and use a separate structure to track the operands
1029 // themselves which should be replaced with undef.
1030 // FIXME: This should instead be escaped in the event we're instrumenting
1031 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +00001032 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +00001033 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +00001034 return;
1035 }
1036
Jingyue Wuec33fa92014-08-22 22:45:57 +00001037 insertUse(I, Offset, Size);
1038 }
1039
Chandler Carruth113dc642014-12-20 02:39:18 +00001040 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001041
Chandler Carruth113dc642014-12-20 02:39:18 +00001042 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001043
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001044 /// Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +00001045 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001046};
1047
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001048AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001049 :
Aaron Ballman615eb472017-10-15 14:32:27 +00001050#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001051 AI(AI),
1052#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001053 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001054 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001055 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001056 if (PtrI.isEscaped() || PtrI.isAborted()) {
1057 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001058 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001059 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1060 : PtrI.getAbortingInst();
1061 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001062 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001063 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001064
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001065 Slices.erase(
1066 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1067 Slices.end());
Benjamin Kramer08e50702013-07-20 08:38:34 +00001068
Hal Finkel29f51312016-03-28 11:13:03 +00001069#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001070 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001071 std::mt19937 MT(static_cast<unsigned>(
1072 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001073 std::shuffle(Slices.begin(), Slices.end(), MT);
1074 }
1075#endif
1076
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001077 // Sort the uses. This arranges for the offsets to be in ascending order,
1078 // and the sizes to be in descending order.
Fangrui Song0cac7262018-09-27 02:13:45 +00001079 llvm::sort(Slices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001080}
1081
Aaron Ballman615eb472017-10-15 14:32:27 +00001082#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001083
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001084void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1085 StringRef Indent) const {
1086 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001087 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001088 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001089}
1090
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001091void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1092 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001093 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001094 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001095 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001096}
1097
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001098void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1099 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001100 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001101}
1102
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001103void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001104 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001105 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001106 << " A pointer to this alloca escaped by:\n"
1107 << " " << *PointerEscapingInstr << "\n";
1108 return;
1109 }
1110
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001111 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001112 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001113 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001114}
1115
Alp Tokerf929e092014-01-04 22:47:48 +00001116LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1117 print(dbgs(), I);
1118}
1119LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001120
Aaron Ballman615eb472017-10-15 14:32:27 +00001121#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001122
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001123/// Walk the range of a partitioning looking for a common type to cover this
1124/// sequence of slices.
1125static Type *findCommonType(AllocaSlices::const_iterator B,
1126 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001127 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001128 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001129 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001130 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001131
1132 // Note that we need to look at *every* alloca slice's Use to ensure we
1133 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001134 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001135 Use *U = I->getUse();
1136 if (isa<IntrinsicInst>(*U->getUser()))
1137 continue;
1138 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1139 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001140
Craig Topperf40110f2014-04-25 05:29:35 +00001141 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001142 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001143 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001144 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001145 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001146 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001147
Chandler Carruth4de31542014-01-21 23:16:05 +00001148 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001149 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001150 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001151 // entity causing the split. Also skip if the type is not a byte width
1152 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001153 if (UserITy->getBitWidth() % 8 != 0 ||
1154 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001155 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001156
Chandler Carruth4de31542014-01-21 23:16:05 +00001157 // Track the largest bitwidth integer type used in this way in case there
1158 // is no common type.
1159 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1160 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001161 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001162
1163 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1164 // depend on types skipped above.
1165 if (!UserTy || (Ty && Ty != UserTy))
1166 TyIsCommon = false; // Give up on anything but an iN type.
1167 else
1168 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001169 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001170
1171 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001172}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001173
Chandler Carruthf0546402013-07-18 07:15:00 +00001174/// PHI instructions that use an alloca and are subsequently loaded can be
1175/// rewritten to load both input pointers in the pred blocks and then PHI the
1176/// results, allowing the load of the alloca to be promoted.
1177/// From this:
1178/// %P2 = phi [i32* %Alloca, i32* %Other]
1179/// %V = load i32* %P2
1180/// to:
1181/// %V1 = load i32* %Alloca -> will be mem2reg'd
1182/// ...
1183/// %V2 = load i32* %Other
1184/// ...
1185/// %V = phi [i32 %V1, i32 %V2]
1186///
1187/// We can do this to a select if its only uses are loads and if the operands
1188/// to the select can be loaded unconditionally.
1189///
1190/// FIXME: This should be hoisted into a generic utility, likely in
1191/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001192static bool isSafePHIToSpeculate(PHINode &PN) {
Tim Northover60afa492019-07-09 11:35:35 +00001193 const DataLayout &DL = PN.getModule()->getDataLayout();
1194
Chandler Carruthf0546402013-07-18 07:15:00 +00001195 // For now, we can only do this promotion if the load is in the same block
1196 // as the PHI, and if there are no stores between the phi and load.
1197 // TODO: Allow recursive phi users.
1198 // TODO: Allow stores.
1199 BasicBlock *BB = PN.getParent();
1200 unsigned MaxAlign = 0;
Tim Northover60afa492019-07-09 11:35:35 +00001201 uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType());
1202 APInt MaxSize(APWidth, 0);
Chandler Carruthf0546402013-07-18 07:15:00 +00001203 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001204 for (User *U : PN.users()) {
1205 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001206 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001207 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001208
Chandler Carruthf0546402013-07-18 07:15:00 +00001209 // For now we only allow loads in the same block as the PHI. This is
1210 // a common case that happens when instcombine merges two loads through
1211 // a PHI.
1212 if (LI->getParent() != BB)
1213 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001214
Chandler Carruthf0546402013-07-18 07:15:00 +00001215 // Ensure that there are no instructions between the PHI and the load that
1216 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001217 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001218 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001219 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001220
Philip Reames26945222019-08-27 19:34:43 +00001221 uint64_t Size = DL.getTypeStoreSize(LI->getType());
Chandler Carruthf0546402013-07-18 07:15:00 +00001222 MaxAlign = std::max(MaxAlign, LI->getAlignment());
Tim Northover60afa492019-07-09 11:35:35 +00001223 MaxSize = MaxSize.ult(Size) ? APInt(APWidth, Size) : MaxSize;
Chandler Carruthf0546402013-07-18 07:15:00 +00001224 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001225 }
1226
Chandler Carruthf0546402013-07-18 07:15:00 +00001227 if (!HaveLoad)
1228 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001229
Chandler Carruthf0546402013-07-18 07:15:00 +00001230 // We can only transform this if it is safe to push the loads into the
1231 // predecessor blocks. The only thing to watch out for is that we can't put
1232 // a possibly trapping load in the predecessor if it is a critical edge.
1233 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001234 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001235 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001236
Chandler Carruthf0546402013-07-18 07:15:00 +00001237 // If the value is produced by the terminator of the predecessor (an
1238 // invoke) or it has side-effects, there is no valid place to put a load
1239 // in the predecessor.
1240 if (TI == InVal || TI->mayHaveSideEffects())
1241 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001242
Chandler Carruthf0546402013-07-18 07:15:00 +00001243 // If the predecessor has a single successor, then the edge isn't
1244 // critical.
1245 if (TI->getNumSuccessors() == 1)
1246 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001247
Chandler Carruthf0546402013-07-18 07:15:00 +00001248 // If this pointer is always safe to load, or if we can prove that there
1249 // is already a load in the block, then we can move the load to the pred
1250 // block.
Tim Northover60afa492019-07-09 11:35:35 +00001251 if (isSafeToLoadUnconditionally(InVal, MaxAlign, MaxSize, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001252 continue;
1253
1254 return false;
1255 }
1256
1257 return true;
1258}
1259
1260static void speculatePHINodeLoads(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001261 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001262
James Y Knight14359ef2019-02-01 20:44:24 +00001263 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1264 Type *LoadTy = SomeLoad->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00001265 IRBuilderTy PHIBuilder(&PN);
1266 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1267 PN.getName() + ".sroa.speculated");
1268
Suyog Sardac62136e2019-09-21 18:03:30 +00001269 // Get the AA tags and alignment to use from one of the loads. It does not
Chandler Carruthf0546402013-07-18 07:15:00 +00001270 // matter which one we get and if any differ.
Hal Finkelcc39b672014-07-24 12:16:19 +00001271 AAMDNodes AATags;
1272 SomeLoad->getAAMetadata(AATags);
Guillaume Chatelet17380222019-09-30 09:37:05 +00001273 const MaybeAlign Align = MaybeAlign(SomeLoad->getAlignment());
Chandler Carruthf0546402013-07-18 07:15:00 +00001274
1275 // Rewrite all loads of the PN to use the new PHI.
1276 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001277 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001278 LI->replaceAllUsesWith(NewPN);
1279 LI->eraseFromParent();
1280 }
1281
1282 // Inject loads into all of the pred blocks.
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001283 DenseMap<BasicBlock*, Value*> InjectedLoads;
Chandler Carruthf0546402013-07-18 07:15:00 +00001284 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1285 BasicBlock *Pred = PN.getIncomingBlock(Idx);
Chandler Carruthf0546402013-07-18 07:15:00 +00001286 Value *InVal = PN.getIncomingValue(Idx);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001287
1288 // A PHI node is allowed to have multiple (duplicated) entries for the same
1289 // basic block, as long as the value is the same. So if we already injected
1290 // a load in the predecessor, then we should reuse the same load for all
1291 // duplicated entries.
1292 if (Value* V = InjectedLoads.lookup(Pred)) {
1293 NewPN->addIncoming(V, Pred);
1294 continue;
1295 }
1296
Chandler Carruthedb12a82018-10-15 10:04:59 +00001297 Instruction *TI = Pred->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001298 IRBuilderTy PredBuilder(TI);
1299
1300 LoadInst *Load = PredBuilder.CreateLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00001301 LoadTy, InVal,
1302 (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
Chandler Carruthf0546402013-07-18 07:15:00 +00001303 ++NumLoadsSpeculated;
1304 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001305 if (AATags)
1306 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001307 NewPN->addIncoming(Load, Pred);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001308 InjectedLoads[Pred] = Load;
Chandler Carruthf0546402013-07-18 07:15:00 +00001309 }
1310
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001311 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001312 PN.eraseFromParent();
1313}
1314
1315/// Select instructions that use an alloca and are subsequently loaded can be
1316/// rewritten to load both input pointers and then select between the result,
1317/// allowing the load of the alloca to be promoted.
1318/// From this:
1319/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1320/// %V = load i32* %P2
1321/// to:
1322/// %V1 = load i32* %Alloca -> will be mem2reg'd
1323/// %V2 = load i32* %Other
1324/// %V = select i1 %cond, i32 %V1, i32 %V2
1325///
1326/// We can do this to a select if its only uses are loads and if the operand
1327/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001328static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001329 Value *TValue = SI.getTrueValue();
1330 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001331 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001332
Chandler Carruthcdf47882014-03-09 03:16:01 +00001333 for (User *U : SI.users()) {
1334 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001335 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001336 return false;
1337
Hiroshi Inoueb3008242017-06-24 15:43:33 +00001338 // Both operands to the select need to be dereferenceable, either
Chandler Carruthf0546402013-07-18 07:15:00 +00001339 // absolutely (e.g. allocas) or at this point because we can see other
1340 // accesses to it.
Tim Northover60afa492019-07-09 11:35:35 +00001341 if (!isSafeToLoadUnconditionally(TValue, LI->getType(), LI->getAlignment(),
1342 DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001343 return false;
Tim Northover60afa492019-07-09 11:35:35 +00001344 if (!isSafeToLoadUnconditionally(FValue, LI->getType(), LI->getAlignment(),
1345 DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001346 return false;
1347 }
1348
1349 return true;
1350}
1351
1352static void speculateSelectInstLoads(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001353 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001354
1355 IRBuilderTy IRB(&SI);
1356 Value *TV = SI.getTrueValue();
1357 Value *FV = SI.getFalseValue();
1358 // Replace the loads of the select with a select of two loads.
1359 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001360 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001361 assert(LI->isSimple() && "We only speculate simple loads");
1362
1363 IRB.SetInsertPoint(LI);
James Y Knight14359ef2019-02-01 20:44:24 +00001364 LoadInst *TL = IRB.CreateLoad(LI->getType(), TV,
1365 LI->getName() + ".sroa.speculate.load.true");
1366 LoadInst *FL = IRB.CreateLoad(LI->getType(), FV,
1367 LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001368 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001369
Hal Finkelcc39b672014-07-24 12:16:19 +00001370 // Transfer alignment and AA info if present.
Guillaume Chatelet17380222019-09-30 09:37:05 +00001371 TL->setAlignment(MaybeAlign(LI->getAlignment()));
1372 FL->setAlignment(MaybeAlign(LI->getAlignment()));
Hal Finkelcc39b672014-07-24 12:16:19 +00001373
1374 AAMDNodes Tags;
1375 LI->getAAMetadata(Tags);
1376 if (Tags) {
1377 TL->setAAMetadata(Tags);
1378 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001379 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001380
1381 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1382 LI->getName() + ".sroa.speculated");
1383
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001384 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001385 LI->replaceAllUsesWith(V);
1386 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001387 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001388 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001389}
1390
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001391/// Build a GEP out of a base pointer and indices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001392///
1393/// This will return the BasePtr if that is valid, or build a new GEP
1394/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001395static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001396 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001397 if (Indices.empty())
1398 return BasePtr;
1399
1400 // A single zero index is a no-op, so check for this and avoid building a GEP
1401 // in that case.
1402 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1403 return BasePtr;
1404
James Y Knight77160752019-02-01 20:44:47 +00001405 return IRB.CreateInBoundsGEP(BasePtr->getType()->getPointerElementType(),
1406 BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001407}
1408
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001409/// Get a natural GEP off of the BasePtr walking through Ty toward
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001410/// TargetTy without changing the offset of the pointer.
1411///
1412/// This routine assumes we've already established a properly offset GEP with
1413/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1414/// zero-indices down through type layers until we find one the same as
1415/// TargetTy. If we can't find one with the same type, we at least try to use
1416/// one with the same size. If none of that works, we just produce the GEP as
1417/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001418static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001419 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001420 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001421 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001422 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001423 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001424
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001425 // Offset size to use for the indices.
1426 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001427
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001428 // See if we can descend into a struct and locate a field with the correct
1429 // type.
1430 unsigned NumLayers = 0;
1431 Type *ElementTy = Ty;
1432 do {
1433 if (ElementTy->isPointerTy())
1434 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001435
1436 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1437 ElementTy = ArrayTy->getElementType();
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001438 Indices.push_back(IRB.getIntN(OffsetSize, 0));
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001439 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1440 ElementTy = VectorTy->getElementType();
1441 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001442 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001443 if (STy->element_begin() == STy->element_end())
1444 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001445 ElementTy = *STy->element_begin();
1446 Indices.push_back(IRB.getInt32(0));
1447 } else {
1448 break;
1449 }
1450 ++NumLayers;
1451 } while (ElementTy != TargetTy);
1452 if (ElementTy != TargetTy)
1453 Indices.erase(Indices.end() - NumLayers, Indices.end());
1454
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001455 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001456}
1457
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001458/// Recursively compute indices for a natural GEP.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001459///
1460/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1461/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001462static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001463 Value *Ptr, Type *Ty, APInt &Offset,
1464 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001465 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001466 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001467 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001468 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1469 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001470
1471 // We can't recurse through pointer types.
1472 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001473 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001474
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001475 // We try to analyze GEPs over vectors here, but note that these GEPs are
1476 // extremely poorly defined currently. The long-term goal is to remove GEPing
1477 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001478 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001479 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001480 if (ElementSizeInBits % 8 != 0) {
1481 // GEPs over non-multiple of 8 size vector elements are invalid.
1482 return nullptr;
1483 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001484 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001485 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001486 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001487 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001488 Offset -= NumSkippedElements * ElementSize;
1489 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001490 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001491 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001492 }
1493
1494 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1495 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001496 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001497 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001498 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001499 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001500
1501 Offset -= NumSkippedElements * ElementSize;
1502 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001503 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001504 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001505 }
1506
1507 StructType *STy = dyn_cast<StructType>(Ty);
1508 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001509 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001510
Chandler Carruth90a735d2013-07-19 07:21:28 +00001511 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001512 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001513 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001514 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001515 unsigned Index = SL->getElementContainingOffset(StructOffset);
1516 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1517 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001518 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001519 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001520
1521 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001522 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001523 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001524}
1525
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001526/// Get a natural GEP from a base pointer to a particular offset and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001527/// resulting in a particular type.
1528///
1529/// The goal is to produce a "natural" looking GEP that works with the existing
1530/// composite types to arrive at the appropriate offset and element type for
1531/// a pointer. TargetTy is the element type the returned GEP should point-to if
1532/// possible. We recurse by decreasing Offset, adding the appropriate index to
1533/// Indices, and setting Ty to the result subtype.
1534///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001535/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001536static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001537 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001538 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001539 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001540 PointerType *Ty = cast<PointerType>(Ptr->getType());
1541
1542 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1543 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001544 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001545 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001546
1547 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001548 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001549 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001550 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001551 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001552 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001553 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001554
1555 Offset -= NumSkippedElements * ElementSize;
1556 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001557 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001558 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001559}
1560
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001561/// Compute an adjusted pointer from Ptr by Offset bytes where the
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001562/// resulting pointer has PointerTy.
1563///
1564/// This tries very hard to compute a "natural" GEP which arrives at the offset
1565/// and produces the pointer type desired. Where it cannot, it will try to use
1566/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1567/// fails, it will try to use an existing i8* and GEP to the byte offset and
1568/// bitcast to the type.
1569///
1570/// The strategy for finding the more natural GEPs is to peel off layers of the
1571/// pointer, walking back through bit casts and GEPs, searching for a base
1572/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001573/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001574/// a single GEP as possible, thus making each GEP more independent of the
1575/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001576static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001577 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001578 // Even though we don't look through PHI nodes, we could be called on an
1579 // instruction in an unreachable block, which may be on a cycle.
1580 SmallPtrSet<Value *, 4> Visited;
1581 Visited.insert(Ptr);
1582 SmallVector<Value *, 4> Indices;
1583
1584 // We may end up computing an offset pointer that has the wrong type. If we
1585 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001586 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001587 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001588 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001589
1590 // Remember any i8 pointer we come across to re-use if we need to do a raw
1591 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001592 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001593 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1594
Matt Arsenault282dac72019-06-14 21:38:31 +00001595 PointerType *TargetPtrTy = cast<PointerType>(PointerTy);
1596 Type *TargetTy = TargetPtrTy->getElementType();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001597
Michael Liao4f7f70e2019-06-18 21:41:13 +00001598 // As `addrspacecast` is , `Ptr` (the storage pointer) may have different
1599 // address space from the expected `PointerTy` (the pointer to be used).
1600 // Adjust the pointer type based the original storage pointer.
1601 auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace();
1602 PointerTy = TargetTy->getPointerTo(AS);
1603
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001604 do {
1605 // First fold any existing GEPs into the offset.
1606 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1607 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001608 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001609 break;
1610 Offset += GEPOffset;
1611 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001612 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001613 break;
1614 }
1615
1616 // See if we can perform a natural GEP here.
1617 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001618 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001619 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001620 // If we have a new natural pointer at the offset, clear out any old
1621 // offset pointer we computed. Unless it is the base pointer or
1622 // a non-instruction, we built a GEP we don't need. Zap it.
1623 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1624 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1625 assert(I->use_empty() && "Built a GEP with uses some how!");
1626 I->eraseFromParent();
1627 }
1628 OffsetPtr = P;
1629 OffsetBasePtr = Ptr;
1630 // If we also found a pointer of the right type, we're done.
1631 if (P->getType() == PointerTy)
Michael Liao4f7f70e2019-06-18 21:41:13 +00001632 break;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001633 }
1634
1635 // Stash this pointer if we've found an i8*.
1636 if (Ptr->getType()->isIntegerTy(8)) {
1637 Int8Ptr = Ptr;
1638 Int8PtrOffset = Offset;
1639 }
1640
1641 // Peel off a layer of the pointer and update the offset appropriately.
1642 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1643 Ptr = cast<Operator>(Ptr)->getOperand(0);
1644 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001645 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001646 break;
1647 Ptr = GA->getAliasee();
1648 } else {
1649 break;
1650 }
1651 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001652 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001653
1654 if (!OffsetPtr) {
1655 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001656 Int8Ptr = IRB.CreateBitCast(
1657 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1658 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001659 Int8PtrOffset = Offset;
1660 }
1661
Chandler Carruth113dc642014-12-20 02:39:18 +00001662 OffsetPtr = Int8PtrOffset == 0
1663 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001664 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1665 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001666 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001667 }
1668 Ptr = OffsetPtr;
1669
1670 // On the off chance we were targeting i8*, guard the bitcast here.
Matt Arsenault282dac72019-06-14 21:38:31 +00001671 if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) {
1672 Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
1673 TargetPtrTy,
1674 NamePrefix + "sroa_cast");
1675 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001676
1677 return Ptr;
1678}
1679
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001680/// Compute the adjusted alignment for a load or store from an offset.
Chandler Carruth0715cba2015-01-01 11:54:38 +00001681static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1682 const DataLayout &DL) {
1683 unsigned Alignment;
1684 Type *Ty;
1685 if (auto *LI = dyn_cast<LoadInst>(I)) {
1686 Alignment = LI->getAlignment();
1687 Ty = LI->getType();
1688 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1689 Alignment = SI->getAlignment();
1690 Ty = SI->getValueOperand()->getType();
1691 } else {
1692 llvm_unreachable("Only loads and stores are allowed!");
1693 }
1694
1695 if (!Alignment)
1696 Alignment = DL.getABITypeAlignment(Ty);
1697
1698 return MinAlign(Alignment, Offset);
1699}
1700
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001701/// Test whether we can convert a value from the old to the new type.
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001702///
1703/// This predicate should be used to guard calls to convertValue in order to
1704/// ensure that we only try to convert viable values. The strategy is that we
1705/// will peel off single element struct and array wrappings to get to an
1706/// underlying value, and convert that value.
1707static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1708 if (OldTy == NewTy)
1709 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001710
1711 // For integer types, we can't handle any bit-width differences. This would
1712 // break both vector conversions with extension and introduce endianness
1713 // issues when in conjunction with loads and stores.
1714 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1715 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1716 cast<IntegerType>(NewTy)->getBitWidth() &&
1717 "We can't have the same bitwidth for different int types");
1718 return false;
1719 }
1720
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001721 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1722 return false;
1723 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1724 return false;
1725
Benjamin Kramer56262592013-09-22 11:24:58 +00001726 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001727 // of pointers and integers.
1728 OldTy = OldTy->getScalarType();
1729 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001730 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001731 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1732 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1733 cast<PointerType>(OldTy)->getPointerAddressSpace();
1734 }
Sanjoy Dasb70ddd82017-06-17 20:28:13 +00001735
1736 // We can convert integers to integral pointers, but not to non-integral
1737 // pointers.
1738 if (OldTy->isIntegerTy())
1739 return !DL.isNonIntegralPointerType(NewTy);
1740
1741 // We can convert integral pointers to integers, but non-integral pointers
1742 // need to remain pointers.
1743 if (!DL.isNonIntegralPointerType(OldTy))
1744 return NewTy->isIntegerTy();
1745
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001746 return false;
1747 }
1748
1749 return true;
1750}
1751
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001752/// Generic routine to convert an SSA value to a value of a different
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001753/// type.
1754///
1755/// This will try various different casting techniques, such as bitcasts,
1756/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1757/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001758static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001759 Type *NewTy) {
1760 Type *OldTy = V->getType();
1761 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1762
1763 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001764 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001765
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001766 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1767 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001768
Benjamin Kramer90901a32013-09-21 20:36:04 +00001769 // See if we need inttoptr for this type pair. A cast involving both scalars
1770 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001771 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001772 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1773 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1774 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1775 NewTy);
1776
1777 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1778 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1779 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1780 NewTy);
1781
1782 return IRB.CreateIntToPtr(V, NewTy);
1783 }
1784
1785 // See if we need ptrtoint for this type pair. A cast involving both scalars
1786 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001787 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001788 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1789 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1790 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1791 NewTy);
1792
1793 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1794 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1795 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1796 NewTy);
1797
1798 return IRB.CreatePtrToInt(V, NewTy);
1799 }
1800
1801 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001802}
1803
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001804/// Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001805///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001806/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001807/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001808static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1809 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001810 uint64_t ElementSize,
1811 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001812 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001813 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001814 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001815 uint64_t BeginIndex = BeginOffset / ElementSize;
1816 if (BeginIndex * ElementSize != BeginOffset ||
1817 BeginIndex >= Ty->getNumElements())
1818 return false;
1819 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001820 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001821 uint64_t EndIndex = EndOffset / ElementSize;
1822 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1823 return false;
1824
1825 assert(EndIndex > BeginIndex && "Empty vector!");
1826 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001827 Type *SliceTy = (NumElements == 1)
1828 ? Ty->getElementType()
1829 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001830
1831 Type *SplitIntTy =
1832 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1833
Chandler Carruthc659df92014-10-16 20:24:07 +00001834 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001835
1836 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1837 if (MI->isVolatile())
1838 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001839 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001840 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001841 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00001842 if (!II->isLifetimeStartOrEnd())
Owen Anderson6c19ab12014-08-07 21:07:35 +00001843 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001844 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1845 // Disable vector promotion when there are loads or stores of an FCA.
1846 return false;
1847 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1848 if (LI->isVolatile())
1849 return false;
1850 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001851 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001852 assert(LTy->isIntegerTy());
1853 LTy = SplitIntTy;
1854 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001855 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001856 return false;
1857 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1858 if (SI->isVolatile())
1859 return false;
1860 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001861 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001862 assert(STy->isIntegerTy());
1863 STy = SplitIntTy;
1864 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001865 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001866 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001867 } else {
1868 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001869 }
1870
1871 return true;
1872}
1873
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001874/// Test whether the given alloca partitioning and range of slices can be
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001875/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001876///
1877/// This is a quick test to check whether we can rewrite a particular alloca
1878/// partition (and its newly formed alloca) into a vector alloca with only
1879/// whole-vector loads and stores such that it could be promoted to a vector
1880/// SSA value. We only can ensure this for a limited set of operations, and we
1881/// don't want to do the rewrites unless we are confident that the result will
1882/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001883static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001884 // Collect the candidate types for vector-based promotion. Also track whether
1885 // we have different element types.
1886 SmallVector<VectorType *, 4> CandidateTys;
1887 Type *CommonEltTy = nullptr;
1888 bool HaveCommonEltTy = true;
1889 auto CheckCandidateType = [&](Type *Ty) {
1890 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
Suyog Sardacd629ea2019-09-21 18:16:37 +00001891 // Return if bitcast to vectors is different for total size in bits.
1892 if (!CandidateTys.empty()) {
1893 VectorType *V = CandidateTys[0];
1894 if (DL.getTypeSizeInBits(VTy) != DL.getTypeSizeInBits(V)) {
1895 CandidateTys.clear();
1896 return;
1897 }
1898 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00001899 CandidateTys.push_back(VTy);
1900 if (!CommonEltTy)
1901 CommonEltTy = VTy->getElementType();
1902 else if (CommonEltTy != VTy->getElementType())
1903 HaveCommonEltTy = false;
1904 }
1905 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001906 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001907 for (const Slice &S : P)
1908 if (S.beginOffset() == P.beginOffset() &&
1909 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001910 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1911 CheckCandidateType(LI->getType());
1912 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1913 CheckCandidateType(SI->getValueOperand()->getType());
1914 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001915
Chandler Carruth2dc96822014-10-18 00:44:02 +00001916 // If we didn't find a vector type, nothing to do here.
1917 if (CandidateTys.empty())
1918 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001919
Chandler Carruth2dc96822014-10-18 00:44:02 +00001920 // Remove non-integer vector types if we had multiple common element types.
1921 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1922 // do that until all the backends are known to produce good code for all
1923 // integer vector types.
1924 if (!HaveCommonEltTy) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001925 CandidateTys.erase(
1926 llvm::remove_if(CandidateTys,
1927 [](VectorType *VTy) {
1928 return !VTy->getElementType()->isIntegerTy();
1929 }),
1930 CandidateTys.end());
Chandler Carruth2dc96822014-10-18 00:44:02 +00001931
1932 // If there were no integer vector types, give up.
1933 if (CandidateTys.empty())
1934 return nullptr;
1935
1936 // Rank the remaining candidate vector types. This is easy because we know
1937 // they're all integer vectors. We sort by ascending number of elements.
1938 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
David L. Jones41cecba2017-01-13 21:02:41 +00001939 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001940 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1941 "Cannot have vector types of different sizes!");
1942 assert(RHSTy->getElementType()->isIntegerTy() &&
1943 "All non-integer types eliminated!");
1944 assert(LHSTy->getElementType()->isIntegerTy() &&
1945 "All non-integer types eliminated!");
1946 return RHSTy->getNumElements() < LHSTy->getNumElements();
1947 };
Fangrui Song0cac7262018-09-27 02:13:45 +00001948 llvm::sort(CandidateTys, RankVectorTypes);
Chandler Carruth2dc96822014-10-18 00:44:02 +00001949 CandidateTys.erase(
1950 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1951 CandidateTys.end());
1952 } else {
1953// The only way to have the same element type in every vector type is to
1954// have the same vector type. Check that and remove all but one.
1955#ifndef NDEBUG
1956 for (VectorType *VTy : CandidateTys) {
1957 assert(VTy->getElementType() == CommonEltTy &&
1958 "Unaccounted for element type!");
1959 assert(VTy == CandidateTys[0] &&
1960 "Different vector types with the same element type!");
1961 }
1962#endif
1963 CandidateTys.resize(1);
1964 }
1965
1966 // Try each vector type, and return the one which works.
1967 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1968 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1969
1970 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1971 // that aren't byte sized.
1972 if (ElementSize % 8)
1973 return false;
1974 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1975 "vector size not a multiple of element size?");
1976 ElementSize /= 8;
1977
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001978 for (const Slice &S : P)
1979 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001980 return false;
1981
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001982 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001983 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001984 return false;
1985
1986 return true;
1987 };
1988 for (VectorType *VTy : CandidateTys)
1989 if (CheckVectorTypeForPromotion(VTy))
1990 return VTy;
1991
1992 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001993}
1994
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001995/// Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001996///
1997/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001998/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001999static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002000 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002001 Type *AllocaTy,
2002 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002003 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002004 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
2005
Chandler Carruthc659df92014-10-16 20:24:07 +00002006 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
2007 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00002008
2009 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002010 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00002011 if (RelEnd > Size)
2012 return false;
2013
Chandler Carruthc659df92014-10-16 20:24:07 +00002014 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00002015
2016 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2017 if (LI->isVolatile())
2018 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002019 // We can't handle loads that extend past the allocated memory.
2020 if (DL.getTypeStoreSize(LI->getType()) > Size)
2021 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00002022 // So far, AllocaSliceRewriter does not support widening split slice tails
2023 // in rewriteIntegerLoad.
2024 if (S.beginOffset() < AllocBeginOffset)
2025 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002026 // Note that we don't count vector loads or stores as whole-alloca
2027 // operations which enable integer widening because we would prefer to use
2028 // vector widening instead.
2029 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002030 WholeAllocaOp = true;
2031 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002032 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00002033 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002034 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002035 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002036 // Non-integer loads need to be convertible from the alloca type so that
2037 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002038 return false;
2039 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002040 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2041 Type *ValueTy = SI->getValueOperand()->getType();
2042 if (SI->isVolatile())
2043 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002044 // We can't handle stores that extend past the allocated memory.
2045 if (DL.getTypeStoreSize(ValueTy) > Size)
2046 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00002047 // So far, AllocaSliceRewriter does not support widening split slice tails
2048 // in rewriteIntegerStore.
2049 if (S.beginOffset() < AllocBeginOffset)
2050 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002051 // Note that we don't count vector loads or stores as whole-alloca
2052 // operations which enable integer widening because we would prefer to use
2053 // vector widening instead.
2054 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002055 WholeAllocaOp = true;
2056 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002057 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002058 return false;
2059 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002060 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002061 // Non-integer stores need to be convertible to the alloca type so that
2062 // they are promotable.
2063 return false;
2064 }
2065 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2066 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2067 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002068 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002069 return false; // Skip any unsplittable intrinsics.
2070 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00002071 if (!II->isLifetimeStartOrEnd())
Chandler Carruthf0546402013-07-18 07:15:00 +00002072 return false;
2073 } else {
2074 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002075 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002076
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002077 return true;
2078}
2079
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002080/// Test whether the given alloca partition's integer operations can be
Chandler Carruth435c4e02012-10-15 08:40:30 +00002081/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002082///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002083/// This is a quick test to check whether we can rewrite the integer loads and
2084/// stores to a particular alloca into wider loads and stores and be able to
2085/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002086static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002087 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002088 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002089 // Don't create integer types larger than the maximum bitwidth.
2090 if (SizeInBits > IntegerType::MAX_INT_BITS)
2091 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002092
2093 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002094 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002095 return false;
2096
Chandler Carruth58d05562012-10-25 04:37:07 +00002097 // We need to ensure that an integer type with the appropriate bitwidth can
2098 // be converted to the alloca type, whatever that is. We don't want to force
2099 // the alloca itself to have an integer type if there is a more suitable one.
2100 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002101 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2102 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002103 return false;
2104
Chandler Carruthf0546402013-07-18 07:15:00 +00002105 // While examining uses, we ensure that the alloca has a covering load or
2106 // store. We don't want to widen the integer operations only to fail to
2107 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002108 // later). However, if there are only splittable uses, go ahead and assume
2109 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002110 // FIXME: We shouldn't consider split slices that happen to start in the
2111 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002112 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002113 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002114
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002115 for (const Slice &S : P)
2116 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2117 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002118 return false;
2119
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002120 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002121 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2122 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002123 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002124
Chandler Carruth92924fd2012-09-24 00:34:20 +00002125 return WholeAllocaOp;
2126}
2127
Chandler Carruthd177f862013-03-20 07:30:36 +00002128static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002129 IntegerType *Ty, uint64_t Offset,
2130 const Twine &Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002131 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002132 IntegerType *IntTy = cast<IntegerType>(V->getType());
2133 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2134 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002135 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002136 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002137 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002138 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002139 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002140 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002141 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002142 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2143 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002144 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002145 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002146 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002147 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002148 return V;
2149}
2150
Chandler Carruthd177f862013-03-20 07:30:36 +00002151static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002152 Value *V, uint64_t Offset, const Twine &Name) {
2153 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2154 IntegerType *Ty = cast<IntegerType>(V->getType());
2155 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2156 "Cannot insert a larger integer!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002157 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002158 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002159 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002160 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002161 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002162 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2163 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002164 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002165 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002166 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002167 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002168 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002169 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002170 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002171
2172 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2173 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2174 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002175 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002176 V = IRB.CreateOr(Old, V, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002177 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002178 }
2179 return V;
2180}
2181
Chandler Carruth113dc642014-12-20 02:39:18 +00002182static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2183 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002184 VectorType *VecTy = cast<VectorType>(V->getType());
2185 unsigned NumElements = EndIndex - BeginIndex;
2186 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2187
2188 if (NumElements == VecTy->getNumElements())
2189 return V;
2190
2191 if (NumElements == 1) {
2192 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2193 Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002194 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002195 return V;
2196 }
2197
Chandler Carruth113dc642014-12-20 02:39:18 +00002198 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002199 Mask.reserve(NumElements);
2200 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2201 Mask.push_back(IRB.getInt32(i));
2202 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002203 ConstantVector::get(Mask), Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002204 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002205 return V;
2206}
2207
Chandler Carruthd177f862013-03-20 07:30:36 +00002208static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002209 unsigned BeginIndex, const Twine &Name) {
2210 VectorType *VecTy = cast<VectorType>(Old->getType());
2211 assert(VecTy && "Can only insert a vector into a vector");
2212
2213 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2214 if (!Ty) {
2215 // Single element to insert.
2216 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2217 Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002218 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002219 return V;
2220 }
2221
2222 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2223 "Too many elements!");
2224 if (Ty->getNumElements() == VecTy->getNumElements()) {
2225 assert(V->getType() == VecTy && "Vector type mismatch");
2226 return V;
2227 }
2228 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2229
2230 // When inserting a smaller vector into the larger to store, we first
2231 // use a shuffle vector to widen it with undef elements, and then
2232 // a second shuffle vector to select between the loaded vector and the
2233 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002234 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002235 Mask.reserve(VecTy->getNumElements());
2236 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2237 if (i >= BeginIndex && i < EndIndex)
2238 Mask.push_back(IRB.getInt32(i - BeginIndex));
2239 else
2240 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2241 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002242 ConstantVector::get(Mask), Name + ".expand");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002243 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002244
2245 Mask.clear();
2246 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002247 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2248
2249 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2250
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002251 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002252 return V;
2253}
2254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002255/// Visitor to rewrite instructions using p particular slice of an alloca
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002256/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002257///
2258/// Also implements the rewriting to vector-based accesses when the partition
2259/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2260/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002261class llvm::sroa::AllocaSliceRewriter
2262 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002263 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002264 friend class InstVisitor<AllocaSliceRewriter, bool>;
2265
2266 using Base = InstVisitor<AllocaSliceRewriter, bool>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002267
Chandler Carruth90a735d2013-07-19 07:21:28 +00002268 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002269 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002270 SROA &Pass;
2271 AllocaInst &OldAI, &NewAI;
2272 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002273 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002274
Chandler Carruth2dc96822014-10-18 00:44:02 +00002275 // This is a convenience and flag variable that will be null unless the new
2276 // alloca's integer operations should be widened to this integer type due to
2277 // passing isIntegerWideningViable above. If it is non-null, the desired
2278 // integer type will be stored here for easy access during rewriting.
2279 IntegerType *IntTy;
2280
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002281 // If we are rewriting an alloca partition which can be written as pure
2282 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002283 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002284 // - The new alloca is exactly the size of the vector type here.
2285 // - The accesses all either map to the entire vector or to a single
2286 // element.
2287 // - The set of accessing instructions is only one of those handled above
2288 // in isVectorPromotionViable. Generally these are the same access kinds
2289 // which are promotable via mem2reg.
2290 VectorType *VecTy;
2291 Type *ElementTy;
2292 uint64_t ElementSize;
2293
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002294 // The original offset of the slice currently being rewritten relative to
2295 // the original alloca.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002296 uint64_t BeginOffset = 0;
2297 uint64_t EndOffset = 0;
2298
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002299 // The new offsets of the slice currently being rewritten relative to the
2300 // original alloca.
2301 uint64_t NewBeginOffset, NewEndOffset;
2302
2303 uint64_t SliceSize;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002304 bool IsSplittable = false;
2305 bool IsSplit = false;
2306 Use *OldUse = nullptr;
2307 Instruction *OldPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002308
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002309 // Track post-rewrite users which are PHI nodes and Selects.
Davide Italiano81a26da2017-04-27 23:09:01 +00002310 SmallSetVector<PHINode *, 8> &PHIUsers;
2311 SmallSetVector<SelectInst *, 8> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002312
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002313 // Utility IR builder, whose name prefix is setup for each visited use, and
2314 // the insertion point is set to point to the user.
2315 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002316
2317public:
Chandler Carruth83934062014-10-16 21:11:55 +00002318 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002319 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002320 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002321 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2322 VectorType *PromotableVecTy,
Davide Italiano81a26da2017-04-27 23:09:01 +00002323 SmallSetVector<PHINode *, 8> &PHIUsers,
2324 SmallSetVector<SelectInst *, 8> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002325 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002326 NewAllocaBeginOffset(NewAllocaBeginOffset),
2327 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002328 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002329 IntTy(IsIntegerPromotable
2330 ? Type::getIntNTy(
2331 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002332 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002333 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002334 VecTy(PromotableVecTy),
2335 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2336 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002337 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002338 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002339 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002340 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002341 "Only multiple-of-8 sized vector elements are viable");
2342 ++NumVectorized;
2343 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002344 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002345 }
2346
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002347 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002348 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002349 BeginOffset = I->beginOffset();
2350 EndOffset = I->endOffset();
2351 IsSplittable = I->isSplittable();
2352 IsSplit =
2353 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002354 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2355 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2356 LLVM_DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002357
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002358 // Compute the intersecting offset range.
2359 assert(BeginOffset < NewAllocaEndOffset);
2360 assert(EndOffset > NewAllocaBeginOffset);
2361 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2362 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2363
2364 SliceSize = NewEndOffset - NewBeginOffset;
2365
Chandler Carruthf0546402013-07-18 07:15:00 +00002366 OldUse = I->getUse();
2367 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002368
Chandler Carruthf0546402013-07-18 07:15:00 +00002369 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2370 IRB.SetInsertPoint(OldUserI);
2371 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2372 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2373
2374 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2375 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002376 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002377 return CanSROA;
2378 }
2379
2380private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002381 // Make sure the other visit overloads are visible.
2382 using Base::visit;
2383
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002384 // Every instruction which can end up as a user must have a rewrite rule.
2385 bool visitInstruction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002386 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002387 llvm_unreachable("No rewrite rule for this instruction!");
2388 }
2389
Chandler Carruth47954c82014-02-26 05:12:43 +00002390 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2391 // Note that the offset computation can use BeginOffset or NewBeginOffset
2392 // interchangeably for unsplit slices.
2393 assert(IsSplit || BeginOffset == NewBeginOffset);
2394 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2395
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002396#ifndef NDEBUG
2397 StringRef OldName = OldPtr->getName();
2398 // Skip through the last '.sroa.' component of the name.
2399 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2400 if (LastSROAPrefix != StringRef::npos) {
2401 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2402 // Look for an SROA slice index.
2403 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2404 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2405 // Strip the index and look for the offset.
2406 OldName = OldName.substr(IndexEnd + 1);
2407 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2408 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2409 // Strip the offset.
2410 OldName = OldName.substr(OffsetEnd + 1);
2411 }
2412 }
2413 // Strip any SROA suffixes as well.
2414 OldName = OldName.substr(0, OldName.find(".sroa_"));
2415#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002416
2417 return getAdjustedPtr(IRB, DL, &NewAI,
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002418 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002419 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002420#ifndef NDEBUG
2421 Twine(OldName) + "."
2422#else
2423 Twine()
2424#endif
2425 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002426 }
2427
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002428 /// Compute suitable alignment to access this slice of the *new*
Chandler Carruth113dc642014-12-20 02:39:18 +00002429 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002430 ///
2431 /// You can optionally pass a type to this routine and if that type's ABI
2432 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002433 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002434 unsigned NewAIAlign = NewAI.getAlignment();
2435 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002436 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002437 unsigned Align =
2438 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002439 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002440 }
2441
Chandler Carruth845b73c2012-11-21 08:16:30 +00002442 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002443 assert(VecTy && "Can only call getIndex when rewriting a vector");
2444 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2445 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2446 uint32_t Index = RelOffset / ElementSize;
2447 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002448 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002449 }
2450
2451 void deleteIfTriviallyDead(Value *V) {
2452 Instruction *I = cast<Instruction>(V);
2453 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002454 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002455 }
2456
Chandler Carruthea27cf02014-02-26 04:25:04 +00002457 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002458 unsigned BeginIndex = getIndex(NewBeginOffset);
2459 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002460 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002461
James Y Knight14359ef2019-02-01 20:44:24 +00002462 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2463 NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002464 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002465 }
2466
Chandler Carruthea27cf02014-02-26 04:25:04 +00002467 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002468 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002469 assert(!LI.isVolatile());
James Y Knight14359ef2019-02-01 20:44:24 +00002470 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2471 NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002472 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002473 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2474 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002475 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2476 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2477 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2478 }
2479 // It is possible that the extracted type is not the load type. This
2480 // happens if there is a load past the end of the alloca, and as
2481 // a consequence the slice is narrower but still a candidate for integer
2482 // lowering. To handle this case, we just zero extend the extracted
2483 // integer.
2484 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2485 "Can only handle an extract for an overly wide load");
2486 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2487 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002488 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002489 }
2490
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002491 bool visitLoadInst(LoadInst &LI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002492 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002493 Value *OldOp = LI.getOperand(0);
2494 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002495
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002496 AAMDNodes AATags;
2497 LI.getAAMetadata(AATags);
2498
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002499 unsigned AS = LI.getPointerAddressSpace();
2500
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002501 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002502 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002503 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002504 bool IsPtrAdjusted = false;
2505 Value *V;
2506 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002507 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002508 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002509 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002510 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002511 NewEndOffset == NewAllocaEndOffset &&
2512 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2513 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2514 TargetTy->isIntegerTy()))) {
James Y Knight14359ef2019-02-01 20:44:24 +00002515 LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2516 NewAI.getAlignment(),
David Majnemer62690b12015-07-14 06:19:58 +00002517 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002518 if (AATags)
2519 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002520 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002521 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Luqman Aden3f807c92017-03-22 19:16:39 +00002522
Chandler Carruth3f81d802017-06-27 08:32:03 +00002523 // Any !nonnull metadata or !range metadata on the old load is also valid
2524 // on the new load. This is even true in some cases even when the loads
2525 // are different types, for example by mapping !nonnull metadata to
2526 // !range metadata by modeling the null pointer constant converted to the
2527 // integer type.
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002528 // FIXME: Add support for range metadata here. Currently the utilities
2529 // for this don't propagate range metadata in trivial cases from one
2530 // integer load to another, don't handle non-addrspace-0 null pointers
2531 // correctly, and don't have any support for mapping ranges as the
2532 // integer type becomes winder or narrower.
Chandler Carruth3f81d802017-06-27 08:32:03 +00002533 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2534 copyNonnullMetadata(LI, N, *NewLI);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002535
2536 // Try to preserve nonnull metadata
David Majnemer62690b12015-07-14 06:19:58 +00002537 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002538
2539 // If this is an integer load past the end of the slice (which means the
2540 // bytes outside the slice are undef or this load is dead) just forcibly
2541 // fix the integer size with correct handling of endianness.
2542 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2543 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2544 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2545 V = IRB.CreateZExt(V, TITy, "load.ext");
2546 if (DL.isBigEndian())
2547 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2548 "endian_shift");
2549 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002550 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002551 Type *LTy = TargetTy->getPointerTo(AS);
James Y Knight14359ef2019-02-01 20:44:24 +00002552 LoadInst *NewLI = IRB.CreateAlignedLoad(
2553 TargetTy, getNewAllocaSlicePtr(IRB, LTy), getSliceAlign(TargetTy),
2554 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002555 if (AATags)
2556 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002557 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002558 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002559
2560 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002561 IsPtrAdjusted = true;
2562 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002563 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002564
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002565 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002566 assert(!LI.isVolatile());
2567 assert(LI.getType()->isIntegerTy() &&
2568 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002569 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002570 "Split load isn't smaller than original load");
Bjorn Petterssonb4771422019-05-24 09:20:20 +00002571 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002572 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002573 // 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 +00002574 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002575 // Create a placeholder value with the same type as LI to use as the
2576 // basis for the new value. This allows us to replace the uses of LI with
2577 // the computed value, and then replace the placeholder with LI, leaving
2578 // LI only used for this computation.
James Y Knight14359ef2019-02-01 20:44:24 +00002579 Value *Placeholder = new LoadInst(
2580 LI.getType(), UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002581 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2582 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002583 LI.replaceAllUsesWith(V);
2584 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002585 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002586 } else {
2587 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002588 }
2589
Chandler Carruth18db7952012-11-20 01:12:50 +00002590 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002591 deleteIfTriviallyDead(OldOp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002592 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002593 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002594 }
2595
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002596 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2597 AAMDNodes AATags) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002598 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002599 unsigned BeginIndex = getIndex(NewBeginOffset);
2600 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002601 assert(EndIndex > BeginIndex && "Empty vector!");
2602 unsigned NumElements = EndIndex - BeginIndex;
2603 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002604 Type *SliceTy = (NumElements == 1)
2605 ? ElementTy
2606 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002607 if (V->getType() != SliceTy)
2608 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002609
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002610 // Mix in the existing elements.
James Y Knight14359ef2019-02-01 20:44:24 +00002611 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2612 NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002613 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2614 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002615 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002616 if (AATags)
2617 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002618 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002619
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002620 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002621 return true;
2622 }
2623
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002624 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002625 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002626 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002627 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
James Y Knight14359ef2019-02-01 20:44:24 +00002628 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2629 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002630 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002631 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2632 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002633 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002634 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002635 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002636 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Michael Kruse978ba612018-12-20 04:58:07 +00002637 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2638 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002639 if (AATags)
2640 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002641 Pass.DeadInsts.insert(&SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002642 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002643 return true;
2644 }
2645
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002646 bool visitStoreInst(StoreInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002647 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002648 Value *OldOp = SI.getOperand(1);
2649 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002650
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002651 AAMDNodes AATags;
2652 SI.getAAMetadata(AATags);
2653
Chandler Carruth18db7952012-11-20 01:12:50 +00002654 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002655
Chandler Carruthac8317f2012-10-04 12:33:50 +00002656 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2657 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002658 if (V->getType()->isPointerTy())
2659 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002660 Pass.PostPromotionWorklist.insert(AI);
2661
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002662 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002663 assert(!SI.isVolatile());
2664 assert(V->getType()->isIntegerTy() &&
2665 "Only integer type loads and stores are split");
Bjorn Petterssonb4771422019-05-24 09:20:20 +00002666 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002667 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002668 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002669 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2670 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002671 }
2672
Chandler Carruth18db7952012-11-20 01:12:50 +00002673 if (VecTy)
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002674 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002675 if (IntTy && V->getType()->isIntegerTy())
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002676 return rewriteIntegerStore(V, SI, AATags);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002677
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002678 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002679 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002680 if (NewBeginOffset == NewAllocaBeginOffset &&
2681 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002682 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2683 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2684 V->getType()->isIntegerTy()))) {
2685 // If this is an integer store past the end of slice (and thus the bytes
2686 // past that point are irrelevant or this is unreachable), truncate the
2687 // value prior to storing.
2688 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2689 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2690 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2691 if (DL.isBigEndian())
2692 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2693 "endian_shift");
2694 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2695 }
2696
Chandler Carruth90a735d2013-07-19 07:21:28 +00002697 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002698 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2699 SI.isVolatile());
2700 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002701 unsigned AS = SI.getPointerAddressSpace();
2702 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002703 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2704 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002705 }
Michael Kruse978ba612018-12-20 04:58:07 +00002706 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2707 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002708 if (AATags)
2709 NewSI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002710 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002711 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002712 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002713 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002714
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002715 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002716 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002717 }
2718
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002719 /// Compute an integer value from splatting an i8 across the given
Chandler Carruth514f34f2012-12-17 04:07:30 +00002720 /// number of bytes.
2721 ///
2722 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2723 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002724 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002725 ///
2726 /// \param V The i8 value to splat.
2727 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002728 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002729 assert(Size > 0 && "Expected a positive number of bytes.");
2730 IntegerType *VTy = cast<IntegerType>(V->getType());
2731 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2732 if (Size == 1)
2733 return V;
2734
Chandler Carruth113dc642014-12-20 02:39:18 +00002735 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2736 V = IRB.CreateMul(
2737 IRB.CreateZExt(V, SplatIntTy, "zext"),
2738 ConstantExpr::getUDiv(
2739 Constant::getAllOnesValue(SplatIntTy),
2740 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2741 SplatIntTy)),
2742 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002743 return V;
2744 }
2745
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002746 /// Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002747 Value *getVectorSplat(Value *V, unsigned NumElements) {
2748 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002749 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
Chandler Carruthccca5042012-12-17 04:07:37 +00002750 return V;
2751 }
2752
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002753 bool visitMemSetInst(MemSetInst &II) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002754 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002755 assert(II.getRawDest() == OldPtr);
2756
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002757 AAMDNodes AATags;
2758 II.getAAMetadata(AATags);
2759
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002760 // If the memset has a variable size, it cannot be split, just adjust the
2761 // pointer to the new alloca.
2762 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002763 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002764 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002765 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Daniel Neilson41e781d2018-03-13 14:25:33 +00002766 II.setDestAlignment(getSliceAlign());
Chandler Carruth208124f2012-09-26 10:59:22 +00002767
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002768 deleteIfTriviallyDead(OldPtr);
2769 return false;
2770 }
2771
2772 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002773 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002774
2775 Type *AllocaTy = NewAI.getAllocatedType();
2776 Type *ScalarTy = AllocaTy->getScalarType();
Philip Reames9b6b4fa2019-03-12 20:15:05 +00002777
2778 const bool CanContinue = [&]() {
2779 if (VecTy || IntTy)
2780 return true;
2781 if (BeginOffset > NewAllocaBeginOffset ||
2782 EndOffset < NewAllocaEndOffset)
2783 return false;
2784 auto *C = cast<ConstantInt>(II.getLength());
2785 if (C->getBitWidth() > 64)
2786 return false;
2787 const auto Len = C->getZExtValue();
2788 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
2789 auto *SrcTy = VectorType::get(Int8Ty, Len);
2790 return canConvertValue(DL, SrcTy, AllocaTy) &&
2791 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy));
2792 }();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002793
2794 // If this doesn't map cleanly onto the alloca type, and that type isn't
2795 // a single value type, just emit a memset.
Philip Reames9b6b4fa2019-03-12 20:15:05 +00002796 if (!CanContinue) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002797 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002798 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2799 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002800 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2801 getSliceAlign(), II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002802 if (AATags)
2803 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002804 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002805 return false;
2806 }
2807
2808 // If we can represent this as a simple value, we have to build the actual
2809 // value to store, which requires expanding the byte present in memset to
2810 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002811 // splatting the byte to a sufficiently wide integer, splatting it across
2812 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002813 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002814
Chandler Carruthccca5042012-12-17 04:07:37 +00002815 if (VecTy) {
2816 // If this is a memset of a vectorized alloca, insert it.
2817 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002818
Chandler Carruthf0546402013-07-18 07:15:00 +00002819 unsigned BeginIndex = getIndex(NewBeginOffset);
2820 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002821 assert(EndIndex > BeginIndex && "Empty vector!");
2822 unsigned NumElements = EndIndex - BeginIndex;
2823 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2824
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002825 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002826 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2827 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002828 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002829 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002830
James Y Knight14359ef2019-02-01 20:44:24 +00002831 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2832 NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002833 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002834 } else if (IntTy) {
2835 // If this is a memset on an alloca where we can widen stores, insert the
2836 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002837 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002838
Chandler Carruthf0546402013-07-18 07:15:00 +00002839 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002840 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002841
2842 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2843 EndOffset != NewAllocaBeginOffset)) {
James Y Knight14359ef2019-02-01 20:44:24 +00002844 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2845 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002846 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002847 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002848 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002849 } else {
2850 assert(V->getType() == IntTy &&
2851 "Wrong type for an alloca wide integer!");
2852 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002853 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002854 } else {
2855 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002856 assert(NewBeginOffset == NewAllocaBeginOffset);
2857 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002858
Chandler Carruth90a735d2013-07-19 07:21:28 +00002859 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002860 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002861 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002862
Chandler Carruth90a735d2013-07-19 07:21:28 +00002863 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002864 }
2865
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002866 StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2867 II.isVolatile());
2868 if (AATags)
2869 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002870 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002871 return !II.isVolatile();
2872 }
2873
2874 bool visitMemTransferInst(MemTransferInst &II) {
2875 // Rewriting of memory transfer instructions can be a bit tricky. We break
2876 // them into two categories: split intrinsics and unsplit intrinsics.
2877
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002878 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002879
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002880 AAMDNodes AATags;
2881 II.getAAMetadata(AATags);
2882
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002883 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002884 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002885 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002886
Chandler Carruthaa72b932014-02-26 07:29:54 +00002887 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002888
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002889 // For unsplit intrinsics, we simply modify the source and destination
2890 // pointers in place. This isn't just an optimization, it is a matter of
2891 // correctness. With unsplit intrinsics we may be dealing with transfers
2892 // within a single alloca before SROA ran, or with transfers that have
2893 // a variable length. We may also be dealing with memmove instead of
2894 // memcpy, and so simply updating the pointers is the necessary for us to
2895 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002896 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002897 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Daniel Neilson41e781d2018-03-13 14:25:33 +00002898 if (IsDest) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002899 II.setDest(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002900 II.setDestAlignment(SliceAlign);
2901 }
2902 else {
Chandler Carruth8183a502014-02-25 11:08:02 +00002903 II.setSource(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002904 II.setSourceAlignment(SliceAlign);
Chandler Carruth181ed052014-02-26 05:33:36 +00002905 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002906
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002907 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002908 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002909 return false;
2910 }
2911 // For split transfer intrinsics we have an incredibly useful assurance:
2912 // the source and destination do not reside within the same alloca, and at
2913 // least one of them does not escape. This means that we can replace
2914 // memmove with memcpy, and we don't need to worry about all manner of
2915 // downsides to splitting and transforming the operations.
2916
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002917 // If this doesn't map cleanly onto the alloca type, and that type isn't
2918 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002919 bool EmitMemCpy =
2920 !VecTy && !IntTy &&
2921 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2922 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2923 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002924
2925 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2926 // size hasn't been shrunk based on analysis of the viable range, this is
2927 // a no-op.
2928 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002929 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002930 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002931
2932 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002933 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002934 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002935 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002936 return false;
2937 }
2938 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002939 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002940
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002941 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2942 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002943 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002944 if (AllocaInst *AI =
2945 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002946 assert(AI != &OldAI && AI != &NewAI &&
2947 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002948 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002949 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002950
Chandler Carruth286d87e2014-02-26 08:25:02 +00002951 Type *OtherPtrTy = OtherPtr->getType();
2952 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2953
Chandler Carruth181ed052014-02-26 05:33:36 +00002954 // Compute the relative offset for the other pointer within the transfer.
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002955 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2956 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002957 unsigned OtherAlign =
2958 IsDest ? II.getSourceAlignment() : II.getDestAlignment();
2959 OtherAlign = MinAlign(OtherAlign ? OtherAlign : 1,
2960 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002961
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002962 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002963 // Compute the other pointer, folding as much as possible to produce
2964 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002965 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002966 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002967
Chandler Carruth47954c82014-02-26 05:12:43 +00002968 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002969 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002970 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002971
Daniel Neilson41e781d2018-03-13 14:25:33 +00002972 Value *DestPtr, *SrcPtr;
2973 unsigned DestAlign, SrcAlign;
2974 // Note: IsDest is true iff we're copying into the new alloca slice
2975 if (IsDest) {
2976 DestPtr = OurPtr;
2977 DestAlign = SliceAlign;
2978 SrcPtr = OtherPtr;
2979 SrcAlign = OtherAlign;
2980 } else {
2981 DestPtr = OtherPtr;
2982 DestAlign = OtherAlign;
2983 SrcPtr = OurPtr;
2984 SrcAlign = SliceAlign;
2985 }
2986 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2987 Size, II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002988 if (AATags)
2989 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002990 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002991 return false;
2992 }
2993
Chandler Carruthf0546402013-07-18 07:15:00 +00002994 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2995 NewEndOffset == NewAllocaEndOffset;
2996 uint64_t Size = NewEndOffset - NewBeginOffset;
2997 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2998 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002999 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00003000 IntegerType *SubIntTy =
3001 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003002
Chandler Carruth286d87e2014-02-26 08:25:02 +00003003 // Reset the other pointer type to match the register type we're going to
3004 // use, but using the address space of the original other pointer.
James Y Knight14359ef2019-02-01 20:44:24 +00003005 Type *OtherTy;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003006 if (VecTy && !IsWholeAlloca) {
3007 if (NumElements == 1)
James Y Knight14359ef2019-02-01 20:44:24 +00003008 OtherTy = VecTy->getElementType();
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003009 else
James Y Knight14359ef2019-02-01 20:44:24 +00003010 OtherTy = VectorType::get(VecTy->getElementType(), NumElements);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003011 } else if (IntTy && !IsWholeAlloca) {
James Y Knight14359ef2019-02-01 20:44:24 +00003012 OtherTy = SubIntTy;
Chandler Carruth286d87e2014-02-26 08:25:02 +00003013 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00003014 OtherTy = NewAllocaTy;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003015 }
James Y Knight14359ef2019-02-01 20:44:24 +00003016 OtherPtrTy = OtherTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003017
Chandler Carruth181ed052014-02-26 05:33:36 +00003018 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00003019 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00003020 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003021 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00003022 unsigned DstAlign = SliceAlign;
3023 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003024 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00003025 std::swap(SrcAlign, DstAlign);
3026 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003027
3028 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003029 if (VecTy && !IsWholeAlloca && !IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003030 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3031 NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003032 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003033 } else if (IntTy && !IsWholeAlloca && !IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003034 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3035 NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003036 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003037 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003038 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003039 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00003040 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3041 II.isVolatile(), "copyload");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003042 if (AATags)
3043 Load->setAAMetadata(AATags);
3044 Src = Load;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003045 }
3046
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003047 if (VecTy && !IsWholeAlloca && IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003048 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3049 NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003050 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003051 } else if (IntTy && !IsWholeAlloca && IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003052 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3053 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003054 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003055 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003056 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3057 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003058 }
3059
Chandler Carruth871ba722012-09-26 10:27:46 +00003060 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00003061 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003062 if (AATags)
3063 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003064 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003065 return !II.isVolatile();
3066 }
3067
3068 bool visitIntrinsicInst(IntrinsicInst &II) {
Vedant Kumarb264d692018-12-21 21:49:40 +00003069 assert(II.isLifetimeStartOrEnd());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003070 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003071 assert(II.getArgOperand(1) == OldPtr);
3072
3073 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003074 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003075
Eli Friedman50967752016-11-28 21:50:34 +00003076 // Lifetime intrinsics are only promotable if they cover the whole alloca.
3077 // Therefore, we drop lifetime intrinsics which don't cover the whole
3078 // alloca.
3079 // (In theory, intrinsics which partially cover an alloca could be
3080 // promoted, but PromoteMemToReg doesn't handle that case.)
3081 // FIXME: Check whether the alloca is promotable before dropping the
3082 // lifetime intrinsics?
3083 if (NewBeginOffset != NewAllocaBeginOffset ||
3084 NewEndOffset != NewAllocaEndOffset)
3085 return true;
3086
Chandler Carruth113dc642014-12-20 02:39:18 +00003087 ConstantInt *Size =
3088 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003089 NewEndOffset - NewBeginOffset);
Gabor Buella3ec170c2019-01-16 12:06:17 +00003090 // Lifetime intrinsics always expect an i8* so directly get such a pointer
3091 // for the new alloca slice.
3092 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3093 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003094 Value *New;
3095 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3096 New = IRB.CreateLifetimeStart(Ptr, Size);
3097 else
3098 New = IRB.CreateLifetimeEnd(Ptr, Size);
3099
Edwin Vane82f80d42013-01-29 17:42:24 +00003100 (void)New;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003101 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00003102
Eli Friedman50967752016-11-28 21:50:34 +00003103 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003104 }
3105
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003106 void fixLoadStoreAlign(Instruction &Root) {
3107 // This algorithm implements the same visitor loop as
3108 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3109 // or store found.
3110 SmallPtrSet<Instruction *, 4> Visited;
3111 SmallVector<Instruction *, 4> Uses;
3112 Visited.insert(&Root);
3113 Uses.push_back(&Root);
3114 do {
3115 Instruction *I = Uses.pop_back_val();
3116
3117 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3118 unsigned LoadAlign = LI->getAlignment();
3119 if (!LoadAlign)
3120 LoadAlign = DL.getABITypeAlignment(LI->getType());
Guillaume Chatelet17380222019-09-30 09:37:05 +00003121 LI->setAlignment(MaybeAlign(std::min(LoadAlign, getSliceAlign())));
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003122 continue;
3123 }
3124 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3125 unsigned StoreAlign = SI->getAlignment();
3126 if (!StoreAlign) {
3127 Value *Op = SI->getOperand(0);
3128 StoreAlign = DL.getABITypeAlignment(Op->getType());
3129 }
Guillaume Chateletd400d452019-10-03 13:17:21 +00003130 SI->setAlignment(MaybeAlign(std::min(StoreAlign, getSliceAlign())));
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003131 continue;
3132 }
3133
Matt Arsenault282dac72019-06-14 21:38:31 +00003134 assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||
3135 isa<PHINode>(I) || isa<SelectInst>(I) ||
3136 isa<GetElementPtrInst>(I));
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003137 for (User *U : I->users())
3138 if (Visited.insert(cast<Instruction>(U)).second)
3139 Uses.push_back(cast<Instruction>(U));
3140 } while (!Uses.empty());
3141 }
3142
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003143 bool visitPHINode(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003144 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003145 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3146 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003147
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003148 // We would like to compute a new pointer in only one place, but have it be
3149 // as local as possible to the PHI. To do that, we re-use the location of
3150 // the old pointer, which necessarily must be in the right position to
3151 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003152 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003153 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003154 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00003155 else
3156 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003157 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003158
Chandler Carruth47954c82014-02-26 05:12:43 +00003159 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003160 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003161 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003162
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003163 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00003164 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003165
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003166 // Fix the alignment of any loads or stores using this PHI node.
3167 fixLoadStoreAlign(PN);
3168
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003169 // PHIs can't be promoted on their own, but often can be speculated. We
3170 // check the speculation outside of the rewriter so that we see the
3171 // fully-rewritten alloca.
3172 PHIUsers.insert(&PN);
3173 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003174 }
3175
3176 bool visitSelectInst(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003177 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003178 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3179 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003180 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3181 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003182
Chandler Carruth47954c82014-02-26 05:12:43 +00003183 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003184 // Replace the operands which were using the old pointer.
3185 if (SI.getOperand(1) == OldPtr)
3186 SI.setOperand(1, NewPtr);
3187 if (SI.getOperand(2) == OldPtr)
3188 SI.setOperand(2, NewPtr);
3189
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003190 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003191 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003192
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003193 // Fix the alignment of any loads or stores using this select.
3194 fixLoadStoreAlign(SI);
3195
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003196 // Selects can't be promoted on their own, but often can be speculated. We
3197 // check the speculation outside of the rewriter so that we see the
3198 // fully-rewritten alloca.
3199 SelectUsers.insert(&SI);
3200 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003201 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003202};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003203
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003204namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003205
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003206/// Visitor to rewrite aggregate loads and stores as scalar.
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003207///
3208/// This pass aggressively rewrites all aggregate loads and stores on
3209/// a particular pointer (or any pointer derived from it which we can identify)
3210/// with scalar loads and stores.
3211class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3212 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003213 friend class InstVisitor<AggLoadStoreRewriter, bool>;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003214
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003215 /// Queue of pointer uses to analyze and potentially rewrite.
3216 SmallVector<Use *, 8> Queue;
3217
3218 /// Set to prevent us from cycling with phi nodes and loops.
3219 SmallPtrSet<User *, 8> Visited;
3220
3221 /// The current pointer use being rewritten. This is used to dig up the used
3222 /// value (as opposed to the user).
3223 Use *U;
3224
Tim Northover856628f2018-12-18 09:29:39 +00003225 /// Used to calculate offsets, and hence alignment, of subobjects.
3226 const DataLayout &DL;
3227
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003228public:
Tim Northover856628f2018-12-18 09:29:39 +00003229 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3230
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003231 /// Rewrite loads and stores through a pointer and all pointers derived from
3232 /// it.
3233 bool rewrite(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003234 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003235 enqueueUsers(I);
3236 bool Changed = false;
3237 while (!Queue.empty()) {
3238 U = Queue.pop_back_val();
3239 Changed |= visit(cast<Instruction>(U->getUser()));
3240 }
3241 return Changed;
3242 }
3243
3244private:
3245 /// Enqueue all the users of the given instruction for further processing.
3246 /// This uses a set to de-duplicate users.
3247 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003248 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003249 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003250 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003251 }
3252
3253 // Conservative default is to not rewrite anything.
3254 bool visitInstruction(Instruction &I) { return false; }
3255
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003256 /// Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003257 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003258 protected:
3259 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003260 IRBuilderTy IRB;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003261
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003262 /// The indices which to be used with insert- or extractvalue to select the
3263 /// appropriate value within the aggregate.
3264 SmallVector<unsigned, 4> Indices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003265
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003266 /// The indices to a GEP instruction which will move Ptr to the correct slot
3267 /// within the aggregate.
3268 SmallVector<Value *, 4> GEPIndices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003269
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003270 /// The base pointer of the original op, used as a base for GEPing the
3271 /// split operations.
3272 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003273
Tim Northover856628f2018-12-18 09:29:39 +00003274 /// The base pointee type being GEPed into.
3275 Type *BaseTy;
3276
3277 /// Known alignment of the base pointer.
3278 unsigned BaseAlign;
3279
3280 /// To calculate offset of each component so we can correctly deduce
3281 /// alignments.
3282 const DataLayout &DL;
3283
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003284 /// Initialize the splitter with an insertion point, Ptr and start with a
3285 /// single zero GEP index.
Tim Northover856628f2018-12-18 09:29:39 +00003286 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3287 unsigned BaseAlign, const DataLayout &DL)
3288 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr),
3289 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003290
3291 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003292 /// Generic recursive split emission routine.
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003293 ///
3294 /// This method recursively splits an aggregate op (load or store) into
3295 /// scalar or vector ops. It splits recursively until it hits a single value
3296 /// and emits that single value operation via the template argument.
3297 ///
3298 /// The logic of this routine relies on GEPs and insertvalue and
3299 /// extractvalue all operating with the same fundamental index list, merely
3300 /// formatted differently (GEPs need actual values).
3301 ///
3302 /// \param Ty The type being split recursively into smaller ops.
3303 /// \param Agg The aggregate value being built up or stored, depending on
3304 /// whether this is splitting a load or a store respectively.
3305 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
Tim Northover856628f2018-12-18 09:29:39 +00003306 if (Ty->isSingleValueType()) {
3307 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3308 return static_cast<Derived *>(this)->emitFunc(
3309 Ty, Agg, MinAlign(BaseAlign, Offset), Name);
3310 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003311
3312 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3313 unsigned OldSize = Indices.size();
3314 (void)OldSize;
3315 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3316 ++Idx) {
3317 assert(Indices.size() == OldSize && "Did not return to the old size");
3318 Indices.push_back(Idx);
3319 GEPIndices.push_back(IRB.getInt32(Idx));
3320 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3321 GEPIndices.pop_back();
3322 Indices.pop_back();
3323 }
3324 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003325 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003326
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003327 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3328 unsigned OldSize = Indices.size();
3329 (void)OldSize;
3330 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3331 ++Idx) {
3332 assert(Indices.size() == OldSize && "Did not return to the old size");
3333 Indices.push_back(Idx);
3334 GEPIndices.push_back(IRB.getInt32(Idx));
3335 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3336 GEPIndices.pop_back();
3337 Indices.pop_back();
3338 }
3339 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003340 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003341
3342 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003343 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003344 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003345
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003346 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003347 AAMDNodes AATags;
3348
Tim Northover856628f2018-12-18 09:29:39 +00003349 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3350 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3351 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3352 DL), AATags(AATags) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003353
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003354 /// Emit a leaf load of a single value. This is called at the leaves of the
3355 /// recursive emission to actually load values.
Tim Northover856628f2018-12-18 09:29:39 +00003356 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003357 assert(Ty->isSingleValueType());
3358 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003359 Value *GEP =
James Y Knight77160752019-02-01 20:44:47 +00003360 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
James Y Knight14359ef2019-02-01 20:44:24 +00003361 LoadInst *Load = IRB.CreateAlignedLoad(Ty, GEP, Align, Name + ".load");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003362 if (AATags)
3363 Load->setAAMetadata(AATags);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003364 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003365 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003366 }
3367 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003368
3369 bool visitLoadInst(LoadInst &LI) {
3370 assert(LI.getPointerOperand() == *U);
3371 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3372 return false;
3373
3374 // We have an aggregate being loaded, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003375 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003376 AAMDNodes AATags;
3377 LI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003378 LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags,
3379 getAdjustedAlignment(&LI, 0, DL), DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003380 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003381 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003382 LI.replaceAllUsesWith(V);
3383 LI.eraseFromParent();
3384 return true;
3385 }
3386
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003387 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Tim Northover856628f2018-12-18 09:29:39 +00003388 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3389 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3390 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3391 DL),
3392 AATags(AATags) {}
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003393 AAMDNodes AATags;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003394 /// Emit a leaf store of a single value. This is called at the leaves of the
3395 /// recursive emission to actually produce stores.
Tim Northover856628f2018-12-18 09:29:39 +00003396 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003397 assert(Ty->isSingleValueType());
3398 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003399 //
3400 // The gep and extractvalue values are factored out of the CreateStore
3401 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003402 Value *ExtractValue =
3403 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3404 Value *InBoundsGEP =
James Y Knight77160752019-02-01 20:44:47 +00003405 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
Tim Northover856628f2018-12-18 09:29:39 +00003406 StoreInst *Store =
3407 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Align);
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003408 if (AATags)
3409 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003410 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003411 }
3412 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003413
3414 bool visitStoreInst(StoreInst &SI) {
3415 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3416 return false;
3417 Value *V = SI.getValueOperand();
3418 if (V->getType()->isSingleValueType())
3419 return false;
3420
3421 // We have an aggregate being stored, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003422 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003423 AAMDNodes AATags;
3424 SI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003425 StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags,
3426 getAdjustedAlignment(&SI, 0, DL), DL);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003427 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003428 SI.eraseFromParent();
3429 return true;
3430 }
3431
3432 bool visitBitCastInst(BitCastInst &BC) {
3433 enqueueUsers(BC);
3434 return false;
3435 }
3436
Matt Arsenault282dac72019-06-14 21:38:31 +00003437 bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
3438 enqueueUsers(ASC);
3439 return false;
3440 }
3441
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003442 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3443 enqueueUsers(GEPI);
3444 return false;
3445 }
3446
3447 bool visitPHINode(PHINode &PN) {
3448 enqueueUsers(PN);
3449 return false;
3450 }
3451
3452 bool visitSelectInst(SelectInst &SI) {
3453 enqueueUsers(SI);
3454 return false;
3455 }
3456};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003457
3458} // end anonymous namespace
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003459
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003460/// Strip aggregate type wrapping.
Chandler Carruthba931992012-10-13 10:49:33 +00003461///
3462/// This removes no-op aggregate types wrapping an underlying type. It will
3463/// strip as many layers of types as it can without changing either the type
3464/// size or the allocated size.
3465static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3466 if (Ty->isSingleValueType())
3467 return Ty;
3468
3469 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3470 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3471
3472 Type *InnerTy;
3473 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3474 InnerTy = ArrTy->getElementType();
3475 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3476 const StructLayout *SL = DL.getStructLayout(STy);
3477 unsigned Index = SL->getElementContainingOffset(0);
3478 InnerTy = STy->getElementType(Index);
3479 } else {
3480 return Ty;
3481 }
3482
3483 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3484 TypeSize > DL.getTypeSizeInBits(InnerTy))
3485 return Ty;
3486
3487 return stripAggregateTypeWrapping(DL, InnerTy);
3488}
3489
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003490/// Try to find a partition of the aggregate type passed in for a given
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003491/// offset and size.
3492///
3493/// This recurses through the aggregate type and tries to compute a subtype
3494/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003495/// of an array, it will even compute a new array type for that sub-section,
3496/// and the same for structs.
3497///
3498/// Note that this routine is very strict and tries to find a partition of the
3499/// type which produces the *exact* right offset and size. It is not forgiving
3500/// when the size or offset cause either end of type-based partition to be off.
3501/// Also, this is a best-effort routine. It is reasonable to give up and not
3502/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003503static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3504 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003505 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3506 return stripAggregateTypeWrapping(DL, Ty);
3507 if (Offset > DL.getTypeAllocSize(Ty) ||
3508 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003509 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003510
3511 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003512 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003513 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003514 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003515 if (NumSkippedElements >= SeqTy->getNumElements())
3516 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003517 Offset -= NumSkippedElements * ElementSize;
3518
3519 // First check if we need to recurse.
3520 if (Offset > 0 || Size < ElementSize) {
3521 // Bail if the partition ends in a different array element.
3522 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003523 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003524 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003525 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003526 }
3527 assert(Offset == 0);
3528
3529 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003530 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003531 assert(Size > ElementSize);
3532 uint64_t NumElements = Size / ElementSize;
3533 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003534 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003535 return ArrayType::get(ElementTy, NumElements);
3536 }
3537
3538 StructType *STy = dyn_cast<StructType>(Ty);
3539 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003540 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003541
Chandler Carruth90a735d2013-07-19 07:21:28 +00003542 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003543 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003544 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003545 uint64_t EndOffset = Offset + Size;
3546 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003547 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003548
3549 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003550 Offset -= SL->getElementOffset(Index);
3551
3552 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003553 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003554 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003555 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003556
3557 // See if any partition must be contained by the element.
3558 if (Offset > 0 || Size < ElementSize) {
3559 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003560 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003561 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003562 }
3563 assert(Offset == 0);
3564
3565 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003566 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003567
3568 StructType::element_iterator EI = STy->element_begin() + Index,
3569 EE = STy->element_end();
3570 if (EndOffset < SL->getSizeInBytes()) {
3571 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3572 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003573 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003574
3575 // Don't try to form "natural" types if the elements don't line up with the
3576 // expected size.
3577 // FIXME: We could potentially recurse down through the last element in the
3578 // sub-struct to find a natural end point.
3579 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003580 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003581
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003582 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003583 EE = STy->element_begin() + EndIndex;
3584 }
3585
3586 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003587 StructType *SubTy =
3588 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003589 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003590 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003591 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003592
Chandler Carruth054a40a2012-09-14 11:08:31 +00003593 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003594}
3595
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003596/// Pre-split loads and stores to simplify rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003597///
3598/// We want to break up the splittable load+store pairs as much as
3599/// possible. This is important to do as a preprocessing step, as once we
3600/// start rewriting the accesses to partitions of the alloca we lose the
3601/// necessary information to correctly split apart paired loads and stores
3602/// which both point into this alloca. The case to consider is something like
3603/// the following:
3604///
3605/// %a = alloca [12 x i8]
3606/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3607/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3608/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3609/// %iptr1 = bitcast i8* %gep1 to i64*
3610/// %iptr2 = bitcast i8* %gep2 to i64*
3611/// %fptr1 = bitcast i8* %gep1 to float*
3612/// %fptr2 = bitcast i8* %gep2 to float*
3613/// %fptr3 = bitcast i8* %gep3 to float*
3614/// store float 0.0, float* %fptr1
3615/// store float 1.0, float* %fptr2
3616/// %v = load i64* %iptr1
3617/// store i64 %v, i64* %iptr2
3618/// %f1 = load float* %fptr2
3619/// %f2 = load float* %fptr3
3620///
3621/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3622/// promote everything so we recover the 2 SSA values that should have been
3623/// there all along.
3624///
3625/// \returns true if any changes are made.
3626bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003627 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003628
3629 // Track the loads and stores which are candidates for pre-splitting here, in
3630 // the order they first appear during the partition scan. These give stable
3631 // iteration order and a basis for tracking which loads and stores we
3632 // actually split.
3633 SmallVector<LoadInst *, 4> Loads;
3634 SmallVector<StoreInst *, 4> Stores;
3635
3636 // We need to accumulate the splits required of each load or store where we
3637 // can find them via a direct lookup. This is important to cross-check loads
3638 // and stores against each other. We also track the slice so that we can kill
3639 // all the slices that end up split.
3640 struct SplitOffsets {
3641 Slice *S;
3642 std::vector<uint64_t> Splits;
3643 };
3644 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3645
Chandler Carruth73b01642015-01-05 04:17:53 +00003646 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3647 // This is important as we also cannot pre-split stores of those loads!
3648 // FIXME: This is all pretty gross. It means that we can be more aggressive
3649 // in pre-splitting when the load feeding the store happens to come from
3650 // a separate alloca. Put another way, the effectiveness of SROA would be
3651 // decreased by a frontend which just concatenated all of its local allocas
3652 // into one big flat alloca. But defeating such patterns is exactly the job
3653 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3654 // change store pre-splitting to actually force pre-splitting of the load
3655 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3656 // maybe it would make it more principled?
3657 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3658
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003659 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003660 for (auto &P : AS.partitions()) {
3661 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003662 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003663 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3664 // If this is a load we have to track that it can't participate in any
3665 // pre-splitting. If this is a store of a load we have to track that
3666 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003667 if (auto *LI = dyn_cast<LoadInst>(I))
3668 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003669 else if (auto *SI = dyn_cast<StoreInst>(I))
3670 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3671 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003672 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003673 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003674 assert(P.endOffset() > S.beginOffset() &&
3675 "Empty or backwards partition!");
3676
3677 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003678 if (auto *LI = dyn_cast<LoadInst>(I)) {
3679 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3680
3681 // The load must be used exclusively to store into other pointers for
3682 // us to be able to arbitrarily pre-split it. The stores must also be
3683 // simple to avoid changing semantics.
3684 auto IsLoadSimplyStored = [](LoadInst *LI) {
3685 for (User *LU : LI->users()) {
3686 auto *SI = dyn_cast<StoreInst>(LU);
3687 if (!SI || !SI->isSimple())
3688 return false;
3689 }
3690 return true;
3691 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003692 if (!IsLoadSimplyStored(LI)) {
3693 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003694 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003695 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003696
3697 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003698 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3699 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3700 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003701 continue;
3702 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3703 if (!StoredLoad || !StoredLoad->isSimple())
3704 continue;
3705 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003706
Chandler Carruth994cde82015-01-01 12:01:03 +00003707 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003708 } else {
3709 // Other uses cannot be pre-split.
3710 continue;
3711 }
3712
3713 // Record the initial split.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003714 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003715 auto &Offsets = SplitOffsetsMap[I];
3716 assert(Offsets.Splits.empty() &&
3717 "Should not have splits the first time we see an instruction!");
3718 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003719 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003720 }
3721
3722 // Now scan the already split slices, and add a split for any of them which
3723 // we're going to pre-split.
3724 for (Slice *S : P.splitSliceTails()) {
3725 auto SplitOffsetsMapI =
3726 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3727 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3728 continue;
3729 auto &Offsets = SplitOffsetsMapI->second;
3730
3731 assert(Offsets.S == S && "Found a mismatched slice!");
3732 assert(!Offsets.Splits.empty() &&
3733 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003734 assert(Offsets.Splits.back() ==
3735 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003736 "Previous split does not end where this one begins!");
3737
3738 // Record each split. The last partition's end isn't needed as the size
3739 // of the slice dictates that.
3740 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003741 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003742 }
3743 }
3744
3745 // We may have split loads where some of their stores are split stores. For
3746 // such loads and stores, we can only pre-split them if their splits exactly
3747 // match relative to their starting offset. We have to verify this prior to
3748 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003749 Stores.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003750 llvm::remove_if(Stores,
3751 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3752 // Lookup the load we are storing in our map of split
3753 // offsets.
3754 auto *LI = cast<LoadInst>(SI->getValueOperand());
3755 // If it was completely unsplittable, then we're done,
3756 // and this store can't be pre-split.
3757 if (UnsplittableLoads.count(LI))
3758 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003759
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003760 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3761 if (LoadOffsetsI == SplitOffsetsMap.end())
3762 return false; // Unrelated loads are definitely safe.
3763 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003764
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003765 // Now lookup the store's offsets.
3766 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003767
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003768 // If the relative offsets of each split in the load and
3769 // store match exactly, then we can split them and we
3770 // don't need to remove them here.
3771 if (LoadOffsets.Splits == StoreOffsets.Splits)
3772 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003773
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003774 LLVM_DEBUG(
3775 dbgs()
3776 << " Mismatched splits for load and store:\n"
3777 << " " << *LI << "\n"
3778 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003779
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003780 // We've found a store and load that we need to split
3781 // with mismatched relative splits. Just give up on them
3782 // and remove both instructions from our list of
3783 // candidates.
3784 UnsplittableLoads.insert(LI);
3785 return true;
3786 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003787 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003788 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003789 // have caused an earlier store's load to become unsplittable and if it is
3790 // unsplittable for the later store, then we can't rely on it being split in
3791 // the earlier store either.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003792 Stores.erase(llvm::remove_if(Stores,
3793 [&UnsplittableLoads](StoreInst *SI) {
3794 auto *LI =
3795 cast<LoadInst>(SI->getValueOperand());
3796 return UnsplittableLoads.count(LI);
3797 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003798 Stores.end());
3799 // Once we've established all the loads that can't be split for some reason,
3800 // filter any that made it into our list out.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003801 Loads.erase(llvm::remove_if(Loads,
3802 [&UnsplittableLoads](LoadInst *LI) {
3803 return UnsplittableLoads.count(LI);
3804 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003805 Loads.end());
3806
3807 // If no loads or stores are left, there is no pre-splitting to be done for
3808 // this alloca.
3809 if (Loads.empty() && Stores.empty())
3810 return false;
3811
3812 // From here on, we can't fail and will be building new accesses, so rig up
3813 // an IR builder.
3814 IRBuilderTy IRB(&AI);
3815
3816 // Collect the new slices which we will merge into the alloca slices.
3817 SmallVector<Slice, 4> NewSlices;
3818
3819 // Track any allocas we end up splitting loads and stores for so we iterate
3820 // on them.
3821 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3822
3823 // At this point, we have collected all of the loads and stores we can
3824 // pre-split, and the specific splits needed for them. We actually do the
3825 // splitting in a specific order in order to handle when one of the loads in
3826 // the value operand to one of the stores.
3827 //
3828 // First, we rewrite all of the split loads, and just accumulate each split
3829 // load in a parallel structure. We also build the slices for them and append
3830 // them to the alloca slices.
3831 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3832 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003833 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003834 for (LoadInst *LI : Loads) {
3835 SplitLoads.clear();
3836
3837 IntegerType *Ty = cast<IntegerType>(LI->getType());
3838 uint64_t LoadSize = Ty->getBitWidth() / 8;
3839 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3840
3841 auto &Offsets = SplitOffsetsMap[LI];
3842 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3843 "Slice size should always match load size exactly!");
3844 uint64_t BaseOffset = Offsets.S->beginOffset();
3845 assert(BaseOffset + LoadSize > BaseOffset &&
3846 "Cannot represent alloca access size using 64-bit integers!");
3847
3848 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003849 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003850
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003851 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003852
3853 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3854 int Idx = 0, Size = Offsets.Splits.size();
3855 for (;;) {
3856 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003857 auto AS = LI->getPointerAddressSpace();
3858 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003859 LoadInst *PLoad = IRB.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00003860 PartTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003861 getAdjustedPtr(IRB, DL, BasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003862 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003863 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003864 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003865 LI->getName());
Michael Kruse978ba612018-12-20 04:58:07 +00003866 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3867 LLVMContext::MD_access_group});
Chandler Carruth0715cba2015-01-01 11:54:38 +00003868
3869 // Append this load onto the list of split loads so we can find it later
3870 // to rewrite the stores.
3871 SplitLoads.push_back(PLoad);
3872
3873 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003874 NewSlices.push_back(
3875 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3876 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003877 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003878 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3879 << ", " << NewSlices.back().endOffset()
3880 << "): " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003881
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003882 // See if we've handled all the splits.
3883 if (Idx >= Size)
3884 break;
3885
Chandler Carruth0715cba2015-01-01 11:54:38 +00003886 // Setup the next partition.
3887 PartOffset = Offsets.Splits[Idx];
3888 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003889 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3890 }
3891
3892 // Now that we have the split loads, do the slow walk over all uses of the
3893 // load and rewrite them as split stores, or save the split loads to use
3894 // below if the store is going to be split there anyways.
3895 bool DeferredStores = false;
3896 for (User *LU : LI->users()) {
3897 StoreInst *SI = cast<StoreInst>(LU);
3898 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3899 DeferredStores = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003900 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
3901 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003902 continue;
3903 }
3904
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003905 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003906 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003907
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003908 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003909
3910 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3911 LoadInst *PLoad = SplitLoads[Idx];
3912 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003913 auto *PartPtrTy =
3914 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003915
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003916 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003917 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003918 PLoad,
3919 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003920 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003921 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003922 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Michael Kruse978ba612018-12-20 04:58:07 +00003923 PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3924 LLVMContext::MD_access_group});
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003925 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003926 }
3927
3928 // We want to immediately iterate on any allocas impacted by splitting
3929 // this store, and we have to track any promotable alloca (indicated by
3930 // a direct store) as needing to be resplit because it is no longer
3931 // promotable.
3932 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3933 ResplitPromotableAllocas.insert(OtherAI);
3934 Worklist.insert(OtherAI);
3935 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3936 StoreBasePtr->stripInBoundsOffsets())) {
3937 Worklist.insert(OtherAI);
3938 }
3939
3940 // Mark the original store as dead.
3941 DeadInsts.insert(SI);
3942 }
3943
3944 // Save the split loads if there are deferred stores among the users.
3945 if (DeferredStores)
3946 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3947
3948 // Mark the original load as dead and kill the original slice.
3949 DeadInsts.insert(LI);
3950 Offsets.S->kill();
3951 }
3952
3953 // Second, we rewrite all of the split stores. At this point, we know that
3954 // all loads from this alloca have been split already. For stores of such
3955 // loads, we can simply look up the pre-existing split loads. For stores of
3956 // other loads, we split those loads first and then write split stores of
3957 // them.
3958 for (StoreInst *SI : Stores) {
3959 auto *LI = cast<LoadInst>(SI->getValueOperand());
3960 IntegerType *Ty = cast<IntegerType>(LI->getType());
3961 uint64_t StoreSize = Ty->getBitWidth() / 8;
3962 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3963
3964 auto &Offsets = SplitOffsetsMap[SI];
3965 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3966 "Slice size should always match load size exactly!");
3967 uint64_t BaseOffset = Offsets.S->beginOffset();
3968 assert(BaseOffset + StoreSize > BaseOffset &&
3969 "Cannot represent alloca access size using 64-bit integers!");
3970
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003971 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003972 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3973
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003974 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003975
3976 // Check whether we have an already split load.
3977 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3978 std::vector<LoadInst *> *SplitLoads = nullptr;
3979 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3980 SplitLoads = &SplitLoadsMapI->second;
3981 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3982 "Too few split loads for the number of splits in the store!");
3983 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003984 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003985 }
3986
Chandler Carruth0715cba2015-01-01 11:54:38 +00003987 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3988 int Idx = 0, Size = Offsets.Splits.size();
3989 for (;;) {
3990 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003991 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3992 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003993
3994 // Either lookup a split load or create one.
3995 LoadInst *PLoad;
3996 if (SplitLoads) {
3997 PLoad = (*SplitLoads)[Idx];
3998 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003999 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004000 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00004001 PLoad = IRB.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00004002 PartTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004003 getAdjustedPtr(IRB, DL, LoadBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00004004 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00004005 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004006 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00004007 LI->getName());
4008 }
4009
4010 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00004011 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004012 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00004013 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004014 PLoad,
4015 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00004016 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00004017 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004018 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00004019
4020 // Now build a new slice for the alloca.
4021 NewSlices.push_back(
4022 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4023 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00004024 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004025 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
4026 << ", " << NewSlices.back().endOffset()
4027 << "): " << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004028 if (!SplitLoads) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004029 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004030 }
4031
Chandler Carruth29c22fa2015-01-02 00:10:22 +00004032 // See if we've finished all the splits.
4033 if (Idx >= Size)
4034 break;
4035
Chandler Carruth0715cba2015-01-01 11:54:38 +00004036 // Setup the next partition.
4037 PartOffset = Offsets.Splits[Idx];
4038 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00004039 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
4040 }
4041
4042 // We want to immediately iterate on any allocas impacted by splitting
4043 // this load, which is only relevant if it isn't a load of this alloca and
4044 // thus we didn't already split the loads above. We also have to keep track
4045 // of any promotable allocas we split loads on as they can no longer be
4046 // promoted.
4047 if (!SplitLoads) {
4048 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
4049 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4050 ResplitPromotableAllocas.insert(OtherAI);
4051 Worklist.insert(OtherAI);
4052 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4053 LoadBasePtr->stripInBoundsOffsets())) {
4054 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4055 Worklist.insert(OtherAI);
4056 }
4057 }
4058
4059 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00004060 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004061 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00004062 // for some other alloca, but it may be a normal load. This may introduce
4063 // redundant loads, but where those can be merged the rest of the optimizer
4064 // should handle the merging, and this uncovers SSA splits which is more
4065 // important. In practice, the original loads will almost always be fully
4066 // split and removed eventually, and the splits will be merged by any
4067 // trivial CSE, including instcombine.
4068 if (LI->hasOneUse()) {
4069 assert(*LI->user_begin() == SI && "Single use isn't this store!");
4070 DeadInsts.insert(LI);
4071 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00004072 DeadInsts.insert(SI);
4073 Offsets.S->kill();
4074 }
4075
Chandler Carruth24ac8302015-01-02 03:55:54 +00004076 // Remove the killed slices that have ben pre-split.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004077 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
4078 AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00004079
Chandler Carruth24ac8302015-01-02 03:55:54 +00004080 // Insert our new slices. This will sort and merge them into the sorted
4081 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004082 AS.insert(NewSlices);
4083
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004084 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004085#ifndef NDEBUG
4086 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004087 LLVM_DEBUG(AS.print(dbgs(), I, " "));
Chandler Carruth0715cba2015-01-01 11:54:38 +00004088#endif
4089
4090 // Finally, don't try to promote any allocas that new require re-splitting.
4091 // They have already been added to the worklist above.
4092 PromotableAllocas.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004093 llvm::remove_if(
David Majnemerc7004902016-08-12 04:32:37 +00004094 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00004095 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
4096 PromotableAllocas.end());
4097
4098 return true;
4099}
4100
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004101/// Rewrite an alloca partition's users.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004102///
4103/// This routine drives both of the rewriting goals of the SROA pass. It tries
4104/// to rewrite uses of an alloca partition to be conducive for SSA value
4105/// promotion. If the partition needs a new, more refined alloca, this will
4106/// build that new alloca, preserving as much type information as possible, and
4107/// rewrite the uses of the old alloca to point at the new one and have the
4108/// appropriate new offsets. It also evaluates how successful the rewrite was
4109/// at enabling promotion and if it was successful queues the alloca to be
4110/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00004111AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00004112 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004113 // Try to compute a friendly type for this partition of the alloca. This
4114 // won't always succeed, in which case we fall back to a legal integer type
4115 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00004116 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004117 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004118 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004119 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004120 SliceTy = CommonUseTy;
4121 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004122 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004123 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004124 SliceTy = TypePartitionTy;
4125 if ((!SliceTy || (SliceTy->isArrayTy() &&
4126 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004127 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004128 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004129 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004130 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004131 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00004132
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004133 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00004134
Chandler Carruth2dc96822014-10-18 00:44:02 +00004135 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004136 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00004137 if (VecTy)
4138 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004139
4140 // Check for the case where we're going to rewrite to a new alloca of the
4141 // exact same type as the original, and with the same access offsets. In that
4142 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00004143 // perform phi and select speculation.
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004144 // P.beginOffset() can be non-zero even with the same type in a case with
4145 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004146 AllocaInst *NewAI;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004147 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004148 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00004149 // FIXME: We should be able to bail at this point with "nothing changed".
4150 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00004151 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004152 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00004153 unsigned Alignment = AI.getAlignment();
4154 if (!Alignment) {
4155 // The minimum alignment which users can rely on when the explicit
4156 // alignment is omitted or zero is that required by the ABI for this
4157 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004158 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00004159 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004160 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00004161 // If we will get at least this much alignment from the type alone, leave
4162 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004163 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00004164 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004165 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004166 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004167 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Anastasis Grammenos425df222018-06-28 18:58:30 +00004168 // Copy the old AI debug location over to the new one.
4169 NewAI->setDebugLoc(AI.getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004170 ++NumNewAllocas;
4171 }
4172
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004173 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4174 << "[" << P.beginOffset() << "," << P.endOffset()
4175 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004176
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004177 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00004178 // promoted allocas. We will reset it to this point if the alloca is not in
4179 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004180 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00004181 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00004182 SmallSetVector<PHINode *, 8> PHIUsers;
4183 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00004184
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004185 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004186 P.endOffset(), IsIntegerPromotable, VecTy,
4187 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00004188 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00004189 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004190 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004191 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004192 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004193 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004194 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004195 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004196 }
4197
Chandler Carruth6c321c12013-07-19 10:57:36 +00004198 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00004199 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004200
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004201 // Now that we've processed all the slices in the new partition, check if any
4202 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00004203 for (PHINode *PHI : PHIUsers)
4204 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004205 Promotable = false;
4206 PHIUsers.clear();
4207 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004208 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004209 }
Davide Italiano81a26da2017-04-27 23:09:01 +00004210
4211 for (SelectInst *Sel : SelectUsers)
4212 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004213 Promotable = false;
4214 PHIUsers.clear();
4215 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004216 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004217 }
4218
4219 if (Promotable) {
4220 if (PHIUsers.empty() && SelectUsers.empty()) {
4221 // Promote the alloca.
4222 PromotableAllocas.push_back(NewAI);
4223 } else {
4224 // If we have either PHIs or Selects to speculate, add them to those
4225 // worklists and re-queue the new alloca so that we promote in on the
4226 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004227 for (PHINode *PHIUser : PHIUsers)
4228 SpeculatablePHIs.insert(PHIUser);
4229 for (SelectInst *SelectUser : SelectUsers)
4230 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004231 Worklist.insert(NewAI);
4232 }
4233 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004234 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004235 while (PostPromotionWorklist.size() > PPWOldSize)
4236 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00004237
4238 // We couldn't promote and we didn't create a new partition, nothing
4239 // happened.
4240 if (NewAI == &AI)
4241 return nullptr;
4242
4243 // If we can't promote the alloca, iterate on it to check for new
4244 // refinements exposed by splitting the current alloca. Don't iterate on an
4245 // alloca which didn't actually change and didn't get promoted.
4246 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00004247 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004248
Adrian Prantl565cc182015-01-20 19:42:22 +00004249 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004250}
4251
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004252/// Walks the slices of an alloca and form partitions based on them,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004253/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004254bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4255 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004256 return false;
4257
Chandler Carruth6c321c12013-07-19 10:57:36 +00004258 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004259 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004260 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004261
Chandler Carruth24ac8302015-01-02 03:55:54 +00004262 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004263 Changed |= presplitLoadsAndStores(AI, AS);
4264
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004265 // Now that we have identified any pre-splitting opportunities,
4266 // mark loads and stores unsplittable except for the following case.
4267 // We leave a slice splittable if all other slices are disjoint or fully
4268 // included in the slice, such as whole-alloca loads and stores.
4269 // If we fail to split these during pre-splitting, we want to force them
4270 // to be rewritten into a partition.
Chandler Carruth24ac8302015-01-02 03:55:54 +00004271 bool IsSorted = true;
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004272
4273 uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType());
4274 const uint64_t MaxBitVectorSize = 1024;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004275 if (AllocaSize <= MaxBitVectorSize) {
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004276 // If a byte boundary is included in any load or store, a slice starting or
4277 // ending at the boundary is not splittable.
4278 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4279 for (Slice &S : AS)
4280 for (unsigned O = S.beginOffset() + 1;
4281 O < S.endOffset() && O < AllocaSize; O++)
4282 SplittableOffset.reset(O);
4283
4284 for (Slice &S : AS) {
4285 if (!S.isSplittable())
4286 continue;
4287
4288 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4289 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4290 continue;
4291
4292 if (isa<LoadInst>(S.getUse()->getUser()) ||
4293 isa<StoreInst>(S.getUse()->getUser())) {
4294 S.makeUnsplittable();
4295 IsSorted = false;
4296 }
Chandler Carruth24ac8302015-01-02 03:55:54 +00004297 }
4298 }
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004299 else {
4300 // We only allow whole-alloca splittable loads and stores
4301 // for a large alloca to avoid creating too large BitVector.
4302 for (Slice &S : AS) {
4303 if (!S.isSplittable())
4304 continue;
4305
4306 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4307 continue;
4308
4309 if (isa<LoadInst>(S.getUse()->getUser()) ||
4310 isa<StoreInst>(S.getUse()->getUser())) {
4311 S.makeUnsplittable();
4312 IsSorted = false;
4313 }
4314 }
4315 }
4316
Chandler Carruth24ac8302015-01-02 03:55:54 +00004317 if (!IsSorted)
Fangrui Song0cac7262018-09-27 02:13:45 +00004318 llvm::sort(AS);
Chandler Carruth24ac8302015-01-02 03:55:54 +00004319
Adrian Prantl941fa752016-12-05 18:04:47 +00004320 /// Describes the allocas introduced by rewritePartition in order to migrate
4321 /// the debug info.
4322 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004323 AllocaInst *Alloca;
4324 uint64_t Offset;
4325 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004326 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004327 : Alloca(AI), Offset(O), Size(S) {}
4328 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004329 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004330
Chandler Carruth0715cba2015-01-01 11:54:38 +00004331 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004332 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004333 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4334 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004335 if (NewAI != &AI) {
4336 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004337 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004338 // Don't include any padding.
4339 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004340 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004341 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004342 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004343 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004344 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004345
Chandler Carruth6c321c12013-07-19 10:57:36 +00004346 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004347 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004348
Adrian Prantl565cc182015-01-20 19:42:22 +00004349 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004350 // and the individual partitions.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004351 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004352 if (!DbgDeclares.empty()) {
4353 auto *Var = DbgDeclares.front()->getVariable();
4354 auto *Expr = DbgDeclares.front()->getExpression();
Adrian Prantld7f6f162017-11-28 00:57:53 +00004355 auto VarSize = Var->getSizeInBits();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004356 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004357 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004358 for (auto Fragment : Fragments) {
4359 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004360 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004361 auto *FragmentExpr = Expr;
4362 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004363 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004364 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004365 auto ExprFragment = Expr->getFragmentInfo();
4366 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004367 uint64_t Start = Offset + Fragment.Offset;
4368 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004369 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004370 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004371 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004372 if (Start >= AbsEnd)
4373 // No need to describe a SROAed padding.
4374 continue;
4375 Size = std::min(Size, AbsEnd - Start);
4376 }
Adrian Prantlb192b542017-08-30 20:04:17 +00004377 // The new, smaller fragment is stenciled out from the old fragment.
4378 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4379 assert(Start >= OrigFragment->OffsetInBits &&
4380 "new fragment is outside of original fragment");
4381 Start -= OrigFragment->OffsetInBits;
4382 }
Adrian Prantl77d90b02017-11-28 21:30:38 +00004383
4384 // The alloca may be larger than the variable.
4385 if (VarSize) {
4386 if (Size > *VarSize)
4387 Size = *VarSize;
4388 if (Size == 0 || Start + Size > *VarSize)
4389 continue;
4390 }
4391
Adrian Prantld7f6f162017-11-28 00:57:53 +00004392 // Avoid creating a fragment expression that covers the entire variable.
4393 if (!VarSize || *VarSize != Size) {
4394 if (auto E =
4395 DIExpression::createFragmentExpression(Expr, Start, Size))
4396 FragmentExpr = *E;
4397 else
4398 continue;
4399 }
Adrian Prantl152ac392015-02-01 00:58:04 +00004400 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004401
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004402 // Remove any existing intrinsics describing the same alloca.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004403 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004404 OldDII->eraseFromParent();
Adrian Prantl565cc182015-01-20 19:42:22 +00004405
Adrian Prantl941fa752016-12-05 18:04:47 +00004406 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004407 DbgDeclares.front()->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004408 }
4409 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004410 return Changed;
4411}
4412
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004413/// Clobber a use with undef, deleting the used value if it becomes dead.
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004414void SROA::clobberUse(Use &U) {
4415 Value *OldV = U;
4416 // Replace the use with an undef value.
4417 U = UndefValue::get(OldV->getType());
4418
4419 // Check for this making an instruction dead. We have to garbage collect
4420 // all the dead instructions to ensure the uses of any alloca end up being
4421 // minimal.
4422 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4423 if (isInstructionTriviallyDead(OldI)) {
4424 DeadInsts.insert(OldI);
4425 }
4426}
4427
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004428/// Analyze an alloca for SROA.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004429///
4430/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004431/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004432/// rewritten as needed.
4433bool SROA::runOnAlloca(AllocaInst &AI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004434 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004435 ++NumAllocasAnalyzed;
4436
4437 // Special case dead allocas, as they're trivial.
4438 if (AI.use_empty()) {
4439 AI.eraseFromParent();
4440 return true;
4441 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004442 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004443
4444 // Skip alloca forms that this analysis can't handle.
4445 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004446 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004447 return false;
4448
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004449 bool Changed = false;
4450
4451 // First, split any FCA loads and stores touching this alloca to promote
4452 // better splitting and promotion opportunities.
Tim Northover856628f2018-12-18 09:29:39 +00004453 AggLoadStoreRewriter AggRewriter(DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004454 Changed |= AggRewriter.rewrite(AI);
4455
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004456 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004457 AllocaSlices AS(DL, AI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004458 LLVM_DEBUG(AS.print(dbgs()));
Chandler Carruth83934062014-10-16 21:11:55 +00004459 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004460 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004461
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004462 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004463 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004464 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004465 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004466 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004467
4468 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004469 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004470
4471 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004472 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004473 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004474 }
Chandler Carruth83934062014-10-16 21:11:55 +00004475 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004476 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004477 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004478 }
4479
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004480 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004481 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004482 return Changed;
4483
Chandler Carruth83934062014-10-16 21:11:55 +00004484 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004485
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004486 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004487 while (!SpeculatablePHIs.empty())
4488 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4489
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004490 LLVM_DEBUG(dbgs() << " Speculating Selects\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004491 while (!SpeculatableSelects.empty())
4492 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4493
4494 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004495}
4496
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004497/// Delete the dead instructions accumulated in this run.
Chandler Carruth19450da2012-09-14 10:26:38 +00004498///
4499/// Recursively deletes the dead instructions we've accumulated. This is done
4500/// at the very end to maximize locality of the recursive delete and to
4501/// minimize the problems of invalidated instruction pointers as such pointers
4502/// are used heavily in the intermediate stages of the algorithm.
4503///
4504/// We also record the alloca instructions deleted here so that they aren't
4505/// subsequently handed to mem2reg to promote.
Teresa Johnson33090022017-11-20 18:33:38 +00004506bool SROA::deleteDeadInstructions(
Chandler Carruth113dc642014-12-20 02:39:18 +00004507 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Teresa Johnson33090022017-11-20 18:33:38 +00004508 bool Changed = false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004509 while (!DeadInsts.empty()) {
4510 Instruction *I = DeadInsts.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004511 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004512
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004513 // If the instruction is an alloca, find the possible dbg.declare connected
4514 // to it, and remove it too. We must do this before calling RAUW or we will
4515 // not be able to find it.
4516 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4517 DeletedAllocas.insert(AI);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004518 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004519 OldDII->eraseFromParent();
4520 }
4521
Chandler Carruth58d05562012-10-25 04:37:07 +00004522 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4523
Chandler Carruth1583e992014-03-03 10:42:58 +00004524 for (Use &Operand : I->operands())
4525 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004526 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004527 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004528 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004529 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004530 }
4531
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004532 ++NumDeleted;
4533 I->eraseFromParent();
Teresa Johnson33090022017-11-20 18:33:38 +00004534 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004535 }
Teresa Johnson33090022017-11-20 18:33:38 +00004536 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004537}
4538
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004539/// Promote the allocas, using the best available technique.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004540///
4541/// This attempts to promote whatever allocas have been identified as viable in
4542/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004543/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004544bool SROA::promoteAllocas(Function &F) {
4545 if (PromotableAllocas.empty())
4546 return false;
4547
4548 NumPromoted += PromotableAllocas.size();
4549
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004550 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004551 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004552 PromotableAllocas.clear();
4553 return true;
4554}
4555
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004556PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4557 AssumptionCache &RunAC) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004558 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004559 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004560 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004561 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004562
4563 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004564 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004565 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004566 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4567 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004568 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004569
4570 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004571 // A set of deleted alloca instruction pointers which should be removed from
4572 // the list of promotable allocas.
4573 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4574
Chandler Carruthac8317f2012-10-04 12:33:50 +00004575 do {
4576 while (!Worklist.empty()) {
4577 Changed |= runOnAlloca(*Worklist.pop_back_val());
Teresa Johnson33090022017-11-20 18:33:38 +00004578 Changed |= deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004579
Chandler Carruthac8317f2012-10-04 12:33:50 +00004580 // Remove the deleted allocas from various lists so that we don't try to
4581 // continue processing them.
4582 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004583 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004584 Worklist.remove_if(IsInSet);
4585 PostPromotionWorklist.remove_if(IsInSet);
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004586 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004587 PromotableAllocas.end());
4588 DeletedAllocas.clear();
4589 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004590 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004591
Chandler Carruthac8317f2012-10-04 12:33:50 +00004592 Changed |= promoteAllocas(F);
4593
4594 Worklist = PostPromotionWorklist;
4595 PostPromotionWorklist.clear();
4596 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004597
Davide Italiano16e96d42016-06-07 13:21:17 +00004598 if (!Changed)
4599 return PreservedAnalyses::all();
4600
Davide Italiano16e96d42016-06-07 13:21:17 +00004601 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004602 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004603 PA.preserve<GlobalsAA>();
4604 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004605}
4606
Sean Silva36e0d012016-08-09 00:28:15 +00004607PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004608 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4609 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004610}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004611
4612/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4613///
4614/// This is in the llvm namespace purely to allow it to be a friend of the \c
4615/// SROA pass.
4616class llvm::sroa::SROALegacyPass : public FunctionPass {
4617 /// The SROA implementation.
4618 SROA Impl;
4619
4620public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004621 static char ID;
4622
Chandler Carruth29a18a42015-09-12 09:09:14 +00004623 SROALegacyPass() : FunctionPass(ID) {
4624 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4625 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004626
Chandler Carruth29a18a42015-09-12 09:09:14 +00004627 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004628 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004629 return false;
4630
4631 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004632 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4633 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004634 return !PA.areAllPreserved();
4635 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004636
Chandler Carruth29a18a42015-09-12 09:09:14 +00004637 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004638 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004639 AU.addRequired<DominatorTreeWrapperPass>();
4640 AU.addPreserved<GlobalsAAWrapperPass>();
4641 AU.setPreservesCFG();
4642 }
4643
Mehdi Amini117296c2016-10-01 02:56:57 +00004644 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004645};
4646
4647char SROALegacyPass::ID = 0;
4648
4649FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4650
4651INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4652 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004653INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004654INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4655INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4656 false, false)