blob: 790a16d2aff770b8f8535949ae318897fee27aca [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
716 void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
717 if (GEPI.use_empty())
718 return markAsDead(GEPI);
719
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000720 if (SROAStrictInbounds && GEPI.isInBounds()) {
721 // FIXME: This is a manually un-factored variant of the basic code inside
722 // of GEPs with checking of the inbounds invariant specified in the
723 // langref in a very strict sense. If we ever want to enable
724 // SROAStrictInbounds, this code should be factored cleanly into
725 // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
Hal Finkel5c83a092016-03-28 11:23:21 +0000726 // by writing out the code here where we have the underlying allocation
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000727 // size readily available.
728 APInt GEPOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000729 const DataLayout &DL = GEPI.getModule()->getDataLayout();
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000730 for (gep_type_iterator GTI = gep_type_begin(GEPI),
731 GTE = gep_type_end(GEPI);
732 GTI != GTE; ++GTI) {
733 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
734 if (!OpC)
735 break;
736
737 // Handle a struct index, which adds its field offset to the pointer.
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000738 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000739 unsigned ElementIdx = OpC->getZExtValue();
740 const StructLayout *SL = DL.getStructLayout(STy);
741 GEPOffset +=
742 APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
743 } else {
Chandler Carruth113dc642014-12-20 02:39:18 +0000744 // For array or vector indices, scale the index by the size of the
745 // type.
Chandler Carruth3b79b2a2014-02-25 21:24:45 +0000746 APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
747 GEPOffset += Index * APInt(Offset.getBitWidth(),
748 DL.getTypeAllocSize(GTI.getIndexedType()));
749 }
750
751 // If this index has computed an intermediate pointer which is not
752 // inbounds, then the result of the GEP is a poison value and we can
753 // delete it and all uses.
754 if (GEPOffset.ugt(AllocSize))
755 return markAsDead(GEPI);
756 }
757 }
758
Chandler Carruthf0546402013-07-18 07:15:00 +0000759 return Base::visitGetElementPtrInst(GEPI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000760 }
761
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000762 void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000763 uint64_t Size, bool IsVolatile) {
Chandler Carruth24ac8302015-01-02 03:55:54 +0000764 // We allow splitting of non-volatile loads and stores where the type is an
765 // integer type. These may be used to implement 'memcpy' or other "transfer
766 // of bits" patterns.
767 bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
Chandler Carruth58d05562012-10-25 04:37:07 +0000768
769 insertUse(I, Offset, Size, IsSplittable);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000770 }
771
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000772 void visitLoadInst(LoadInst &LI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000773 assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
774 "All simple FCA loads should have been pre-split");
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000775
776 if (!IsOffsetKnown)
777 return PI.setAborted(&LI);
778
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000779 const DataLayout &DL = LI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000780 uint64_t Size = DL.getTypeStoreSize(LI.getType());
781 return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000782 }
783
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000784 void visitStoreInst(StoreInst &SI) {
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000785 Value *ValOp = SI.getValueOperand();
786 if (ValOp == *U)
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000787 return PI.setEscapedAndAborted(&SI);
788 if (!IsOffsetKnown)
789 return PI.setAborted(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000790
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000791 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000792 uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
793
794 // If this memory access can be shown to *statically* extend outside the
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000795 // bounds of the allocation, it's behavior is undefined, so simply
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000796 // ignore it. Note that this is more strict than the generic clamping
797 // behavior of insertUse. We also try to handle cases which might run the
798 // risk of overflow.
799 // FIXME: We should instead consider the pointer to have escaped if this
800 // function is being instrumented for addressing bugs or race conditions.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000801 if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000802 LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
803 << Offset << " which extends past the end of the "
804 << AllocSize << " byte alloca:\n"
805 << " alloca: " << AS.AI << "\n"
806 << " use: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +0000807 return markAsDead(SI);
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000808 }
809
Chandler Carruth42cb9cb2012-09-18 12:57:43 +0000810 assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
811 "All simple FCA stores should have been pre-split");
Chandler Carrutha1c54bb2013-03-14 11:32:24 +0000812 handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000813 }
814
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000815 void visitMemSetInst(MemSetInst &II) {
Chandler Carruthb0de6dd2012-09-14 10:26:34 +0000816 assert(II.getRawDest() == *U && "Pointer use is not the destination?");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000817 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000818 if ((Length && Length->getValue() == 0) ||
Chandler Carruth6aedc102014-02-26 03:14:14 +0000819 (IsOffsetKnown && Offset.uge(AllocSize)))
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000820 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000821 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000822
823 if (!IsOffsetKnown)
824 return PI.setAborted(&II);
825
Chandler Carruth113dc642014-12-20 02:39:18 +0000826 insertUse(II, Offset, Length ? Length->getLimitedValue()
827 : AllocSize - Offset.getLimitedValue(),
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000828 (bool)Length);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000829 }
830
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000831 void visitMemTransferInst(MemTransferInst &II) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000832 ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000833 if (Length && Length->getValue() == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000834 // Zero-length mem transfer intrinsics can be ignored entirely.
Chandler Carruthf0546402013-07-18 07:15:00 +0000835 return markAsDead(II);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000836
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000837 // Because we can visit these intrinsics twice, also check to see if the
838 // first time marked this instruction as dead. If so, skip it.
839 if (VisitedDeadInsts.count(&II))
840 return;
841
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000842 if (!IsOffsetKnown)
843 return PI.setAborted(&II);
844
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000845 // This side of the transfer is completely out-of-bounds, and so we can
846 // nuke the entire transfer. However, we also need to nuke the other side
847 // if already added to our partitions.
848 // FIXME: Yet another place we really should bypass this when
849 // instrumenting for ASan.
Chandler Carruth6aedc102014-02-26 03:14:14 +0000850 if (Offset.uge(AllocSize)) {
Chandler Carruth113dc642014-12-20 02:39:18 +0000851 SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
852 MemTransferSliceMap.find(&II);
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000853 if (MTPI != MemTransferSliceMap.end())
Chandler Carruth83934062014-10-16 21:11:55 +0000854 AS.Slices[MTPI->second].kill();
Chandler Carruth1bf38c62014-01-19 12:16:54 +0000855 return markAsDead(II);
856 }
857
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000858 uint64_t RawOffset = Offset.getLimitedValue();
Chandler Carruth113dc642014-12-20 02:39:18 +0000859 uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000860
Chandler Carruthf0546402013-07-18 07:15:00 +0000861 // Check for the special case where the same exact value is used for both
862 // source and dest.
863 if (*U == II.getRawDest() && *U == II.getRawSource()) {
864 // For non-volatile transfers this is a no-op.
865 if (!II.isVolatile())
866 return markAsDead(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000867
Nick Lewycky6ab9d932013-07-22 23:38:27 +0000868 return insertUse(II, Offset, Size, /*IsSplittable=*/false);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000869 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000870
Chandler Carruthf0546402013-07-18 07:15:00 +0000871 // If we have seen both source and destination for a mem transfer, then
872 // they both point to the same alloca.
873 bool Inserted;
874 SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000875 std::tie(MTPI, Inserted) =
Chandler Carruth83934062014-10-16 21:11:55 +0000876 MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
Chandler Carruthf0546402013-07-18 07:15:00 +0000877 unsigned PrevIdx = MTPI->second;
878 if (!Inserted) {
Chandler Carruth83934062014-10-16 21:11:55 +0000879 Slice &PrevP = AS.Slices[PrevIdx];
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000880
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000881 // Check if the begin offsets match and this is a non-volatile transfer.
882 // In that case, we can completely elide the transfer.
Chandler Carruthf0546402013-07-18 07:15:00 +0000883 if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
884 PrevP.kill();
885 return markAsDead(II);
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000886 }
887
888 // Otherwise we have an offset transfer within the same alloca. We can't
889 // split those.
Chandler Carruthf0546402013-07-18 07:15:00 +0000890 PrevP.makeUnsplittable();
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +0000891 }
892
Chandler Carruthe3899f22013-07-15 17:36:21 +0000893 // Insert the use now that we've fixed up the splittable nature.
Chandler Carruthf0546402013-07-18 07:15:00 +0000894 insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
Chandler Carruthe3899f22013-07-15 17:36:21 +0000895
Chandler Carruthf0546402013-07-18 07:15:00 +0000896 // Check that we ended up with a valid index in the map.
Chandler Carruth83934062014-10-16 21:11:55 +0000897 assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000898 "Map index doesn't point back to a slice with this user.");
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000899 }
900
901 // Disable SRoA for any intrinsics except for lifetime invariants.
Jakub Staszak086f6cd2013-02-19 22:02:21 +0000902 // FIXME: What about debug intrinsics? This matches old behavior, but
Chandler Carruth4b40e002012-09-14 10:26:36 +0000903 // doesn't make sense.
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000904 void visitIntrinsicInst(IntrinsicInst &II) {
905 if (!IsOffsetKnown)
906 return PI.setAborted(&II);
907
Vedant Kumarb264d692018-12-21 21:49:40 +0000908 if (II.isLifetimeStartOrEnd()) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000909 ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000910 uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
911 Length->getLimitedValue());
Chandler Carruth97121172012-09-16 19:39:50 +0000912 insertUse(II, Offset, Size, true);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000913 return;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000914 }
915
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000916 Base::visitIntrinsicInst(II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000917 }
918
919 Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
920 // We consider any PHI or select that results in a direct load or store of
Chandler Carruth9f21fe12013-07-19 09:13:58 +0000921 // the same offset to be a viable use for slicing purposes. These uses
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000922 // are considered unsplittable and the size is the maximum loaded or stored
923 // size.
924 SmallPtrSet<Instruction *, 4> Visited;
925 SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
926 Visited.insert(Root);
927 Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000928 const DataLayout &DL = Root->getModule()->getDataLayout();
Chandler Carruth8b907e82012-09-25 10:03:40 +0000929 // If there are no loads or stores, the access is dead. We mark that as
930 // a size zero access.
931 Size = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000932 do {
933 Instruction *I, *UsedI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000934 std::tie(UsedI, I) = Uses.pop_back_val();
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000935
936 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000937 Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000938 continue;
939 }
940 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
941 Value *Op = SI->getOperand(0);
942 if (Op == UsedI)
943 return SI;
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000944 Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000945 continue;
946 }
947
948 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
949 if (!GEP->hasAllZeroIndices())
950 return GEP;
951 } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
952 !isa<SelectInst>(I)) {
953 return I;
954 }
955
Chandler Carruthcdf47882014-03-09 03:16:01 +0000956 for (User *U : I->users())
David Blaikie70573dc2014-11-19 07:49:26 +0000957 if (Visited.insert(cast<Instruction>(U)).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000958 Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000959 } while (!Uses.empty());
960
Craig Topperf40110f2014-04-25 05:29:35 +0000961 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000962 }
963
Jingyue Wuec33fa92014-08-22 22:45:57 +0000964 void visitPHINodeOrSelectInst(Instruction &I) {
965 assert(isa<PHINode>(I) || isa<SelectInst>(I));
966 if (I.use_empty())
967 return markAsDead(I);
Chandler Carruthe41e7b72012-12-10 08:28:39 +0000968
Jingyue Wuec33fa92014-08-22 22:45:57 +0000969 // TODO: We could use SimplifyInstruction here to fold PHINodes and
970 // SelectInsts. However, doing so requires to change the current
971 // dead-operand-tracking mechanism. For instance, suppose neither loading
972 // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
973 // trap either. However, if we simply replace %U with undef using the
974 // current dead-operand-tracking mechanism, "load (select undef, undef,
975 // %other)" may trap because the select may return the first operand
976 // "undef".
977 if (Value *Result = foldPHINodeOrSelectInst(I)) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000978 if (Result == *U)
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000979 // If the result of the constant fold will be the pointer, recurse
Jingyue Wuec33fa92014-08-22 22:45:57 +0000980 // through the PHI/select as if we had RAUW'ed it.
981 enqueueUsers(I);
Nick Lewyckyc7776f72013-08-13 22:51:58 +0000982 else
Jingyue Wuec33fa92014-08-22 22:45:57 +0000983 // Otherwise the operand to the PHI/select is dead, and we can replace
984 // it with undef.
Chandler Carruth83934062014-10-16 21:11:55 +0000985 AS.DeadOperands.push_back(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000986
987 return;
988 }
Jingyue Wuec33fa92014-08-22 22:45:57 +0000989
Chandler Carruthf0546402013-07-18 07:15:00 +0000990 if (!IsOffsetKnown)
Jingyue Wuec33fa92014-08-22 22:45:57 +0000991 return PI.setAborted(&I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +0000992
Chandler Carruthf0546402013-07-18 07:15:00 +0000993 // See if we already have computed info on this node.
Jingyue Wuec33fa92014-08-22 22:45:57 +0000994 uint64_t &Size = PHIOrSelectSizes[&I];
995 if (!Size) {
996 // This is a new PHI/Select, check for an unsafe use of it.
997 if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
Chandler Carruthf0546402013-07-18 07:15:00 +0000998 return PI.setAborted(UnsafeI);
999 }
1000
1001 // For PHI and select operands outside the alloca, we can't nuke the entire
1002 // phi or select -- the other side might still be relevant, so we special
1003 // case them here and use a separate structure to track the operands
1004 // themselves which should be replaced with undef.
1005 // FIXME: This should instead be escaped in the event we're instrumenting
1006 // for address sanitization.
Chandler Carruth6aedc102014-02-26 03:14:14 +00001007 if (Offset.uge(AllocSize)) {
Chandler Carruth83934062014-10-16 21:11:55 +00001008 AS.DeadOperands.push_back(U);
Chandler Carruthf0546402013-07-18 07:15:00 +00001009 return;
1010 }
1011
Jingyue Wuec33fa92014-08-22 22:45:57 +00001012 insertUse(I, Offset, Size);
1013 }
1014
Chandler Carruth113dc642014-12-20 02:39:18 +00001015 void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
Jingyue Wuec33fa92014-08-22 22:45:57 +00001016
Chandler Carruth113dc642014-12-20 02:39:18 +00001017 void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001018
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001019 /// Disable SROA entirely if there are unhandled users of the alloca.
Chandler Carruth113dc642014-12-20 02:39:18 +00001020 void visitInstruction(Instruction &I) { PI.setAborted(&I); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001021};
1022
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001023AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001024 :
Aaron Ballman615eb472017-10-15 14:32:27 +00001025#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001026 AI(AI),
1027#endif
Craig Topperf40110f2014-04-25 05:29:35 +00001028 PointerEscapingInstr(nullptr) {
Nick Lewyckyc7776f72013-08-13 22:51:58 +00001029 SliceBuilder PB(DL, AI, *this);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001030 SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001031 if (PtrI.isEscaped() || PtrI.isAborted()) {
1032 // FIXME: We should sink the escape vs. abort info into the caller nicely,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001033 // possibly by just storing the PtrInfo in the AllocaSlices.
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001034 PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
1035 : PtrI.getAbortingInst();
1036 assert(PointerEscapingInstr && "Did not track a bad instruction");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001037 return;
Chandler Carruthe41e7b72012-12-10 08:28:39 +00001038 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001039
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001040 Slices.erase(
1041 llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1042 Slices.end());
Benjamin Kramer08e50702013-07-20 08:38:34 +00001043
Hal Finkel29f51312016-03-28 11:13:03 +00001044#ifndef NDEBUG
Chandler Carruth83cee772014-02-25 03:59:29 +00001045 if (SROARandomShuffleSlices) {
Pavel Labathc207bec2016-11-09 12:07:12 +00001046 std::mt19937 MT(static_cast<unsigned>(
1047 std::chrono::system_clock::now().time_since_epoch().count()));
Chandler Carruth83cee772014-02-25 03:59:29 +00001048 std::shuffle(Slices.begin(), Slices.end(), MT);
1049 }
1050#endif
1051
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00001052 // Sort the uses. This arranges for the offsets to be in ascending order,
1053 // and the sizes to be in descending order.
Fangrui Song0cac7262018-09-27 02:13:45 +00001054 llvm::sort(Slices);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001055}
1056
Aaron Ballman615eb472017-10-15 14:32:27 +00001057#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001058
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001059void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1060 StringRef Indent) const {
1061 printSlice(OS, I, Indent);
Chandler Carruth0715cba2015-01-01 11:54:38 +00001062 OS << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001063 printUse(OS, I, Indent);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001064}
1065
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001066void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1067 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001068 OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001069 << " slice #" << (I - begin())
Chandler Carruth0715cba2015-01-01 11:54:38 +00001070 << (I->isSplittable() ? " (splittable)" : "");
Chandler Carruthf0546402013-07-18 07:15:00 +00001071}
1072
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001073void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1074 StringRef Indent) const {
Chandler Carruthf0546402013-07-18 07:15:00 +00001075 OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001076}
1077
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001078void AllocaSlices::print(raw_ostream &OS) const {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001079 if (PointerEscapingInstr) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001080 OS << "Can't analyze slices for alloca: " << AI << "\n"
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001081 << " A pointer to this alloca escaped by:\n"
1082 << " " << *PointerEscapingInstr << "\n";
1083 return;
1084 }
1085
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001086 OS << "Slices of alloca: " << AI << "\n";
Chandler Carruthf0546402013-07-18 07:15:00 +00001087 for (const_iterator I = begin(), E = end(); I != E; ++I)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001088 print(OS, I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001089}
1090
Alp Tokerf929e092014-01-04 22:47:48 +00001091LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1092 print(dbgs(), I);
1093}
1094LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001095
Aaron Ballman615eb472017-10-15 14:32:27 +00001096#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruth25fb23d2012-09-14 10:18:51 +00001097
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001098/// Walk the range of a partitioning looking for a common type to cover this
1099/// sequence of slices.
1100static Type *findCommonType(AllocaSlices::const_iterator B,
1101 AllocaSlices::const_iterator E,
Chandler Carruthf0546402013-07-18 07:15:00 +00001102 uint64_t EndOffset) {
Craig Topperf40110f2014-04-25 05:29:35 +00001103 Type *Ty = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001104 bool TyIsCommon = true;
Craig Topperf40110f2014-04-25 05:29:35 +00001105 IntegerType *ITy = nullptr;
Chandler Carruth4de31542014-01-21 23:16:05 +00001106
1107 // Note that we need to look at *every* alloca slice's Use to ensure we
1108 // always get consistent results regardless of the order of slices.
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001109 for (AllocaSlices::const_iterator I = B; I != E; ++I) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001110 Use *U = I->getUse();
1111 if (isa<IntrinsicInst>(*U->getUser()))
1112 continue;
1113 if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
1114 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001115
Craig Topperf40110f2014-04-25 05:29:35 +00001116 Type *UserTy = nullptr;
Chandler Carrutha1262002013-11-19 09:03:18 +00001117 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001118 UserTy = LI->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001119 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001120 UserTy = SI->getValueOperand()->getType();
Chandler Carrutha1262002013-11-19 09:03:18 +00001121 }
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001122
Chandler Carruth4de31542014-01-21 23:16:05 +00001123 if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001124 // If the type is larger than the partition, skip it. We only encounter
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001125 // this for split integer operations where we want to use the type of the
Chandler Carrutha1262002013-11-19 09:03:18 +00001126 // entity causing the split. Also skip if the type is not a byte width
1127 // multiple.
Chandler Carruth4de31542014-01-21 23:16:05 +00001128 if (UserITy->getBitWidth() % 8 != 0 ||
1129 UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
Chandler Carruthf0546402013-07-18 07:15:00 +00001130 continue;
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001131
Chandler Carruth4de31542014-01-21 23:16:05 +00001132 // Track the largest bitwidth integer type used in this way in case there
1133 // is no common type.
1134 if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
1135 ITy = UserITy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001136 }
Duncan P. N. Exon Smith73686d32014-06-17 00:19:35 +00001137
1138 // To avoid depending on the order of slices, Ty and TyIsCommon must not
1139 // depend on types skipped above.
1140 if (!UserTy || (Ty && Ty != UserTy))
1141 TyIsCommon = false; // Give up on anything but an iN type.
1142 else
1143 Ty = UserTy;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001144 }
Chandler Carruth4de31542014-01-21 23:16:05 +00001145
1146 return TyIsCommon ? Ty : ITy;
Chandler Carruthf0546402013-07-18 07:15:00 +00001147}
Chandler Carruthe3899f22013-07-15 17:36:21 +00001148
Chandler Carruthf0546402013-07-18 07:15:00 +00001149/// PHI instructions that use an alloca and are subsequently loaded can be
1150/// rewritten to load both input pointers in the pred blocks and then PHI the
1151/// results, allowing the load of the alloca to be promoted.
1152/// From this:
1153/// %P2 = phi [i32* %Alloca, i32* %Other]
1154/// %V = load i32* %P2
1155/// to:
1156/// %V1 = load i32* %Alloca -> will be mem2reg'd
1157/// ...
1158/// %V2 = load i32* %Other
1159/// ...
1160/// %V = phi [i32 %V1, i32 %V2]
1161///
1162/// We can do this to a select if its only uses are loads and if the operands
1163/// to the select can be loaded unconditionally.
1164///
1165/// FIXME: This should be hoisted into a generic utility, likely in
1166/// Transforms/Util/Local.h
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001167static bool isSafePHIToSpeculate(PHINode &PN) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001168 // For now, we can only do this promotion if the load is in the same block
1169 // as the PHI, and if there are no stores between the phi and load.
1170 // TODO: Allow recursive phi users.
1171 // TODO: Allow stores.
1172 BasicBlock *BB = PN.getParent();
1173 unsigned MaxAlign = 0;
1174 bool HaveLoad = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001175 for (User *U : PN.users()) {
1176 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001177 if (!LI || !LI->isSimple())
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001178 return false;
Chandler Carruthe74ff4c2013-07-15 10:30:19 +00001179
Chandler Carruthf0546402013-07-18 07:15:00 +00001180 // For now we only allow loads in the same block as the PHI. This is
1181 // a common case that happens when instcombine merges two loads through
1182 // a PHI.
1183 if (LI->getParent() != BB)
1184 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001185
Chandler Carruthf0546402013-07-18 07:15:00 +00001186 // Ensure that there are no instructions between the PHI and the load that
1187 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001188 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chandler Carruthf0546402013-07-18 07:15:00 +00001189 if (BBI->mayWriteToMemory())
Chandler Carruthe3899f22013-07-15 17:36:21 +00001190 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001191
Chandler Carruthf0546402013-07-18 07:15:00 +00001192 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1193 HaveLoad = true;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001194 }
1195
Chandler Carruthf0546402013-07-18 07:15:00 +00001196 if (!HaveLoad)
1197 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001198
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001199 const DataLayout &DL = PN.getModule()->getDataLayout();
1200
Chandler Carruthf0546402013-07-18 07:15:00 +00001201 // We can only transform this if it is safe to push the loads into the
1202 // predecessor blocks. The only thing to watch out for is that we can't put
1203 // a possibly trapping load in the predecessor if it is a critical edge.
1204 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
Chandler Carruthedb12a82018-10-15 10:04:59 +00001205 Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001206 Value *InVal = PN.getIncomingValue(Idx);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001207
Chandler Carruthf0546402013-07-18 07:15:00 +00001208 // If the value is produced by the terminator of the predecessor (an
1209 // invoke) or it has side-effects, there is no valid place to put a load
1210 // in the predecessor.
1211 if (TI == InVal || TI->mayHaveSideEffects())
1212 return false;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001213
Chandler Carruthf0546402013-07-18 07:15:00 +00001214 // If the predecessor has a single successor, then the edge isn't
1215 // critical.
1216 if (TI->getNumSuccessors() == 1)
1217 continue;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001218
Chandler Carruthf0546402013-07-18 07:15:00 +00001219 // If this pointer is always safe to load, or if we can prove that there
1220 // is already a load in the block, then we can move the load to the pred
1221 // block.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001222 if (isSafeToLoadUnconditionally(InVal, MaxAlign, DL, TI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001223 continue;
1224
1225 return false;
1226 }
1227
1228 return true;
1229}
1230
1231static void speculatePHINodeLoads(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001232 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001233
James Y Knight14359ef2019-02-01 20:44:24 +00001234 LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1235 Type *LoadTy = SomeLoad->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00001236 IRBuilderTy PHIBuilder(&PN);
1237 PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1238 PN.getName() + ".sroa.speculated");
1239
Hal Finkelcc39b672014-07-24 12:16:19 +00001240 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chandler Carruthf0546402013-07-18 07:15:00 +00001241 // matter which one we get and if any differ.
Hal Finkelcc39b672014-07-24 12:16:19 +00001242 AAMDNodes AATags;
1243 SomeLoad->getAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001244 unsigned Align = SomeLoad->getAlignment();
1245
1246 // Rewrite all loads of the PN to use the new PHI.
1247 while (!PN.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001248 LoadInst *LI = cast<LoadInst>(PN.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001249 LI->replaceAllUsesWith(NewPN);
1250 LI->eraseFromParent();
1251 }
1252
1253 // Inject loads into all of the pred blocks.
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001254 DenseMap<BasicBlock*, Value*> InjectedLoads;
Chandler Carruthf0546402013-07-18 07:15:00 +00001255 for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
1256 BasicBlock *Pred = PN.getIncomingBlock(Idx);
Chandler Carruthf0546402013-07-18 07:15:00 +00001257 Value *InVal = PN.getIncomingValue(Idx);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001258
1259 // A PHI node is allowed to have multiple (duplicated) entries for the same
1260 // basic block, as long as the value is the same. So if we already injected
1261 // a load in the predecessor, then we should reuse the same load for all
1262 // duplicated entries.
1263 if (Value* V = InjectedLoads.lookup(Pred)) {
1264 NewPN->addIncoming(V, Pred);
1265 continue;
1266 }
1267
Chandler Carruthedb12a82018-10-15 10:04:59 +00001268 Instruction *TI = Pred->getTerminator();
Chandler Carruthf0546402013-07-18 07:15:00 +00001269 IRBuilderTy PredBuilder(TI);
1270
1271 LoadInst *Load = PredBuilder.CreateLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00001272 LoadTy, InVal,
1273 (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
Chandler Carruthf0546402013-07-18 07:15:00 +00001274 ++NumLoadsSpeculated;
1275 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001276 if (AATags)
1277 Load->setAAMetadata(AATags);
Chandler Carruthf0546402013-07-18 07:15:00 +00001278 NewPN->addIncoming(Load, Pred);
Bjorn Pettersson81a76a32018-05-17 07:21:41 +00001279 InjectedLoads[Pred] = Load;
Chandler Carruthf0546402013-07-18 07:15:00 +00001280 }
1281
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001282 LLVM_DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001283 PN.eraseFromParent();
1284}
1285
1286/// Select instructions that use an alloca and are subsequently loaded can be
1287/// rewritten to load both input pointers and then select between the result,
1288/// allowing the load of the alloca to be promoted.
1289/// From this:
1290/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1291/// %V = load i32* %P2
1292/// to:
1293/// %V1 = load i32* %Alloca -> will be mem2reg'd
1294/// %V2 = load i32* %Other
1295/// %V = select i1 %cond, i32 %V1, i32 %V2
1296///
1297/// We can do this to a select if its only uses are loads and if the operand
1298/// to the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001299static bool isSafeSelectToSpeculate(SelectInst &SI) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001300 Value *TValue = SI.getTrueValue();
1301 Value *FValue = SI.getFalseValue();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001302 const DataLayout &DL = SI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00001303
Chandler Carruthcdf47882014-03-09 03:16:01 +00001304 for (User *U : SI.users()) {
1305 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001306 if (!LI || !LI->isSimple())
Chandler Carruthf0546402013-07-18 07:15:00 +00001307 return false;
1308
Hiroshi Inoueb3008242017-06-24 15:43:33 +00001309 // Both operands to the select need to be dereferenceable, either
Chandler Carruthf0546402013-07-18 07:15:00 +00001310 // absolutely (e.g. allocas) or at this point because we can see other
1311 // accesses to it.
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001312 if (!isSafeToLoadUnconditionally(TValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001313 return false;
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001314 if (!isSafeToLoadUnconditionally(FValue, LI->getAlignment(), DL, LI))
Chandler Carruthf0546402013-07-18 07:15:00 +00001315 return false;
1316 }
1317
1318 return true;
1319}
1320
1321static void speculateSelectInstLoads(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001322 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001323
1324 IRBuilderTy IRB(&SI);
1325 Value *TV = SI.getTrueValue();
1326 Value *FV = SI.getFalseValue();
1327 // Replace the loads of the select with a select of two loads.
1328 while (!SI.use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001329 LoadInst *LI = cast<LoadInst>(SI.user_back());
Chandler Carruthf0546402013-07-18 07:15:00 +00001330 assert(LI->isSimple() && "We only speculate simple loads");
1331
1332 IRB.SetInsertPoint(LI);
James Y Knight14359ef2019-02-01 20:44:24 +00001333 LoadInst *TL = IRB.CreateLoad(LI->getType(), TV,
1334 LI->getName() + ".sroa.speculate.load.true");
1335 LoadInst *FL = IRB.CreateLoad(LI->getType(), FV,
1336 LI->getName() + ".sroa.speculate.load.false");
Chandler Carruthf0546402013-07-18 07:15:00 +00001337 NumLoadsSpeculated += 2;
Chandler Carruthe3899f22013-07-15 17:36:21 +00001338
Hal Finkelcc39b672014-07-24 12:16:19 +00001339 // Transfer alignment and AA info if present.
Chandler Carruthf0546402013-07-18 07:15:00 +00001340 TL->setAlignment(LI->getAlignment());
1341 FL->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001342
1343 AAMDNodes Tags;
1344 LI->getAAMetadata(Tags);
1345 if (Tags) {
1346 TL->setAAMetadata(Tags);
1347 FL->setAAMetadata(Tags);
Chandler Carruthe3899f22013-07-15 17:36:21 +00001348 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001349
1350 Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1351 LI->getName() + ".sroa.speculated");
1352
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001353 LLVM_DEBUG(dbgs() << " speculated to: " << *V << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00001354 LI->replaceAllUsesWith(V);
1355 LI->eraseFromParent();
Chandler Carruthe3899f22013-07-15 17:36:21 +00001356 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001357 SI.eraseFromParent();
Chandler Carruth90c4a3a2012-10-05 01:29:06 +00001358}
1359
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001360/// Build a GEP out of a base pointer and indices.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001361///
1362/// This will return the BasePtr if that is valid, or build a new GEP
1363/// instruction using the IRBuilder if GEP-ing is needed.
Chandler Carruthd177f862013-03-20 07:30:36 +00001364static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001365 SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001366 if (Indices.empty())
1367 return BasePtr;
1368
1369 // A single zero index is a no-op, so check for this and avoid building a GEP
1370 // in that case.
1371 if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
1372 return BasePtr;
1373
James Y Knight77160752019-02-01 20:44:47 +00001374 return IRB.CreateInBoundsGEP(BasePtr->getType()->getPointerElementType(),
1375 BasePtr, Indices, NamePrefix + "sroa_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001376}
1377
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001378/// Get a natural GEP off of the BasePtr walking through Ty toward
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001379/// TargetTy without changing the offset of the pointer.
1380///
1381/// This routine assumes we've already established a properly offset GEP with
1382/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1383/// zero-indices down through type layers until we find one the same as
1384/// TargetTy. If we can't find one with the same type, we at least try to use
1385/// one with the same size. If none of that works, we just produce the GEP as
1386/// indicated by Indices to have the correct offset.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001387static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001388 Value *BasePtr, Type *Ty, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001389 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001390 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001391 if (Ty == TargetTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001392 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001393
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001394 // Offset size to use for the indices.
1395 unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001396
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001397 // See if we can descend into a struct and locate a field with the correct
1398 // type.
1399 unsigned NumLayers = 0;
1400 Type *ElementTy = Ty;
1401 do {
1402 if (ElementTy->isPointerTy())
1403 break;
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001404
1405 if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1406 ElementTy = ArrayTy->getElementType();
Nicola Zaghenf96383c2018-10-30 11:15:04 +00001407 Indices.push_back(IRB.getIntN(OffsetSize, 0));
Chandler Carruthdfb2efd2014-02-26 10:08:16 +00001408 } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1409 ElementTy = VectorTy->getElementType();
1410 Indices.push_back(IRB.getInt32(0));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001411 } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
Chandler Carruth503eb2b2012-10-09 01:58:35 +00001412 if (STy->element_begin() == STy->element_end())
1413 break; // Nothing left to descend into.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001414 ElementTy = *STy->element_begin();
1415 Indices.push_back(IRB.getInt32(0));
1416 } else {
1417 break;
1418 }
1419 ++NumLayers;
1420 } while (ElementTy != TargetTy);
1421 if (ElementTy != TargetTy)
1422 Indices.erase(Indices.end() - NumLayers, Indices.end());
1423
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001424 return buildGEP(IRB, BasePtr, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001425}
1426
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001427/// Recursively compute indices for a natural GEP.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001428///
1429/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1430/// element types adding appropriate indices for the GEP.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001431static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001432 Value *Ptr, Type *Ty, APInt &Offset,
1433 Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001434 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001435 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001436 if (Offset == 0)
Chandler Carruth113dc642014-12-20 02:39:18 +00001437 return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1438 NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001439
1440 // We can't recurse through pointer types.
1441 if (Ty->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +00001442 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001443
Chandler Carruthdd3cea82012-09-14 10:30:40 +00001444 // We try to analyze GEPs over vectors here, but note that these GEPs are
1445 // extremely poorly defined currently. The long-term goal is to remove GEPing
1446 // over a vector from the IR completely.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001447 if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001448 unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
Craig Topperf40110f2014-04-25 05:29:35 +00001449 if (ElementSizeInBits % 8 != 0) {
1450 // GEPs over non-multiple of 8 size vector elements are invalid.
1451 return nullptr;
1452 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001453 APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001454 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001455 if (NumSkippedElements.ugt(VecTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001456 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001457 Offset -= NumSkippedElements * ElementSize;
1458 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001459 return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001460 Offset, TargetTy, Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001461 }
1462
1463 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1464 Type *ElementTy = ArrTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001465 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001466 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001467 if (NumSkippedElements.ugt(ArrTy->getNumElements()))
Craig Topperf40110f2014-04-25 05:29:35 +00001468 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001469
1470 Offset -= NumSkippedElements * ElementSize;
1471 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001472 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001473 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001474 }
1475
1476 StructType *STy = dyn_cast<StructType>(Ty);
1477 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00001478 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001479
Chandler Carruth90a735d2013-07-19 07:21:28 +00001480 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001481 uint64_t StructOffset = Offset.getZExtValue();
Chandler Carruthcabd96c2012-09-14 10:30:42 +00001482 if (StructOffset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00001483 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001484 unsigned Index = SL->getElementContainingOffset(StructOffset);
1485 Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1486 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001487 if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
Craig Topperf40110f2014-04-25 05:29:35 +00001488 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001489
1490 Indices.push_back(IRB.getInt32(Index));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001491 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001492 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001493}
1494
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001495/// Get a natural GEP from a base pointer to a particular offset and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001496/// resulting in a particular type.
1497///
1498/// The goal is to produce a "natural" looking GEP that works with the existing
1499/// composite types to arrive at the appropriate offset and element type for
1500/// a pointer. TargetTy is the element type the returned GEP should point-to if
1501/// possible. We recurse by decreasing Offset, adding the appropriate index to
1502/// Indices, and setting Ty to the result subtype.
1503///
Chandler Carruth93a21e72012-09-14 10:18:49 +00001504/// If no natural GEP can be constructed, this function returns null.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001505static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001506 Value *Ptr, APInt Offset, Type *TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001507 SmallVectorImpl<Value *> &Indices,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001508 Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001509 PointerType *Ty = cast<PointerType>(Ptr->getType());
1510
1511 // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1512 // an i8.
Chandler Carruth286d87e2014-02-26 08:25:02 +00001513 if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +00001514 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001515
1516 Type *ElementTy = Ty->getElementType();
Chandler Carruth3f882d42012-09-18 22:37:19 +00001517 if (!ElementTy->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +00001518 return nullptr; // We can't GEP through an unsized element.
Chandler Carruth90a735d2013-07-19 07:21:28 +00001519 APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001520 if (ElementSize == 0)
Craig Topperf40110f2014-04-25 05:29:35 +00001521 return nullptr; // Zero-length arrays can't help us build a natural GEP.
Chandler Carruth6fab42a2012-10-17 09:23:48 +00001522 APInt NumSkippedElements = Offset.sdiv(ElementSize);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001523
1524 Offset -= NumSkippedElements * ElementSize;
1525 Indices.push_back(IRB.getInt(NumSkippedElements));
Chandler Carruth90a735d2013-07-19 07:21:28 +00001526 return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001527 Indices, NamePrefix);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001528}
1529
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001530/// Compute an adjusted pointer from Ptr by Offset bytes where the
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001531/// resulting pointer has PointerTy.
1532///
1533/// This tries very hard to compute a "natural" GEP which arrives at the offset
1534/// and produces the pointer type desired. Where it cannot, it will try to use
1535/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1536/// fails, it will try to use an existing i8* and GEP to the byte offset and
1537/// bitcast to the type.
1538///
1539/// The strategy for finding the more natural GEPs is to peel off layers of the
1540/// pointer, walking back through bit casts and GEPs, searching for a base
1541/// pointer from which we can compute a natural GEP with the desired
Jakub Staszak086f6cd2013-02-19 22:02:21 +00001542/// properties. The algorithm tries to fold as many constant indices into
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001543/// a single GEP as possible, thus making each GEP more independent of the
1544/// surrounding code.
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001545static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
Zachary Turner41a9ee92017-10-11 23:54:34 +00001546 APInt Offset, Type *PointerTy, Twine NamePrefix) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001547 // Even though we don't look through PHI nodes, we could be called on an
1548 // instruction in an unreachable block, which may be on a cycle.
1549 SmallPtrSet<Value *, 4> Visited;
1550 Visited.insert(Ptr);
1551 SmallVector<Value *, 4> Indices;
1552
1553 // We may end up computing an offset pointer that has the wrong type. If we
1554 // never are able to compute one directly that has the correct type, we'll
Chandler Carruth5986b542015-01-02 02:47:38 +00001555 // fall back to it, so keep it and the base it was computed from around here.
Craig Topperf40110f2014-04-25 05:29:35 +00001556 Value *OffsetPtr = nullptr;
Chandler Carruth5986b542015-01-02 02:47:38 +00001557 Value *OffsetBasePtr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001558
1559 // Remember any i8 pointer we come across to re-use if we need to do a raw
1560 // byte offset.
Craig Topperf40110f2014-04-25 05:29:35 +00001561 Value *Int8Ptr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001562 APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1563
1564 Type *TargetTy = PointerTy->getPointerElementType();
1565
1566 do {
1567 // First fold any existing GEPs into the offset.
1568 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1569 APInt GEPOffset(Offset.getBitWidth(), 0);
Chandler Carruth90a735d2013-07-19 07:21:28 +00001570 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001571 break;
1572 Offset += GEPOffset;
1573 Ptr = GEP->getPointerOperand();
David Blaikie70573dc2014-11-19 07:49:26 +00001574 if (!Visited.insert(Ptr).second)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001575 break;
1576 }
1577
1578 // See if we can perform a natural GEP here.
1579 Indices.clear();
Chandler Carruth90a735d2013-07-19 07:21:28 +00001580 if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001581 Indices, NamePrefix)) {
Chandler Carruth5986b542015-01-02 02:47:38 +00001582 // If we have a new natural pointer at the offset, clear out any old
1583 // offset pointer we computed. Unless it is the base pointer or
1584 // a non-instruction, we built a GEP we don't need. Zap it.
1585 if (OffsetPtr && OffsetPtr != OffsetBasePtr)
1586 if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1587 assert(I->use_empty() && "Built a GEP with uses some how!");
1588 I->eraseFromParent();
1589 }
1590 OffsetPtr = P;
1591 OffsetBasePtr = Ptr;
1592 // If we also found a pointer of the right type, we're done.
1593 if (P->getType() == PointerTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001594 return P;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001595 }
1596
1597 // Stash this pointer if we've found an i8*.
1598 if (Ptr->getType()->isIntegerTy(8)) {
1599 Int8Ptr = Ptr;
1600 Int8PtrOffset = Offset;
1601 }
1602
1603 // Peel off a layer of the pointer and update the offset appropriately.
1604 if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1605 Ptr = cast<Operator>(Ptr)->getOperand(0);
1606 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001607 if (GA->isInterposable())
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001608 break;
1609 Ptr = GA->getAliasee();
1610 } else {
1611 break;
1612 }
1613 assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +00001614 } while (Visited.insert(Ptr).second);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001615
1616 if (!OffsetPtr) {
1617 if (!Int8Ptr) {
Chandler Carruth286d87e2014-02-26 08:25:02 +00001618 Int8Ptr = IRB.CreateBitCast(
1619 Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1620 NamePrefix + "sroa_raw_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001621 Int8PtrOffset = Offset;
1622 }
1623
Chandler Carruth113dc642014-12-20 02:39:18 +00001624 OffsetPtr = Int8PtrOffset == 0
1625 ? Int8Ptr
David Blaikieaa41cd52015-04-03 21:33:42 +00001626 : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1627 IRB.getInt(Int8PtrOffset),
Chandler Carruth113dc642014-12-20 02:39:18 +00001628 NamePrefix + "sroa_raw_idx");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001629 }
1630 Ptr = OffsetPtr;
1631
1632 // On the off chance we were targeting i8*, guard the bitcast here.
1633 if (Ptr->getType() != PointerTy)
Chandler Carruthcb93cd22014-02-25 11:19:56 +00001634 Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001635
1636 return Ptr;
1637}
1638
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001639/// Compute the adjusted alignment for a load or store from an offset.
Chandler Carruth0715cba2015-01-01 11:54:38 +00001640static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1641 const DataLayout &DL) {
1642 unsigned Alignment;
1643 Type *Ty;
1644 if (auto *LI = dyn_cast<LoadInst>(I)) {
1645 Alignment = LI->getAlignment();
1646 Ty = LI->getType();
1647 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1648 Alignment = SI->getAlignment();
1649 Ty = SI->getValueOperand()->getType();
1650 } else {
1651 llvm_unreachable("Only loads and stores are allowed!");
1652 }
1653
1654 if (!Alignment)
1655 Alignment = DL.getABITypeAlignment(Ty);
1656
1657 return MinAlign(Alignment, Offset);
1658}
1659
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001660/// Test whether we can convert a value from the old to the new type.
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001661///
1662/// This predicate should be used to guard calls to convertValue in order to
1663/// ensure that we only try to convert viable values. The strategy is that we
1664/// will peel off single element struct and array wrappings to get to an
1665/// underlying value, and convert that value.
1666static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1667 if (OldTy == NewTy)
1668 return true;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001669
1670 // For integer types, we can't handle any bit-width differences. This would
1671 // break both vector conversions with extension and introduce endianness
1672 // issues when in conjunction with loads and stores.
1673 if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
1674 assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1675 cast<IntegerType>(NewTy)->getBitWidth() &&
1676 "We can't have the same bitwidth for different int types");
1677 return false;
1678 }
1679
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001680 if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1681 return false;
1682 if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
1683 return false;
1684
Benjamin Kramer56262592013-09-22 11:24:58 +00001685 // We can convert pointers to integers and vice-versa. Same for vectors
Benjamin Kramer90901a32013-09-21 20:36:04 +00001686 // of pointers and integers.
1687 OldTy = OldTy->getScalarType();
1688 NewTy = NewTy->getScalarType();
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001689 if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
Jack Liuf101c0f2016-05-03 19:30:48 +00001690 if (NewTy->isPointerTy() && OldTy->isPointerTy()) {
1691 return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1692 cast<PointerType>(OldTy)->getPointerAddressSpace();
1693 }
Sanjoy Dasb70ddd82017-06-17 20:28:13 +00001694
1695 // We can convert integers to integral pointers, but not to non-integral
1696 // pointers.
1697 if (OldTy->isIntegerTy())
1698 return !DL.isNonIntegralPointerType(NewTy);
1699
1700 // We can convert integral pointers to integers, but non-integral pointers
1701 // need to remain pointers.
1702 if (!DL.isNonIntegralPointerType(OldTy))
1703 return NewTy->isIntegerTy();
1704
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001705 return false;
1706 }
1707
1708 return true;
1709}
1710
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001711/// Generic routine to convert an SSA value to a value of a different
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001712/// type.
1713///
1714/// This will try various different casting techniques, such as bitcasts,
1715/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1716/// two types for viability with this routine.
Chandler Carruthd177f862013-03-20 07:30:36 +00001717static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Benjamin Kramer90901a32013-09-21 20:36:04 +00001718 Type *NewTy) {
1719 Type *OldTy = V->getType();
1720 assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1721
1722 if (OldTy == NewTy)
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001723 return V;
Benjamin Kramer90901a32013-09-21 20:36:04 +00001724
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001725 assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1726 "Integer types must be the exact same to convert.");
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001727
Benjamin Kramer90901a32013-09-21 20:36:04 +00001728 // See if we need inttoptr for this type pair. A cast involving both scalars
1729 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001730 if (OldTy->isIntOrIntVectorTy() && NewTy->isPtrOrPtrVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001731 // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1732 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1733 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1734 NewTy);
1735
1736 // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1737 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1738 return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1739 NewTy);
1740
1741 return IRB.CreateIntToPtr(V, NewTy);
1742 }
1743
1744 // See if we need ptrtoint for this type pair. A cast involving both scalars
1745 // and vectors requires and additional bitcast.
Craig Topper95d23472017-07-09 07:04:00 +00001746 if (OldTy->isPtrOrPtrVectorTy() && NewTy->isIntOrIntVectorTy()) {
Benjamin Kramer90901a32013-09-21 20:36:04 +00001747 // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1748 if (OldTy->isVectorTy() && !NewTy->isVectorTy())
1749 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1750 NewTy);
1751
1752 // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1753 if (!OldTy->isVectorTy() && NewTy->isVectorTy())
1754 return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1755 NewTy);
1756
1757 return IRB.CreatePtrToInt(V, NewTy);
1758 }
1759
1760 return IRB.CreateBitCast(V, NewTy);
Chandler Carruthaa6afbb2012-10-15 08:40:22 +00001761}
1762
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001763/// Test whether the given slice use can be promoted to a vector.
Chandler Carruthf0546402013-07-18 07:15:00 +00001764///
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001765/// This function is called to test each entry in a partition which is slated
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001766/// for a single slice.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001767static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1768 VectorType *Ty,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001769 uint64_t ElementSize,
1770 const DataLayout &DL) {
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001771 // First validate the slice offsets.
Chandler Carruthf0546402013-07-18 07:15:00 +00001772 uint64_t BeginOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001773 std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001774 uint64_t BeginIndex = BeginOffset / ElementSize;
1775 if (BeginIndex * ElementSize != BeginOffset ||
1776 BeginIndex >= Ty->getNumElements())
1777 return false;
1778 uint64_t EndOffset =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001779 std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
Chandler Carruthf0546402013-07-18 07:15:00 +00001780 uint64_t EndIndex = EndOffset / ElementSize;
1781 if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1782 return false;
1783
1784 assert(EndIndex > BeginIndex && "Empty vector!");
1785 uint64_t NumElements = EndIndex - BeginIndex;
Chandler Carruthc659df92014-10-16 20:24:07 +00001786 Type *SliceTy = (NumElements == 1)
1787 ? Ty->getElementType()
1788 : VectorType::get(Ty->getElementType(), NumElements);
Chandler Carruthf0546402013-07-18 07:15:00 +00001789
1790 Type *SplitIntTy =
1791 Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1792
Chandler Carruthc659df92014-10-16 20:24:07 +00001793 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001794
1795 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1796 if (MI->isVolatile())
1797 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00001798 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00001799 return false; // Skip any unsplittable intrinsics.
Owen Anderson6c19ab12014-08-07 21:07:35 +00001800 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00001801 if (!II->isLifetimeStartOrEnd())
Owen Anderson6c19ab12014-08-07 21:07:35 +00001802 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001803 } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1804 // Disable vector promotion when there are loads or stores of an FCA.
1805 return false;
1806 } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1807 if (LI->isVolatile())
1808 return false;
1809 Type *LTy = LI->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001810 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001811 assert(LTy->isIntegerTy());
1812 LTy = SplitIntTy;
1813 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001814 if (!canConvertValue(DL, SliceTy, LTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001815 return false;
1816 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1817 if (SI->isVolatile())
1818 return false;
1819 Type *STy = SI->getValueOperand()->getType();
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001820 if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001821 assert(STy->isIntegerTy());
1822 STy = SplitIntTy;
1823 }
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001824 if (!canConvertValue(DL, STy, SliceTy))
Chandler Carruthf0546402013-07-18 07:15:00 +00001825 return false;
Chandler Carruth1ed848d2013-07-19 10:57:32 +00001826 } else {
1827 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001828 }
1829
1830 return true;
1831}
1832
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001833/// Test whether the given alloca partitioning and range of slices can be
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001834/// promoted to a vector.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001835///
1836/// This is a quick test to check whether we can rewrite a particular alloca
1837/// partition (and its newly formed alloca) into a vector alloca with only
1838/// whole-vector loads and stores such that it could be promoted to a vector
1839/// SSA value. We only can ensure this for a limited set of operations, and we
1840/// don't want to do the rewrites unless we are confident that the result will
1841/// be promotable, so we have an early test here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00001842static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001843 // Collect the candidate types for vector-based promotion. Also track whether
1844 // we have different element types.
1845 SmallVector<VectorType *, 4> CandidateTys;
1846 Type *CommonEltTy = nullptr;
1847 bool HaveCommonEltTy = true;
1848 auto CheckCandidateType = [&](Type *Ty) {
1849 if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1850 CandidateTys.push_back(VTy);
1851 if (!CommonEltTy)
1852 CommonEltTy = VTy->getElementType();
1853 else if (CommonEltTy != VTy->getElementType())
1854 HaveCommonEltTy = false;
1855 }
1856 };
Chandler Carruth2dc96822014-10-18 00:44:02 +00001857 // Consider any loads or stores that are the exact size of the slice.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001858 for (const Slice &S : P)
1859 if (S.beginOffset() == P.beginOffset() &&
1860 S.endOffset() == P.endOffset()) {
Chandler Carruth2dc96822014-10-18 00:44:02 +00001861 if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1862 CheckCandidateType(LI->getType());
1863 else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1864 CheckCandidateType(SI->getValueOperand()->getType());
1865 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001866
Chandler Carruth2dc96822014-10-18 00:44:02 +00001867 // If we didn't find a vector type, nothing to do here.
1868 if (CandidateTys.empty())
1869 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001870
Chandler Carruth2dc96822014-10-18 00:44:02 +00001871 // Remove non-integer vector types if we had multiple common element types.
1872 // FIXME: It'd be nice to replace them with integer vector types, but we can't
1873 // do that until all the backends are known to produce good code for all
1874 // integer vector types.
1875 if (!HaveCommonEltTy) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00001876 CandidateTys.erase(
1877 llvm::remove_if(CandidateTys,
1878 [](VectorType *VTy) {
1879 return !VTy->getElementType()->isIntegerTy();
1880 }),
1881 CandidateTys.end());
Chandler Carruth2dc96822014-10-18 00:44:02 +00001882
1883 // If there were no integer vector types, give up.
1884 if (CandidateTys.empty())
1885 return nullptr;
1886
1887 // Rank the remaining candidate vector types. This is easy because we know
1888 // they're all integer vectors. We sort by ascending number of elements.
1889 auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
David L. Jones41cecba2017-01-13 21:02:41 +00001890 (void)DL;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001891 assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1892 "Cannot have vector types of different sizes!");
1893 assert(RHSTy->getElementType()->isIntegerTy() &&
1894 "All non-integer types eliminated!");
1895 assert(LHSTy->getElementType()->isIntegerTy() &&
1896 "All non-integer types eliminated!");
1897 return RHSTy->getNumElements() < LHSTy->getNumElements();
1898 };
Fangrui Song0cac7262018-09-27 02:13:45 +00001899 llvm::sort(CandidateTys, RankVectorTypes);
Chandler Carruth2dc96822014-10-18 00:44:02 +00001900 CandidateTys.erase(
1901 std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1902 CandidateTys.end());
1903 } else {
1904// The only way to have the same element type in every vector type is to
1905// have the same vector type. Check that and remove all but one.
1906#ifndef NDEBUG
1907 for (VectorType *VTy : CandidateTys) {
1908 assert(VTy->getElementType() == CommonEltTy &&
1909 "Unaccounted for element type!");
1910 assert(VTy == CandidateTys[0] &&
1911 "Different vector types with the same element type!");
1912 }
1913#endif
1914 CandidateTys.resize(1);
1915 }
1916
1917 // Try each vector type, and return the one which works.
1918 auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1919 uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1920
1921 // While the definition of LLVM vectors is bitpacked, we don't support sizes
1922 // that aren't byte sized.
1923 if (ElementSize % 8)
1924 return false;
1925 assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1926 "vector size not a multiple of element size?");
1927 ElementSize /= 8;
1928
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001929 for (const Slice &S : P)
1930 if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001931 return false;
1932
Chandler Carruthffb7ce52014-12-24 01:48:09 +00001933 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001934 if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
Chandler Carruth2dc96822014-10-18 00:44:02 +00001935 return false;
1936
1937 return true;
1938 };
1939 for (VectorType *VTy : CandidateTys)
1940 if (CheckVectorTypeForPromotion(VTy))
1941 return VTy;
1942
1943 return nullptr;
Chandler Carruthf0546402013-07-18 07:15:00 +00001944}
1945
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001946/// Test whether a slice of an alloca is valid for integer widening.
Chandler Carruthf0546402013-07-18 07:15:00 +00001947///
1948/// This implements the necessary checking for the \c isIntegerWideningViable
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001949/// test below on a single slice of the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001950static bool isIntegerWideningViableForSlice(const Slice &S,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001951 uint64_t AllocBeginOffset,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001952 Type *AllocaTy,
1953 const DataLayout &DL,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00001954 bool &WholeAllocaOp) {
Chandler Carruth5031bbe2014-12-24 01:05:14 +00001955 uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1956
Chandler Carruthc659df92014-10-16 20:24:07 +00001957 uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1958 uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
Chandler Carruthf0546402013-07-18 07:15:00 +00001959
1960 // We can't reasonably handle cases where the load or store extends past
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001961 // the end of the alloca's type and into its padding.
Chandler Carruthf0546402013-07-18 07:15:00 +00001962 if (RelEnd > Size)
1963 return false;
1964
Chandler Carruthc659df92014-10-16 20:24:07 +00001965 Use *U = S.getUse();
Chandler Carruthf0546402013-07-18 07:15:00 +00001966
1967 if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1968 if (LI->isVolatile())
1969 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001970 // We can't handle loads that extend past the allocated memory.
1971 if (DL.getTypeStoreSize(LI->getType()) > Size)
1972 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00001973 // So far, AllocaSliceRewriter does not support widening split slice tails
1974 // in rewriteIntegerLoad.
1975 if (S.beginOffset() < AllocBeginOffset)
1976 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00001977 // Note that we don't count vector loads or stores as whole-alloca
1978 // operations which enable integer widening because we would prefer to use
1979 // vector widening instead.
1980 if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00001981 WholeAllocaOp = true;
1982 if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00001983 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthe3899f22013-07-15 17:36:21 +00001984 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00001985 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00001986 !canConvertValue(DL, AllocaTy, LI->getType())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00001987 // Non-integer loads need to be convertible from the alloca type so that
1988 // they are promotable.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00001989 return false;
1990 }
Chandler Carruthf0546402013-07-18 07:15:00 +00001991 } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1992 Type *ValueTy = SI->getValueOperand()->getType();
1993 if (SI->isVolatile())
1994 return false;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00001995 // We can't handle stores that extend past the allocated memory.
1996 if (DL.getTypeStoreSize(ValueTy) > Size)
1997 return false;
Hiroshi Inouef5c0e6c2018-05-17 06:32:17 +00001998 // So far, AllocaSliceRewriter does not support widening split slice tails
1999 // in rewriteIntegerStore.
2000 if (S.beginOffset() < AllocBeginOffset)
2001 return false;
Chandler Carruth2dc96822014-10-18 00:44:02 +00002002 // Note that we don't count vector loads or stores as whole-alloca
2003 // operations which enable integer widening because we would prefer to use
2004 // vector widening instead.
2005 if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
Chandler Carruthf0546402013-07-18 07:15:00 +00002006 WholeAllocaOp = true;
2007 if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002008 if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
Chandler Carruthf0546402013-07-18 07:15:00 +00002009 return false;
2010 } else if (RelBegin != 0 || RelEnd != Size ||
Chandler Carruth90a735d2013-07-19 07:21:28 +00002011 !canConvertValue(DL, ValueTy, AllocaTy)) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002012 // Non-integer stores need to be convertible to the alloca type so that
2013 // they are promotable.
2014 return false;
2015 }
2016 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2017 if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
2018 return false;
Chandler Carruthc659df92014-10-16 20:24:07 +00002019 if (!S.isSplittable())
Chandler Carruthf0546402013-07-18 07:15:00 +00002020 return false; // Skip any unsplittable intrinsics.
2021 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
Vedant Kumarb264d692018-12-21 21:49:40 +00002022 if (!II->isLifetimeStartOrEnd())
Chandler Carruthf0546402013-07-18 07:15:00 +00002023 return false;
2024 } else {
2025 return false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002026 }
Chandler Carruthf0546402013-07-18 07:15:00 +00002027
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002028 return true;
2029}
2030
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002031/// Test whether the given alloca partition's integer operations can be
Chandler Carruth435c4e02012-10-15 08:40:30 +00002032/// widened to promotable ones.
Chandler Carruth92924fd2012-09-24 00:34:20 +00002033///
Chandler Carruth435c4e02012-10-15 08:40:30 +00002034/// This is a quick test to check whether we can rewrite the integer loads and
2035/// stores to a particular alloca into wider loads and stores and be able to
2036/// promote the resulting alloca.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002037static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002038 const DataLayout &DL) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002039 uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
Benjamin Kramer47534c72012-12-01 11:53:32 +00002040 // Don't create integer types larger than the maximum bitwidth.
2041 if (SizeInBits > IntegerType::MAX_INT_BITS)
2042 return false;
Chandler Carruth435c4e02012-10-15 08:40:30 +00002043
2044 // Don't try to handle allocas with bit-padding.
Chandler Carruth90a735d2013-07-19 07:21:28 +00002045 if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002046 return false;
2047
Chandler Carruth58d05562012-10-25 04:37:07 +00002048 // We need to ensure that an integer type with the appropriate bitwidth can
2049 // be converted to the alloca type, whatever that is. We don't want to force
2050 // the alloca itself to have an integer type if there is a more suitable one.
2051 Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
Chandler Carruth90a735d2013-07-19 07:21:28 +00002052 if (!canConvertValue(DL, AllocaTy, IntTy) ||
2053 !canConvertValue(DL, IntTy, AllocaTy))
Chandler Carruth58d05562012-10-25 04:37:07 +00002054 return false;
2055
Chandler Carruthf0546402013-07-18 07:15:00 +00002056 // While examining uses, we ensure that the alloca has a covering load or
2057 // store. We don't want to widen the integer operations only to fail to
2058 // promote due to some other unsplittable entry (which we may make splittable
Chandler Carruth5955c9e2013-07-19 07:12:23 +00002059 // later). However, if there are only splittable uses, go ahead and assume
2060 // that we cover the alloca.
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002061 // FIXME: We shouldn't consider split slices that happen to start in the
2062 // partition here...
Chandler Carruthc659df92014-10-16 20:24:07 +00002063 bool WholeAllocaOp =
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002064 P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
Chandler Carruth43c8b462012-10-04 10:39:28 +00002065
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002066 for (const Slice &S : P)
2067 if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2068 WholeAllocaOp))
Chandler Carruth43c8b462012-10-04 10:39:28 +00002069 return false;
2070
Chandler Carruthffb7ce52014-12-24 01:48:09 +00002071 for (const Slice *S : P.splitSliceTails())
Chandler Carruth5031bbe2014-12-24 01:05:14 +00002072 if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2073 WholeAllocaOp))
Chandler Carruth92924fd2012-09-24 00:34:20 +00002074 return false;
Chandler Carruthf0546402013-07-18 07:15:00 +00002075
Chandler Carruth92924fd2012-09-24 00:34:20 +00002076 return WholeAllocaOp;
2077}
2078
Chandler Carruthd177f862013-03-20 07:30:36 +00002079static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002080 IntegerType *Ty, uint64_t Offset,
2081 const Twine &Name) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002082 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002083 IntegerType *IntTy = cast<IntegerType>(V->getType());
2084 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2085 "Element extends past full value");
Chandler Carruth113dc642014-12-20 02:39:18 +00002086 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002087 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002088 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002089 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002090 V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002091 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002092 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002093 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2094 "Cannot extract to a larger integer!");
Chandler Carruth18db7952012-11-20 01:12:50 +00002095 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002096 V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002097 LLVM_DEBUG(dbgs() << " trunced: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002098 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002099 return V;
2100}
2101
Chandler Carruthd177f862013-03-20 07:30:36 +00002102static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002103 Value *V, uint64_t Offset, const Twine &Name) {
2104 IntegerType *IntTy = cast<IntegerType>(Old->getType());
2105 IntegerType *Ty = cast<IntegerType>(V->getType());
2106 assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2107 "Cannot insert a larger integer!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002108 LLVM_DEBUG(dbgs() << " start: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002109 if (Ty != IntTy) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002110 V = IRB.CreateZExt(V, IntTy, Name + ".ext");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002111 LLVM_DEBUG(dbgs() << " extended: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002112 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002113 assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2114 "Element store outside of alloca store");
Chandler Carruth113dc642014-12-20 02:39:18 +00002115 uint64_t ShAmt = 8 * Offset;
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002116 if (DL.isBigEndian())
Chandler Carruth113dc642014-12-20 02:39:18 +00002117 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
Chandler Carruth18db7952012-11-20 01:12:50 +00002118 if (ShAmt) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002119 V = IRB.CreateShl(V, ShAmt, Name + ".shift");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002120 LLVM_DEBUG(dbgs() << " shifted: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002121 }
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002122
2123 if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
2124 APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2125 Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002126 LLVM_DEBUG(dbgs() << " masked: " << *Old << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002127 V = IRB.CreateOr(Old, V, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002128 LLVM_DEBUG(dbgs() << " inserted: " << *V << "\n");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002129 }
2130 return V;
2131}
2132
Chandler Carruth113dc642014-12-20 02:39:18 +00002133static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2134 unsigned EndIndex, const Twine &Name) {
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002135 VectorType *VecTy = cast<VectorType>(V->getType());
2136 unsigned NumElements = EndIndex - BeginIndex;
2137 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2138
2139 if (NumElements == VecTy->getNumElements())
2140 return V;
2141
2142 if (NumElements == 1) {
2143 V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2144 Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002145 LLVM_DEBUG(dbgs() << " extract: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002146 return V;
2147 }
2148
Chandler Carruth113dc642014-12-20 02:39:18 +00002149 SmallVector<Constant *, 8> Mask;
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002150 Mask.reserve(NumElements);
2151 for (unsigned i = BeginIndex; i != EndIndex; ++i)
2152 Mask.push_back(IRB.getInt32(i));
2153 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002154 ConstantVector::get(Mask), Name + ".extract");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002155 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002156 return V;
2157}
2158
Chandler Carruthd177f862013-03-20 07:30:36 +00002159static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
Chandler Carruthce4562b2012-12-17 13:41:21 +00002160 unsigned BeginIndex, const Twine &Name) {
2161 VectorType *VecTy = cast<VectorType>(Old->getType());
2162 assert(VecTy && "Can only insert a vector into a vector");
2163
2164 VectorType *Ty = dyn_cast<VectorType>(V->getType());
2165 if (!Ty) {
2166 // Single element to insert.
2167 V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2168 Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002169 LLVM_DEBUG(dbgs() << " insert: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002170 return V;
2171 }
2172
2173 assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2174 "Too many elements!");
2175 if (Ty->getNumElements() == VecTy->getNumElements()) {
2176 assert(V->getType() == VecTy && "Vector type mismatch");
2177 return V;
2178 }
2179 unsigned EndIndex = BeginIndex + Ty->getNumElements();
2180
2181 // When inserting a smaller vector into the larger to store, we first
2182 // use a shuffle vector to widen it with undef elements, and then
2183 // a second shuffle vector to select between the loaded vector and the
2184 // incoming vector.
Chandler Carruth113dc642014-12-20 02:39:18 +00002185 SmallVector<Constant *, 8> Mask;
Chandler Carruthce4562b2012-12-17 13:41:21 +00002186 Mask.reserve(VecTy->getNumElements());
2187 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
2188 if (i >= BeginIndex && i < EndIndex)
2189 Mask.push_back(IRB.getInt32(i - BeginIndex));
2190 else
2191 Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2192 V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
Chandler Carruth113dc642014-12-20 02:39:18 +00002193 ConstantVector::get(Mask), Name + ".expand");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002194 LLVM_DEBUG(dbgs() << " shuffle: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002195
2196 Mask.clear();
2197 for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
Nadav Rotem1e211912013-05-01 19:53:30 +00002198 Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
2199
2200 V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2201
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002202 LLVM_DEBUG(dbgs() << " blend: " << *V << "\n");
Chandler Carruthce4562b2012-12-17 13:41:21 +00002203 return V;
2204}
2205
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002206/// Visitor to rewrite instructions using p particular slice of an alloca
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002207/// to use a new alloca.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002208///
2209/// Also implements the rewriting to vector-based accesses when the partition
2210/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2211/// lives here.
Chandler Carruth29a18a42015-09-12 09:09:14 +00002212class llvm::sroa::AllocaSliceRewriter
2213 : public InstVisitor<AllocaSliceRewriter, bool> {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002214 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002215 friend class InstVisitor<AllocaSliceRewriter, bool>;
2216
2217 using Base = InstVisitor<AllocaSliceRewriter, bool>;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002218
Chandler Carruth90a735d2013-07-19 07:21:28 +00002219 const DataLayout &DL;
Chandler Carruth83934062014-10-16 21:11:55 +00002220 AllocaSlices &AS;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002221 SROA &Pass;
2222 AllocaInst &OldAI, &NewAI;
2223 const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
Chandler Carruth891fec02012-10-13 02:41:05 +00002224 Type *NewAllocaTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002225
Chandler Carruth2dc96822014-10-18 00:44:02 +00002226 // This is a convenience and flag variable that will be null unless the new
2227 // alloca's integer operations should be widened to this integer type due to
2228 // passing isIntegerWideningViable above. If it is non-null, the desired
2229 // integer type will be stored here for easy access during rewriting.
2230 IntegerType *IntTy;
2231
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002232 // If we are rewriting an alloca partition which can be written as pure
2233 // vector operations, we stash extra information here. When VecTy is
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002234 // non-null, we have some strict guarantees about the rewritten alloca:
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002235 // - The new alloca is exactly the size of the vector type here.
2236 // - The accesses all either map to the entire vector or to a single
2237 // element.
2238 // - The set of accessing instructions is only one of those handled above
2239 // in isVectorPromotionViable. Generally these are the same access kinds
2240 // which are promotable via mem2reg.
2241 VectorType *VecTy;
2242 Type *ElementTy;
2243 uint64_t ElementSize;
2244
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002245 // The original offset of the slice currently being rewritten relative to
2246 // the original alloca.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002247 uint64_t BeginOffset = 0;
2248 uint64_t EndOffset = 0;
2249
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002250 // The new offsets of the slice currently being rewritten relative to the
2251 // original alloca.
2252 uint64_t NewBeginOffset, NewEndOffset;
2253
2254 uint64_t SliceSize;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002255 bool IsSplittable = false;
2256 bool IsSplit = false;
2257 Use *OldUse = nullptr;
2258 Instruction *OldPtr = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002259
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00002260 // Track post-rewrite users which are PHI nodes and Selects.
Davide Italiano81a26da2017-04-27 23:09:01 +00002261 SmallSetVector<PHINode *, 8> &PHIUsers;
2262 SmallSetVector<SelectInst *, 8> &SelectUsers;
Chandler Carruth83ea1952013-07-24 09:47:28 +00002263
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002264 // Utility IR builder, whose name prefix is setup for each visited use, and
2265 // the insertion point is set to point to the user.
2266 IRBuilderTy IRB;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002267
2268public:
Chandler Carruth83934062014-10-16 21:11:55 +00002269 AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002270 AllocaInst &OldAI, AllocaInst &NewAI,
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002271 uint64_t NewAllocaBeginOffset,
Chandler Carruth2dc96822014-10-18 00:44:02 +00002272 uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2273 VectorType *PromotableVecTy,
Davide Italiano81a26da2017-04-27 23:09:01 +00002274 SmallSetVector<PHINode *, 8> &PHIUsers,
2275 SmallSetVector<SelectInst *, 8> &SelectUsers)
Chandler Carruth83934062014-10-16 21:11:55 +00002276 : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002277 NewAllocaBeginOffset(NewAllocaBeginOffset),
2278 NewAllocaEndOffset(NewAllocaEndOffset),
Chandler Carruthf0546402013-07-18 07:15:00 +00002279 NewAllocaTy(NewAI.getAllocatedType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00002280 IntTy(IsIntegerPromotable
2281 ? Type::getIntNTy(
2282 NewAI.getContext(),
Chandler Carruth90a735d2013-07-19 07:21:28 +00002283 DL.getTypeSizeInBits(NewAI.getAllocatedType()))
Craig Topperf40110f2014-04-25 05:29:35 +00002284 : nullptr),
Chandler Carruth2dc96822014-10-18 00:44:02 +00002285 VecTy(PromotableVecTy),
2286 ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2287 ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002288 PHIUsers(PHIUsers), SelectUsers(SelectUsers),
Chandler Carruth83ea1952013-07-24 09:47:28 +00002289 IRB(NewAI.getContext(), ConstantFolder()) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002290 if (VecTy) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00002291 assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
Chandler Carruthf0546402013-07-18 07:15:00 +00002292 "Only multiple-of-8 sized vector elements are viable");
2293 ++NumVectorized;
2294 }
Chandler Carruth2dc96822014-10-18 00:44:02 +00002295 assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002296 }
2297
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002298 bool visit(AllocaSlices::const_iterator I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002299 bool CanSROA = true;
Chandler Carruthf0546402013-07-18 07:15:00 +00002300 BeginOffset = I->beginOffset();
2301 EndOffset = I->endOffset();
2302 IsSplittable = I->isSplittable();
2303 IsSplit =
2304 BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002305 LLVM_DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
2306 LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2307 LLVM_DEBUG(dbgs() << "\n");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002308
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002309 // Compute the intersecting offset range.
2310 assert(BeginOffset < NewAllocaEndOffset);
2311 assert(EndOffset > NewAllocaBeginOffset);
2312 NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2313 NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2314
2315 SliceSize = NewEndOffset - NewBeginOffset;
2316
Chandler Carruthf0546402013-07-18 07:15:00 +00002317 OldUse = I->getUse();
2318 OldPtr = cast<Instruction>(OldUse->get());
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002319
Chandler Carruthf0546402013-07-18 07:15:00 +00002320 Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2321 IRB.SetInsertPoint(OldUserI);
2322 IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2323 IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2324
2325 CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2326 if (VecTy || IntTy)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002327 assert(CanSROA);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002328 return CanSROA;
2329 }
2330
2331private:
Chandler Carruthf0546402013-07-18 07:15:00 +00002332 // Make sure the other visit overloads are visible.
2333 using Base::visit;
2334
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002335 // Every instruction which can end up as a user must have a rewrite rule.
2336 bool visitInstruction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002337 LLVM_DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002338 llvm_unreachable("No rewrite rule for this instruction!");
2339 }
2340
Chandler Carruth47954c82014-02-26 05:12:43 +00002341 Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2342 // Note that the offset computation can use BeginOffset or NewBeginOffset
2343 // interchangeably for unsplit slices.
2344 assert(IsSplit || BeginOffset == NewBeginOffset);
2345 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2346
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002347#ifndef NDEBUG
2348 StringRef OldName = OldPtr->getName();
2349 // Skip through the last '.sroa.' component of the name.
2350 size_t LastSROAPrefix = OldName.rfind(".sroa.");
2351 if (LastSROAPrefix != StringRef::npos) {
2352 OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2353 // Look for an SROA slice index.
2354 size_t IndexEnd = OldName.find_first_not_of("0123456789");
2355 if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2356 // Strip the index and look for the offset.
2357 OldName = OldName.substr(IndexEnd + 1);
2358 size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2359 if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2360 // Strip the offset.
2361 OldName = OldName.substr(OffsetEnd + 1);
2362 }
2363 }
2364 // Strip any SROA suffixes as well.
2365 OldName = OldName.substr(0, OldName.find(".sroa_"));
2366#endif
Chandler Carruth47954c82014-02-26 05:12:43 +00002367
2368 return getAdjustedPtr(IRB, DL, &NewAI,
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002369 APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002370 PointerTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002371#ifndef NDEBUG
2372 Twine(OldName) + "."
2373#else
2374 Twine()
2375#endif
2376 );
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002377 }
2378
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002379 /// Compute suitable alignment to access this slice of the *new*
Chandler Carruth113dc642014-12-20 02:39:18 +00002380 /// alloca.
Chandler Carruth2659e502014-02-26 05:02:19 +00002381 ///
2382 /// You can optionally pass a type to this routine and if that type's ABI
2383 /// alignment is itself suitable, this will return zero.
Craig Topperf40110f2014-04-25 05:29:35 +00002384 unsigned getSliceAlign(Type *Ty = nullptr) {
Chandler Carruth176ca712012-10-01 12:16:54 +00002385 unsigned NewAIAlign = NewAI.getAlignment();
2386 if (!NewAIAlign)
Chandler Carruth90a735d2013-07-19 07:21:28 +00002387 NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
Chandler Carruth113dc642014-12-20 02:39:18 +00002388 unsigned Align =
2389 MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
Chandler Carruth2659e502014-02-26 05:02:19 +00002390 return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
Chandler Carruth4b2b38d2012-10-03 08:14:02 +00002391 }
2392
Chandler Carruth845b73c2012-11-21 08:16:30 +00002393 unsigned getIndex(uint64_t Offset) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002394 assert(VecTy && "Can only call getIndex when rewriting a vector");
2395 uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2396 assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2397 uint32_t Index = RelOffset / ElementSize;
2398 assert(Index * ElementSize == RelOffset);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002399 return Index;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002400 }
2401
2402 void deleteIfTriviallyDead(Value *V) {
2403 Instruction *I = cast<Instruction>(V);
2404 if (isInstructionTriviallyDead(I))
Chandler Carruth18db7952012-11-20 01:12:50 +00002405 Pass.DeadInsts.insert(I);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002406 }
2407
Chandler Carruthea27cf02014-02-26 04:25:04 +00002408 Value *rewriteVectorizedLoadInst() {
Chandler Carruthf0546402013-07-18 07:15:00 +00002409 unsigned BeginIndex = getIndex(NewBeginOffset);
2410 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruth769445e2012-12-17 12:50:21 +00002411 assert(EndIndex > BeginIndex && "Empty vector!");
Chandler Carruthb6bc8742012-12-17 13:07:30 +00002412
James Y Knight14359ef2019-02-01 20:44:24 +00002413 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2414 NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002415 return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
Chandler Carruth769445e2012-12-17 12:50:21 +00002416 }
2417
Chandler Carruthea27cf02014-02-26 04:25:04 +00002418 Value *rewriteIntegerLoad(LoadInst &LI) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002419 assert(IntTy && "We cannot insert an integer to the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002420 assert(!LI.isVolatile());
James Y Knight14359ef2019-02-01 20:44:24 +00002421 Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2422 NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002423 V = convertValue(DL, IRB, V, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002424 assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2425 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth4b682f62015-08-28 09:03:52 +00002426 if (Offset > 0 || NewEndOffset < NewAllocaEndOffset) {
2427 IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2428 V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2429 }
2430 // It is possible that the extracted type is not the load type. This
2431 // happens if there is a load past the end of the alloca, and as
2432 // a consequence the slice is narrower but still a candidate for integer
2433 // lowering. To handle this case, we just zero extend the extracted
2434 // integer.
2435 assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2436 "Can only handle an extract for an overly wide load");
2437 if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2438 V = IRB.CreateZExt(V, LI.getType());
Chandler Carruth18db7952012-11-20 01:12:50 +00002439 return V;
Chandler Carruth92924fd2012-09-24 00:34:20 +00002440 }
2441
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002442 bool visitLoadInst(LoadInst &LI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002443 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002444 Value *OldOp = LI.getOperand(0);
2445 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002446
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002447 AAMDNodes AATags;
2448 LI.getAAMetadata(AATags);
2449
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002450 unsigned AS = LI.getPointerAddressSpace();
2451
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002452 Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002453 : LI.getType();
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002454 const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002455 bool IsPtrAdjusted = false;
2456 Value *V;
2457 if (VecTy) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002458 V = rewriteVectorizedLoadInst();
Chandler Carruth18db7952012-11-20 01:12:50 +00002459 } else if (IntTy && LI.getType()->isIntegerTy()) {
Chandler Carruthea27cf02014-02-26 04:25:04 +00002460 V = rewriteIntegerLoad(LI);
Chandler Carruthf0546402013-07-18 07:15:00 +00002461 } else if (NewBeginOffset == NewAllocaBeginOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002462 NewEndOffset == NewAllocaEndOffset &&
2463 (canConvertValue(DL, NewAllocaTy, TargetTy) ||
2464 (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
2465 TargetTy->isIntegerTy()))) {
James Y Knight14359ef2019-02-01 20:44:24 +00002466 LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2467 NewAI.getAlignment(),
David Majnemer62690b12015-07-14 06:19:58 +00002468 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002469 if (AATags)
2470 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002471 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002472 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Luqman Aden3f807c92017-03-22 19:16:39 +00002473
Chandler Carruth3f81d802017-06-27 08:32:03 +00002474 // Any !nonnull metadata or !range metadata on the old load is also valid
2475 // on the new load. This is even true in some cases even when the loads
2476 // are different types, for example by mapping !nonnull metadata to
2477 // !range metadata by modeling the null pointer constant converted to the
2478 // integer type.
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002479 // FIXME: Add support for range metadata here. Currently the utilities
2480 // for this don't propagate range metadata in trivial cases from one
2481 // integer load to another, don't handle non-addrspace-0 null pointers
2482 // correctly, and don't have any support for mapping ranges as the
2483 // integer type becomes winder or narrower.
Chandler Carruth3f81d802017-06-27 08:32:03 +00002484 if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2485 copyNonnullMetadata(LI, N, *NewLI);
Rafael Espindolac06f55e2017-11-28 01:25:38 +00002486
2487 // Try to preserve nonnull metadata
David Majnemer62690b12015-07-14 06:19:58 +00002488 V = NewLI;
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002489
2490 // If this is an integer load past the end of the slice (which means the
2491 // bytes outside the slice are undef or this load is dead) just forcibly
2492 // fix the integer size with correct handling of endianness.
2493 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2494 if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2495 if (AITy->getBitWidth() < TITy->getBitWidth()) {
2496 V = IRB.CreateZExt(V, TITy, "load.ext");
2497 if (DL.isBigEndian())
2498 V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2499 "endian_shift");
2500 }
Chandler Carruth18db7952012-11-20 01:12:50 +00002501 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002502 Type *LTy = TargetTy->getPointerTo(AS);
James Y Knight14359ef2019-02-01 20:44:24 +00002503 LoadInst *NewLI = IRB.CreateAlignedLoad(
2504 TargetTy, getNewAllocaSlicePtr(IRB, LTy), getSliceAlign(TargetTy),
2505 LI.isVolatile(), LI.getName());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002506 if (AATags)
2507 NewLI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002508 if (LI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002509 NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
David Majnemer62690b12015-07-14 06:19:58 +00002510
2511 V = NewLI;
Chandler Carruth18db7952012-11-20 01:12:50 +00002512 IsPtrAdjusted = true;
2513 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002514 V = convertValue(DL, IRB, V, TargetTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002515
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002516 if (IsSplit) {
Chandler Carruth58d05562012-10-25 04:37:07 +00002517 assert(!LI.isVolatile());
2518 assert(LI.getType()->isIntegerTy() &&
2519 "Only integer type loads and stores are split");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002520 assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
Chandler Carrutha1c54bb2013-03-14 11:32:24 +00002521 "Split load isn't smaller than original load");
Bjorn Petterssonb4771422019-05-24 09:20:20 +00002522 assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
Chandler Carruth58d05562012-10-25 04:37:07 +00002523 "Non-byte-multiple bit width");
Chandler Carruth58d05562012-10-25 04:37:07 +00002524 // 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 +00002525 IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
Chandler Carruth58d05562012-10-25 04:37:07 +00002526 // Create a placeholder value with the same type as LI to use as the
2527 // basis for the new value. This allows us to replace the uses of LI with
2528 // the computed value, and then replace the placeholder with LI, leaving
2529 // LI only used for this computation.
James Y Knight14359ef2019-02-01 20:44:24 +00002530 Value *Placeholder = new LoadInst(
2531 LI.getType(), UndefValue::get(LI.getType()->getPointerTo(AS)));
Chandler Carruth24ac8302015-01-02 03:55:54 +00002532 V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2533 "insert");
Chandler Carruth58d05562012-10-25 04:37:07 +00002534 LI.replaceAllUsesWith(V);
2535 Placeholder->replaceAllUsesWith(&LI);
Reid Kleckner96ab8722017-05-18 17:24:10 +00002536 Placeholder->deleteValue();
Chandler Carruth18db7952012-11-20 01:12:50 +00002537 } else {
2538 LI.replaceAllUsesWith(V);
Chandler Carruth58d05562012-10-25 04:37:07 +00002539 }
2540
Chandler Carruth18db7952012-11-20 01:12:50 +00002541 Pass.DeadInsts.insert(&LI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002542 deleteIfTriviallyDead(OldOp);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002543 LLVM_DEBUG(dbgs() << " to: " << *V << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002544 return !LI.isVolatile() && !IsPtrAdjusted;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002545 }
2546
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002547 bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2548 AAMDNodes AATags) {
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002549 if (V->getType() != VecTy) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002550 unsigned BeginIndex = getIndex(NewBeginOffset);
2551 unsigned EndIndex = getIndex(NewEndOffset);
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002552 assert(EndIndex > BeginIndex && "Empty vector!");
2553 unsigned NumElements = EndIndex - BeginIndex;
2554 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
Chandler Carruth113dc642014-12-20 02:39:18 +00002555 Type *SliceTy = (NumElements == 1)
2556 ? ElementTy
2557 : VectorType::get(ElementTy, NumElements);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00002558 if (V->getType() != SliceTy)
2559 V = convertValue(DL, IRB, V, SliceTy);
Chandler Carruth845b73c2012-11-21 08:16:30 +00002560
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002561 // Mix in the existing elements.
James Y Knight14359ef2019-02-01 20:44:24 +00002562 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2563 NewAI.getAlignment(), "load");
Bob Wilsonacfc01d2013-06-25 19:09:50 +00002564 V = insertVector(IRB, Old, V, BeginIndex, "vec");
2565 }
Chandler Carruth871ba722012-09-26 10:27:46 +00002566 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002567 if (AATags)
2568 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002569 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002570
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002571 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002572 return true;
2573 }
2574
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002575 bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002576 assert(IntTy && "We cannot extract an integer from the alloca");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002577 assert(!SI.isVolatile());
Chandler Carruth90a735d2013-07-19 07:21:28 +00002578 if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
James Y Knight14359ef2019-02-01 20:44:24 +00002579 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2580 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002581 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002582 assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2583 uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
Chandler Carruth113dc642014-12-20 02:39:18 +00002584 V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002585 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002586 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth59ff93af2012-10-18 09:56:08 +00002587 StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Michael Kruse978ba612018-12-20 04:58:07 +00002588 Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2589 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002590 if (AATags)
2591 Store->setAAMetadata(AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002592 Pass.DeadInsts.insert(&SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002593 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth92924fd2012-09-24 00:34:20 +00002594 return true;
2595 }
2596
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002597 bool visitStoreInst(StoreInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002598 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002599 Value *OldOp = SI.getOperand(1);
2600 assert(OldOp == OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002601
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002602 AAMDNodes AATags;
2603 SI.getAAMetadata(AATags);
2604
Chandler Carruth18db7952012-11-20 01:12:50 +00002605 Value *V = SI.getValueOperand();
Chandler Carruth891fec02012-10-13 02:41:05 +00002606
Chandler Carruthac8317f2012-10-04 12:33:50 +00002607 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2608 // alloca that should be re-examined after promoting this alloca.
Chandler Carruth18db7952012-11-20 01:12:50 +00002609 if (V->getType()->isPointerTy())
2610 if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
Chandler Carruthac8317f2012-10-04 12:33:50 +00002611 Pass.PostPromotionWorklist.insert(AI);
2612
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002613 if (SliceSize < DL.getTypeStoreSize(V->getType())) {
Chandler Carruth18db7952012-11-20 01:12:50 +00002614 assert(!SI.isVolatile());
2615 assert(V->getType()->isIntegerTy() &&
2616 "Only integer type loads and stores are split");
Bjorn Petterssonb4771422019-05-24 09:20:20 +00002617 assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
Chandler Carruth18db7952012-11-20 01:12:50 +00002618 "Non-byte-multiple bit width");
Chandler Carruthc46b6eb2014-02-26 04:20:00 +00002619 IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
Chandler Carruth24ac8302015-01-02 03:55:54 +00002620 V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2621 "extract");
Chandler Carruth891fec02012-10-13 02:41:05 +00002622 }
2623
Chandler Carruth18db7952012-11-20 01:12:50 +00002624 if (VecTy)
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002625 return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
Chandler Carruth18db7952012-11-20 01:12:50 +00002626 if (IntTy && V->getType()->isIntegerTy())
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002627 return rewriteIntegerStore(V, SI, AATags);
Chandler Carruth435c4e02012-10-15 08:40:30 +00002628
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002629 const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
Chandler Carruth18db7952012-11-20 01:12:50 +00002630 StoreInst *NewSI;
Chandler Carruthf0546402013-07-18 07:15:00 +00002631 if (NewBeginOffset == NewAllocaBeginOffset &&
2632 NewEndOffset == NewAllocaEndOffset &&
Chandler Carruthccffdaf2015-07-22 03:32:42 +00002633 (canConvertValue(DL, V->getType(), NewAllocaTy) ||
2634 (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
2635 V->getType()->isIntegerTy()))) {
2636 // If this is an integer store past the end of slice (and thus the bytes
2637 // past that point are irrelevant or this is unreachable), truncate the
2638 // value prior to storing.
2639 if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2640 if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2641 if (VITy->getBitWidth() > AITy->getBitWidth()) {
2642 if (DL.isBigEndian())
2643 V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2644 "endian_shift");
2645 V = IRB.CreateTrunc(V, AITy, "load.trunc");
2646 }
2647
Chandler Carruth90a735d2013-07-19 07:21:28 +00002648 V = convertValue(DL, IRB, V, NewAllocaTy);
Chandler Carruth18db7952012-11-20 01:12:50 +00002649 NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2650 SI.isVolatile());
2651 } else {
Matt Arsenault3c1fc762017-04-10 22:27:50 +00002652 unsigned AS = SI.getPointerAddressSpace();
2653 Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
Chandler Carruth2659e502014-02-26 05:02:19 +00002654 NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2655 SI.isVolatile());
Chandler Carruth18db7952012-11-20 01:12:50 +00002656 }
Michael Kruse978ba612018-12-20 04:58:07 +00002657 NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2658 LLVMContext::MD_access_group});
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002659 if (AATags)
2660 NewSI->setAAMetadata(AATags);
David Majnemer62690b12015-07-14 06:19:58 +00002661 if (SI.isVolatile())
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00002662 NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruth18db7952012-11-20 01:12:50 +00002663 Pass.DeadInsts.insert(&SI);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002664 deleteIfTriviallyDead(OldOp);
Chandler Carruth18db7952012-11-20 01:12:50 +00002665
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002666 LLVM_DEBUG(dbgs() << " to: " << *NewSI << "\n");
Chandler Carruth18db7952012-11-20 01:12:50 +00002667 return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002668 }
2669
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002670 /// Compute an integer value from splatting an i8 across the given
Chandler Carruth514f34f2012-12-17 04:07:30 +00002671 /// number of bytes.
2672 ///
2673 /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2674 /// call this routine.
Jakub Staszak086f6cd2013-02-19 22:02:21 +00002675 /// FIXME: Heed the advice above.
Chandler Carruth514f34f2012-12-17 04:07:30 +00002676 ///
2677 /// \param V The i8 value to splat.
2678 /// \param Size The number of bytes in the output (assuming i8 is one byte)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002679 Value *getIntegerSplat(Value *V, unsigned Size) {
Chandler Carruth514f34f2012-12-17 04:07:30 +00002680 assert(Size > 0 && "Expected a positive number of bytes.");
2681 IntegerType *VTy = cast<IntegerType>(V->getType());
2682 assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2683 if (Size == 1)
2684 return V;
2685
Chandler Carruth113dc642014-12-20 02:39:18 +00002686 Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2687 V = IRB.CreateMul(
2688 IRB.CreateZExt(V, SplatIntTy, "zext"),
2689 ConstantExpr::getUDiv(
2690 Constant::getAllOnesValue(SplatIntTy),
2691 ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2692 SplatIntTy)),
2693 "isplat");
Chandler Carruth514f34f2012-12-17 04:07:30 +00002694 return V;
2695 }
2696
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002697 /// Compute a vector splat for a given element value.
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002698 Value *getVectorSplat(Value *V, unsigned NumElements) {
2699 V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002700 LLVM_DEBUG(dbgs() << " splat: " << *V << "\n");
Chandler Carruthccca5042012-12-17 04:07:37 +00002701 return V;
2702 }
2703
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002704 bool visitMemSetInst(MemSetInst &II) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002705 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002706 assert(II.getRawDest() == OldPtr);
2707
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002708 AAMDNodes AATags;
2709 II.getAAMetadata(AATags);
2710
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002711 // If the memset has a variable size, it cannot be split, just adjust the
2712 // pointer to the new alloca.
2713 if (!isa<Constant>(II.getLength())) {
Chandler Carruthf0546402013-07-18 07:15:00 +00002714 assert(!IsSplit);
Chandler Carruth735d5be2014-02-26 04:45:24 +00002715 assert(NewBeginOffset == BeginOffset);
Chandler Carruth47954c82014-02-26 05:12:43 +00002716 II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
Daniel Neilson41e781d2018-03-13 14:25:33 +00002717 II.setDestAlignment(getSliceAlign());
Chandler Carruth208124f2012-09-26 10:59:22 +00002718
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002719 deleteIfTriviallyDead(OldPtr);
2720 return false;
2721 }
2722
2723 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002724 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002725
2726 Type *AllocaTy = NewAI.getAllocatedType();
2727 Type *ScalarTy = AllocaTy->getScalarType();
Philip Reames9b6b4fa2019-03-12 20:15:05 +00002728
2729 const bool CanContinue = [&]() {
2730 if (VecTy || IntTy)
2731 return true;
2732 if (BeginOffset > NewAllocaBeginOffset ||
2733 EndOffset < NewAllocaEndOffset)
2734 return false;
2735 auto *C = cast<ConstantInt>(II.getLength());
2736 if (C->getBitWidth() > 64)
2737 return false;
2738 const auto Len = C->getZExtValue();
2739 auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
2740 auto *SrcTy = VectorType::get(Int8Ty, Len);
2741 return canConvertValue(DL, SrcTy, AllocaTy) &&
2742 DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy));
2743 }();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002744
2745 // If this doesn't map cleanly onto the alloca type, and that type isn't
2746 // a single value type, just emit a memset.
Philip Reames9b6b4fa2019-03-12 20:15:05 +00002747 if (!CanContinue) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002748 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002749 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2750 CallInst *New = IRB.CreateMemSet(
Chandler Carruth47954c82014-02-26 05:12:43 +00002751 getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2752 getSliceAlign(), II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002753 if (AATags)
2754 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002755 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002756 return false;
2757 }
2758
2759 // If we can represent this as a simple value, we have to build the actual
2760 // value to store, which requires expanding the byte present in memset to
2761 // a sensible representation for the alloca type. This is essentially
Chandler Carruthccca5042012-12-17 04:07:37 +00002762 // splatting the byte to a sufficiently wide integer, splatting it across
2763 // any desired vector width, and bitcasting to the final type.
Benjamin Kramerc003a452013-01-01 16:13:35 +00002764 Value *V;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002765
Chandler Carruthccca5042012-12-17 04:07:37 +00002766 if (VecTy) {
2767 // If this is a memset of a vectorized alloca, insert it.
2768 assert(ElementTy == ScalarTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002769
Chandler Carruthf0546402013-07-18 07:15:00 +00002770 unsigned BeginIndex = getIndex(NewBeginOffset);
2771 unsigned EndIndex = getIndex(NewEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002772 assert(EndIndex > BeginIndex && "Empty vector!");
2773 unsigned NumElements = EndIndex - BeginIndex;
2774 assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2775
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002776 Value *Splat =
Chandler Carruth90a735d2013-07-19 07:21:28 +00002777 getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2778 Splat = convertValue(DL, IRB, Splat, ElementTy);
Chandler Carruthcacda252012-12-17 14:03:01 +00002779 if (NumElements > 1)
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002780 Splat = getVectorSplat(Splat, NumElements);
Chandler Carruthccca5042012-12-17 04:07:37 +00002781
James Y Knight14359ef2019-02-01 20:44:24 +00002782 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2783 NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002784 V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
Chandler Carruthccca5042012-12-17 04:07:37 +00002785 } else if (IntTy) {
2786 // If this is a memset on an alloca where we can widen stores, insert the
2787 // set integer.
Chandler Carruth9d966a22012-10-15 10:24:40 +00002788 assert(!II.isVolatile());
Chandler Carruthccca5042012-12-17 04:07:37 +00002789
Chandler Carruthf0546402013-07-18 07:15:00 +00002790 uint64_t Size = NewEndOffset - NewBeginOffset;
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002791 V = getIntegerSplat(II.getValue(), Size);
Chandler Carruthccca5042012-12-17 04:07:37 +00002792
2793 if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2794 EndOffset != NewAllocaBeginOffset)) {
James Y Knight14359ef2019-02-01 20:44:24 +00002795 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2796 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002797 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002798 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002799 V = insertInteger(DL, IRB, Old, V, Offset, "insert");
Chandler Carruthccca5042012-12-17 04:07:37 +00002800 } else {
2801 assert(V->getType() == IntTy &&
2802 "Wrong type for an alloca wide integer!");
2803 }
Chandler Carruth90a735d2013-07-19 07:21:28 +00002804 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruthccca5042012-12-17 04:07:37 +00002805 } else {
2806 // Established these invariants above.
Chandler Carruthf0546402013-07-18 07:15:00 +00002807 assert(NewBeginOffset == NewAllocaBeginOffset);
2808 assert(NewEndOffset == NewAllocaEndOffset);
Chandler Carruthccca5042012-12-17 04:07:37 +00002809
Chandler Carruth90a735d2013-07-19 07:21:28 +00002810 V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
Chandler Carruthccca5042012-12-17 04:07:37 +00002811 if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002812 V = getVectorSplat(V, AllocaVecTy->getNumElements());
Chandler Carruth95e1fb82012-12-17 13:51:03 +00002813
Chandler Carruth90a735d2013-07-19 07:21:28 +00002814 V = convertValue(DL, IRB, V, AllocaTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002815 }
2816
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002817 StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2818 II.isVolatile());
2819 if (AATags)
2820 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002821 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002822 return !II.isVolatile();
2823 }
2824
2825 bool visitMemTransferInst(MemTransferInst &II) {
2826 // Rewriting of memory transfer instructions can be a bit tricky. We break
2827 // them into two categories: split intrinsics and unsplit intrinsics.
2828
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002829 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002830
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002831 AAMDNodes AATags;
2832 II.getAAMetadata(AATags);
2833
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002834 bool IsDest = &II.getRawDestUse() == OldUse;
Alexey Samsonov26af6f72014-02-25 07:56:00 +00002835 assert((IsDest && II.getRawDest() == OldPtr) ||
Chandler Carruthbb2a9322014-02-25 03:50:14 +00002836 (!IsDest && II.getRawSource() == OldPtr));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002837
Chandler Carruthaa72b932014-02-26 07:29:54 +00002838 unsigned SliceAlign = getSliceAlign();
Chandler Carruth176ca712012-10-01 12:16:54 +00002839
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002840 // For unsplit intrinsics, we simply modify the source and destination
2841 // pointers in place. This isn't just an optimization, it is a matter of
2842 // correctness. With unsplit intrinsics we may be dealing with transfers
2843 // within a single alloca before SROA ran, or with transfers that have
2844 // a variable length. We may also be dealing with memmove instead of
2845 // memcpy, and so simply updating the pointers is the necessary for us to
2846 // update both source and dest of a single call.
Chandler Carruthf0546402013-07-18 07:15:00 +00002847 if (!IsSplittable) {
Chandler Carruth47954c82014-02-26 05:12:43 +00002848 Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Daniel Neilson41e781d2018-03-13 14:25:33 +00002849 if (IsDest) {
Chandler Carruth8183a502014-02-25 11:08:02 +00002850 II.setDest(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002851 II.setDestAlignment(SliceAlign);
2852 }
2853 else {
Chandler Carruth8183a502014-02-25 11:08:02 +00002854 II.setSource(AdjustedPtr);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002855 II.setSourceAlignment(SliceAlign);
Chandler Carruth181ed052014-02-26 05:33:36 +00002856 }
Chandler Carruth208124f2012-09-26 10:59:22 +00002857
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002858 LLVM_DEBUG(dbgs() << " to: " << II << "\n");
Chandler Carruth8183a502014-02-25 11:08:02 +00002859 deleteIfTriviallyDead(OldPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002860 return false;
2861 }
2862 // For split transfer intrinsics we have an incredibly useful assurance:
2863 // the source and destination do not reside within the same alloca, and at
2864 // least one of them does not escape. This means that we can replace
2865 // memmove with memcpy, and we don't need to worry about all manner of
2866 // downsides to splitting and transforming the operations.
2867
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002868 // If this doesn't map cleanly onto the alloca type, and that type isn't
2869 // a single value type, just emit a memcpy.
Reid Klecknerc36f48f2014-08-22 00:09:56 +00002870 bool EmitMemCpy =
2871 !VecTy && !IntTy &&
2872 (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
2873 SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
2874 !NewAI.getAllocatedType()->isSingleValueType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002875
2876 // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2877 // size hasn't been shrunk based on analysis of the viable range, this is
2878 // a no-op.
2879 if (EmitMemCpy && &OldAI == &NewAI) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002880 // Ensure the start lines up.
Chandler Carruthf0546402013-07-18 07:15:00 +00002881 assert(NewBeginOffset == BeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002882
2883 // Rewrite the size as needed.
Chandler Carruthf0546402013-07-18 07:15:00 +00002884 if (NewEndOffset != EndOffset)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002885 II.setLength(ConstantInt::get(II.getLength()->getType(),
Chandler Carruthf0546402013-07-18 07:15:00 +00002886 NewEndOffset - NewBeginOffset));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002887 return false;
2888 }
2889 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00002890 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002891
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002892 // Strip all inbounds GEPs and pointer casts to try to dig out any root
2893 // alloca that should be re-examined after rewriting this instruction.
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002894 Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
Chandler Carruth113dc642014-12-20 02:39:18 +00002895 if (AllocaInst *AI =
2896 dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002897 assert(AI != &OldAI && AI != &NewAI &&
2898 "Splittable transfers cannot reach the same alloca on both ends.");
Chandler Carruth4bd8f662012-09-26 07:41:40 +00002899 Pass.Worklist.insert(AI);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00002900 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002901
Chandler Carruth286d87e2014-02-26 08:25:02 +00002902 Type *OtherPtrTy = OtherPtr->getType();
2903 unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2904
Chandler Carruth181ed052014-02-26 05:33:36 +00002905 // Compute the relative offset for the other pointer within the transfer.
Nicola Zaghenf96383c2018-10-30 11:15:04 +00002906 unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2907 APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
Daniel Neilson41e781d2018-03-13 14:25:33 +00002908 unsigned OtherAlign =
2909 IsDest ? II.getSourceAlignment() : II.getDestAlignment();
2910 OtherAlign = MinAlign(OtherAlign ? OtherAlign : 1,
2911 OtherOffset.zextOrTrunc(64).getZExtValue());
Chandler Carruth181ed052014-02-26 05:33:36 +00002912
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002913 if (EmitMemCpy) {
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002914 // Compute the other pointer, folding as much as possible to produce
2915 // a single, simple GEP in most cases.
Chandler Carruth181ed052014-02-26 05:33:36 +00002916 OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002917 OtherPtr->getName() + ".");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002918
Chandler Carruth47954c82014-02-26 05:12:43 +00002919 Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002920 Type *SizeTy = II.getLength()->getType();
Chandler Carruthf0546402013-07-18 07:15:00 +00002921 Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002922
Daniel Neilson41e781d2018-03-13 14:25:33 +00002923 Value *DestPtr, *SrcPtr;
2924 unsigned DestAlign, SrcAlign;
2925 // Note: IsDest is true iff we're copying into the new alloca slice
2926 if (IsDest) {
2927 DestPtr = OurPtr;
2928 DestAlign = SliceAlign;
2929 SrcPtr = OtherPtr;
2930 SrcAlign = OtherAlign;
2931 } else {
2932 DestPtr = OtherPtr;
2933 DestAlign = OtherAlign;
2934 SrcPtr = OurPtr;
2935 SrcAlign = SliceAlign;
2936 }
2937 CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2938 Size, II.isVolatile());
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002939 if (AATags)
2940 New->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002941 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002942 return false;
2943 }
2944
Chandler Carruthf0546402013-07-18 07:15:00 +00002945 bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2946 NewEndOffset == NewAllocaEndOffset;
2947 uint64_t Size = NewEndOffset - NewBeginOffset;
2948 unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
2949 unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002950 unsigned NumElements = EndIndex - BeginIndex;
Chandler Carruth113dc642014-12-20 02:39:18 +00002951 IntegerType *SubIntTy =
2952 IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002953
Chandler Carruth286d87e2014-02-26 08:25:02 +00002954 // Reset the other pointer type to match the register type we're going to
2955 // use, but using the address space of the original other pointer.
James Y Knight14359ef2019-02-01 20:44:24 +00002956 Type *OtherTy;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002957 if (VecTy && !IsWholeAlloca) {
2958 if (NumElements == 1)
James Y Knight14359ef2019-02-01 20:44:24 +00002959 OtherTy = VecTy->getElementType();
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002960 else
James Y Knight14359ef2019-02-01 20:44:24 +00002961 OtherTy = VectorType::get(VecTy->getElementType(), NumElements);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002962 } else if (IntTy && !IsWholeAlloca) {
James Y Knight14359ef2019-02-01 20:44:24 +00002963 OtherTy = SubIntTy;
Chandler Carruth286d87e2014-02-26 08:25:02 +00002964 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00002965 OtherTy = NewAllocaTy;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002966 }
James Y Knight14359ef2019-02-01 20:44:24 +00002967 OtherPtrTy = OtherTy->getPointerTo(OtherAS);
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002968
Chandler Carruth181ed052014-02-26 05:33:36 +00002969 Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
Chandler Carruthcb93cd22014-02-25 11:19:56 +00002970 OtherPtr->getName() + ".");
Pete Cooper67cf9a72015-11-19 05:56:52 +00002971 unsigned SrcAlign = OtherAlign;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002972 Value *DstPtr = &NewAI;
Chandler Carruthaa72b932014-02-26 07:29:54 +00002973 unsigned DstAlign = SliceAlign;
2974 if (!IsDest) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002975 std::swap(SrcPtr, DstPtr);
Chandler Carruthaa72b932014-02-26 07:29:54 +00002976 std::swap(SrcAlign, DstAlign);
2977 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002978
2979 Value *Src;
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002980 if (VecTy && !IsWholeAlloca && !IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00002981 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2982 NewAI.getAlignment(), "load");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00002983 Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
Chandler Carruth49c8eea2012-10-15 10:24:43 +00002984 } else if (IntTy && !IsWholeAlloca && !IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00002985 Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2986 NewAI.getAlignment(), "load");
Chandler Carruth90a735d2013-07-19 07:21:28 +00002987 Src = convertValue(DL, IRB, Src, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00002988 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00002989 Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002990 } else {
James Y Knight14359ef2019-02-01 20:44:24 +00002991 LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
2992 II.isVolatile(), "copyload");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00002993 if (AATags)
2994 Load->setAAMetadata(AATags);
2995 Src = Load;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00002996 }
2997
Chandler Carruth21eb4e92012-12-17 14:51:24 +00002998 if (VecTy && !IsWholeAlloca && IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00002999 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3000 NewAI.getAlignment(), "oldload");
Chandler Carruth34f0c7f2013-03-21 09:52:18 +00003001 Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
Chandler Carruth21eb4e92012-12-17 14:51:24 +00003002 } else if (IntTy && !IsWholeAlloca && IsDest) {
James Y Knight14359ef2019-02-01 20:44:24 +00003003 Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3004 NewAI.getAlignment(), "oldload");
Chandler Carruth90a735d2013-07-19 07:21:28 +00003005 Old = convertValue(DL, IRB, Old, IntTy);
Chandler Carruthf0546402013-07-18 07:15:00 +00003006 uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003007 Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3008 Src = convertValue(DL, IRB, Src, NewAllocaTy);
Chandler Carruth49c8eea2012-10-15 10:24:43 +00003009 }
3010
Chandler Carruth871ba722012-09-26 10:27:46 +00003011 StoreInst *Store = cast<StoreInst>(
Chandler Carruthaa72b932014-02-26 07:29:54 +00003012 IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003013 if (AATags)
3014 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003015 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003016 return !II.isVolatile();
3017 }
3018
3019 bool visitIntrinsicInst(IntrinsicInst &II) {
Vedant Kumarb264d692018-12-21 21:49:40 +00003020 assert(II.isLifetimeStartOrEnd());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003021 LLVM_DEBUG(dbgs() << " original: " << II << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003022 assert(II.getArgOperand(1) == OldPtr);
3023
3024 // Record this instruction for deletion.
Chandler Carruth18db7952012-11-20 01:12:50 +00003025 Pass.DeadInsts.insert(&II);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003026
Eli Friedman50967752016-11-28 21:50:34 +00003027 // Lifetime intrinsics are only promotable if they cover the whole alloca.
3028 // Therefore, we drop lifetime intrinsics which don't cover the whole
3029 // alloca.
3030 // (In theory, intrinsics which partially cover an alloca could be
3031 // promoted, but PromoteMemToReg doesn't handle that case.)
3032 // FIXME: Check whether the alloca is promotable before dropping the
3033 // lifetime intrinsics?
3034 if (NewBeginOffset != NewAllocaBeginOffset ||
3035 NewEndOffset != NewAllocaEndOffset)
3036 return true;
3037
Chandler Carruth113dc642014-12-20 02:39:18 +00003038 ConstantInt *Size =
3039 ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
Chandler Carruthf0546402013-07-18 07:15:00 +00003040 NewEndOffset - NewBeginOffset);
Gabor Buella3ec170c2019-01-16 12:06:17 +00003041 // Lifetime intrinsics always expect an i8* so directly get such a pointer
3042 // for the new alloca slice.
3043 Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3044 Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003045 Value *New;
3046 if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3047 New = IRB.CreateLifetimeStart(Ptr, Size);
3048 else
3049 New = IRB.CreateLifetimeEnd(Ptr, Size);
3050
Edwin Vane82f80d42013-01-29 17:42:24 +00003051 (void)New;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003052 LLVM_DEBUG(dbgs() << " to: " << *New << "\n");
Eli Friedman2a65dd12016-08-08 01:30:53 +00003053
Eli Friedman50967752016-11-28 21:50:34 +00003054 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003055 }
3056
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003057 void fixLoadStoreAlign(Instruction &Root) {
3058 // This algorithm implements the same visitor loop as
3059 // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3060 // or store found.
3061 SmallPtrSet<Instruction *, 4> Visited;
3062 SmallVector<Instruction *, 4> Uses;
3063 Visited.insert(&Root);
3064 Uses.push_back(&Root);
3065 do {
3066 Instruction *I = Uses.pop_back_val();
3067
3068 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3069 unsigned LoadAlign = LI->getAlignment();
3070 if (!LoadAlign)
3071 LoadAlign = DL.getABITypeAlignment(LI->getType());
3072 LI->setAlignment(std::min(LoadAlign, getSliceAlign()));
3073 continue;
3074 }
3075 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3076 unsigned StoreAlign = SI->getAlignment();
3077 if (!StoreAlign) {
3078 Value *Op = SI->getOperand(0);
3079 StoreAlign = DL.getABITypeAlignment(Op->getType());
3080 }
3081 SI->setAlignment(std::min(StoreAlign, getSliceAlign()));
3082 continue;
3083 }
3084
3085 assert(isa<BitCastInst>(I) || isa<PHINode>(I) ||
3086 isa<SelectInst>(I) || isa<GetElementPtrInst>(I));
3087 for (User *U : I->users())
3088 if (Visited.insert(cast<Instruction>(U)).second)
3089 Uses.push_back(cast<Instruction>(U));
3090 } while (!Uses.empty());
3091 }
3092
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003093 bool visitPHINode(PHINode &PN) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003094 LLVM_DEBUG(dbgs() << " original: " << PN << "\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00003095 assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3096 assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003097
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003098 // We would like to compute a new pointer in only one place, but have it be
3099 // as local as possible to the PHI. To do that, we re-use the location of
3100 // the old pointer, which necessarily must be in the right position to
3101 // dominate the PHI.
Chandler Carruth51175532014-02-25 11:12:04 +00003102 IRBuilderTy PtrBuilder(IRB);
David Majnemerd4cffcf2014-09-01 21:20:14 +00003103 if (isa<PHINode>(OldPtr))
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003104 PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
David Majnemerd4cffcf2014-09-01 21:20:14 +00003105 else
3106 PtrBuilder.SetInsertPoint(OldPtr);
Chandler Carruth51175532014-02-25 11:12:04 +00003107 PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003108
Chandler Carruth47954c82014-02-26 05:12:43 +00003109 Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
Chandler Carruth82a57542012-10-01 10:54:05 +00003110 // Replace the operands which were using the old pointer.
Benjamin Kramer7ddd7052012-10-20 12:04:57 +00003111 std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003112
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003113 LLVM_DEBUG(dbgs() << " to: " << PN << "\n");
Chandler Carruth82a57542012-10-01 10:54:05 +00003114 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003115
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003116 // Fix the alignment of any loads or stores using this PHI node.
3117 fixLoadStoreAlign(PN);
3118
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003119 // PHIs can't be promoted on their own, but often can be speculated. We
3120 // check the speculation outside of the rewriter so that we see the
3121 // fully-rewritten alloca.
3122 PHIUsers.insert(&PN);
3123 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003124 }
3125
3126 bool visitSelectInst(SelectInst &SI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003127 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003128 assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3129 "Pointer isn't an operand!");
Chandler Carruthf0546402013-07-18 07:15:00 +00003130 assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3131 assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
Chandler Carruth82a57542012-10-01 10:54:05 +00003132
Chandler Carruth47954c82014-02-26 05:12:43 +00003133 Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
Benjamin Kramer0212dc22013-04-21 17:48:39 +00003134 // Replace the operands which were using the old pointer.
3135 if (SI.getOperand(1) == OldPtr)
3136 SI.setOperand(1, NewPtr);
3137 if (SI.getOperand(2) == OldPtr)
3138 SI.setOperand(2, NewPtr);
3139
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003140 LLVM_DEBUG(dbgs() << " to: " << SI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003141 deleteIfTriviallyDead(OldPtr);
Chandler Carruthf0546402013-07-18 07:15:00 +00003142
Eli Friedman94d3e4d2018-08-30 18:59:24 +00003143 // Fix the alignment of any loads or stores using this select.
3144 fixLoadStoreAlign(SI);
3145
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00003146 // Selects can't be promoted on their own, but often can be speculated. We
3147 // check the speculation outside of the rewriter so that we see the
3148 // fully-rewritten alloca.
3149 SelectUsers.insert(&SI);
3150 return true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003151 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003152};
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003153
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003154namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003155
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003156/// Visitor to rewrite aggregate loads and stores as scalar.
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003157///
3158/// This pass aggressively rewrites all aggregate loads and stores on
3159/// a particular pointer (or any pointer derived from it which we can identify)
3160/// with scalar loads and stores.
3161class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3162 // Befriend the base class so it can delegate to private visit methods.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003163 friend class InstVisitor<AggLoadStoreRewriter, bool>;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003164
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003165 /// Queue of pointer uses to analyze and potentially rewrite.
3166 SmallVector<Use *, 8> Queue;
3167
3168 /// Set to prevent us from cycling with phi nodes and loops.
3169 SmallPtrSet<User *, 8> Visited;
3170
3171 /// The current pointer use being rewritten. This is used to dig up the used
3172 /// value (as opposed to the user).
3173 Use *U;
3174
Tim Northover856628f2018-12-18 09:29:39 +00003175 /// Used to calculate offsets, and hence alignment, of subobjects.
3176 const DataLayout &DL;
3177
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003178public:
Tim Northover856628f2018-12-18 09:29:39 +00003179 AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3180
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003181 /// Rewrite loads and stores through a pointer and all pointers derived from
3182 /// it.
3183 bool rewrite(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003184 LLVM_DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003185 enqueueUsers(I);
3186 bool Changed = false;
3187 while (!Queue.empty()) {
3188 U = Queue.pop_back_val();
3189 Changed |= visit(cast<Instruction>(U->getUser()));
3190 }
3191 return Changed;
3192 }
3193
3194private:
3195 /// Enqueue all the users of the given instruction for further processing.
3196 /// This uses a set to de-duplicate users.
3197 void enqueueUsers(Instruction &I) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003198 for (Use &U : I.uses())
David Blaikie70573dc2014-11-19 07:49:26 +00003199 if (Visited.insert(U.getUser()).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +00003200 Queue.push_back(&U);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003201 }
3202
3203 // Conservative default is to not rewrite anything.
3204 bool visitInstruction(Instruction &I) { return false; }
3205
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003206 /// Generic recursive split emission class.
Chandler Carruth113dc642014-12-20 02:39:18 +00003207 template <typename Derived> class OpSplitter {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003208 protected:
3209 /// The builder used to form new instructions.
Chandler Carruthd177f862013-03-20 07:30:36 +00003210 IRBuilderTy IRB;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003211
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003212 /// The indices which to be used with insert- or extractvalue to select the
3213 /// appropriate value within the aggregate.
3214 SmallVector<unsigned, 4> Indices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003215
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003216 /// The indices to a GEP instruction which will move Ptr to the correct slot
3217 /// within the aggregate.
3218 SmallVector<Value *, 4> GEPIndices;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003219
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003220 /// The base pointer of the original op, used as a base for GEPing the
3221 /// split operations.
3222 Value *Ptr;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003223
Tim Northover856628f2018-12-18 09:29:39 +00003224 /// The base pointee type being GEPed into.
3225 Type *BaseTy;
3226
3227 /// Known alignment of the base pointer.
3228 unsigned BaseAlign;
3229
3230 /// To calculate offset of each component so we can correctly deduce
3231 /// alignments.
3232 const DataLayout &DL;
3233
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003234 /// Initialize the splitter with an insertion point, Ptr and start with a
3235 /// single zero GEP index.
Tim Northover856628f2018-12-18 09:29:39 +00003236 OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3237 unsigned BaseAlign, const DataLayout &DL)
3238 : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr),
3239 BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003240
3241 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003242 /// Generic recursive split emission routine.
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003243 ///
3244 /// This method recursively splits an aggregate op (load or store) into
3245 /// scalar or vector ops. It splits recursively until it hits a single value
3246 /// and emits that single value operation via the template argument.
3247 ///
3248 /// The logic of this routine relies on GEPs and insertvalue and
3249 /// extractvalue all operating with the same fundamental index list, merely
3250 /// formatted differently (GEPs need actual values).
3251 ///
3252 /// \param Ty The type being split recursively into smaller ops.
3253 /// \param Agg The aggregate value being built up or stored, depending on
3254 /// whether this is splitting a load or a store respectively.
3255 void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
Tim Northover856628f2018-12-18 09:29:39 +00003256 if (Ty->isSingleValueType()) {
3257 unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3258 return static_cast<Derived *>(this)->emitFunc(
3259 Ty, Agg, MinAlign(BaseAlign, Offset), Name);
3260 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003261
3262 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3263 unsigned OldSize = Indices.size();
3264 (void)OldSize;
3265 for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3266 ++Idx) {
3267 assert(Indices.size() == OldSize && "Did not return to the old size");
3268 Indices.push_back(Idx);
3269 GEPIndices.push_back(IRB.getInt32(Idx));
3270 emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3271 GEPIndices.pop_back();
3272 Indices.pop_back();
3273 }
3274 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003275 }
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003276
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003277 if (StructType *STy = dyn_cast<StructType>(Ty)) {
3278 unsigned OldSize = Indices.size();
3279 (void)OldSize;
3280 for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3281 ++Idx) {
3282 assert(Indices.size() == OldSize && "Did not return to the old size");
3283 Indices.push_back(Idx);
3284 GEPIndices.push_back(IRB.getInt32(Idx));
3285 emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3286 GEPIndices.pop_back();
3287 Indices.pop_back();
3288 }
3289 return;
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003290 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003291
3292 llvm_unreachable("Only arrays and structs are aggregate loadable types");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003293 }
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003294 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003295
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003296 struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003297 AAMDNodes AATags;
3298
Tim Northover856628f2018-12-18 09:29:39 +00003299 LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3300 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3301 : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3302 DL), AATags(AATags) {}
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003303
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003304 /// Emit a leaf load of a single value. This is called at the leaves of the
3305 /// recursive emission to actually load values.
Tim Northover856628f2018-12-18 09:29:39 +00003306 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003307 assert(Ty->isSingleValueType());
3308 // Load the single value and insert it using the indices.
David Blaikieaa41cd52015-04-03 21:33:42 +00003309 Value *GEP =
James Y Knight77160752019-02-01 20:44:47 +00003310 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
James Y Knight14359ef2019-02-01 20:44:24 +00003311 LoadInst *Load = IRB.CreateAlignedLoad(Ty, GEP, Align, Name + ".load");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003312 if (AATags)
3313 Load->setAAMetadata(AATags);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003314 Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003315 LLVM_DEBUG(dbgs() << " to: " << *Load << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003316 }
3317 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003318
3319 bool visitLoadInst(LoadInst &LI) {
3320 assert(LI.getPointerOperand() == *U);
3321 if (!LI.isSimple() || LI.getType()->isSingleValueType())
3322 return false;
3323
3324 // We have an aggregate being loaded, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003325 LLVM_DEBUG(dbgs() << " original: " << LI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003326 AAMDNodes AATags;
3327 LI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003328 LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags,
3329 getAdjustedAlignment(&LI, 0, DL), DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003330 Value *V = UndefValue::get(LI.getType());
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003331 Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003332 LI.replaceAllUsesWith(V);
3333 LI.eraseFromParent();
3334 return true;
3335 }
3336
Benjamin Kramer73a9e4a2012-09-18 17:06:32 +00003337 struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
Tim Northover856628f2018-12-18 09:29:39 +00003338 StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3339 AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3340 : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3341 DL),
3342 AATags(AATags) {}
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003343 AAMDNodes AATags;
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003344 /// Emit a leaf store of a single value. This is called at the leaves of the
3345 /// recursive emission to actually produce stores.
Tim Northover856628f2018-12-18 09:29:39 +00003346 void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003347 assert(Ty->isSingleValueType());
3348 // Extract the single value and store it using the indices.
Patrik Hagglunda83706e2016-06-20 10:19:00 +00003349 //
3350 // The gep and extractvalue values are factored out of the CreateStore
3351 // call to make the output independent of the argument evaluation order.
Patrik Hagglund4e0bd842016-06-20 11:19:58 +00003352 Value *ExtractValue =
3353 IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3354 Value *InBoundsGEP =
James Y Knight77160752019-02-01 20:44:47 +00003355 IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
Tim Northover856628f2018-12-18 09:29:39 +00003356 StoreInst *Store =
3357 IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Align);
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003358 if (AATags)
3359 Store->setAAMetadata(AATags);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003360 LLVM_DEBUG(dbgs() << " to: " << *Store << "\n");
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003361 }
3362 };
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003363
3364 bool visitStoreInst(StoreInst &SI) {
3365 if (!SI.isSimple() || SI.getPointerOperand() != *U)
3366 return false;
3367 Value *V = SI.getValueOperand();
3368 if (V->getType()->isSingleValueType())
3369 return false;
3370
3371 // We have an aggregate being stored, split it apart.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003372 LLVM_DEBUG(dbgs() << " original: " << SI << "\n");
Ivan A. Kosarev53270d02018-02-16 10:10:29 +00003373 AAMDNodes AATags;
3374 SI.getAAMetadata(AATags);
Tim Northover856628f2018-12-18 09:29:39 +00003375 StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags,
3376 getAdjustedAlignment(&SI, 0, DL), DL);
Benjamin Kramer65f8c882012-09-18 16:20:46 +00003377 Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003378 SI.eraseFromParent();
3379 return true;
3380 }
3381
3382 bool visitBitCastInst(BitCastInst &BC) {
3383 enqueueUsers(BC);
3384 return false;
3385 }
3386
3387 bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3388 enqueueUsers(GEPI);
3389 return false;
3390 }
3391
3392 bool visitPHINode(PHINode &PN) {
3393 enqueueUsers(PN);
3394 return false;
3395 }
3396
3397 bool visitSelectInst(SelectInst &SI) {
3398 enqueueUsers(SI);
3399 return false;
3400 }
3401};
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003402
3403} // end anonymous namespace
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00003404
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003405/// Strip aggregate type wrapping.
Chandler Carruthba931992012-10-13 10:49:33 +00003406///
3407/// This removes no-op aggregate types wrapping an underlying type. It will
3408/// strip as many layers of types as it can without changing either the type
3409/// size or the allocated size.
3410static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3411 if (Ty->isSingleValueType())
3412 return Ty;
3413
3414 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3415 uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3416
3417 Type *InnerTy;
3418 if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3419 InnerTy = ArrTy->getElementType();
3420 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3421 const StructLayout *SL = DL.getStructLayout(STy);
3422 unsigned Index = SL->getElementContainingOffset(0);
3423 InnerTy = STy->getElementType(Index);
3424 } else {
3425 return Ty;
3426 }
3427
3428 if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3429 TypeSize > DL.getTypeSizeInBits(InnerTy))
3430 return Ty;
3431
3432 return stripAggregateTypeWrapping(DL, InnerTy);
3433}
3434
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003435/// Try to find a partition of the aggregate type passed in for a given
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003436/// offset and size.
3437///
3438/// This recurses through the aggregate type and tries to compute a subtype
3439/// based on the offset and size. When the offset and size span a sub-section
Chandler Carruth054a40a2012-09-14 11:08:31 +00003440/// of an array, it will even compute a new array type for that sub-section,
3441/// and the same for structs.
3442///
3443/// Note that this routine is very strict and tries to find a partition of the
3444/// type which produces the *exact* right offset and size. It is not forgiving
3445/// when the size or offset cause either end of type-based partition to be off.
3446/// Also, this is a best-effort routine. It is reasonable to give up and not
3447/// return a type if necessary.
Chandler Carruth113dc642014-12-20 02:39:18 +00003448static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3449 uint64_t Size) {
Chandler Carruth90a735d2013-07-19 07:21:28 +00003450 if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
3451 return stripAggregateTypeWrapping(DL, Ty);
3452 if (Offset > DL.getTypeAllocSize(Ty) ||
3453 (DL.getTypeAllocSize(Ty) - Offset) < Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003454 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003455
3456 if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003457 Type *ElementTy = SeqTy->getElementType();
Chandler Carruth90a735d2013-07-19 07:21:28 +00003458 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003459 uint64_t NumSkippedElements = Offset / ElementSize;
Peter Collingbournebc070522016-12-02 03:20:58 +00003460 if (NumSkippedElements >= SeqTy->getNumElements())
3461 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003462 Offset -= NumSkippedElements * ElementSize;
3463
3464 // First check if we need to recurse.
3465 if (Offset > 0 || Size < ElementSize) {
3466 // Bail if the partition ends in a different array element.
3467 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003468 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003469 // Recurse through the element type trying to peel off offset bytes.
Chandler Carruth90a735d2013-07-19 07:21:28 +00003470 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003471 }
3472 assert(Offset == 0);
3473
3474 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003475 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003476 assert(Size > ElementSize);
3477 uint64_t NumElements = Size / ElementSize;
3478 if (NumElements * ElementSize != Size)
Craig Topperf40110f2014-04-25 05:29:35 +00003479 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003480 return ArrayType::get(ElementTy, NumElements);
3481 }
3482
3483 StructType *STy = dyn_cast<StructType>(Ty);
3484 if (!STy)
Craig Topperf40110f2014-04-25 05:29:35 +00003485 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003486
Chandler Carruth90a735d2013-07-19 07:21:28 +00003487 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003488 if (Offset >= SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003489 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003490 uint64_t EndOffset = Offset + Size;
3491 if (EndOffset > SL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003492 return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003493
3494 unsigned Index = SL->getElementContainingOffset(Offset);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003495 Offset -= SL->getElementOffset(Index);
3496
3497 Type *ElementTy = STy->getElementType(Index);
Chandler Carruth90a735d2013-07-19 07:21:28 +00003498 uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003499 if (Offset >= ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003500 return nullptr; // The offset points into alignment padding.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003501
3502 // See if any partition must be contained by the element.
3503 if (Offset > 0 || Size < ElementSize) {
3504 if ((Offset + Size) > ElementSize)
Craig Topperf40110f2014-04-25 05:29:35 +00003505 return nullptr;
Chandler Carruth90a735d2013-07-19 07:21:28 +00003506 return getTypePartition(DL, ElementTy, Offset, Size);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003507 }
3508 assert(Offset == 0);
3509
3510 if (Size == ElementSize)
Chandler Carruth90a735d2013-07-19 07:21:28 +00003511 return stripAggregateTypeWrapping(DL, ElementTy);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003512
3513 StructType::element_iterator EI = STy->element_begin() + Index,
3514 EE = STy->element_end();
3515 if (EndOffset < SL->getSizeInBytes()) {
3516 unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3517 if (Index == EndIndex)
Craig Topperf40110f2014-04-25 05:29:35 +00003518 return nullptr; // Within a single element and its padding.
Chandler Carruth054a40a2012-09-14 11:08:31 +00003519
3520 // Don't try to form "natural" types if the elements don't line up with the
3521 // expected size.
3522 // FIXME: We could potentially recurse down through the last element in the
3523 // sub-struct to find a natural end point.
3524 if (SL->getElementOffset(EndIndex) != EndOffset)
Craig Topperf40110f2014-04-25 05:29:35 +00003525 return nullptr;
Chandler Carruth054a40a2012-09-14 11:08:31 +00003526
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003527 assert(Index < EndIndex);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003528 EE = STy->element_begin() + EndIndex;
3529 }
3530
3531 // Try to build up a sub-structure.
Chandler Carruth113dc642014-12-20 02:39:18 +00003532 StructType *SubTy =
3533 StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
Chandler Carruth90a735d2013-07-19 07:21:28 +00003534 const StructLayout *SubSL = DL.getStructLayout(SubTy);
Chandler Carruth054a40a2012-09-14 11:08:31 +00003535 if (Size != SubSL->getSizeInBytes())
Craig Topperf40110f2014-04-25 05:29:35 +00003536 return nullptr; // The sub-struct doesn't have quite the size needed.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003537
Chandler Carruth054a40a2012-09-14 11:08:31 +00003538 return SubTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00003539}
3540
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003541/// Pre-split loads and stores to simplify rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003542///
3543/// We want to break up the splittable load+store pairs as much as
3544/// possible. This is important to do as a preprocessing step, as once we
3545/// start rewriting the accesses to partitions of the alloca we lose the
3546/// necessary information to correctly split apart paired loads and stores
3547/// which both point into this alloca. The case to consider is something like
3548/// the following:
3549///
3550/// %a = alloca [12 x i8]
3551/// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3552/// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3553/// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3554/// %iptr1 = bitcast i8* %gep1 to i64*
3555/// %iptr2 = bitcast i8* %gep2 to i64*
3556/// %fptr1 = bitcast i8* %gep1 to float*
3557/// %fptr2 = bitcast i8* %gep2 to float*
3558/// %fptr3 = bitcast i8* %gep3 to float*
3559/// store float 0.0, float* %fptr1
3560/// store float 1.0, float* %fptr2
3561/// %v = load i64* %iptr1
3562/// store i64 %v, i64* %iptr2
3563/// %f1 = load float* %fptr2
3564/// %f2 = load float* %fptr3
3565///
3566/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3567/// promote everything so we recover the 2 SSA values that should have been
3568/// there all along.
3569///
3570/// \returns true if any changes are made.
3571bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003572 LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003573
3574 // Track the loads and stores which are candidates for pre-splitting here, in
3575 // the order they first appear during the partition scan. These give stable
3576 // iteration order and a basis for tracking which loads and stores we
3577 // actually split.
3578 SmallVector<LoadInst *, 4> Loads;
3579 SmallVector<StoreInst *, 4> Stores;
3580
3581 // We need to accumulate the splits required of each load or store where we
3582 // can find them via a direct lookup. This is important to cross-check loads
3583 // and stores against each other. We also track the slice so that we can kill
3584 // all the slices that end up split.
3585 struct SplitOffsets {
3586 Slice *S;
3587 std::vector<uint64_t> Splits;
3588 };
3589 SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3590
Chandler Carruth73b01642015-01-05 04:17:53 +00003591 // Track loads out of this alloca which cannot, for any reason, be pre-split.
3592 // This is important as we also cannot pre-split stores of those loads!
3593 // FIXME: This is all pretty gross. It means that we can be more aggressive
3594 // in pre-splitting when the load feeding the store happens to come from
3595 // a separate alloca. Put another way, the effectiveness of SROA would be
3596 // decreased by a frontend which just concatenated all of its local allocas
3597 // into one big flat alloca. But defeating such patterns is exactly the job
3598 // SROA is tasked with! Sadly, to not have this discrepancy we would have
3599 // change store pre-splitting to actually force pre-splitting of the load
3600 // that feeds it *and all stores*. That makes pre-splitting much harder, but
3601 // maybe it would make it more principled?
3602 SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3603
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003604 LLVM_DEBUG(dbgs() << " Searching for candidate loads and stores\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003605 for (auto &P : AS.partitions()) {
3606 for (Slice &S : P) {
Chandler Carruth73b01642015-01-05 04:17:53 +00003607 Instruction *I = cast<Instruction>(S.getUse()->getUser());
Chandler Carruth37f1f122016-03-10 15:31:17 +00003608 if (!S.isSplittable() || S.endOffset() <= P.endOffset()) {
3609 // If this is a load we have to track that it can't participate in any
3610 // pre-splitting. If this is a store of a load we have to track that
3611 // that load also can't participate in any pre-splitting.
Chandler Carruth73b01642015-01-05 04:17:53 +00003612 if (auto *LI = dyn_cast<LoadInst>(I))
3613 UnsplittableLoads.insert(LI);
Chandler Carruth37f1f122016-03-10 15:31:17 +00003614 else if (auto *SI = dyn_cast<StoreInst>(I))
3615 if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3616 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003617 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003618 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003619 assert(P.endOffset() > S.beginOffset() &&
3620 "Empty or backwards partition!");
3621
3622 // Determine if this is a pre-splittable slice.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003623 if (auto *LI = dyn_cast<LoadInst>(I)) {
3624 assert(!LI->isVolatile() && "Cannot split volatile loads!");
3625
3626 // The load must be used exclusively to store into other pointers for
3627 // us to be able to arbitrarily pre-split it. The stores must also be
3628 // simple to avoid changing semantics.
3629 auto IsLoadSimplyStored = [](LoadInst *LI) {
3630 for (User *LU : LI->users()) {
3631 auto *SI = dyn_cast<StoreInst>(LU);
3632 if (!SI || !SI->isSimple())
3633 return false;
3634 }
3635 return true;
3636 };
Chandler Carruth73b01642015-01-05 04:17:53 +00003637 if (!IsLoadSimplyStored(LI)) {
3638 UnsplittableLoads.insert(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003639 continue;
Chandler Carruth73b01642015-01-05 04:17:53 +00003640 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00003641
3642 Loads.push_back(LI);
Chandler Carruthd94a5962016-03-10 14:16:18 +00003643 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3644 if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3645 // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
Chandler Carruth994cde82015-01-01 12:01:03 +00003646 continue;
3647 auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3648 if (!StoredLoad || !StoredLoad->isSimple())
3649 continue;
3650 assert(!SI->isVolatile() && "Cannot split volatile stores!");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003651
Chandler Carruth994cde82015-01-01 12:01:03 +00003652 Stores.push_back(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003653 } else {
3654 // Other uses cannot be pre-split.
3655 continue;
3656 }
3657
3658 // Record the initial split.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003659 LLVM_DEBUG(dbgs() << " Candidate: " << *I << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003660 auto &Offsets = SplitOffsetsMap[I];
3661 assert(Offsets.Splits.empty() &&
3662 "Should not have splits the first time we see an instruction!");
3663 Offsets.S = &S;
Chandler Carruth24ac8302015-01-02 03:55:54 +00003664 Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003665 }
3666
3667 // Now scan the already split slices, and add a split for any of them which
3668 // we're going to pre-split.
3669 for (Slice *S : P.splitSliceTails()) {
3670 auto SplitOffsetsMapI =
3671 SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3672 if (SplitOffsetsMapI == SplitOffsetsMap.end())
3673 continue;
3674 auto &Offsets = SplitOffsetsMapI->second;
3675
3676 assert(Offsets.S == S && "Found a mismatched slice!");
3677 assert(!Offsets.Splits.empty() &&
3678 "Cannot have an empty set of splits on the second partition!");
Chandler Carruth24ac8302015-01-02 03:55:54 +00003679 assert(Offsets.Splits.back() ==
3680 P.beginOffset() - Offsets.S->beginOffset() &&
Chandler Carruth0715cba2015-01-01 11:54:38 +00003681 "Previous split does not end where this one begins!");
3682
3683 // Record each split. The last partition's end isn't needed as the size
3684 // of the slice dictates that.
3685 if (S->endOffset() > P.endOffset())
Chandler Carruth24ac8302015-01-02 03:55:54 +00003686 Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003687 }
3688 }
3689
3690 // We may have split loads where some of their stores are split stores. For
3691 // such loads and stores, we can only pre-split them if their splits exactly
3692 // match relative to their starting offset. We have to verify this prior to
3693 // any rewriting.
Chandler Carruth0715cba2015-01-01 11:54:38 +00003694 Stores.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003695 llvm::remove_if(Stores,
3696 [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3697 // Lookup the load we are storing in our map of split
3698 // offsets.
3699 auto *LI = cast<LoadInst>(SI->getValueOperand());
3700 // If it was completely unsplittable, then we're done,
3701 // and this store can't be pre-split.
3702 if (UnsplittableLoads.count(LI))
3703 return true;
Chandler Carruth73b01642015-01-05 04:17:53 +00003704
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003705 auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3706 if (LoadOffsetsI == SplitOffsetsMap.end())
3707 return false; // Unrelated loads are definitely safe.
3708 auto &LoadOffsets = LoadOffsetsI->second;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003709
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003710 // Now lookup the store's offsets.
3711 auto &StoreOffsets = SplitOffsetsMap[SI];
Chandler Carruth0715cba2015-01-01 11:54:38 +00003712
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003713 // If the relative offsets of each split in the load and
3714 // store match exactly, then we can split them and we
3715 // don't need to remove them here.
3716 if (LoadOffsets.Splits == StoreOffsets.Splits)
3717 return false;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003718
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003719 LLVM_DEBUG(
3720 dbgs()
3721 << " Mismatched splits for load and store:\n"
3722 << " " << *LI << "\n"
3723 << " " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003724
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003725 // We've found a store and load that we need to split
3726 // with mismatched relative splits. Just give up on them
3727 // and remove both instructions from our list of
3728 // candidates.
3729 UnsplittableLoads.insert(LI);
3730 return true;
3731 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003732 Stores.end());
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003733 // Now we have to go *back* through all the stores, because a later store may
Chandler Carruth73b01642015-01-05 04:17:53 +00003734 // have caused an earlier store's load to become unsplittable and if it is
3735 // unsplittable for the later store, then we can't rely on it being split in
3736 // the earlier store either.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003737 Stores.erase(llvm::remove_if(Stores,
3738 [&UnsplittableLoads](StoreInst *SI) {
3739 auto *LI =
3740 cast<LoadInst>(SI->getValueOperand());
3741 return UnsplittableLoads.count(LI);
3742 }),
Chandler Carruth73b01642015-01-05 04:17:53 +00003743 Stores.end());
3744 // Once we've established all the loads that can't be split for some reason,
3745 // filter any that made it into our list out.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003746 Loads.erase(llvm::remove_if(Loads,
3747 [&UnsplittableLoads](LoadInst *LI) {
3748 return UnsplittableLoads.count(LI);
3749 }),
Chandler Carruth0715cba2015-01-01 11:54:38 +00003750 Loads.end());
3751
3752 // If no loads or stores are left, there is no pre-splitting to be done for
3753 // this alloca.
3754 if (Loads.empty() && Stores.empty())
3755 return false;
3756
3757 // From here on, we can't fail and will be building new accesses, so rig up
3758 // an IR builder.
3759 IRBuilderTy IRB(&AI);
3760
3761 // Collect the new slices which we will merge into the alloca slices.
3762 SmallVector<Slice, 4> NewSlices;
3763
3764 // Track any allocas we end up splitting loads and stores for so we iterate
3765 // on them.
3766 SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3767
3768 // At this point, we have collected all of the loads and stores we can
3769 // pre-split, and the specific splits needed for them. We actually do the
3770 // splitting in a specific order in order to handle when one of the loads in
3771 // the value operand to one of the stores.
3772 //
3773 // First, we rewrite all of the split loads, and just accumulate each split
3774 // load in a parallel structure. We also build the slices for them and append
3775 // them to the alloca slices.
3776 SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3777 std::vector<LoadInst *> SplitLoads;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003778 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003779 for (LoadInst *LI : Loads) {
3780 SplitLoads.clear();
3781
3782 IntegerType *Ty = cast<IntegerType>(LI->getType());
3783 uint64_t LoadSize = Ty->getBitWidth() / 8;
3784 assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3785
3786 auto &Offsets = SplitOffsetsMap[LI];
3787 assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3788 "Slice size should always match load size exactly!");
3789 uint64_t BaseOffset = Offsets.S->beginOffset();
3790 assert(BaseOffset + LoadSize > BaseOffset &&
3791 "Cannot represent alloca access size using 64-bit integers!");
3792
3793 Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003794 IRB.SetInsertPoint(LI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003795
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003796 LLVM_DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003797
3798 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3799 int Idx = 0, Size = Offsets.Splits.size();
3800 for (;;) {
3801 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Yaxun Liu7c44f342017-06-27 18:26:06 +00003802 auto AS = LI->getPointerAddressSpace();
3803 auto *PartPtrTy = PartTy->getPointerTo(AS);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003804 LoadInst *PLoad = IRB.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00003805 PartTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003806 getAdjustedPtr(IRB, DL, BasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003807 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Chandler Carruth994cde82015-01-01 12:01:03 +00003808 PartPtrTy, BasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003809 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003810 LI->getName());
Michael Kruse978ba612018-12-20 04:58:07 +00003811 PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3812 LLVMContext::MD_access_group});
Chandler Carruth0715cba2015-01-01 11:54:38 +00003813
3814 // Append this load onto the list of split loads so we can find it later
3815 // to rewrite the stores.
3816 SplitLoads.push_back(PLoad);
3817
3818 // Now build a new slice for the alloca.
Chandler Carruth994cde82015-01-01 12:01:03 +00003819 NewSlices.push_back(
3820 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3821 &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003822 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003823 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3824 << ", " << NewSlices.back().endOffset()
3825 << "): " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003826
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003827 // See if we've handled all the splits.
3828 if (Idx >= Size)
3829 break;
3830
Chandler Carruth0715cba2015-01-01 11:54:38 +00003831 // Setup the next partition.
3832 PartOffset = Offsets.Splits[Idx];
3833 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003834 PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
3835 }
3836
3837 // Now that we have the split loads, do the slow walk over all uses of the
3838 // load and rewrite them as split stores, or save the split loads to use
3839 // below if the store is going to be split there anyways.
3840 bool DeferredStores = false;
3841 for (User *LU : LI->users()) {
3842 StoreInst *SI = cast<StoreInst>(LU);
3843 if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
3844 DeferredStores = true;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003845 LLVM_DEBUG(dbgs() << " Deferred splitting of store: " << *SI
3846 << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003847 continue;
3848 }
3849
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003850 Value *StoreBasePtr = SI->getPointerOperand();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003851 IRB.SetInsertPoint(SI);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003852
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003853 LLVM_DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003854
3855 for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
3856 LoadInst *PLoad = SplitLoads[Idx];
3857 uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
Chandler Carruth994cde82015-01-01 12:01:03 +00003858 auto *PartPtrTy =
3859 PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003860
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003861 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003862 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003863 PLoad,
3864 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003865 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003866 PartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003867 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Michael Kruse978ba612018-12-20 04:58:07 +00003868 PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3869 LLVMContext::MD_access_group});
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003870 LLVM_DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003871 }
3872
3873 // We want to immediately iterate on any allocas impacted by splitting
3874 // this store, and we have to track any promotable alloca (indicated by
3875 // a direct store) as needing to be resplit because it is no longer
3876 // promotable.
3877 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3878 ResplitPromotableAllocas.insert(OtherAI);
3879 Worklist.insert(OtherAI);
3880 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3881 StoreBasePtr->stripInBoundsOffsets())) {
3882 Worklist.insert(OtherAI);
3883 }
3884
3885 // Mark the original store as dead.
3886 DeadInsts.insert(SI);
3887 }
3888
3889 // Save the split loads if there are deferred stores among the users.
3890 if (DeferredStores)
3891 SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3892
3893 // Mark the original load as dead and kill the original slice.
3894 DeadInsts.insert(LI);
3895 Offsets.S->kill();
3896 }
3897
3898 // Second, we rewrite all of the split stores. At this point, we know that
3899 // all loads from this alloca have been split already. For stores of such
3900 // loads, we can simply look up the pre-existing split loads. For stores of
3901 // other loads, we split those loads first and then write split stores of
3902 // them.
3903 for (StoreInst *SI : Stores) {
3904 auto *LI = cast<LoadInst>(SI->getValueOperand());
3905 IntegerType *Ty = cast<IntegerType>(LI->getType());
3906 uint64_t StoreSize = Ty->getBitWidth() / 8;
3907 assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3908
3909 auto &Offsets = SplitOffsetsMap[SI];
3910 assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3911 "Slice size should always match load size exactly!");
3912 uint64_t BaseOffset = Offsets.S->beginOffset();
3913 assert(BaseOffset + StoreSize > BaseOffset &&
3914 "Cannot represent alloca access size using 64-bit integers!");
3915
Chandler Carruthc39eaa52015-01-01 23:26:16 +00003916 Value *LoadBasePtr = LI->getPointerOperand();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003917 Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3918
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003919 LLVM_DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003920
3921 // Check whether we have an already split load.
3922 auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3923 std::vector<LoadInst *> *SplitLoads = nullptr;
3924 if (SplitLoadsMapI != SplitLoadsMap.end()) {
3925 SplitLoads = &SplitLoadsMapI->second;
3926 assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3927 "Too few split loads for the number of splits in the store!");
3928 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003929 LLVM_DEBUG(dbgs() << " of load: " << *LI << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003930 }
3931
Chandler Carruth0715cba2015-01-01 11:54:38 +00003932 uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3933 int Idx = 0, Size = Offsets.Splits.size();
3934 for (;;) {
3935 auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
Keno Fischer514a6a52017-06-02 19:04:17 +00003936 auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3937 auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
Chandler Carruth0715cba2015-01-01 11:54:38 +00003938
3939 // Either lookup a split load or create one.
3940 LoadInst *PLoad;
3941 if (SplitLoads) {
3942 PLoad = (*SplitLoads)[Idx];
3943 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003944 IRB.SetInsertPoint(LI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003945 auto AS = LI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003946 PLoad = IRB.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00003947 PartTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003948 getAdjustedPtr(IRB, DL, LoadBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003949 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Keno Fischer514a6a52017-06-02 19:04:17 +00003950 LoadPartPtrTy, LoadBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003951 getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
Chandler Carruth0715cba2015-01-01 11:54:38 +00003952 LI->getName());
3953 }
3954
3955 // And store this partition.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00003956 IRB.SetInsertPoint(SI);
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003957 auto AS = SI->getPointerAddressSpace();
Chandler Carruth0715cba2015-01-01 11:54:38 +00003958 StoreInst *PStore = IRB.CreateAlignedStore(
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003959 PLoad,
3960 getAdjustedPtr(IRB, DL, StoreBasePtr,
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003961 APInt(DL.getIndexSizeInBits(AS), PartOffset),
Yaxun Liu6455b0d2017-06-09 20:46:29 +00003962 StorePartPtrTy, StoreBasePtr->getName() + "."),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003963 getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
Chandler Carruth0715cba2015-01-01 11:54:38 +00003964
3965 // Now build a new slice for the alloca.
3966 NewSlices.push_back(
3967 Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3968 &PStore->getOperandUse(PStore->getPointerOperandIndex()),
Chandler Carruth24ac8302015-01-02 03:55:54 +00003969 /*IsSplittable*/ false));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003970 LLVM_DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
3971 << ", " << NewSlices.back().endOffset()
3972 << "): " << *PStore << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003973 if (!SplitLoads) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003974 LLVM_DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00003975 }
3976
Chandler Carruth29c22fa2015-01-02 00:10:22 +00003977 // See if we've finished all the splits.
3978 if (Idx >= Size)
3979 break;
3980
Chandler Carruth0715cba2015-01-01 11:54:38 +00003981 // Setup the next partition.
3982 PartOffset = Offsets.Splits[Idx];
3983 ++Idx;
Chandler Carruth0715cba2015-01-01 11:54:38 +00003984 PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
3985 }
3986
3987 // We want to immediately iterate on any allocas impacted by splitting
3988 // this load, which is only relevant if it isn't a load of this alloca and
3989 // thus we didn't already split the loads above. We also have to keep track
3990 // of any promotable allocas we split loads on as they can no longer be
3991 // promoted.
3992 if (!SplitLoads) {
3993 if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
3994 assert(OtherAI != &AI && "We can't re-split our own alloca!");
3995 ResplitPromotableAllocas.insert(OtherAI);
3996 Worklist.insert(OtherAI);
3997 } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3998 LoadBasePtr->stripInBoundsOffsets())) {
3999 assert(OtherAI != &AI && "We can't re-split our own alloca!");
4000 Worklist.insert(OtherAI);
4001 }
4002 }
4003
4004 // Mark the original store as dead now that we've split it up and kill its
Chandler Carruth24ac8302015-01-02 03:55:54 +00004005 // slice. Note that we leave the original load in place unless this store
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004006 // was its only use. It may in turn be split up if it is an alloca load
Chandler Carruth24ac8302015-01-02 03:55:54 +00004007 // for some other alloca, but it may be a normal load. This may introduce
4008 // redundant loads, but where those can be merged the rest of the optimizer
4009 // should handle the merging, and this uncovers SSA splits which is more
4010 // important. In practice, the original loads will almost always be fully
4011 // split and removed eventually, and the splits will be merged by any
4012 // trivial CSE, including instcombine.
4013 if (LI->hasOneUse()) {
4014 assert(*LI->user_begin() == SI && "Single use isn't this store!");
4015 DeadInsts.insert(LI);
4016 }
Chandler Carruth0715cba2015-01-01 11:54:38 +00004017 DeadInsts.insert(SI);
4018 Offsets.S->kill();
4019 }
4020
Chandler Carruth24ac8302015-01-02 03:55:54 +00004021 // Remove the killed slices that have ben pre-split.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004022 AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
4023 AS.end());
Chandler Carruth0715cba2015-01-01 11:54:38 +00004024
Chandler Carruth24ac8302015-01-02 03:55:54 +00004025 // Insert our new slices. This will sort and merge them into the sorted
4026 // sequence.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004027 AS.insert(NewSlices);
4028
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004029 LLVM_DEBUG(dbgs() << " Pre-split slices:\n");
Chandler Carruth0715cba2015-01-01 11:54:38 +00004030#ifndef NDEBUG
4031 for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004032 LLVM_DEBUG(AS.print(dbgs(), I, " "));
Chandler Carruth0715cba2015-01-01 11:54:38 +00004033#endif
4034
4035 // Finally, don't try to promote any allocas that new require re-splitting.
4036 // They have already been added to the worklist above.
4037 PromotableAllocas.erase(
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004038 llvm::remove_if(
David Majnemerc7004902016-08-12 04:32:37 +00004039 PromotableAllocas,
Chandler Carruth0715cba2015-01-01 11:54:38 +00004040 [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
4041 PromotableAllocas.end());
4042
4043 return true;
4044}
4045
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004046/// Rewrite an alloca partition's users.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004047///
4048/// This routine drives both of the rewriting goals of the SROA pass. It tries
4049/// to rewrite uses of an alloca partition to be conducive for SSA value
4050/// promotion. If the partition needs a new, more refined alloca, this will
4051/// build that new alloca, preserving as much type information as possible, and
4052/// rewrite the uses of the old alloca to point at the new one and have the
4053/// appropriate new offsets. It also evaluates how successful the rewrite was
4054/// at enabling promotion and if it was successful queues the alloca to be
4055/// promoted.
Adrian Prantl565cc182015-01-20 19:42:22 +00004056AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
Chandler Carruth29a18a42015-09-12 09:09:14 +00004057 Partition &P) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004058 // Try to compute a friendly type for this partition of the alloca. This
4059 // won't always succeed, in which case we fall back to a legal integer type
4060 // or an i8 array of an appropriate size.
Craig Topperf40110f2014-04-25 05:29:35 +00004061 Type *SliceTy = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004062 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004063 if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004064 if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004065 SliceTy = CommonUseTy;
4066 if (!SliceTy)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004067 if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004068 P.beginOffset(), P.size()))
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004069 SliceTy = TypePartitionTy;
4070 if ((!SliceTy || (SliceTy->isArrayTy() &&
4071 SliceTy->getArrayElementType()->isIntegerTy())) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004072 DL.isLegalInteger(P.size() * 8))
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004073 SliceTy = Type::getIntNTy(*C, P.size() * 8);
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004074 if (!SliceTy)
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004075 SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004076 assert(DL.getTypeAllocSize(SliceTy) >= P.size());
Chandler Carruthf0546402013-07-18 07:15:00 +00004077
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004078 bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
Chandler Carruthf0546402013-07-18 07:15:00 +00004079
Chandler Carruth2dc96822014-10-18 00:44:02 +00004080 VectorType *VecTy =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004081 IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
Chandler Carruth2dc96822014-10-18 00:44:02 +00004082 if (VecTy)
4083 SliceTy = VecTy;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004084
4085 // Check for the case where we're going to rewrite to a new alloca of the
4086 // exact same type as the original, and with the same access offsets. In that
4087 // case, re-use the existing alloca, but still run through the rewriter to
Jakub Staszak086f6cd2013-02-19 22:02:21 +00004088 // perform phi and select speculation.
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004089 // P.beginOffset() can be non-zero even with the same type in a case with
4090 // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004091 AllocaInst *NewAI;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004092 if (SliceTy == AI.getAllocatedType() && P.beginOffset() == 0) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004093 NewAI = &AI;
Chandler Carruthf0546402013-07-18 07:15:00 +00004094 // FIXME: We should be able to bail at this point with "nothing changed".
4095 // FIXME: We might want to defer PHI speculation until after here.
Adrian Prantl565cc182015-01-20 19:42:22 +00004096 // FIXME: return nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004097 } else {
Chandler Carruth903790e2012-09-29 10:41:21 +00004098 unsigned Alignment = AI.getAlignment();
4099 if (!Alignment) {
4100 // The minimum alignment which users can rely on when the explicit
4101 // alignment is omitted or zero is that required by the ABI for this
4102 // type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004103 Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
Chandler Carruth903790e2012-09-29 10:41:21 +00004104 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004105 Alignment = MinAlign(Alignment, P.beginOffset());
Chandler Carruth903790e2012-09-29 10:41:21 +00004106 // If we will get at least this much alignment from the type alone, leave
4107 // the alloca's alignment unconstrained.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004108 if (Alignment <= DL.getABITypeAlignment(SliceTy))
Chandler Carruth903790e2012-09-29 10:41:21 +00004109 Alignment = 0;
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004110 NewAI = new AllocaInst(
Matt Arsenault3c1fc762017-04-10 22:27:50 +00004111 SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004112 AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
Anastasis Grammenos425df222018-06-28 18:58:30 +00004113 // Copy the old AI debug location over to the new one.
4114 NewAI->setDebugLoc(AI.getDebugLoc());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004115 ++NumNewAllocas;
4116 }
4117
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004118 LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4119 << "[" << P.beginOffset() << "," << P.endOffset()
4120 << ") to: " << *NewAI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004121
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004122 // Track the high watermark on the worklist as it is only relevant for
Chandler Carruthf0546402013-07-18 07:15:00 +00004123 // promoted allocas. We will reset it to this point if the alloca is not in
4124 // fact scheduled for promotion.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004125 unsigned PPWOldSize = PostPromotionWorklist.size();
Chandler Carruth6c321c12013-07-19 10:57:36 +00004126 unsigned NumUses = 0;
Davide Italiano81a26da2017-04-27 23:09:01 +00004127 SmallSetVector<PHINode *, 8> PHIUsers;
4128 SmallSetVector<SelectInst *, 8> SelectUsers;
Chandler Carruth6c321c12013-07-19 10:57:36 +00004129
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004130 AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004131 P.endOffset(), IsIntegerPromotable, VecTy,
4132 PHIUsers, SelectUsers);
Chandler Carruthf0546402013-07-18 07:15:00 +00004133 bool Promotable = true;
Chandler Carruthffb7ce52014-12-24 01:48:09 +00004134 for (Slice *S : P.splitSliceTails()) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004135 Promotable &= Rewriter.visit(S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004136 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004137 }
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004138 for (Slice &S : P) {
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004139 Promotable &= Rewriter.visit(&S);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004140 ++NumUses;
Chandler Carruthf0546402013-07-18 07:15:00 +00004141 }
4142
Chandler Carruth6c321c12013-07-19 10:57:36 +00004143 NumAllocaPartitionUses += NumUses;
Craig Topper8a950272017-05-18 00:51:39 +00004144 MaxUsesPerAllocaPartition.updateMax(NumUses);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004145
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004146 // Now that we've processed all the slices in the new partition, check if any
4147 // PHIs or Selects would block promotion.
Davide Italiano81a26da2017-04-27 23:09:01 +00004148 for (PHINode *PHI : PHIUsers)
4149 if (!isSafePHIToSpeculate(*PHI)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004150 Promotable = false;
4151 PHIUsers.clear();
4152 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004153 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004154 }
Davide Italiano81a26da2017-04-27 23:09:01 +00004155
4156 for (SelectInst *Sel : SelectUsers)
4157 if (!isSafeSelectToSpeculate(*Sel)) {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004158 Promotable = false;
4159 PHIUsers.clear();
4160 SelectUsers.clear();
Chandler Carrutha8c4cc62014-02-25 09:45:27 +00004161 break;
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004162 }
4163
4164 if (Promotable) {
4165 if (PHIUsers.empty() && SelectUsers.empty()) {
4166 // Promote the alloca.
4167 PromotableAllocas.push_back(NewAI);
4168 } else {
4169 // If we have either PHIs or Selects to speculate, add them to those
4170 // worklists and re-queue the new alloca so that we promote in on the
4171 // next iteration.
Chandler Carruth61747042014-10-16 21:05:14 +00004172 for (PHINode *PHIUser : PHIUsers)
4173 SpeculatablePHIs.insert(PHIUser);
4174 for (SelectInst *SelectUser : SelectUsers)
4175 SpeculatableSelects.insert(SelectUser);
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004176 Worklist.insert(NewAI);
4177 }
4178 } else {
Chandler Carruth3bf18ed2014-02-25 00:07:09 +00004179 // Drop any post-promotion work items if promotion didn't happen.
Chandler Carruthac8317f2012-10-04 12:33:50 +00004180 while (PostPromotionWorklist.size() > PPWOldSize)
4181 PostPromotionWorklist.pop_back();
David Majnemer30ffc4c2016-04-26 01:05:00 +00004182
4183 // We couldn't promote and we didn't create a new partition, nothing
4184 // happened.
4185 if (NewAI == &AI)
4186 return nullptr;
4187
4188 // If we can't promote the alloca, iterate on it to check for new
4189 // refinements exposed by splitting the current alloca. Don't iterate on an
4190 // alloca which didn't actually change and didn't get promoted.
4191 Worklist.insert(NewAI);
Chandler Carruthf0546402013-07-18 07:15:00 +00004192 }
Chandler Carruthac8317f2012-10-04 12:33:50 +00004193
Adrian Prantl565cc182015-01-20 19:42:22 +00004194 return NewAI;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004195}
4196
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004197/// Walks the slices of an alloca and form partitions based on them,
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004198/// rewriting each of their uses.
Chandler Carruth83934062014-10-16 21:11:55 +00004199bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4200 if (AS.begin() == AS.end())
Chandler Carruthf0546402013-07-18 07:15:00 +00004201 return false;
4202
Chandler Carruth6c321c12013-07-19 10:57:36 +00004203 unsigned NumPartitions = 0;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004204 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004205 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruthf0546402013-07-18 07:15:00 +00004206
Chandler Carruth24ac8302015-01-02 03:55:54 +00004207 // First try to pre-split loads and stores.
Chandler Carruth0715cba2015-01-01 11:54:38 +00004208 Changed |= presplitLoadsAndStores(AI, AS);
4209
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004210 // Now that we have identified any pre-splitting opportunities,
4211 // mark loads and stores unsplittable except for the following case.
4212 // We leave a slice splittable if all other slices are disjoint or fully
4213 // included in the slice, such as whole-alloca loads and stores.
4214 // If we fail to split these during pre-splitting, we want to force them
4215 // to be rewritten into a partition.
Chandler Carruth24ac8302015-01-02 03:55:54 +00004216 bool IsSorted = true;
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004217
4218 uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType());
4219 const uint64_t MaxBitVectorSize = 1024;
Hiroshi Inoue99a8faa2018-01-16 06:23:05 +00004220 if (AllocaSize <= MaxBitVectorSize) {
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004221 // If a byte boundary is included in any load or store, a slice starting or
4222 // ending at the boundary is not splittable.
4223 SmallBitVector SplittableOffset(AllocaSize + 1, true);
4224 for (Slice &S : AS)
4225 for (unsigned O = S.beginOffset() + 1;
4226 O < S.endOffset() && O < AllocaSize; O++)
4227 SplittableOffset.reset(O);
4228
4229 for (Slice &S : AS) {
4230 if (!S.isSplittable())
4231 continue;
4232
4233 if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4234 (S.endOffset() > AllocaSize || SplittableOffset[S.endOffset()]))
4235 continue;
4236
4237 if (isa<LoadInst>(S.getUse()->getUser()) ||
4238 isa<StoreInst>(S.getUse()->getUser())) {
4239 S.makeUnsplittable();
4240 IsSorted = false;
4241 }
Chandler Carruth24ac8302015-01-02 03:55:54 +00004242 }
4243 }
Hiroshi Inoue48e4c7a2017-12-01 06:05:05 +00004244 else {
4245 // We only allow whole-alloca splittable loads and stores
4246 // for a large alloca to avoid creating too large BitVector.
4247 for (Slice &S : AS) {
4248 if (!S.isSplittable())
4249 continue;
4250
4251 if (S.beginOffset() == 0 && S.endOffset() >= AllocaSize)
4252 continue;
4253
4254 if (isa<LoadInst>(S.getUse()->getUser()) ||
4255 isa<StoreInst>(S.getUse()->getUser())) {
4256 S.makeUnsplittable();
4257 IsSorted = false;
4258 }
4259 }
4260 }
4261
Chandler Carruth24ac8302015-01-02 03:55:54 +00004262 if (!IsSorted)
Fangrui Song0cac7262018-09-27 02:13:45 +00004263 llvm::sort(AS);
Chandler Carruth24ac8302015-01-02 03:55:54 +00004264
Adrian Prantl941fa752016-12-05 18:04:47 +00004265 /// Describes the allocas introduced by rewritePartition in order to migrate
4266 /// the debug info.
4267 struct Fragment {
Adrian Prantl565cc182015-01-20 19:42:22 +00004268 AllocaInst *Alloca;
4269 uint64_t Offset;
4270 uint64_t Size;
Adrian Prantl941fa752016-12-05 18:04:47 +00004271 Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
Adrian Prantl565cc182015-01-20 19:42:22 +00004272 : Alloca(AI), Offset(O), Size(S) {}
4273 };
Adrian Prantl941fa752016-12-05 18:04:47 +00004274 SmallVector<Fragment, 4> Fragments;
Adrian Prantl565cc182015-01-20 19:42:22 +00004275
Chandler Carruth0715cba2015-01-01 11:54:38 +00004276 // Rewrite each partition.
Chandler Carruthe2f66ce2014-12-22 22:46:00 +00004277 for (auto &P : AS.partitions()) {
Adrian Prantl565cc182015-01-20 19:42:22 +00004278 if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4279 Changed = true;
Adrian Prantl34e75902015-02-09 23:57:22 +00004280 if (NewAI != &AI) {
4281 uint64_t SizeOfByte = 8;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004282 uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
Adrian Prantl34e75902015-02-09 23:57:22 +00004283 // Don't include any padding.
4284 uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
Adrian Prantl941fa752016-12-05 18:04:47 +00004285 Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
Adrian Prantl34e75902015-02-09 23:57:22 +00004286 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004287 }
Chandler Carruth6c321c12013-07-19 10:57:36 +00004288 ++NumPartitions;
Chandler Carruthf0546402013-07-18 07:15:00 +00004289 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004290
Chandler Carruth6c321c12013-07-19 10:57:36 +00004291 NumAllocaPartitions += NumPartitions;
Craig Topper8a950272017-05-18 00:51:39 +00004292 MaxPartitionsPerAlloca.updateMax(NumPartitions);
Chandler Carruth6c321c12013-07-19 10:57:36 +00004293
Adrian Prantl565cc182015-01-20 19:42:22 +00004294 // Migrate debug information from the old alloca to the new alloca(s)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004295 // and the individual partitions.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004296 TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004297 if (!DbgDeclares.empty()) {
4298 auto *Var = DbgDeclares.front()->getVariable();
4299 auto *Expr = DbgDeclares.front()->getExpression();
Adrian Prantld7f6f162017-11-28 00:57:53 +00004300 auto VarSize = Var->getSizeInBits();
Sanjay Patelaf674fb2015-12-14 17:24:23 +00004301 DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
Keno Fischerd5354fd2016-01-14 20:06:34 +00004302 uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
Adrian Prantl941fa752016-12-05 18:04:47 +00004303 for (auto Fragment : Fragments) {
4304 // Create a fragment expression describing the new partition or reuse AI's
Adrian Prantl565cc182015-01-20 19:42:22 +00004305 // expression if there is only one partition.
Adrian Prantl941fa752016-12-05 18:04:47 +00004306 auto *FragmentExpr = Expr;
4307 if (Fragment.Size < AllocaSize || Expr->isFragment()) {
Adrian Prantl152ac392015-02-01 00:58:04 +00004308 // If this alloca is already a scalar replacement of a larger aggregate,
Adrian Prantl941fa752016-12-05 18:04:47 +00004309 // Fragment.Offset describes the offset inside the scalar.
Adrian Prantl49797ca2016-12-22 05:27:12 +00004310 auto ExprFragment = Expr->getFragmentInfo();
4311 uint64_t Offset = ExprFragment ? ExprFragment->OffsetInBits : 0;
Adrian Prantl941fa752016-12-05 18:04:47 +00004312 uint64_t Start = Offset + Fragment.Offset;
4313 uint64_t Size = Fragment.Size;
Adrian Prantl49797ca2016-12-22 05:27:12 +00004314 if (ExprFragment) {
Adrian Prantl941fa752016-12-05 18:04:47 +00004315 uint64_t AbsEnd =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00004316 ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
Adrian Prantl34e75902015-02-09 23:57:22 +00004317 if (Start >= AbsEnd)
4318 // No need to describe a SROAed padding.
4319 continue;
4320 Size = std::min(Size, AbsEnd - Start);
4321 }
Adrian Prantlb192b542017-08-30 20:04:17 +00004322 // The new, smaller fragment is stenciled out from the old fragment.
4323 if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4324 assert(Start >= OrigFragment->OffsetInBits &&
4325 "new fragment is outside of original fragment");
4326 Start -= OrigFragment->OffsetInBits;
4327 }
Adrian Prantl77d90b02017-11-28 21:30:38 +00004328
4329 // The alloca may be larger than the variable.
4330 if (VarSize) {
4331 if (Size > *VarSize)
4332 Size = *VarSize;
4333 if (Size == 0 || Start + Size > *VarSize)
4334 continue;
4335 }
4336
Adrian Prantld7f6f162017-11-28 00:57:53 +00004337 // Avoid creating a fragment expression that covers the entire variable.
4338 if (!VarSize || *VarSize != Size) {
4339 if (auto E =
4340 DIExpression::createFragmentExpression(Expr, Start, Size))
4341 FragmentExpr = *E;
4342 else
4343 continue;
4344 }
Adrian Prantl152ac392015-02-01 00:58:04 +00004345 }
Adrian Prantl565cc182015-01-20 19:42:22 +00004346
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004347 // Remove any existing intrinsics describing the same alloca.
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004348 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004349 OldDII->eraseFromParent();
Adrian Prantl565cc182015-01-20 19:42:22 +00004350
Adrian Prantl941fa752016-12-05 18:04:47 +00004351 DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004352 DbgDeclares.front()->getDebugLoc(), &AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004353 }
4354 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004355 return Changed;
4356}
4357
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004358/// Clobber a use with undef, deleting the used value if it becomes dead.
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004359void SROA::clobberUse(Use &U) {
4360 Value *OldV = U;
4361 // Replace the use with an undef value.
4362 U = UndefValue::get(OldV->getType());
4363
4364 // Check for this making an instruction dead. We have to garbage collect
4365 // all the dead instructions to ensure the uses of any alloca end up being
4366 // minimal.
4367 if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4368 if (isInstructionTriviallyDead(OldI)) {
4369 DeadInsts.insert(OldI);
4370 }
4371}
4372
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004373/// Analyze an alloca for SROA.
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004374///
4375/// This analyzes the alloca to ensure we can reason about it, builds
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004376/// the slices of the alloca, and then hands it off to be split and
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004377/// rewritten as needed.
4378bool SROA::runOnAlloca(AllocaInst &AI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004379 LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004380 ++NumAllocasAnalyzed;
4381
4382 // Special case dead allocas, as they're trivial.
4383 if (AI.use_empty()) {
4384 AI.eraseFromParent();
4385 return true;
4386 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004387 const DataLayout &DL = AI.getModule()->getDataLayout();
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004388
4389 // Skip alloca forms that this analysis can't handle.
4390 if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004391 DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004392 return false;
4393
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004394 bool Changed = false;
4395
4396 // First, split any FCA loads and stores touching this alloca to promote
4397 // better splitting and promotion opportunities.
Tim Northover856628f2018-12-18 09:29:39 +00004398 AggLoadStoreRewriter AggRewriter(DL);
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004399 Changed |= AggRewriter.rewrite(AI);
4400
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004401 // Build the slices using a recursive instruction-visiting builder.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004402 AllocaSlices AS(DL, AI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004403 LLVM_DEBUG(AS.print(dbgs()));
Chandler Carruth83934062014-10-16 21:11:55 +00004404 if (AS.isEscaped())
Chandler Carruth42cb9cb2012-09-18 12:57:43 +00004405 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004406
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004407 // Delete all the dead users of this alloca before splitting and rewriting it.
Chandler Carruth83934062014-10-16 21:11:55 +00004408 for (Instruction *DeadUser : AS.getDeadUsers()) {
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004409 // Free up everything used by this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004410 for (Use &DeadOp : DeadUser->operands())
Chandler Carruth1583e992014-03-03 10:42:58 +00004411 clobberUse(DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004412
4413 // Now replace the uses of this instruction.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004414 DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004415
4416 // And mark it for deletion.
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004417 DeadInsts.insert(DeadUser);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004418 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004419 }
Chandler Carruth83934062014-10-16 21:11:55 +00004420 for (Use *DeadOp : AS.getDeadOperands()) {
Chandler Carruth57d4cae2014-10-16 20:42:08 +00004421 clobberUse(*DeadOp);
Chandler Carruth1bf38c62014-01-19 12:16:54 +00004422 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004423 }
4424
Chandler Carruth9f21fe12013-07-19 09:13:58 +00004425 // No slices to split. Leave the dead alloca for a later pass to clean up.
Chandler Carruth83934062014-10-16 21:11:55 +00004426 if (AS.begin() == AS.end())
Chandler Carruthe5b7a2c2012-10-05 01:29:09 +00004427 return Changed;
4428
Chandler Carruth83934062014-10-16 21:11:55 +00004429 Changed |= splitAlloca(AI, AS);
Chandler Carruthf0546402013-07-18 07:15:00 +00004430
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004431 LLVM_DEBUG(dbgs() << " Speculating PHIs\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004432 while (!SpeculatablePHIs.empty())
4433 speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4434
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004435 LLVM_DEBUG(dbgs() << " Speculating Selects\n");
Chandler Carruthf0546402013-07-18 07:15:00 +00004436 while (!SpeculatableSelects.empty())
4437 speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4438
4439 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004440}
4441
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004442/// Delete the dead instructions accumulated in this run.
Chandler Carruth19450da2012-09-14 10:26:38 +00004443///
4444/// Recursively deletes the dead instructions we've accumulated. This is done
4445/// at the very end to maximize locality of the recursive delete and to
4446/// minimize the problems of invalidated instruction pointers as such pointers
4447/// are used heavily in the intermediate stages of the algorithm.
4448///
4449/// We also record the alloca instructions deleted here so that they aren't
4450/// subsequently handed to mem2reg to promote.
Teresa Johnson33090022017-11-20 18:33:38 +00004451bool SROA::deleteDeadInstructions(
Chandler Carruth113dc642014-12-20 02:39:18 +00004452 SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
Teresa Johnson33090022017-11-20 18:33:38 +00004453 bool Changed = false;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004454 while (!DeadInsts.empty()) {
4455 Instruction *I = DeadInsts.pop_back_val();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004456 LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004457
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004458 // If the instruction is an alloca, find the possible dbg.declare connected
4459 // to it, and remove it too. We must do this before calling RAUW or we will
4460 // not be able to find it.
4461 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4462 DeletedAllocas.insert(AI);
Hsiangkai Wangef72e482018-08-06 03:59:47 +00004463 for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
Reid Kleckner0fe506b2017-09-21 19:52:03 +00004464 OldDII->eraseFromParent();
4465 }
4466
Chandler Carruth58d05562012-10-25 04:37:07 +00004467 I->replaceAllUsesWith(UndefValue::get(I->getType()));
4468
Chandler Carruth1583e992014-03-03 10:42:58 +00004469 for (Use &Operand : I->operands())
4470 if (Instruction *U = dyn_cast<Instruction>(Operand)) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004471 // Zero out the operand and see if it becomes trivially dead.
Craig Topperf40110f2014-04-25 05:29:35 +00004472 Operand = nullptr;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004473 if (isInstructionTriviallyDead(U))
Chandler Carruth18db7952012-11-20 01:12:50 +00004474 DeadInsts.insert(U);
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004475 }
4476
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004477 ++NumDeleted;
4478 I->eraseFromParent();
Teresa Johnson33090022017-11-20 18:33:38 +00004479 Changed = true;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004480 }
Teresa Johnson33090022017-11-20 18:33:38 +00004481 return Changed;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004482}
4483
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004484/// Promote the allocas, using the best available technique.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004485///
4486/// This attempts to promote whatever allocas have been identified as viable in
4487/// the PromotableAllocas list. If that list is empty, there is nothing to do.
Chandler Carruth748d0952015-08-26 09:09:29 +00004488/// This function returns whether any promotion occurred.
Chandler Carruth70b44c52012-09-15 11:43:14 +00004489bool SROA::promoteAllocas(Function &F) {
4490 if (PromotableAllocas.empty())
4491 return false;
4492
4493 NumPromoted += PromotableAllocas.size();
4494
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004495 LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
Davide Italiano612d5a92017-04-09 20:47:14 +00004496 PromoteMemToReg(PromotableAllocas, *DT, AC);
Chandler Carruth70b44c52012-09-15 11:43:14 +00004497 PromotableAllocas.clear();
4498 return true;
4499}
4500
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004501PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4502 AssumptionCache &RunAC) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004503 LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004504 C = &F.getContext();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004505 DT = &RunDT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004506 AC = &RunAC;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004507
4508 BasicBlock &EntryBB = F.getEntryBlock();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004509 for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
Adrian Prantl565cc182015-01-20 19:42:22 +00004510 I != E; ++I) {
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004511 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4512 Worklist.insert(AI);
Adrian Prantl565cc182015-01-20 19:42:22 +00004513 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004514
4515 bool Changed = false;
Chandler Carruth19450da2012-09-14 10:26:38 +00004516 // A set of deleted alloca instruction pointers which should be removed from
4517 // the list of promotable allocas.
4518 SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4519
Chandler Carruthac8317f2012-10-04 12:33:50 +00004520 do {
4521 while (!Worklist.empty()) {
4522 Changed |= runOnAlloca(*Worklist.pop_back_val());
Teresa Johnson33090022017-11-20 18:33:38 +00004523 Changed |= deleteDeadInstructions(DeletedAllocas);
Chandler Carruthb09f0a32012-10-02 22:46:45 +00004524
Chandler Carruthac8317f2012-10-04 12:33:50 +00004525 // Remove the deleted allocas from various lists so that we don't try to
4526 // continue processing them.
4527 if (!DeletedAllocas.empty()) {
Chandler Carruth113dc642014-12-20 02:39:18 +00004528 auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00004529 Worklist.remove_if(IsInSet);
4530 PostPromotionWorklist.remove_if(IsInSet);
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004531 PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
Chandler Carruthac8317f2012-10-04 12:33:50 +00004532 PromotableAllocas.end());
4533 DeletedAllocas.clear();
4534 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004535 }
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004536
Chandler Carruthac8317f2012-10-04 12:33:50 +00004537 Changed |= promoteAllocas(F);
4538
4539 Worklist = PostPromotionWorklist;
4540 PostPromotionWorklist.clear();
4541 } while (!Worklist.empty());
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004542
Davide Italiano16e96d42016-06-07 13:21:17 +00004543 if (!Changed)
4544 return PreservedAnalyses::all();
4545
Davide Italiano16e96d42016-06-07 13:21:17 +00004546 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00004547 PA.preserveSet<CFGAnalyses>();
Davide Italiano16e96d42016-06-07 13:21:17 +00004548 PA.preserve<GlobalsAA>();
4549 return PA;
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004550}
4551
Sean Silva36e0d012016-08-09 00:28:15 +00004552PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004553 return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4554 AM.getResult<AssumptionAnalysis>(F));
Chandler Carruth1b398ae2012-09-14 09:22:59 +00004555}
Chandler Carruth29a18a42015-09-12 09:09:14 +00004556
4557/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4558///
4559/// This is in the llvm namespace purely to allow it to be a friend of the \c
4560/// SROA pass.
4561class llvm::sroa::SROALegacyPass : public FunctionPass {
4562 /// The SROA implementation.
4563 SROA Impl;
4564
4565public:
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004566 static char ID;
4567
Chandler Carruth29a18a42015-09-12 09:09:14 +00004568 SROALegacyPass() : FunctionPass(ID) {
4569 initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4570 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004571
Chandler Carruth29a18a42015-09-12 09:09:14 +00004572 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00004573 if (skipFunction(F))
Chandler Carruth29a18a42015-09-12 09:09:14 +00004574 return false;
4575
4576 auto PA = Impl.runImpl(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004577 F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4578 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
Chandler Carruth29a18a42015-09-12 09:09:14 +00004579 return !PA.areAllPreserved();
4580 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004581
Chandler Carruth29a18a42015-09-12 09:09:14 +00004582 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004583 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth29a18a42015-09-12 09:09:14 +00004584 AU.addRequired<DominatorTreeWrapperPass>();
4585 AU.addPreserved<GlobalsAAWrapperPass>();
4586 AU.setPreservesCFG();
4587 }
4588
Mehdi Amini117296c2016-10-01 02:56:57 +00004589 StringRef getPassName() const override { return "SROA"; }
Chandler Carruth29a18a42015-09-12 09:09:14 +00004590};
4591
4592char SROALegacyPass::ID = 0;
4593
4594FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4595
4596INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4597 "Scalar Replacement Of Aggregates", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004598INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth29a18a42015-09-12 09:09:14 +00004599INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4600INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4601 false, false)